diff --git a/public/__redirects b/public/__redirects index 6bbbb219a1f..1347c26dc5f 100644 --- a/public/__redirects +++ b/public/__redirects @@ -660,9 +660,10 @@ /containers/wrangler-configuration/ /containers/reference/wrangler-configuration/ 301 /containers/wrangler-commands/ /containers/reference/wrangler-commands/ 301 # Sandbox -/sandbox/platform/beta-info/ /sandbox/platform/ 301 -/sandbox/guides/openai-agents-sdk/ /sandbox/tutorials/openai-agents/ 301 -/sandbox/guides/production-deployment/ /sandbox/guides/preview-urls-custom-domain/ 301 +/sandbox/platform/beta-info/ /sandbox/sdk/platform/ 301 +/sandbox/guides/openai-agents-sdk/ /sandbox/sdk/tutorials/openai-agents/ 301 +/sandbox/guides/production-deployment/ /sandbox/sdk/guides/preview-urls-custom-domain/ 301 +/sandbox/get-started/ /sandbox/sdk/get-started/ 301 # D1 /d1/client-api/ /d1/worker-api/ 301 /d1/build-with-d1/d1-client-api/ /d1/worker-api/ 301 @@ -2833,6 +2834,14 @@ /browser-rendering/rest-api/* /browser-run/quick-actions/:splat 301 /browser-rendering/quick-actions-rest-api/* /browser-run/quick-actions/:splat 301 /browser-rendering/* /browser-run/:splat 301 +/sandbox/1-0-preview/* /sandbox/ 301 +/sandbox/api/* /sandbox/sdk/api/:splat 301 +/sandbox/configuration/* /sandbox/sdk/configuration/:splat 301 +/sandbox/bridge/* /sandbox/sdk/bridge/:splat 301 +/sandbox/concepts/* /sandbox/sdk/concepts/:splat 301 +/sandbox/guides/* /sandbox/sdk/guides/:splat 301 +/sandbox/tutorials/* /sandbox/sdk/tutorials/:splat 301 +/sandbox/platform/* /sandbox/sdk/platform/:splat 301 /*/sitemap.xml /sitemap-index.xml 301 /api-security/* /api-shield/:splat 301 /api-shield/products/* /api-shield/security/:splat 301 diff --git a/src/components/landing/sidebar-data.ts b/src/components/landing/sidebar-data.ts index e355759d50a..92187bab154 100644 --- a/src/components/landing/sidebar-data.ts +++ b/src/components/landing/sidebar-data.ts @@ -97,7 +97,7 @@ export const sidebarSections: SidebarSection[] = [ link("Agents", "/agents/"), link("Agent Memory", "/agent-memory/"), link("Wallets", "/wallets/"), - link("Sandbox SDK", "/sandbox/"), + link("Sandboxes", "/sandbox/"), link("Vectorize", "/vectorize/"), link("AI Search", "/ai-search/"), link("AI Crawl Control", "/ai-crawl-control/"), diff --git a/src/content/changelog/sandbox/2026-08-07-sandbox-sdk-1-0-preview.mdx b/src/content/changelog/sandbox/2026-08-07-sandbox-sdk-1-0-preview.mdx deleted file mode 100644 index b71ccf4307d..00000000000 --- a/src/content/changelog/sandbox/2026-08-07-sandbox-sdk-1-0-preview.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Sandbox SDK 1.0 preview on @next -description: Preview a thinner Sandbox SDK on Cloudflare Containers — one process handle API, no sessions or transport selection, interpreter as an extension. -products: - - sandbox -date: 2026-08-07 ---- - -import { PackageManagers } from "~/components"; - -**Sandbox SDK 1.0** is available to preview under the npm `@next` tag. For existing applications, the current stable package remains published on the 0.12.x line. - -Sandbox SDK first shipped to provide a rich library for running untrusted and agent-driven work on [Cloudflare Containers](/containers/). Since then, both Sandbox and Containers have matured. This preview is a thinner SDK built on a richer Cloudflare Containers foundation. - - - -## What this preview is - -- **A single execution interface** — `sandbox.exec()` takes an argument list, returns when the process **starts**, and gives you a handle for output, logs, waits, and signals. Both short commands and long-running services use the same API. -- **Removed session execution** — the SDK no longer maintains shell state between executions. Each launch is independent. Pass `cwd` and `env` when you need them, or put multi-step shell syntax in one explicit shell command. -- **RPC as the only transport** — the SDK talks to the container exclusively over RPC. Remove `SANDBOX_TRANSPORT`, `transport` on `getSandbox()`, and `setTransport()`. -- **Improved PTY and terminal interface** — interactive PTYs use `createTerminal` / `connect`, not the older session-shaped helpers. -- **Code interpreter as an extension** — configure the code interpreter on your `Sandbox` subclass so you only ship what you need. - -Start new projects on `@next`. Migrate existing apps when you can so you are ready when 1.0 becomes stable. Deploy the Worker package and container image from the **same** `@next` line. - -Coding agents: install [Cloudflare Skills](https://github.com/cloudflare/skills) ([Agent setup](/agent-setup/)). Use **`sandbox-next`** for `@next` (recommended for new projects), **`sandbox-stable`** for the current stable package, and **`sandbox-migrate-to-next`** when you are ready to port. Stable-package deprecated-API cleanup is in the [2026 deprecation guide](/sandbox/guides/2026-deprecation/). - -The main [Sandbox documentation](/sandbox/) still describes today's stable package. Preview docs: - -- [1.0 preview](/sandbox/1-0-preview/) -- [Get started](/sandbox/1-0-preview/get-started/) -- [Migrate](/sandbox/1-0-preview/migrate/) -- [Processes](/sandbox/1-0-preview/processes/) · [Terminals](/sandbox/1-0-preview/terminals/) · [Errors](/sandbox/1-0-preview/errors/) -- [API reference](/sandbox/1-0-preview/api/) - -The self-deployed Sandbox bridge is not currently part of this preview. We are working on bringing it in line with the latest code. Until then, use the [stable bridge](/sandbox/bridge/) with the matching stable package and container image. - -## Timeline for 1.0 - -Further Cloudflare Containers features will let us keep reducing the size of the Sandbox SDK. We aim to ship Sandbox SDK 1.0 once those are in. In the meantime we continue to support and maintain the 1.0 preview (`@next`) alongside the current stable release. diff --git a/src/content/directory/sandbox.yaml b/src/content/directory/sandbox.yaml index db8d6140755..1862f58fcab 100644 --- a/src/content/directory/sandbox.yaml +++ b/src/content/directory/sandbox.yaml @@ -1,14 +1,14 @@ id: XN9oQt -name: Sandbox SDK +name: Sandboxes entry: - title: Sandbox SDK + title: Sandboxes url: /sandbox/ group: Developer platform additional_groups: [AI] tags: [AI] meta: - title: Cloudflare Sandbox SDK docs - description: Build secure, isolated code execution environments + title: Cloudflare Sandboxes docs + description: Isolated execution on Cloudflare using Dynamic Workers and Containers author: "@cloudflare" diff --git a/src/content/docs/agents/tools/sandbox.mdx b/src/content/docs/agents/tools/sandbox.mdx index 7bf1400be2b..1ed3c08b4fc 100644 --- a/src/content/docs/agents/tools/sandbox.mdx +++ b/src/content/docs/agents/tools/sandbox.mdx @@ -112,12 +112,12 @@ For long-running sandbox work, pair Sandbox with [durable execution with fibers] diff --git a/src/content/docs/artifacts/examples/sandbox-sdk-artifacts.mdx b/src/content/docs/artifacts/examples/sandbox-sdk-artifacts.mdx index 754904dfa3d..d4365bcfb8d 100644 --- a/src/content/docs/artifacts/examples/sandbox-sdk-artifacts.mdx +++ b/src/content/docs/artifacts/examples/sandbox-sdk-artifacts.mdx @@ -12,7 +12,7 @@ import { PackageManagers, TypeScriptExample } from "~/components"; This example uses the `git-repo-per-sandbox` Sandbox SDK template and highlights the Artifacts-specific pieces. -Start from the template with `create cloudflare`, as shown in [Run Claude Code on a Sandbox](/sandbox/tutorials/claude-code/#1-create-your-project). Then adapt the Artifacts flow with the focused snippets below. +Start from the template with `create cloudflare`, as shown in [Run Claude Code on a Sandbox](/sandbox/sdk/tutorials/claude-code/#1-create-your-project). Then adapt the Artifacts flow with the focused snippets below. - Creates or reuses a sandbox by ID. - Creates or reuses an Artifacts repo with the same ID. diff --git a/src/content/docs/artifacts/guides/build-and-deploy-on-push.mdx b/src/content/docs/artifacts/guides/build-and-deploy-on-push.mdx index abbfceee6a7..95a21c30cec 100644 --- a/src/content/docs/artifacts/guides/build-and-deploy-on-push.mdx +++ b/src/content/docs/artifacts/guides/build-and-deploy-on-push.mdx @@ -50,7 +50,7 @@ Use the `@cloudflare/ci` SDK to define the CI steps. The SDK provides two tools ![Diagram showing three sequential commits: commit 1 has a cache miss so the install step runs and its sandbox snapshot is cached; commit 2 has an unchanged pnpm-lock.yaml so the cache key matches and the cached snapshot is served, skipping install; commit 3 has a changed pnpm-lock.yaml so the cache key misses and install runs again.](~/assets/images/artifacts/snapshot-cache-flow.svg) -A cached runner takes a [snapshot](/sandbox/api/backups/) of its sandbox, which later runners reuse. Multiple runners can branch from the same cached result — for example, lint, type-check, and test runners can all reuse one cached install. +A cached runner takes a [snapshot](/sandbox/sdk/api/backups/) of its sandbox, which later runners reuse. Multiple runners can branch from the same cached result — for example, lint, type-check, and test runners can all reuse one cached install. diff --git a/src/content/docs/containers/guides/outbound-traffic.mdx b/src/content/docs/containers/guides/outbound-traffic.mdx index fbe1ee0e430..a71b3b81183 100644 --- a/src/content/docs/containers/guides/outbound-traffic.mdx +++ b/src/content/docs/containers/guides/outbound-traffic.mdx @@ -412,6 +412,6 @@ The `Container` class calls these methods automatically when you use the functio ## Related resources - [Connect to Workers bindings](/containers/configuration/workers-connections/) — Access KV, R2, Durable Objects, and other bindings from a container -- [Control outbound traffic (Sandboxes)](/sandbox/guides/outbound-traffic/) — Sandbox SDK API for outbound handlers +- [Control outbound traffic (Sandboxes)](/sandbox/sdk/guides/outbound-traffic/) — Sandbox SDK API for outbound handlers - [Environment variables and secrets](/containers/configuration/environment-variables/) — Configure secrets and environment variables - [Durable Object interface](/durable-objects/api/container/) — Full `ctx.container` API reference diff --git a/src/content/docs/reference-architecture/diagrams/ai/ai-vibe-coding-platform.mdx b/src/content/docs/reference-architecture/diagrams/ai/ai-vibe-coding-platform.mdx index e28931f5574..6f20baf79fd 100644 --- a/src/content/docs/reference-architecture/diagrams/ai/ai-vibe-coding-platform.mdx +++ b/src/content/docs/reference-architecture/diagrams/ai/ai-vibe-coding-platform.mdx @@ -64,7 +64,7 @@ Both [Sandboxes](/sandbox/) and [Containers](/containers/) provide secure, isola - **Preview URLs** to allow users to test applications during development - **Global edge deployment** on Cloudflare's network for low-latency execution worldwide -**Sandboxes provide a fully-managed solution** that works out-of-the-box, with [pre-built APIs](/sandbox/api/) for code execution, output formatting, and developer tools, making them ideal for most AI code execution use cases. +**Sandboxes provide a fully-managed solution** that works out-of-the-box, with [pre-built APIs](/sandbox/sdk/api/) for code execution, output formatting, and developer tools, making them ideal for most AI code execution use cases. ![Figure 3: Vibe Code Development - Sandbox SDK](~/assets/images/reference-architecture/ai-vibe-coding/ai-platform-sandbox.svg) diff --git a/src/content/docs/sandbox/1-0-preview/api/errors.mdx b/src/content/docs/sandbox/1-0-preview/api/errors.mdx deleted file mode 100644 index 5431f20b320..00000000000 --- a/src/content/docs/sandbox/1-0-preview/api/errors.mdx +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: Errors -pcx_content_type: reference -sidebar: - order: 3 -description: Error classes, codes, and context fields for @cloudflare/sandbox@next. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page is the error reference for `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. When to retry or relaunch: [Errors and recovery](/sandbox/1-0-preview/errors/). -::: - -Error classes and codes returned by the Sandbox SDK 1.0 preview, with short recommended actions. For full recovery procedures, refer to [Errors and recovery](/sandbox/1-0-preview/errors/). - -## How errors are returned - -Operations throw exceptions you can catch. Prefer `instanceof` on classes from `@cloudflare/sandbox`. Use `code` and `context` for metrics and stable field access. - - -```ts -import { - ContainerUnavailableError, - OperationInterruptedError, - RPCTransportError, -} from "@cloudflare/sandbox"; - -try { - await sandbox.exec(["npm", "test"], { cwd: "/workspace/app" }); -} catch (error) { - if (error instanceof ContainerUnavailableError) { - // error.code === "CONTAINER_UNAVAILABLE" - // error.context.reason, error.context.retryAfterMs - } - if (error instanceof OperationInterruptedError) { - // Convenience getters: error.reason, error.retryable, error.operationName - // admitted is only on context: error.context.admitted - } - if (error instanceof RPCTransportError) { - // Convenience getters: error.kind, error.originalMessage - } -} -``` - - -### Imports - -Common lifecycle, process, terminal, and backup errors are available from the package root: - - -```ts -import { - ContainerUnavailableError, - OperationInterruptedError, - RPCTransportError, - StaleProcessHandleError, - // ... -} from "@cloudflare/sandbox"; -``` - - -The full module also exports `ErrorCode`, `SandboxError`, `createErrorFromResponse`, and other domain errors (files, ports, interpreter, mounts, and related context types): - - -```ts -import { - ErrorCode, - SandboxError, - createErrorFromResponse, - FileNotFoundError, - // ... -} from "@cloudflare/sandbox/errors"; -``` - - -Platform helpers (not `SandboxError` subclasses): - - -```ts -import { - isPlatformTransientError, - isDurableObjectCodeUpdateReset, -} from "@cloudflare/sandbox"; -``` - - -### `SandboxError` shape - -Most SDK errors extend `SandboxError`: - -| Member | Description | -| ------ | ----------- | -| `name` | Class name (for example `ContainerUnavailableError`) | -| `message` | Human-readable message | -| `code` | Stable `ErrorCode` string (for example `CONTAINER_UNAVAILABLE`) | -| `context` | Structured fields for the error type | -| `httpStatus` | Mapped HTTP status when applicable | -| `operation` | Operation label when provided | -| `suggestion` | Optional actionable suggestion | -| `timestamp` | ISO timestamp when provided | -| `toJSON()` | Serializes the error fields for logs | - -`RuntimeIdentityInactiveError` extends `Error` directly (not `SandboxError`). It means the current container is no longer the active one for this handle or call. - -Tables include a **Recommended fix** column. For longer recovery procedures, refer to [Errors and recovery](/sandbox/1-0-preview/errors/). - -Availability errors and deployment mismatch errors are listed in separate sections. Do not use the same retry loop for both. - ---- - -## Container availability and interrupted calls - -These errors come from ordinary start, idle stop, replace, or lost contact while a call is running. - -| Class | Code | Key context | Details | Recommended fix | -| ----- | ---- | ----------- | ------- | ---------------- | -| `ContainerUnavailableError` | `CONTAINER_UNAVAILABLE` | `reason`, `retryable: true`, `retryAfterMs?` | Container not ready before the operation started. | Back off (honor `retryAfterMs` when set), then try the same kind of work again. | -| `OperationInterruptedError` | `OPERATION_INTERRUPTED` | `reason`, `operation`, `admitted`, `retryable` | Container or sandbox changed after the operation may have started. | Read `reason` and `retryable`. Check sandbox or app state before repeating work that changes state. | -| `RPCTransportError` | `RPC_TRANSPORT_ERROR` | `kind`, `originalMessage`, `errorName`, `closeCode?` | SDK lost contact with the container during a call. | A later call may work. This call may already have changed something. | -| `RuntimeIdentityInactiveError` | — | — | Current container is no longer active for this call or handle. Plain `Error`, not `SandboxError`. | Check whether the resource still exists; if not, start the work again from stored state. | - -### `ContainerUnavailableError` reasons - -`context.reason`: - -| Reason | Meaning | -| ------ | ------- | -| `container_starting` | Container is still starting | -| `container_unhealthy` | Container is not healthy | -| `container_replaced` | Container was replaced | -| `rpc_upgrade_failed` | Could not establish communication with the container | - -### `OperationInterruptedError` reasons - -`reason` / `context.reason`: - -| Reason | Meaning | -| ------ | ------- | -| `runtime_replaced` | Underlying container instance was replaced | -| `container_stopped` | Container stopped | -| `transport_disposed` | Communication session was disposed | -| `sandbox_destroyed` | Sandbox was destroyed | -| `sandbox_lifetime_changed` | Sandbox lifetime configuration changed | -| `recovery_exhausted` | Recovery attempts were exhausted | -| `unknown` | Unclassified interruption | - -Convenience getters on the error: `reason`, `retryable`, and `operationName`. Other fields such as `admitted`, `operationId`, `phase`, and backup-related metadata are on `error.context` only (`admitted` is `true | "unknown"`). - -### `RPCTransportError` kinds - -`kind` / `context.kind`: - -| Kind | Meaning | -| ---- | ------- | -| `peer_closed` | Peer closed the connection | -| `connection_failed` | Connection failed | -| `upgrade_failed` | Connection setup failed | -| `invalid_frame` | Unexpected frame | -| `protocol_error` | Frame rejected by the protocol | -| `session_disposed` | Session disposed | -| `unknown` | Unclassified failure | - ---- - -## Worker and container image mismatch - -These failures usually mean the Worker package and container image do not match, the image cannot start, or setup metadata does not match what the SDK expects. Fix the deployment. Do not treat them like a slow container start. - -Deploy the Worker package and the sandbox container image from the same `@cloudflare/sandbox@next` line. A preview Worker with a stable image (or the reverse) often fails here. - -| Class | Code | Key context | Details | Recommended fix | -| ----- | ---- | ----------- | ------- | ---------------- | -| `RuntimeControlProtocolError` | `INTERNAL_ERROR` | `reason` | Worker and container could not complete setup together (metadata or protocol mismatch). The code is the shared `INTERNAL_ERROR` value — identify this class with `instanceof RuntimeControlProtocolError` or by pairing `code === "INTERNAL_ERROR"` with `context.reason`. | Deploy the Worker package and container image from the same release line. Fix configuration if needed. | - -### `RuntimeControlProtocolError` reasons - -`context.reason`: - -| Reason | Meaning | Notes | -| ------ | ------- | ----- | -| `unsupported-protocol-version` | Worker and container protocol versions do not match | Worker package and container image are not from the same release | -| `missing-metadata` | Required setup metadata missing from the container | Bad or incomplete image/build | -| `malformed-metadata` | Setup metadata could not be parsed | Bad or incomplete image/build | -| `activation-mismatch` | Activation did not match the expected container | Can appear after container replace; if it keeps happening, check Worker and image pairing | - -The following permanent problems are related and return the same response: - -| Problem | Recommended fix | -| ------- | ---------------- | -| Wrong or missing container image in `wrangler` / registry | Deploy the Worker package and container image from the same release line. Fix configuration if needed. | -| Container exits before it becomes ready | Fix the image or entrypoint and redeploy. Do not only retry the app call. | -| Account or location capacity limits | Refer to [Production capacity limits](#production-capacity-limits) | - ---- - -## Process - -| Class | Code | Key context | Details | Recommended fix | -| ----- | ---- | ----------- | ------- | ---------------- | -| `ProcessNotFoundError` | `PROCESS_NOT_FOUND` | `processId` | Unknown process ID in the current container. | Use the correct ID, or start the process again from stored state. | -| `StaleProcessHandleError` | `STALE_PROCESS_HANDLE` | `processId`, `pid`, `operation` | Handle or ID from a previous container. | Start the work again from stored state. Do not reuse the old handle. | -| `ProcessSpawnFailedError` | `PROCESS_SPAWN_FAILED` | `processId`, `command`, `cwd?`, `stderr?` | Process could not start. | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | -| `InvalidProcessCwdError` | `INVALID_PROCESS_CWD` | `cwd`, `reason` | Invalid working directory. | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | -| `InvalidProcessEnvironmentError` | `INVALID_PROCESS_ENVIRONMENT` | `name?`, `reason` | Invalid environment overlay. | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | -| `InvalidProcessCursorError` | `INVALID_PROCESS_CURSOR` | `processId`, `cursor?`, `reason` | Bad log cursor. | Correct the cursor or other arguments. Do not retry the same invalid value. | -| `ProcessWaitTimeoutError` | `PROCESS_WAIT_TIMEOUT` | `processId`, `operation`, `timeout` | Local `output`, `waitForExit`, or `waitForLog` timed out. | The wait ended. The process or terminal may still be running. | -| `ProcessAbortedError` | `PROCESS_ABORTED` | `processId`, `operation` | Local `AbortSignal` ended a wait or stream. | The wait ended. The process or terminal may still be running. | -| `ProcessReadyTimeoutError` | `PROCESS_READY_TIMEOUT` | `processId`, `command`, `condition`, `timeout` | Readiness wait timed out. | Check whether the process is still running before starting another. | -| `ProcessExitedBeforeReadyError` | `PROCESS_EXITED_BEFORE_READY` | `processId`, `command`, `condition`, `exitCode` | Process exited before readiness. | Correct the command or environment, then start again if needed. | -| `ProcessExitedBeforeLogError` | `PROCESS_EXITED_BEFORE_LOG` | `processId`, `pid`, `exit` | Process exited before a log match. | Correct the command or environment, then start again if needed. | -| `ProcessError` | `PROCESS_ERROR` | `processId`, `pid?`, `exitCode?`, `stderr?` | General process failure. | Check sandbox or app state before repeating work that changes state. | - -`getProcess` and `listProcesses` returning `null` or `[]` is not an error. - ---- - -## Terminal - -| Class | Code | Key context | Details | Recommended fix | -| ----- | ---- | ----------- | ------- | ---------------- | -| `TerminalNotFoundError` | `TERMINAL_NOT_FOUND` | `terminalId` | Unknown terminal ID in the current container. | Use the correct ID, or start the terminal again from stored state. | -| `StaleTerminalHandleError` | `STALE_TERMINAL_HANDLE` | `terminalId`, `operation` | Handle or ID from a previous container. | Start the work again from stored state. Do not reuse the old handle. | -| `InvalidTerminalCwdError` | `INVALID_TERMINAL_CWD` | `terminalId`, `cwd`, `reason` | Invalid working directory at create. | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | -| `InvalidTerminalCursorError` | `INVALID_TERMINAL_CURSOR` | `terminalId`, `cursor?`, `reason` | Bad output cursor. | Correct the cursor or other arguments. Do not retry the same invalid value. | -| `TerminalControlError` | `TERMINAL_CONTROL_ERROR` | `terminalId`, `operation`, `reason?` | Interrupt, terminate, resize, or related control failed. | Check sandbox or app state before repeating work that changes state. | - -`getTerminal` and `listTerminals` returning `null` or `[]` is not an error. - ---- - -## Backup - -| Class | Code | Details | Recommended fix | -| ----- | ---- | ------- | ---------------- | -| `BackupCreateError` | `BACKUP_CREATE_FAILED` | Backup create failed. | Check failure details; correct options if they are invalid. | -| `BackupRestoreError` | `BACKUP_RESTORE_FAILED` | Backup restore failed. | Check failure details; correct options if they are invalid. | -| `BackupNotFoundError` | `BACKUP_NOT_FOUND` | Unknown backup ID. | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | -| `BackupExpiredError` | `BACKUP_EXPIRED` | Backup past validity. | Correct options, or create a new backup. | -| `InvalidBackupConfigError` | `INVALID_BACKUP_CONFIG` | Invalid backup options. | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | - ---- - -## Other domains - -These classes are available from `@cloudflare/sandbox/errors` (and some mount helpers from the package root). Confirm details against your installed package. Preview-specific guides for every domain are not all published yet. - -| Domain | Examples | Recommended fix | -| ------ | -------- | ---------------- | -| Filesystem | `FileNotFoundError`, `FileExistsError`, `PermissionDeniedError`, `FileTooLargeError`, `FileSystemError` | Correct the path or handle a missing file. | -| Ports / preview | `PortAlreadyExposedError`, `PortNotExposedError`, `InvalidPortError`, `PortInUseError`, `ServiceNotRespondingError`, `CustomDomainRequiredError` | Correct port options or expose settings. | -| Interpreter (extension) | `InterpreterNotReadyError`, `ContextNotFoundError`, `CodeExecutionError` | If the interpreter is not ready, back off and try again. Otherwise correct the request. | -| Mounts | `BucketMountError`, `BucketUnmountError`, `S3FSMountError`, `MissingCredentialsError`, `InvalidMountConfigError` | Correct mount options or credentials. | -| Validation | `ValidationFailedError` | Correct the path, environment, command, or other arguments. Do not retry the same invalid request. | - -Other domain classes may exist on `@cloudflare/sandbox/errors` in your installed package. Confirm against that package before depending on undocumented surfaces. - -Mount-related errors are also exported from `@cloudflare/sandbox` next to the mount APIs. - ---- - -## Platform helpers - -| Helper | Details | Recommended fix | -| ------ | ------- | ---------------- | -| `isPlatformTransientError(error)` | True for some transient platform signals (for example connection lost, certain Durable Object storage startup resets, or retryable platform errors). | Prefer a new request or operation. | -| `isDurableObjectCodeUpdateReset(error)` | True when the Durable Object isolate was replaced by a code update or deploy. | Do not keep retrying inside the same request. Let a new request run on the new isolate. | - -These helpers complement `SandboxError` subclasses. They do not replace the recovery rules on [Errors and recovery](/sandbox/1-0-preview/errors/). - ---- - -## Production capacity limits - -In production, the Containers platform may reject work when account or deployment limits are exceeded (for example `SURPASSED_BASE_LIMITS`, `SURPASSED_TOTAL_LIMITS`, `LOCATION_SURPASSED_BASE_LIMITS`). Retrying the same overload does not fix that. Reduce concurrency, raise limits, or fail to an operator path. These limits usually do not appear in local `wrangler dev`. - -Refer to [Platform limits](/sandbox/platform/limits/). - ---- - -## Related - -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Processes API](/sandbox/1-0-preview/api/processes/) -- [Terminals API](/sandbox/1-0-preview/api/terminals/) -- [Migrate](/sandbox/1-0-preview/migrate/) diff --git a/src/content/docs/sandbox/1-0-preview/api/index.mdx b/src/content/docs/sandbox/1-0-preview/api/index.mdx deleted file mode 100644 index 1a006cc40c5..00000000000 --- a/src/content/docs/sandbox/1-0-preview/api/index.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: API reference -pcx_content_type: navigation -sidebar: - order: 8 -description: API reference for @cloudflare/sandbox@next — processes, terminals, errors, and related preview surfaces. -products: - - sandbox ---- - -import { CardGrid, LinkTitleCard } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This section documents APIs on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For today's stable package, refer to [API reference](/sandbox/api/). -::: - -Reference for the preview public surface. Start with the mental model pages when you need *why*. Use these pages for signatures and types. - - - - - `exec`, process handles, logs, waits, and kill. - - - - `createTerminal`, handles, output, connect, interrupt, and terminate. - - - - Error classes, codes, and recommended fixes. - - - - `withInterpreter`, contexts, `runCode`, and results. - - - - -## Other API surfaces - -Files, mounts, backups, ports, tunnels, and related options remain available. Use the main reference for signatures: - -- [Files](/sandbox/api/files/) and [file watching](/sandbox/api/file-watching/) -- [Storage](/sandbox/api/storage/) and [backups](/sandbox/api/backups/) -- [Ports](/sandbox/api/ports/) and [tunnels](/sandbox/api/tunnels/) -- [Lifecycle](/sandbox/api/lifecycle/) and [sandbox options](/sandbox/configuration/sandbox-options/) -- [Outbound traffic](/sandbox/guides/outbound-traffic/) - -Where those pages still describe sessions or transport selection, that guidance does not apply on `@next`. - -## Related concepts and guides - -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Process execution](/sandbox/1-0-preview/processes/) -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Environment variables](/sandbox/1-0-preview/environment/) -- [Code interpreter](/sandbox/1-0-preview/interpreter/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Troubleshooting](/sandbox/1-0-preview/troubleshooting/) -- [Migrate](/sandbox/1-0-preview/migrate/) diff --git a/src/content/docs/sandbox/1-0-preview/api/interpreter.mdx b/src/content/docs/sandbox/1-0-preview/api/interpreter.mdx deleted file mode 100644 index 7132591e226..00000000000 --- a/src/content/docs/sandbox/1-0-preview/api/interpreter.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Interpreter -pcx_content_type: reference -sidebar: - order: 4 -description: Reference for the code interpreter extension on @cloudflare/sandbox@next. -products: - - sandbox ---- - -:::note[Path to Sandbox SDK 1.0] -This page documents `@cloudflare/sandbox/interpreter` on `@cloudflare/sandbox@next`. For the current stable package, refer to [Interpreter API](/sandbox/api/interpreter/). -::: - -Methods live on `sandbox.interpreter` after you attach `withInterpreter` on your `Sandbox` subclass. Method names match the stable interpreter; `runCode` returns plain serializable data. Attach and first run: [Code interpreter](/sandbox/1-0-preview/interpreter/). - -## `createCodeContext()` - -```ts -createCodeContext(options?: CreateContextOptions): Promise -``` - -### `CreateContextOptions` - -`createCodeContext` accepts the following options: - -| Field | Type | Description | -| ----- | ---- | ----------- | -| `language` | `"python" \| "javascript" \| "typescript"` | Interpreter language. Default: `python`. | -| `cwd` | `string` | Working directory. Default: `/workspace`. | - -### `CodeContext` - -A created context has the following fields: - -| Field | Type | Description | -| ----- | ---- | ----------- | -| `id` | `string` | Context id in the current container | -| `language` | `string` | Language of the context | -| `cwd` | `string` | Working directory | -| `createdAt` | `Date` | Created time | -| `lastUsed` | `Date` | Last used time | - -## `runCode()` - -```ts -runCode(code: string, options?: RunCodeOptions): Promise -``` - -### `RunCodeOptions` - -`runCode` accepts the following options. The callback fields apply to `runCode` only. - -| Field | Type | Description | -| ----- | ---- | ----------- | -| `context` | `CodeContext` | Context to use. If omitted, a default context for `language` is used. | -| `language` | `"python" \| "javascript" \| "typescript"` | Used when creating or selecting a default context. Default: `python`. | -| `onStdout` | `(output: OutputMessage) => void \| Promise` | Called for stdout chunks while running | -| `onStderr` | `(output: OutputMessage) => void \| Promise` | Called for stderr chunks while running | -| `onResult` | `(result: ResultData) => void \| Promise` | Called for rich results (plain data) | -| `onError` | `(error: ExecutionError) => void \| Promise` | Called when the run reports an execution error | - -### `OutputMessage` - -```ts -interface OutputMessage { - text: string; - timestamp: number; -} -``` - -### `ExecutionResult` - -```ts -interface ExecutionResult { - code: string; - logs: { - stdout: string[]; - stderr: string[]; - }; - error?: ExecutionError; - executionCount?: number; - results: ResultData[]; -} -``` - -`ResultData` may include plain fields such as `text`, `html`, `png`, `jpeg`, `svg`, `latex`, `markdown`, `json`, and `chart` when the runtime produces them. - -### `ExecutionError` - -```ts -interface ExecutionError { - name: string; - message: string; - traceback: string[]; - lineNumber?: number; -} -``` - -## `runCodeStream()` - -```ts -runCodeStream( - code: string, - options?: RunCodeOptions, -): Promise> -``` - -Returns an SSE byte stream of execution events. The TypeScript type reuses `RunCodeOptions` for `context` and `language`, but the stream path does **not** invoke `onStdout`, `onStderr`, `onResult`, or `onError` — consume the SSE body instead. Canceling the stream may interrupt the in-flight run. - -## `listCodeContexts()` - -```ts -listCodeContexts(): Promise -``` - -## `deleteCodeContext()` - -```ts -deleteCodeContext(contextId: string): Promise -``` - -## Errors - -Interpreter failures may surface as `InterpreterNotReadyError`, `ContextNotFoundError`, or `CodeExecutionError`. Refer to [Errors API](/sandbox/1-0-preview/api/errors/) and [Errors and recovery](/sandbox/1-0-preview/errors/). - -Python requires the **`-python`** container image variant. Deploy the Worker package and container image from the same preview line. - -## Related - -- [Code interpreter](/sandbox/1-0-preview/interpreter/) -- [Extensions](/sandbox/1-0-preview/extensions/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- Stable: [Interpreter API](/sandbox/api/interpreter/) diff --git a/src/content/docs/sandbox/1-0-preview/api/processes.mdx b/src/content/docs/sandbox/1-0-preview/api/processes.mdx deleted file mode 100644 index 1528db0bae1..00000000000 --- a/src/content/docs/sandbox/1-0-preview/api/processes.mdx +++ /dev/null @@ -1,480 +0,0 @@ ---- -title: Processes -pcx_content_type: reference -sidebar: - order: 1 -description: Reference for argv exec, SandboxProcess handles, logs, waits, and related types in the Sandbox SDK 1.0 preview. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents the process API on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For today's stable command surface, refer to [Commands](/sandbox/api/commands/). -::: - -Launch and observe supervised processes in the current container for a sandbox. - -For the mental model, refer to [Process execution](/sandbox/1-0-preview/processes/). For interactive PTY input and browser terminals, refer to [Terminals](/sandbox/1-0-preview/terminals/) and the [Terminals API](/sandbox/1-0-preview/api/terminals/). - -Process handles have **no standard input**. Use `cwd`, `env`, and argv (or an explicit shell script) for non-interactive work. Use a [terminal](/sandbox/1-0-preview/terminals/) when you need an interactive PTY. - -## `exec()` - -Start a process from **argv** (executable, then arguments). Resolves when launch succeeds, not when the process exits. The SDK does not run a shell and does not shell-escape argv — each entry is one process argument. - -```ts -exec(command: SandboxCommand, options?: ExecOptions): Promise -``` - -### `SandboxCommand` - -```ts -type SandboxCommand = readonly [executable: string, ...args: string[]]; -``` - -- `command[0]` must be a non-empty executable path or name. -- Later arguments may be empty strings. -- Entries are passed through as-is (no shell escaping of argv). -- Shell syntax requires an explicit shell, for example `['/bin/bash', '-lc', script]`. - -### `ExecOptions` - -| Field | Type | Description | -| --------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | Working directory for this launch. Defaults to `/workspace` when unset. | -| `env` | `Record` | Environment overlay for this launch. Does not mutate later launches. Sandbox-level env still applies. | -| `timeout` | `number` | Remote process lifetime in milliseconds. The supervisor may stop the process; completion can report `timedOut: true`. | - -### Returns - -`Promise` - - -```ts -const process = await sandbox.exec(["node", "--version"]); -const output = await process.output({ encoding: "utf8" }); - -console.log(process.id, process.pid, output.stdout, output.exitCode); -``` - - -## `getProcess()` - -Return a handle for a process running in the **current container** for this sandbox, or `null`. - -Does not start a container if none is running. Returns `null` when no container is up, when the process ID is unknown in the current container, or when that process belonged to a previous container for the same sandbox ID. - -```ts -getProcess(id: string): Promise -``` - -Process IDs are not durable across container stop or replace. Refer to [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). - -## `listProcesses()` - -List processes in the current container for this sandbox. Does not start a container if none is running. Returns an empty list when no container is up. - -```ts -listProcesses(): Promise -``` - -Each entry is a [ProcessStatus](#processstatus) value (the same shape as `status()`). - -## `SandboxProcess` - -| Member | Description | -| ------------------------------- | --------------------------------------------------------------------------- | -| `id` | Process ID in the current container. | -| `pid` | Container pid at launch. | -| `exitCode` | `Promise` that resolves when the supervised process group settles. | -| `status()` | Current discriminated status. | -| `logs(options?)` | Cursor-based log stream. | -| `output(options?)` | Buffered stdout and stderr plus exit metadata. | -| `waitForExit(options?)` | Wait until the supervised process group settles. | -| `waitForLog(pattern, options?)` | Wait until stdout or stderr matches. | -| `waitForPort(port, options?)` | Wait until a port is ready or readiness fails. | -| `kill(signal?)` | Send a numeric signal. Default `15` (`SIGTERM`). | - -There is no process stdin API on this handle. - -### `status()` - -```ts -status(): Promise -``` - -Refer to [ProcessStatus](#processstatus). A process stays `running` until the supervised **process group** has settled, even if the root pid exits while descendants continue. - -### `output()` - -Buffer stdout and stderr until the process completes (or the local wait ends), then return exit metadata. - -```ts -output(options?: ProcessOutputOptions): Promise> -output( - options: ProcessOutputOptions & { encoding: "utf8" }, -): Promise> -``` - -#### `ProcessOutput` - -```ts -interface ProcessOutput { - stdout: T; - stderr: T; - exitCode: number; - signal?: number; - timedOut: boolean; - truncated: boolean; -} -``` - -Default body encoding is binary (`Uint8Array`) unless you pass `encoding: "utf8"`. Prefer `logs()` when output may exceed what you want to buffer. - -#### `ProcessOutputOptions` - -| Field | Type | Description | -| ---------- | ------------- | --------------------------------------------------------------------------- | -| `encoding` | `"utf8"` | Decode stdout/stderr as strings. | -| `maxBytes` | `number` | Cap buffered bytes per stream side of the result; may set `truncated: true`. No default cap when omitted. | -| `timeout` | `number` | Local wait deadline in milliseconds only; does not kill the process. | -| `signal` | `AbortSignal` | Cancel this wait only; does not kill the process. | - -`maxBytes` must be a non-negative finite number when set. - - -```ts -const process = await sandbox.exec(["/bin/bash", "-lc", "npm test"], { - cwd: "/workspace/app", -}); -const result = await process.output({ encoding: "utf8", timeout: 120_000 }); - -console.log(result.exitCode, result.stdout, result.timedOut, result.truncated); -``` - - -### `logs()` - -Stream replayable log events with an opaque cursor. - -```ts -logs(options?: ProcessLogsOptions): Promise> -``` - -#### `ProcessLogsOptions` - -| Field | Type | Description | -| -------- | ------------- | ------------------------------------------------------------------- | -| `since` | `string` | Opaque cursor; resume after a previous event. | -| `replay` | `boolean` | Include buffered history when resuming. | -| `follow` | `boolean` | Keep the stream open for live output. | -| `signal` | `AbortSignal` | Cancel this subscription only; the process keeps running. | - -#### `ProcessLogEvent` - -```ts -type ProcessLogEvent = - | { - type: "stdout" | "stderr"; - cursor: string; - timestamp: string; - data: Uint8Array; - } - | { - type: "terminal"; - state: "exited"; - cursor: string; - timestamp: string; - exit: ProcessExit; - } - | { - type: "terminal"; - state: "error"; - cursor: string; - timestamp: string; - error: ProcessFailure; - } - | { - type: "truncated"; - cursor?: string; - timestamp: string; - }; -``` - -Retain the latest `cursor` from delivered events if a later Worker request resumes with `logs({ since: cursor, replay: true, follow: true })` on the **same** process in the **same** container. - - -```ts -const process = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], { - cwd: "/workspace/app", -}); - -const stream = await process.logs({ follow: true, replay: true }); -const reader = stream.getReader(); -const decoder = new TextDecoder(); - -for (;;) { - const { done, value } = await reader.read(); - if (done) break; - - if (value.type === "stdout" || value.type === "stderr") { - // Keep value.cursor if you will resume later - console.log(value.type, decoder.decode(value.data, { stream: true })); - continue; - } - - if (value.type === "terminal") { - console.log("done", value.state); - break; - } -} -``` - - -### `waitForExit()` - -Wait until the supervised process group settles. - -```ts -waitForExit(options?: { - timeout?: number; - signal?: AbortSignal; -}): Promise -``` - -| Field | Type | Description | -| --------- | ------------- | --------------------------------------------------------- | -| `timeout` | `number` | Local wait deadline only; does not kill the process. | -| `signal` | `AbortSignal` | Cancel this wait only; does not kill the process. | - -Returns [ProcessExit](#processexit). Local timeout surfaces as `ProcessWaitTimeoutError`. Local abort surfaces as `ProcessAbortedError`. - - -```ts -const build = await sandbox.exec(["/bin/bash", "-lc", "npm run build"], { - cwd: "/workspace/app", -}); -const exit = await build.waitForExit({ timeout: 600_000 }); -console.log(exit.code, exit.signal, exit.timedOut); -``` - - -### `waitForLog()` - -Wait until stdout and/or stderr matches a pattern. - -```ts -waitForLog( - pattern: string | RegExp, - options?: WaitForLogOptions, -): Promise -``` - -#### `WaitForLogOptions` - -| Field | Type | Description | -| --------- | --------------------------------- | ---------------------------------------------------- | -| `stream` | `"stdout" \| "stderr" \| "both"` | Which streams to match. Default: `"both"`. | -| `timeout` | `number` | Local wait deadline only; does not kill the process. | -| `signal` | `AbortSignal` | Cancel this wait only; does not kill the process. | - -#### `WaitForLogResult` - -```ts -interface WaitForLogResult { - stream: "stdout" | "stderr"; - text: string; - match: string; - cursor?: string; -} -``` - -- `text` is the matching window of decoded output for that stream. -- `match` is the matched substring. -- `cursor` is the log cursor at the match when available. - -If the process exits before a match, the SDK throws `ProcessExitedBeforeLogError`. A local wait timeout throws `ProcessWaitTimeoutError`. - - -```ts -const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], { - cwd: "/workspace/app", -}); - -const ready = await server.waitForLog(/listening on/i, { - stream: "both", - timeout: 60_000, -}); -console.log(ready.stream, ready.match); -``` - - -### `waitForPort()` - -Wait until a port is ready, or fail if the process exits first or the local wait ends. - -```ts -waitForPort(port: number, options?: WaitForPortOptions): Promise -``` - -#### `WaitForPortOptions` - -| Field | Type | Description | -| ---------- | ----------------------------------------- | ----------- | -| `mode` | `"tcp" \| "http"` | Readiness check. Default: `"tcp"` (accepts a TCP connection). | -| `path` | `string` | HTTP path to request when `mode` is `"http"`. Default: `"/"`. | -| `status` | `number \| { min: number; max: number }` | Expected HTTP status or inclusive range when `mode` is `"http"`. Default: `{ min: 200, max: 399 }`. | -| `interval` | `number` | Milliseconds between checks. Default: `500`. | -| `timeout` | `number` | Local wait deadline only; does not kill the process. No default timeout when omitted. | -| `signal` | `AbortSignal` | Cancel this wait only; does not kill the process. | - -**TCP mode** (default) succeeds when the port accepts a connection: - - -```ts -const db = await sandbox.exec(["redis-server"]); - -await db.waitForPort(6379, { - mode: "tcp", - timeout: 10_000, -}); -``` - - -**HTTP mode** issues an HTTP request and checks the response status: - - -```ts -const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], { - cwd: "/workspace/app", -}); - -await server.waitForPort(3000, { - mode: "http", - path: "/health", - status: { min: 200, max: 299 }, - timeout: 60_000, -}); -``` - - -Typical failures: - -- `ProcessReadyTimeoutError` — port not ready before the local timeout -- `ProcessExitedBeforeReadyError` — process exited before the port was ready -- `ProcessAbortedError` — local `AbortSignal` cancelled the wait (process may still run) - -### `kill()` - -Send a numeric signal to the process. - -```ts -kill(signal?: number): Promise -``` - -Default `signal` is `15` (`SIGTERM`). Pass a numeric signal only (for example `9` for `SIGKILL`). String signal names are not accepted. - -Stopping the process is separate from cancelling a local wait or log subscription. - -### `exitCode` - -```ts -readonly exitCode: Promise -``` - -Resolves to the exit code when the supervised process group has settled (the same completion boundary as `waitForExit()`). Prefer `waitForExit()` when you also need `signal` or `timedOut`. - -## ProcessStatus - -```ts -type ProcessStatus = - | { - state: "running"; - id: string; - pid: number; - command: SandboxCommand; - cwd?: string; - startedAt: string; - } - | { - state: "exited"; - id: string; - pid: number; - command: SandboxCommand; - cwd?: string; - startedAt: string; - endedAt: string; - exit: ProcessExit; - } - | { - state: "error"; - id: string; - pid: number; - command: SandboxCommand; - cwd?: string; - startedAt: string; - endedAt: string; - error: ProcessFailure; - }; -``` - -`listProcesses()` returns `ProcessStatus[]` using this shape. - -### `ProcessExit` - -Outcome observed for the **root** subprocess when the supervised group settles. - -```ts -interface ProcessExit { - code: number; - signal?: number; - timedOut: boolean; -} -``` - -Signals delivered only to descendants do not rewrite this outcome. Refer to [Process execution](/sandbox/1-0-preview/processes/). - -### `ProcessFailure` - -```ts -interface ProcessFailure { - code: string; - message: string; -} -``` - -## Common errors - -`getProcess` and `listProcesses` do not throw for missing work. They return `null` or `[]` when no container is up, the ID is unknown in the current container, or the process belonged to a previous container. The following error classes apply to operations on a process handle (and to launch), not to those lookups. - -| Situation | Class / outcome | -| --------- | --------------- | -| `getProcess` / `listProcesses` while no container is running | `null` / `[]` (not an error; does not start a container) | -| `getProcess` for an unknown ID or a process from a previous container | `null` | -| Operation on a handle after the container was replaced | `StaleProcessHandleError` | -| Operation on a handle when the process is gone in the current container | `ProcessNotFoundError` | -| Local wait timed out (`output` / `waitForExit` / `waitForLog`) | `ProcessWaitTimeoutError` | -| Local `AbortSignal` on a wait or stream | `ProcessAbortedError` | -| Port not ready before local timeout | `ProcessReadyTimeoutError` | -| Process exited before port readiness | `ProcessExitedBeforeReadyError` | -| Process exited before a log match | `ProcessExitedBeforeLogError` | -| Invalid working directory at launch | `InvalidProcessCwdError` | -| Invalid environment at launch | `InvalidProcessEnvironmentError` | -| Invalid log cursor | `InvalidProcessCursorError` | -| Process failed to start | `ProcessSpawnFailedError` | -| Container not ready; work did not start | `ContainerUnavailableError` | -| Work interrupted after it may have started | `OperationInterruptedError` | - -Recovery guidance: [Errors and recovery](/sandbox/1-0-preview/errors/). Full catalog: [Errors API](/sandbox/1-0-preview/api/errors/). Lifetime: [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). - -## Related - -- [Process execution](/sandbox/1-0-preview/processes/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [Terminals API](/sandbox/1-0-preview/api/terminals/) -- [API reference](/sandbox/1-0-preview/api/) -- [Migrate from the stable SDK](/sandbox/1-0-preview/migrate/) -- Stable: [Commands](/sandbox/api/commands/) diff --git a/src/content/docs/sandbox/1-0-preview/api/terminals.mdx b/src/content/docs/sandbox/1-0-preview/api/terminals.mdx deleted file mode 100644 index ad80da833e4..00000000000 --- a/src/content/docs/sandbox/1-0-preview/api/terminals.mdx +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: Terminals -pcx_content_type: reference -sidebar: - order: 2 -description: Reference for createTerminal, Terminal handles, output streams, connect, and control methods in the Sandbox SDK 1.0 preview. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents the terminal API on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For today's stable `sandbox.terminal()` helper, refer to [Terminal](/sandbox/api/terminal/). -::: - -Create and control interactive PTY terminals in the current container for a sandbox. - -For the mental model and browser connect walkthrough, refer to [Terminals](/sandbox/1-0-preview/terminals/). - -## `createTerminal()` - -Start a terminal from **argv** (usually a shell). Resolves when the terminal resource is created. Same rules as process `exec`: no implicit shell wrapping, and argv entries are not shell-escaped. - -```ts -createTerminal(options: CreateTerminalOptions): Promise -``` - -### `CreateTerminalOptions` - -| Field | Type | Description | -| ------------ | ------------------------ | --------------------------------------------------------------------------- | -| `command` | `SandboxCommand` | Argv to run under the PTY. Required. Example: `['bash']` or `['/bin/bash']`. | -| `cwd` | `string` | Working directory for the terminal process. | -| `env` | `Record` | Environment overlay for this terminal. Does not mutate later launches. | -| `cols` | `number` | Initial width in columns. | -| `rows` | `number` | Initial height in rows. | -| `bufferSize` | `number` | Output buffer sizing for replay (when supported by the runtime). | - -`SandboxCommand` is the same argv type as process `exec`: `readonly [executable: string, ...args: string[]]`. - -### Returns - -`Promise` — a handle for the terminal in the **current container**. - - -```ts -const terminal = await sandbox.createTerminal({ - command: ["bash"], - cwd: "/workspace", - env: { TERM: "xterm-256color" }, - cols: 120, - rows: 40, -}); - -console.log(terminal.id); -``` - - -## `getTerminal()` - -Return a handle for a terminal in the **current container**, or `null`. - -Does not start a container if none is running. Returns `null` when no container is up, when the terminal ID is unknown in the current container, or when that terminal belonged to a previous container for the same sandbox ID. - -```ts -getTerminal(id: string): Promise -``` - -## `listTerminals()` - -List terminals in the current container for this sandbox. Does not start a container if none is running. Returns an empty list when no container is up. - -```ts -listTerminals(): Promise -``` - -## `Terminal` - -| Member | Description | -| ------------------------ | --------------------------------------------------------------------------- | -| `id` | Terminal ID in the current container. | -| `getSnapshot()` | Current snapshot (`running` / `exited` / `error`). | -| `write(data)` | Write bytes to the PTY (stdin). | -| `resize(cols, rows)` | Resize the PTY. | -| `output(options?)` | Cursor-based output event stream. | -| `waitForExit(options?)` | Wait until the terminal completes. | -| `interrupt()` | Send an interrupt to the terminal session (for example Ctrl-C semantics). | -| `terminate()` | End the terminal resource. | -| `connect(request, opts?)` | Accept a browser WebSocket upgrade and attach it to this terminal. | - -### `getSnapshot()` - -```ts -interface TerminalSnapshot { - id: string; - pid?: number; - command: SandboxCommand; - cwd?: string; - status: "running" | "exited" | "error"; - exit?: ProcessExit; - error?: ProcessFailure; -} -``` - -### `write()` - -```ts -write(data: Uint8Array): Promise -``` - -Write bytes to the PTY. Browser keystrokes normally arrive through `connect()` instead. - -### `resize()` - -```ts -resize(cols: number, rows: number): Promise -``` - -### `output()` - -```ts -output(options?: TerminalOutputOptions): Promise> -``` - -#### `TerminalOutputOptions` - -| Field | Type | Description | -| --------- | ------------- | ------------------------------------------------ | -| `since` | `string` | Opaque cursor; resume after a previous event. | -| `replay` | `boolean` | Include buffered history when resuming. | -| `follow` | `boolean` | Keep the stream open for live output. | -| `signal` | `AbortSignal` | Cancel this subscription only. The terminal keeps running. | - -#### `TerminalOutputEvent` - -```ts -type TerminalOutputEvent = - | { - type: "data"; - terminalId: string; - cursor: string; - timestamp: string; - data: Uint8Array; - } - | { - type: "terminal"; - terminalId: string; - cursor: string; - timestamp: string; - state: "exited"; - exit: ProcessExit; - } - | { - type: "terminal"; - terminalId: string; - cursor: string; - timestamp: string; - state: "error"; - error: ProcessFailure; - } - | { - type: "truncated"; - terminalId: string; - cursor?: string; - timestamp: string; - }; -``` - -Retain the latest `cursor` from delivered events if you reconnect or call `output({ since, replay: true })` later on the **same** terminal in the **same** container. - -### `waitForExit()` - -```ts -waitForExit(options?: { - timeout?: number; - signal?: AbortSignal; -}): Promise -``` - -Local `timeout` / `signal` cancel only the wait. They do not terminate the terminal. Call `terminate()` or `interrupt()` when you intend to stop it. - -### `interrupt()` and `terminate()` - -```ts -interrupt(): Promise -terminate(): Promise -``` - -These are terminal control operations. They are not the same as process `kill(signal)` on an `exec` handle. - -### `connect()` - -Attach a browser (or other) WebSocket upgrade request to this terminal. - -```ts -connect( - request: Request, - options?: { - cursor?: string; - cols?: number; - rows?: number; - }, -): Promise -``` - -- `request` must be a WebSocket upgrade request. -- `cursor` resumes output replay after a previous disconnect when the client has one. -- `cols` / `rows` set the PTY size for this attachment when provided. - -Returns the WebSocket upgrade `Response` your Worker should return to the client. - - -```ts -const url = new URL(request.url); -const terminalId = url.searchParams.get("terminalId"); -if (!terminalId) { - return new Response("terminalId is required", { status: 400 }); -} - -const terminal = await sandbox.getTerminal(terminalId); -if (!terminal) { - return new Response("Terminal not found", { status: 404 }); -} - -return terminal.connect(request, { - cursor: url.searchParams.get("cursor") ?? undefined, - cols: 120, - rows: 40, -}); -``` - - -For the full Worker + xterm.js path, refer to [Terminals](/sandbox/1-0-preview/terminals/#browser-connect). - -## Client helper: `@cloudflare/sandbox/xterm` - -`SandboxAddon` integrates [xterm.js](https://xtermjs.org/) with preview terminals. - - -```ts -import { SandboxAddon } from "@cloudflare/sandbox/xterm"; - -const addon = new SandboxAddon({ - // `origin` is already a WebSocket origin (`wss://` or `ws://`). - getWebSocketUrl: ({ sandboxId, terminalId, cursor, origin }) => { - const params = new URLSearchParams({ sandboxId }); - if (terminalId) params.set("terminalId", terminalId); - if (cursor) params.set("cursor", cursor); - return `${origin}/ws/terminal?${params}`; - }, - reconnect: true, - onStateChange: (state, error) => { - /* update UI */ - }, -}); -``` - - -| Item | Preview detail | -| ---- | -------------- | -| Connection target | `{ sandboxId, terminalId? }` | -| `getWebSocketUrl` params | `sandboxId`, `terminalId?`, `cursor?`, `origin` | -| Properties | `state`, `sandboxId`, `terminalId` | - -`@xterm/xterm` is an optional peer dependency of the preview package. - -## Common errors - -| Situation | Class / outcome | -| --------- | --------------- | -| Unknown terminal ID in the current container | `TerminalNotFoundError` | -| `getTerminal` / `listTerminals` while no container is running | `null` / `[]` (not an error; does not start a container) | -| Handle or terminal ID from a previous container | `StaleTerminalHandleError` | -| Invalid working directory at create | `InvalidTerminalCwdError` | -| Invalid output cursor | `InvalidTerminalCursorError` | -| Control operation failed | `TerminalControlError` | - -Recovery guidance: [Errors and recovery](/sandbox/1-0-preview/errors/). Full catalog: [Errors API](/sandbox/1-0-preview/api/errors/). Lifetime: [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). - -## Related - -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [Processes API](/sandbox/1-0-preview/api/processes/) -- [API reference](/sandbox/1-0-preview/api/) -- [Migrate](/sandbox/1-0-preview/migrate/) -- Stable: [Terminal](/sandbox/api/terminal/) diff --git a/src/content/docs/sandbox/1-0-preview/environment.mdx b/src/content/docs/sandbox/1-0-preview/environment.mdx deleted file mode 100644 index ff2e72b6f55..00000000000 --- a/src/content/docs/sandbox/1-0-preview/environment.mdx +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Environment variables -pcx_content_type: concept -sidebar: - order: 6 -description: How processes and terminals get environment variables in the Sandbox SDK 1.0 preview. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents environment variables on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For the current stable package, refer to [Environment variables](/sandbox/configuration/environment-variables/). -::: - -Each `exec()` and `createTerminal()` starts an independent process. Shell `export` in one process does not apply to the next launch. Configure process environment with the container image, `setEnvVars`, and per-launch `env`. - -Use environment variables for **non-secret** configuration (paths, feature flags, `NODE_ENV`, and similar). Do not put live API keys or other long-lived credentials into the sandbox. To call external services that need credentials, use [outbound traffic handlers](/sandbox/guides/outbound-traffic/) so secrets stay in the Worker. - -## How a process gets its environment - -When a process starts, the runtime builds its environment from: - -1. The **container** environment (image `ENV` and defaults). -2. Names from **`setEnvVars`**, when you use `exec()` (described in the next section). -3. The **`env` option** on that launch, if you pass one. - -Later launches do not keep overlays from earlier launches. A command that runs `export FOO=bar` inside one process does not change the next `exec()`. - -Worker bindings in your `fetch` handler are not process environment variables. Only values you pass through `setEnvVars` or launch `env` appear inside the process (and those should not be long-lived secrets). - -## `setEnvVars()` - -```ts -setEnvVars(envVars: Record): Promise -``` - -| Value | Effect | -| ----- | ------ | -| string | Set this environment variable for later `exec()` launches | -| `undefined` | Remove a previously stored variable | - -On each `exec()`, the SDK merges stored names into that process’s environment at launch. - -Stored names live in the sandbox Durable Object’s memory. They are not written to the container filesystem and are not part of a backup. After the Durable Object is evicted or replaced, call `setEnvVars` again if you still need those names, or pass `env` on each `exec()`. - - -```ts -const sandbox = getSandbox(env.Sandbox, "user-123"); - -await sandbox.setEnvVars({ - NODE_ENV: "production", - APP_HOME: "/workspace/app", - LOG_LEVEL: "info", -}); - -const migrate = await sandbox.exec(["python", "migrate.py"], { - cwd: "/workspace/app", -}); -await migrate.output({ encoding: "utf8" }); - -const seed = await sandbox.exec(["python", "seed.py"], { - cwd: "/workspace/app", -}); -await seed.output({ encoding: "utf8" }); - -await sandbox.setEnvVars({ - LOG_LEVEL: "debug", - TEMP_FLAG: undefined, -}); -``` - - -## `env` on `exec()` - - -```ts -const process = await sandbox.exec(["node", "app.js"], { - cwd: "/workspace/app", - env: { - NODE_ENV: "production", - PORT: "3000", - }, -}); -``` - - -| Behavior | Detail | -| -------- | ------ | -| Scope | This launch only | -| Merge order | Container environment, then `setEnvVars`, then this `env` | -| Side effects | Does not update `setEnvVars` storage | - -Omit `env` when sandbox-wide names (and the container environment) are enough. - -## `env` on `createTerminal()` - - -```ts -const terminal = await sandbox.createTerminal({ - command: ["bash"], - cwd: "/workspace", - env: { - TERM: "xterm-256color", - APP_HOME: "/workspace/app", - }, -}); -``` - - -The terminal’s launch `env` overlays the container environment for that terminal only. Pass the names the terminal needs on `createTerminal`. - -Inside an interactive shell, `export` applies for the life of that terminal. It does not apply to later `exec()` calls. Refer to [Terminals](/sandbox/1-0-preview/terminals/). - -## External APIs and credentials - -Code inside the sandbox should not hold live provider credentials. Keep secrets in the Worker and intercept outbound HTTP(S) with `outboundByHost` (and related policy such as `enableInternet` / `allowedHosts`). The sandbox can send ordinary requests—or placeholders client libraries require—while the Worker attaches real credentials before the request leaves your account. - -Refer to [Handle outbound traffic](/sandbox/guides/outbound-traffic/), including securely injecting credentials. For Workers bindings (KV, R2, and similar) reached by hostname from the sandbox, refer to [Connect to Workers bindings](/sandbox/guides/workers-connections/). - -## Related - -- [Handle outbound traffic](/sandbox/guides/outbound-traffic/) -- [Connect to Workers bindings](/sandbox/guides/workers-connections/) -- [Process execution](/sandbox/1-0-preview/processes/) -- [Processes API](/sandbox/1-0-preview/api/processes/) -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Migrate](/sandbox/1-0-preview/migrate/) diff --git a/src/content/docs/sandbox/1-0-preview/errors.mdx b/src/content/docs/sandbox/1-0-preview/errors.mdx deleted file mode 100644 index c827c24ee4b..00000000000 --- a/src/content/docs/sandbox/1-0-preview/errors.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Errors and recovery -pcx_content_type: how-to -sidebar: - order: 5 -description: Retry and recover from Sandbox SDK 1.0 preview failures when containers start, stop, or interrupt work. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents error handling on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. Class names, codes, and context fields: [Errors API](/sandbox/1-0-preview/api/errors/). -::: - -Some failures mean the container never started your work. Others mean the work may already have started. Those cases need different recovery. - -The same **sandbox ID** can later use a **new container**. Processes, terminals, and local files from the previous container do not return on their own. Refer to [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) and [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). - -Class catalog: [Errors API](/sandbox/1-0-preview/api/errors/). Symptom table: [Troubleshooting](/sandbox/1-0-preview/troubleshooting/). - -## Before the container starts the work - -If the container is not ready, the SDK may throw `ContainerUnavailableError` (`CONTAINER_UNAVAILABLE`). The operation did not run inside the container. - -That often happens on cold start, after idle stop, or during a deploy. - -The error context includes `retryable: true`, a `reason` (for example `container_starting`), and optional `retryAfterMs`. Back off (use `retryAfterMs` when present), then try the same kind of work again. - -Do not use that same “always retry” rule for failures that occur after the container may already have started the work. - - -```ts -import { ContainerUnavailableError } from "@cloudflare/sandbox"; - -try { - const process = await sandbox.exec(["npm", "install"], { - cwd: "/workspace/app", - }); - await process.waitForExit(); -} catch (error) { - if (error instanceof ContainerUnavailableError) { - // Safe to retry the whole operation after backoff. - } -} -``` - - -## After the container may have started the work - -Once the container has accepted an operation, a failure can leave partial results: a process may be running, a file may exist, a backup may have begun. - -### Container replaced or sandbox ended during a call - -`OperationInterruptedError` means the container or sandbox changed while the call was already underway. The work may have started. - -Use `reason` and `retryable` on the error (refer to [Errors API](/sandbox/1-0-preview/api/errors/) for fields). If the steps change state, check the sandbox or your own records before running the same steps again. - -### SDK lost contact during a call - -`RPCTransportError` means the SDK lost contact with the current container during a call. A later call can succeed against the container again. - -That does **not** mean the interrupted call did nothing. Prefer checkpoints and steps that are safe to run twice, or inspect state, before repeating the same work. Diagnostic `kind` values are listed on the [Errors API](/sandbox/1-0-preview/api/errors/). - -### Stale process or terminal handles - -Process and terminal IDs belong to the **current** container for a sandbox ID. After stop or replace, calls on an old handle throw `StaleProcessHandleError` or `StaleTerminalHandleError`. `getProcess`, `getTerminal`, `listProcesses`, and `listTerminals` do not start a container. They return `null` or `[]` when no container is running, or when the ID is unknown in the current container. That is not an exception. - -Store the job (command, `cwd`, `env`, checkpoint), not only the resource ID. Then start a new `exec` or `createTerminal` when the old handle is gone. - -### Local waits and aborts - -Timeouts and `AbortSignal` on `output()`, `waitForExit()`, `waitForLog()`, `waitForPort()`, and `logs()` end **that wait or stream only**. They do not kill the process. Canceling terminal output does not terminate the PTY. - -Use `process.kill()` or `terminal.interrupt()` / `terminal.terminate()` when you intend to stop the resource. Typical errors: `ProcessWaitTimeoutError`, `ProcessAbortedError`. - -### Invalid arguments - -Invalid `cwd` or environment variables, a missing executable, or similar request problems fail until you change those values. Do not retry the same invalid request. Typical classes: `InvalidProcessCwdError`, `InvalidProcessEnvironmentError`, `ProcessSpawnFailedError`. - -### Worker and container image mismatch - -Some failures mean the Worker package and container image do not match, the image cannot start, or setup between Worker and container failed. - -| Signal | Response | -| ------ | -------- | -| `RuntimeControlProtocolError` (for example `unsupported-protocol-version`, missing or malformed metadata) | Deploy the Worker package and container image from the same `@cloudflare/sandbox@next` line. Do not mix preview and stable packages. | -| Wrong or missing image, or the container exits before it is ready | Fix `wrangler`, the image, or the entrypoint. Retrying the same application call will not help. | -| Account or location capacity limits | Lower concurrency or raise limits. Refer to [Platform limits](/sandbox/platform/limits/). | - -Catalog detail: [Worker and container image mismatch](/sandbox/1-0-preview/api/errors/#worker-and-container-image-mismatch). - -These are not the same as a slow start (`ContainerUnavailableError`). Do not use the same backoff-and-retry loop for both. - -## Common recovery paths - -### First use or wake after idle - -**Error:** `ContainerUnavailableError` - -Back off, then run the full unit of work again (for example setup plus `exec`), not an arbitrary middle step without a checkpoint. - -### Long job across Worker requests - -1. Persist the job and checkpoint (and a process or terminal ID while it is useful). -2. On a later request, call `getProcess` or `getTerminal` if you still have an ID. -3. If you get a handle, continue (logs, connect, wait). -4. If you get `null` or a stale-handle error, start again from the checkpoint. -5. If you get `ContainerUnavailableError`, backoff and continue with a new operation. - -### Deploy or replace while a call is in flight - -**Error:** `OperationInterruptedError` - -Read `reason` and `retryable`. If the call may have changed something, inspect before repeating it. - -### Lost contact during a call - -**Error:** `RPCTransportError` - -Log `kind` if you need diagnostics. Assume in-flight work may have run. Continue from checkpoints or inspection, then start a new operation if the job still needs it. - -### You only stopped waiting - -**Errors:** `ProcessWaitTimeoutError`, `ProcessAbortedError` - -Either keep observing (`getProcess` and `logs({ since })`) or stop the process with `kill`. Do not assume the process exited because the wait ended. - -### Invalid arguments - -**Errors:** `InvalidProcessCwdError`, `InvalidProcessEnvironmentError`, `ProcessSpawnFailedError`, and similar - -Correct the path, environment, or command (or the files in the image if the binary is missing). Do not retry unchanged values. - -### Worker and container image mismatch - -**Situation:** After a deploy, calls fail with protocol or setup errors, or the container never becomes usable. - -**Errors / signals:** `RuntimeControlProtocolError`; wrong image; container exits before it is ready - -**Do:** Redeploy the Worker package and container image from the same `@cloudflare/sandbox@next` line. Confirm the image name and entrypoint. - -**Do not:** Treat this like a slow container start and only back off. - -## Example - - -```ts -import { - ContainerUnavailableError, - OperationInterruptedError, - RPCTransportError, - StaleProcessHandleError, - ProcessWaitTimeoutError, - ProcessAbortedError, -} from "@cloudflare/sandbox"; - -try { - const process = await sandbox.exec(["npm", "test"], { - cwd: "/workspace/app", - }); - const result = await process.output({ encoding: "utf8" }); - console.log(result.exitCode, result.stdout); -} catch (error) { - if (error instanceof ContainerUnavailableError) { - // Container never started the work — back off, then try the work again. - } else if (error instanceof StaleProcessHandleError) { - // Previous container — start again from what you stored about the work. - } else if (error instanceof OperationInterruptedError) { - // Work may have started — read reason/retryable and check state before repeating. - } else if (error instanceof RPCTransportError) { - // Lost contact during the call — a later call may work; this call may already have run. - } else if ( - error instanceof ProcessWaitTimeoutError || - error instanceof ProcessAbortedError - ) { - // Wait ended only — process may still be running. - } else { - throw error; - } -} -``` - - -Prefer `instanceof` with classes from `@cloudflare/sandbox`. Full tables: [Errors API](/sandbox/1-0-preview/api/errors/). - -## Related - -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [Process execution](/sandbox/1-0-preview/processes/) -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Migrate](/sandbox/1-0-preview/migrate/) -- [Processes API](/sandbox/1-0-preview/api/processes/) · [Terminals API](/sandbox/1-0-preview/api/terminals/) diff --git a/src/content/docs/sandbox/1-0-preview/extensions.mdx b/src/content/docs/sandbox/1-0-preview/extensions.mdx deleted file mode 100644 index e1fd193e196..00000000000 --- a/src/content/docs/sandbox/1-0-preview/extensions.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Extensions -pcx_content_type: how-to -sidebar: - order: 8 -description: Attach optional Sandbox capabilities on @cloudflare/sandbox@next. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents extensions on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. -::: - -Extensions add optional capabilities to your `Sandbox` subclass as nested namespaces (for example `sandbox.interpreter.*`). They are not free-floating globals on every app. - -## Attach pattern - - -```ts -import { Sandbox as BaseSandbox } from "@cloudflare/sandbox"; -import { withInterpreter } from "@cloudflare/sandbox/interpreter"; - -export class Sandbox extends BaseSandbox { - interpreter = withInterpreter(this); -} -``` - - -Export that class from your Worker. Call extension methods through the nested property from application code. - -## First-party extensions - -The following first-party extensions are available on the preview package: - -| Extension | Package | Docs | -| --------- | ------- | ---- | -| Code interpreter | `@cloudflare/sandbox/interpreter` | [Code interpreter](/sandbox/1-0-preview/interpreter/), [Interpreter API](/sandbox/1-0-preview/api/interpreter/) | -| OpenCode | `@cloudflare/sandbox/opencode` | Confirm exports in your installed `@next` version (for example `withOpenCode` and client/proxy helpers). | - -For the interpreter, attach once, then use the same method names as the stable package (`createCodeContext`, `runCode`, and related calls) on `sandbox.interpreter`. Python needs the **`-python`** image variant. For the full how-to, refer to [Code interpreter](/sandbox/1-0-preview/interpreter/). - -## Custom extensions - -Application-defined extensions are experimental. Helpers exist under `@cloudflare/sandbox/extensions`, but preview documentation does not yet cover authoring or publishing a custom extension. Prefer the first-party extensions in the table, or keep any custom code inside your application until a supported authoring guide ships. - -## Related - -- [Code interpreter](/sandbox/1-0-preview/interpreter/) -- [Interpreter API](/sandbox/1-0-preview/api/interpreter/) -- [API reference](/sandbox/1-0-preview/api/) -- [Migrate](/sandbox/1-0-preview/migrate/) diff --git a/src/content/docs/sandbox/1-0-preview/get-started.mdx b/src/content/docs/sandbox/1-0-preview/get-started.mdx deleted file mode 100644 index 1d5224b896c..00000000000 --- a/src/content/docs/sandbox/1-0-preview/get-started.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Get started -pcx_content_type: get-started -sidebar: - order: 1 -description: Install @cloudflare/sandbox@next and run your first process handle in a sandbox. -products: - - sandbox ---- - -import { PackageManagers, TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page uses `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. Prefer this path for new projects. For today's stable package, refer to [Getting started](/sandbox/get-started/). -::: - -## 1. Install the preview package - -In a Workers project that already uses Sandbox, or a new project from the Sandbox template: - - - -Build and deploy the Worker **and** the sandbox container image from the same preview line. - -## 2. Export your Sandbox class - - -```ts -import { Sandbox } from "@cloudflare/sandbox"; - -export { Sandbox }; -``` - - -Keep your `wrangler` Durable Object binding and container configuration. Preview-specific transport variables are not required. - -## 3. Run a process - -`exec()` starts a program from **argv** — an array of the executable path or name, then its arguments. It waits until the sandbox can start the process, then returns a **process handle**. It does **not** wait for the process to exit. - -Collect results with handle methods such as `output()`, or stream with `logs()`. - - -```ts -import { getSandbox, proxyToSandbox } from "@cloudflare/sandbox"; - -export { Sandbox } from "@cloudflare/sandbox"; - -type Env = { - Sandbox: DurableObjectNamespace; -}; - -export default { - async fetch(request: Request, env: Env): Promise { - const proxy = await proxyToSandbox(request, env); - if (proxy) return proxy; - - const sandbox = getSandbox(env.Sandbox, "preview-demo"); - const process = await sandbox.exec(["python3", "-c", "print(2 + 2)"]); - const output = await process.output({ encoding: "utf8" }); - - return Response.json({ - id: process.id, - pid: process.pid, - stdout: output.stdout, - exitCode: output.exitCode, - }); - }, -}; -``` - - -Each argv entry is one argument to the process. The SDK does **not** run a shell and does **not** shell-escape argv. Spaces and special characters in an entry stay inside that argument. - -Shell syntax (`&&`, pipes, redirects, globs) needs an explicit shell, with the script as its own argument: - - -```ts -const process = await sandbox.exec([ - "/bin/bash", - "-lc", - "echo hello && uname -a", -]); -const { stdout } = await process.output({ encoding: "utf8" }); -``` - - -## 4. How this differs from the stable package - -- `await sandbox.exec(...)` creates a process. It does **not** wait for exit. Use `output()`, `waitForExit()`, or other handle methods for completion. -- Each `exec()` is independent. A `cd` or `export` in one call is not remembered in the next. -- Pass `cwd` and `env` on each `exec()` when you need them, or use `setEnvVars` for sandbox-wide values. Refer to [Environment variables](/sandbox/1-0-preview/environment/). -- A process runs only in the **current container** for that sandbox. After the container stops or is replaced, start a new process. Model: [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/). -- Before production traffic, learn which failures are safe to retry: [Errors and recovery](/sandbox/1-0-preview/errors/). - -## Next - -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) — sandbox ID, container, stop, and replace -- [Process execution](/sandbox/1-0-preview/processes/) — `exec()`, handles, and continuing work across requests -- [Errors and recovery](/sandbox/1-0-preview/errors/) — retries, interrupted calls, and stale handles -- [Migrate](/sandbox/1-0-preview/migrate/) — update an existing stable app -- [API reference](/sandbox/1-0-preview/api/) — processes, terminals, and errors -- [Terminals](/sandbox/1-0-preview/terminals/) — interactive PTY and browser connections -- [Extensions](/sandbox/1-0-preview/extensions/) diff --git a/src/content/docs/sandbox/1-0-preview/index.mdx b/src/content/docs/sandbox/1-0-preview/index.mdx deleted file mode 100644 index 3b3504c5ff7..00000000000 --- a/src/content/docs/sandbox/1-0-preview/index.mdx +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: 1.0 preview -pcx_content_type: overview -sidebar: - order: 3 -head: - - tag: title - content: Overview -description: Install @cloudflare/sandbox@next — a thinner Sandbox SDK on Cloudflare Containers — and migrate when you are ready for Sandbox SDK 1.0. -products: - - sandbox ---- - -import { CardGrid, LinkTitleCard, PackageManagers, TypeScriptExample } from "~/components"; - -**Sandbox SDK 1.0** is the next major release of the SDK. It is available now as a preview on the npm `@next` tag. The current stable package remains published for existing apps. - -Sandbox still runs isolated work on [Cloudflare Containers](/containers/). The 1.0 preview is a **thinner** SDK on that foundation: one process handle for short and long-running work, no session-based command state, no transport picker, terminals as first-class PTYs, and the code interpreter as an opt-in extension. - -We recommend that **new projects** start on `@cloudflare/sandbox@next` and follow this section. **Existing apps** should migrate when you can, so you are ready when 1.0 becomes the stable release. Follow [Migrate](/sandbox/1-0-preview/migrate/). - -The main [Sandbox documentation](/sandbox/) still documents today's stable package. Use **this** section for preview APIs and the migration path. - -:::note[Self-deployed bridge] -The self-deployed Sandbox bridge is not part of the 1.0 preview. Use the [stable bridge](/sandbox/bridge/) with the matching stable package and container image. -::: - -## Install the preview - - - -Deploy the Worker package and the sandbox container image from the **same** preview line. Do not mix a preview Worker package with a stable container image (or the reverse). For ongoing deploys, refer to [Deploy a Sandbox application](/sandbox/guides/deploy/). For a breaking cutover, refer to [Migrate](/sandbox/1-0-preview/migrate/). - -## What 1.0 is aiming at - -The stable package grew several ways to run commands (`exec`, `startProcess`, `execStream`), optional session state across launches, and selectable transports between the Durable Object and the container. That surface worked, but it duplicated ideas and hid how sandboxes actually behave on containers. - -The preview collapses that toward a smaller contract: - -| You want… | In the preview | -| --------- | -------------- | -| Run a program | `exec(argv)` → process handle when **launch** succeeds | -| See output or wait for readiness | `output()`, `logs()`, `waitForExit()`, `waitForLog()`, `waitForPort()` on the handle | -| Stop a process | `kill(signal?)` (numeric signal; default `15`) | -| Keep shell state across many interactive steps | A [terminal](/sandbox/1-0-preview/terminals/) (PTY), not a hidden default session | -| Run Python / JS cells | [Code interpreter](/sandbox/1-0-preview/interpreter/) extension on your `Sandbox` subclass | -| Talk to the container control plane | Always RPC — no transport setting | - -Procedures: [Migrate](/sandbox/1-0-preview/migrate/). Mental model: [Process execution](/sandbox/1-0-preview/processes/) and [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/). - -## What changes from the stable package - -### Command execution - -**Stable:** `sandbox.exec(string)` resolves when the command **finishes** with buffered output. Long-running services and streaming use separate APIs (`startProcess`, `execStream`). - -**Preview:** `sandbox.exec()` takes **argv** and resolves when the process **starts**. The same handle covers short commands and long-running services. - - -```ts -// Current stable package -const result = await sandbox.exec("npm test"); -console.log(result.stdout, result.exitCode); - -// 1.0 preview -const process = await sandbox.exec(["npm", "test"]); -const result = await process.output({ encoding: "utf8" }); -console.log(result.stdout, result.exitCode); -``` - - -Shell features such as pipes and `&&` need an explicit shell, for example `['/bin/bash', '-lc', 'cd app && npm test']`. Pass `cwd` and `env` on each `exec()` when the process needs them. Details: [Process execution](/sandbox/1-0-preview/processes/), [Processes API](/sandbox/1-0-preview/api/processes/). - -### Sessions - -**Stable:** a default session can preserve working directory and environment variables across `exec()` calls. Apps can also create named sessions with `createSession()`. - -**Preview:** no session execution on the SDK. Each `exec()` is independent. Pass `cwd` and `env` on each launch, or put multi-step shell syntax in one explicit shell argv. Isolate end users with **separate sandboxes**, not sessions inside one sandbox. Environment model: [Environment variables](/sandbox/1-0-preview/environment/). - -### Terminals - -**Stable:** browser shells often use `sandbox.terminal(request)` with session helpers and xterm `sessionId`. - -**Preview:** terminals are PTY resources — `createTerminal`, `getTerminal`, `listTerminals`, and `terminal.connect(request)`. The xterm helper uses `terminalId`. Refer to [Terminals](/sandbox/1-0-preview/terminals/). - -### Code interpreter - -**Stable:** interpreter methods live on `Sandbox`. - -**Preview:** attach the interpreter on your subclass, then call `sandbox.interpreter.*`. Refer to [Code interpreter](/sandbox/1-0-preview/interpreter/). - -### Transport configuration - -**Stable:** apps can select HTTP, WebSocket, or RPC between the Durable Object and the container. - -**Preview:** the SDK always uses RPC. Remove `SANDBOX_TRANSPORT`, the `transport` option on `getSandbox()`, and `setTransport()`. No replacement setting is required. - -## Same platform model, clearer handles - -This is **not** a new container product. You still address a sandbox with a stable **sandbox ID**: - - -```ts -const sandbox = getSandbox(env.Sandbox, "user-123"); -``` - - -That sandbox runs in a **container**. The ID is stable. The container instance behind it is not always the same one. Processes and terminals you start exist only in the **current** container. When that container stops or is replaced, those processes and terminals are gone — old handles fail closed instead of quietly attaching to a new container for the same sandbox ID. - -Container stop and replace already happened on the stable line. The preview makes process and terminal APIs honest about that lifetime. Full model: [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/). Process detail: [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). Recovery: [Errors and recovery](/sandbox/1-0-preview/errors/). - -## What usually stays the same - -These remain available. Use the main Sandbox documentation for signatures, and ignore session or transport options where those pages still mention them: - -- [Files](/sandbox/api/files/) and [file watching](/sandbox/api/file-watching/) -- [Storage](/sandbox/api/storage/) and [backups](/sandbox/api/backups/) -- [Ports](/sandbox/api/ports/) and [tunnels](/sandbox/api/tunnels/) -- [Lifecycle options](/sandbox/api/lifecycle/) and [sandbox options](/sandbox/configuration/sandbox-options/) (except removed session/transport fields) -- [Outbound traffic](/sandbox/guides/outbound-traffic/) (credential injection and egress policy) - -For process environment on `@next`, use [Environment variables](/sandbox/1-0-preview/environment/) in this section. - -## Start here - - - - - Install `@next` and run your first process handle. - - - - Update an existing app, including deploy cutover on `@next`. - - - - Sandbox ID, container, stop, replace, and what your app should store. - - - - How `exec()` works, process handles, and how long processes live. - - - - Interactive PTYs, lifetime, and browser connect. - - - - How to retry, inspect, and relaunch after common failures. - - - - `setEnvVars`, per-launch `env`, and how processes get their environment. - - - - Attach the interpreter extension and run Python or JS/TS. - - - - Process, terminal, error, and interpreter signatures for `@next`. - - - - Attach the code interpreter and other optional capabilities. - - - - Common `@next` failures and where to fix them. - - - - -## Coding agents - -Install [Cloudflare Skills](https://github.com/cloudflare/skills) for your agent ([Agent setup](/agent-setup/)). Use **`sandbox-next`** for work on `@next` (recommended for new projects). Existing apps on the current stable package should use **`sandbox-stable`** until you are ready to move, then **`sandbox-migrate-to-next`**. Deprecated-API cleanup while staying on stable is covered in the [2026 deprecation guide](/sandbox/guides/2026-deprecation/) and **`sandbox-stable`**. - -## Stable documentation - -While you remain on the current stable package, use the main docs: - -- [Get started](/sandbox/get-started/) -- [Commands](/sandbox/api/commands/) -- [Sessions](/sandbox/concepts/sessions/) -- [2026 deprecation migration](/sandbox/guides/2026-deprecation/) diff --git a/src/content/docs/sandbox/1-0-preview/interpreter.mdx b/src/content/docs/sandbox/1-0-preview/interpreter.mdx deleted file mode 100644 index 45cd6d87c08..00000000000 --- a/src/content/docs/sandbox/1-0-preview/interpreter.mdx +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Code interpreter -pcx_content_type: how-to -sidebar: - order: 7 -description: Run Python, JavaScript, or TypeScript in a sandbox with the interpreter extension on @cloudflare/sandbox@next. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page uses the interpreter extension on `@cloudflare/sandbox@next`. On today's stable package, interpreter methods live on `Sandbox` — refer to [Use code interpreter](/sandbox/guides/code-execution/). -::: - -On `@next`, the code interpreter is an opt-in extension, not methods on bare `Sandbox`. Method names match the stable interpreter. You attach once, then call `sandbox.interpreter.*`. `runCode` returns plain serializable data across the Worker and Durable Object boundary. - -Signatures and types: [Interpreter API](/sandbox/1-0-preview/api/interpreter/). - -## Attach - - -```ts -import { Sandbox as BaseSandbox } from "@cloudflare/sandbox"; -import { withInterpreter } from "@cloudflare/sandbox/interpreter"; - -export class Sandbox extends BaseSandbox { - interpreter = withInterpreter(this); -} -``` - - -Export that class from your Worker. The sidecar provisions on first use. - -## Image - -| Language | Image | -| -------- | ----- | -| JavaScript / TypeScript | Default sandbox image (or any variant with a JS runtime) | -| Python | **`-python`** image variant | - -Use the same preview Worker package and container image line. Refer to [Dockerfile](/sandbox/configuration/dockerfile/). - -## Run code - -A **context** keeps variables and imports until you delete it or the container is replaced. - - -```ts -const sandbox = getSandbox(env.Sandbox, "user-123"); - -const context = await sandbox.interpreter.createCodeContext({ - language: "python", - cwd: "/workspace", -}); - -await sandbox.interpreter.runCode("x = 2", { context }); -const result = await sandbox.interpreter.runCode("x * 21", { context }); - -if (result.error) { - console.error(result.error.name, result.error.message); -} else { - console.log(result.results, result.logs.stdout); -} -``` - - -If you omit `context`, `runCode` uses a default context for the language (default language: `python`). Languages: `python`, `javascript`, `typescript`. - -For result fields, streaming (`runCodeStream`), and list/delete context methods, refer to the [Interpreter API](/sandbox/1-0-preview/api/interpreter/). - -Contexts exist only in the **current container**. After stop or replace, create new ones. Refer to [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/). - -## Related - -- [Interpreter API](/sandbox/1-0-preview/api/interpreter/) -- [Extensions](/sandbox/1-0-preview/extensions/) -- [Migrate](/sandbox/1-0-preview/migrate/) -- Stable guide: [Use code interpreter](/sandbox/guides/code-execution/) diff --git a/src/content/docs/sandbox/1-0-preview/lifecycle.mdx b/src/content/docs/sandbox/1-0-preview/lifecycle.mdx deleted file mode 100644 index 1f35806de51..00000000000 --- a/src/content/docs/sandbox/1-0-preview/lifecycle.mdx +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Sandbox lifecycle -pcx_content_type: concept -sidebar: - order: 2 -description: Sandbox IDs, containers, and what survives stop, replace, and destroy in the Sandbox SDK 1.0 preview. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents sandbox lifecycle on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For the current stable package, also refer to [Sandbox lifecycle](/sandbox/concepts/sandboxes/). Platform placement and shutdown details live in [Lifecycle of a Container](/containers/concepts/architecture/). -::: - -Your app addresses a sandbox with a **sandbox ID**. The Linux environment that runs commands and holds local files is a **container**. The ID can outlive any one container. - -That distinction matters for processes, terminals, files, and recovery after idle stop or replace. - -## Sandbox ID and container - -Most apps use one sandbox per user or task: - - -```ts -const sandbox = getSandbox(env.Sandbox, "user-123"); -``` - - -| | Meaning | -| - | ------- | -| **Sandbox ID** | The string you pass to `getSandbox` (for example `"user-123"`). Use the same ID to reach the same sandbox later. | -| **Durable Object** | The coordinator behind that ID. The same ID maps to the same Durable Object identity. | -| **Container** | The current [Containers](/containers/) instance that runs Linux work for the sandbox. | -| **Process or terminal** | A program or interactive PTY inside the **current** container. | -| **Local files** | Files on that container’s disk (for example under `/workspace`). | - -**Same sandbox ID does not mean the same container.** After the container stops or is replaced, the next work for that ID may run in a new container. - -## When the container starts - -`getSandbox()` returns immediately. It does not start a container by itself. - -The container starts when an operation needs it — for example `exec()`, `createTerminal()`, or writing a file. The first start after deploy or idle can take longer than a warm call. If the container is not ready yet, the SDK may throw `ContainerUnavailableError`. That error means the operation did not start inside the container. Refer to [Errors and recovery](/sandbox/1-0-preview/errors/). - -## While the container is running - -While a container is up for a sandbox ID: - -- Processes and terminals keep running until they exit or you stop them. -- Local files stay available in that container. -- Later Worker requests can call `getProcess` or `getTerminal` and continue, as long as **that** container still has the resource. - -Process detail: [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). Terminals: [Terminals](/sandbox/1-0-preview/terminals/). - -## When the container stops or is replaced - -A container is not permanent. Cloudflare may stop it after idle time. It can also stop after failures, or when the platform replaces it during normal operations (for example after some deploys). - -When that happens: - -- Your app still uses the same sandbox ID. -- Processes and terminals from the old container are gone, including their IDs and live log buffers. -- Local files from the old container are gone unless your app restored them (for example with a [backup](/sandbox/guides/backup-restore/) or a mounted bucket). -- The next real work may start a **new** container for the same sandbox ID. -- Handles from the previous container fail closed. `getProcess` and `getTerminal` return `null` when the resource is not in the current container. Those lookups do not start a container only to answer the question. - -To continue work later, store the **job** (what to run, `cwd`, `env`, and any app checkpoint), not only a process or terminal ID. - -## Idle stop, replace, and destroy - -| Event | What stays | What is gone | -| ----- | ---------- | ------------ | -| **Idle stop** | Sandbox ID and Durable Object identity | Processes, terminals, local files from the stopped container | -| **Replace** (failure, deploy, or other replacement) | Sandbox ID and Durable Object identity | Same as idle stop for the previous container | -| **`destroy()`** | The sandbox ID string can be used again later | Treat prior work for that generation as finished | - -After idle stop or replace, the next real work may start a **new** container for the same sandbox ID. Old process and terminal handles are invalid. Recovery procedures: [Errors and recovery](/sandbox/1-0-preview/errors/). - -`keepAlive` and `sleepAfter` change idle behavior. They do not keep one container instance forever. Refer to the stable [Lifecycle API](/sandbox/api/lifecycle/) and [Sandbox options](/sandbox/configuration/sandbox-options/) (ignore transport and default-session options on `@next`). - -## State that outlives a container - -Only what **your app** keeps (or restores) survives a new container: - -| Need | What must live outside the container | -| ---- | ------------------------------------ | -| Find the sandbox again | The **sandbox ID** | -| Continue work on a later request | Resource ID **while** the current container still has it, plus enough job context to start again if it does not | -| Survive stop or replace | The **job**: command or terminal setup, `cwd`, `env`, checkpoint | -| Keep files after a new container | Backup metadata, mount configuration, or another durable store | - -## Related - -- [Process execution](/sandbox/1-0-preview/processes/) -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Lifecycle of a Container](/containers/concepts/architecture/) -- Stable: [Sandbox lifecycle](/sandbox/concepts/sandboxes/) diff --git a/src/content/docs/sandbox/1-0-preview/migrate.mdx b/src/content/docs/sandbox/1-0-preview/migrate.mdx deleted file mode 100644 index 79fc0a682d4..00000000000 --- a/src/content/docs/sandbox/1-0-preview/migrate.mdx +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: Migrate -pcx_content_type: how-to -sidebar: - order: 9 -description: Update an existing Sandbox SDK application from the stable package to @cloudflare/sandbox@next. -products: - - sandbox ---- - -import { PackageManagers, TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This guide moves a project onto `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. Migrate when you can so you are ready when 1.0 becomes the stable release. For the full preview section, refer to [1.0 preview](/sandbox/1-0-preview/). -::: - -## Before you start - -1. Work on a branch or staging deployment. Finish the code migration steps in this guide, then cut production over in one deploy. -2. Expect a short cutover window. Live processes, terminals, and other container work stop when the new image replaces the old one. -3. Inventory call sites in the Worker: - - Commands: `exec`, `execStream`, `startProcess`, string kill signals, process stdin - - Sessions and transport: `createSession`, `enableDefaultSession`, `SANDBOX_TRANSPORT`, `setTransport` - - Terminals: `sandbox.terminal`, session `terminal()`, xterm `sessionId` - - Interpreter: `createCodeContext` / `runCode` on bare `Sandbox` - - Git: `gitCheckout` - -If you still need stable-line cleanup first (RPC transport, `exposePort`, stream helpers), complete the [2026 deprecation migration](/sandbox/guides/2026-deprecation/), then return here. - -## What you will change - -| Stable surface | Preview action | -| -------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -| `SANDBOX_TRANSPORT`, `transport` on `getSandbox()`, `setTransport()` | Remove. The preview uses RPC automatically; no transport setting. | -| `await sandbox.exec(string)` → buffered result | `await sandbox.exec(argv)` then `await process.output(...)`. | -| `execStream`, `startProcess`, process log helpers | Process handle: `logs`, `kill`, `waitFor*`. | -| Default session / `enableDefaultSession` | Gone. Each `exec` is independent. | -| `createSession` / `ExecutionSession` | Gone from the core public surface. Pass `cwd`/`env` per `exec`, or one shell argv script. | -| Interpreter methods on `Sandbox` | Same method names on `sandbox.interpreter` after `withInterpreter`. `runCode` returns plain `ExecutionResult`. Refer to [Code interpreter](/sandbox/1-0-preview/interpreter/). | -| String kill signals | Numeric signals on `process.kill`. | -| `waitForPort` default mode | Preview default is **`tcp`**. Pass `mode: "http"` for HTTP checks. | -| Process / stream **stdin** | No process stdin on the handle. Non-interactive: argv/`cwd`/`env`. Interactive PTY: [terminals](/sandbox/1-0-preview/terminals/). | -| `sandbox.terminal(request)` / session `terminal()` | `createTerminal`, then `terminal.connect(request)`. | -| xterm `sessionId` | `terminalId` (and optional `cursor`). | -| `sandbox.gitCheckout(...)` | Removed. Run `git` with argv `exec`, for example `['git', 'clone', '--', url, dir]`, then `output()` / waits as needed. | - -Files, mounts, backups, ports, tunnels, `proxyToSandbox`, and most lifecycle options stay available. Use the main Sandbox docs for those signatures. Where a stable page still describes sessions, transport selection, string `exec` helpers, or `sandbox.terminal`, follow this preview section instead. - -## Install the preview package and image - - - -Confirm the lockfile resolves `@cloudflare/sandbox` to a preview build. Point your Dockerfile at the matching preview image, for example `cloudflare/sandbox:next` (or the `-python` / other variant you use). - -Do not mix a preview Worker package with a stable container image, or the reverse. Both sides must come from the same `@next` line. - -## Remove transport selection - -Delete `SANDBOX_TRANSPORT`, the `transport` option on `getSandbox()`, `SandboxTransport` types, and `sandbox.setTransport()`. No replacement setting is required. - -## Migrate command execution - -### Buffered commands - -Stable: - -```txt -const result = await sandbox.exec("npm test"); -console.log(result.stdout, result.exitCode); -``` - -Preview: - - -```ts -const process = await sandbox.exec(["/bin/bash", "-lc", "npm test"]); -const result = await process.output({ encoding: "utf8" }); -console.log(result.stdout, result.exitCode); -``` - - -Rules: - -- `await sandbox.exec(...)` means **launch succeeded**, not **command finished**. -- Prefer argv without a shell when you run a single binary: `['npm', 'test']` with `cwd` set. -- `output()` defaults to **byte** streams (`Uint8Array`). Pass `{ encoding: "utf8" }` for strings. -- There is no `sandbox.run()` compatibility helper on the current preview tip. - -### Background processes and streaming - - -```ts -const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], { - cwd: "/workspace/app", -}); - -// Default readiness mode is TCP. Use mode: "http" when you need an HTTP check. -await server.waitForPort(3000, { timeout: 60_000 }); -// await server.waitForPort(3000, { mode: "http", path: "/health", timeout: 60_000 }); - -const stream = await server.logs({ follow: true, replay: true }); -// consume stream... - -await server.kill(); // numeric signal; default 15 -``` - - -Process handle details (waits, log events, `kill`, no stdin): [Processes API](/sandbox/1-0-preview/api/processes/). - -Across Worker requests, keep `server.id` and resume with `getProcess(id)` only while that process may still be running in the current container. If the container stopped, `getProcess` may return `null`. If you still hold a handle from a previous container, expect a stale-handle error. In both cases, start a new `exec` from the work you still need to run. Refer to [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). - -### Working directory and environment - -| Stable | Preview | -| ------ | ------- | -| `exec("cd /app"); exec("npm test");` | `exec(['/bin/bash', '-lc', 'cd /app && npm test'])` or `exec(['npm', 'test'], { cwd: '/app' })` | -| Exported vars in the default session | `setEnvVars` and/or `env` on each `exec` | -| `createSession({ env })` | `setEnvVars` and/or `env` on each `exec` / `createTerminal` | - -Details: [Environment variables](/sandbox/1-0-preview/environment/). - -Do not put live API keys or long-lived provider credentials into `setEnvVars` or launch `env`. Keep secrets in the Worker and inject them with [outbound traffic](/sandbox/guides/outbound-traffic/) handlers when the process must call an external API. - -### Timeouts and cancellation - -| Goal | API | -| ---- | --- | -| Limit process lifetime | `exec(argv, { timeout })` — may finish with `timedOut: true` | -| Limit how long you wait | Options or `AbortSignal` on `output` / waits / `logs` — does **not** kill the process | - -## Drop session APIs - -Remove `createSession`, `getSession`, `deleteSession`, and `sessionId` options on core calls. - -User isolation remains **one sandbox per user** (or per trust boundary), not sessions inside one sandbox. - -## Attach the interpreter - -Refer to [Code interpreter](/sandbox/1-0-preview/interpreter/). Minimum: - - -```ts -import { Sandbox as BaseSandbox } from "@cloudflare/sandbox"; -import { withInterpreter } from "@cloudflare/sandbox/interpreter"; - -export class Sandbox extends BaseSandbox { - interpreter = withInterpreter(this); -} -``` - - -Use the **`-python`** image variant when you run Python. Keep the Worker package and container image on the same `@next` line. - -## Git - -`sandbox.gitCheckout` is removed. Clone or fetch with argv `exec`, for example: - - -```ts -const clone = await sandbox.exec( - ["git", "clone", "--depth", "1", "--", repoUrl, "/workspace/repo"], - { cwd: "/workspace" }, -); -const result = await clone.output({ encoding: "utf8" }); -``` - - -## Terminals - -Replace stable `sandbox.terminal(request)` (and session-scoped `terminal()`) with the preview terminal resource API: - -1. `const terminal = await sandbox.createTerminal({ command: ['bash'], ... })` -2. Store `terminal.id` with the sandbox id. -3. On WebSocket upgrade: `getTerminal(id)` then `terminal.connect(request, { cursor?, cols?, rows? })`. -4. In the browser, `@cloudflare/sandbox/xterm` uses `terminalId`. - -Details: [Terminals](/sandbox/1-0-preview/terminals/), [Terminals API](/sandbox/1-0-preview/api/terminals/). - -## Self-deployed bridge - -This guide covers Worker SDK applications on `@next`. - -The self-deployed [Sandbox bridge](/sandbox/bridge/) stays on the stable release line. Keep its Worker package, container image, and HTTP clients on matching stable versions. Do not pair a bridge deployment with `@cloudflare/sandbox@next`. - -## Handle lifecycle the preview way - -On `@next`, a **sandbox ID** stays stable, but the **container** behind it can be replaced. Processes and terminals live only in the current container. After replacement, old handles fail and you start the work again. - -That is normal after idle time, restarts, and this migration cutover. Full model: [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) and [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). Recovery patterns: [Errors and recovery](/sandbox/1-0-preview/errors/). Catalog: [Errors API](/sandbox/1-0-preview/api/errors/). - -When you migrate long-running work: - -1. Do not treat a stored `process.id` or `terminal.id` as enough to resume after an arbitrary delay or after deploy. -2. Persist the command, `cwd`, `env`, and any app checkpoint you need to relaunch. -3. On a later request, call `getProcess(id)` / `getTerminal(id)` only if that resource might still be running in the current container. If you get `null` or a stale-handle error, start again from the stored work. - -Handle at least these errors as follows: - -| Error | What to do | -| ----- | ---------- | -| `ContainerUnavailableError` | Container did not start the work — back off (`retryAfterMs` when set), then try the work again | -| `StaleProcessHandleError` / `StaleTerminalHandleError` | Previous container — start again from stored work state | -| `OperationInterruptedError` | Work may have started — read `reason` / `retryable`; check state before repeating | -| `RPCTransportError` | Lost contact during the call — a later call may work; this call may already have run | -| `ProcessWaitTimeoutError` / `ProcessAbortedError` | Wait ended only — process may still be running | -| `RuntimeControlProtocolError` or unusable image after deploy | Worker package and container image must match on the same `@next` line; do not treat as a slow start | - -`getProcess` / `getTerminal` / `list*` do not start a container. They return `null` or `[]` when none is running (not an exception). - -## Deploy the cutover - -Finish the code migration steps in this guide on a branch first. Production cutover is one deploy of the preview Worker package and the matching container image. - -Stable Sandbox and `@next` use different control protocols. A mixed pair does not work in either direction: new Worker code against an old container image fails, and old Worker code against a new container image fails. - -On a normal `wrangler deploy`, Worker code becomes active immediately while container instances can still update gradually. That leaves a window where new Worker code can reach old containers. For this migration, roll containers out in one step: - -```sh -npx wrangler deploy --containers-rollout=immediate -``` - -`--containers-rollout=immediate` does not override [`rollout_active_grace_period`](/workers/wrangler/configuration/#containers). Leave that setting at its default of `0` for the cutover (or set it to `0` if you raised it earlier). A nonzero grace period keeps active old containers eligible longer while the new Worker is already live. - -Before production: - -1. Finish or stop work you need to keep through the cutover. -2. Deploy with the immediate container rollout command from the previous section. -3. Wait until the new container image is serving traffic. -4. Treat process and terminal IDs from before the deploy as invalid. Start that work again and keep the new IDs. -5. Run the checks in [Verify](#verify). - -For routine deploys after migration, refer to [Deploy a Sandbox application](/sandbox/guides/deploy/). For rollout options, refer to [Rollouts](/containers/configuration/rollouts/). - -## Verify - -1. Confirm the lockfile and Dockerfile are both on the same `@next` line, then deploy with `--containers-rollout=immediate`. -2. Run one argv `exec` and `output({ encoding: "utf8" })`. -3. Run one long-lived process with `waitForPort` or `logs`. -4. If the app uses a browser terminal: create, connect, and resume with `getTerminal` while the container still has it. -5. Exercise the interpreter only if your app uses that extension (Python needs `-python`). -6. Confirm error handling distinguishes unavailable, interrupted/RPC, stale handle, and local wait timeouts — [Errors and recovery](/sandbox/1-0-preview/errors/). -7. Confirm secrets are not stored in sandbox env. Use outbound handlers where needed. -8. Grep again for removed APIs (transport, sessions, `execStream`, `startProcess`, `sandbox.terminal`, `gitCheckout`, xterm `sessionId`). - -## Coding agents - -Install [Cloudflare Skills](https://github.com/cloudflare/skills) for your agent ([Agent setup](/agent-setup/)). The **`sandbox-migrate-to-next`** skill performs this migration. For new apps on `@next`, use **`sandbox-next`**. For day-to-day work on the current stable package, use **`sandbox-stable`**. Deprecated-API cleanup while staying on stable is in the [2026 deprecation guide](/sandbox/guides/2026-deprecation/) (and **`sandbox-stable`**) before or instead of this guide. - -## Related - -- [1.0 preview overview](/sandbox/1-0-preview/) -- [Get started](/sandbox/1-0-preview/get-started/) -- [Environment variables](/sandbox/1-0-preview/environment/) -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Process execution](/sandbox/1-0-preview/processes/) (including [how long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives)) -- [Processes API](/sandbox/1-0-preview/api/processes/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [API reference](/sandbox/1-0-preview/api/) -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Terminals API](/sandbox/1-0-preview/api/terminals/) -- [Code interpreter](/sandbox/1-0-preview/interpreter/) -- [Extensions](/sandbox/1-0-preview/extensions/) -- [Troubleshooting](/sandbox/1-0-preview/troubleshooting/) -- [Deploy a Sandbox application](/sandbox/guides/deploy/) -- [Deploy Containers](/containers/guides/deploy/) -- [Rollouts](/containers/configuration/rollouts/) diff --git a/src/content/docs/sandbox/1-0-preview/processes.mdx b/src/content/docs/sandbox/1-0-preview/processes.mdx deleted file mode 100644 index d4b401b9035..00000000000 --- a/src/content/docs/sandbox/1-0-preview/processes.mdx +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: Process execution -pcx_content_type: concept -sidebar: - order: 3 -description: How the Sandbox SDK 1.0 preview runs commands — argv launches, process handles, and container lifetime. -products: - - sandbox ---- - -import { TypeScriptExample } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents process execution on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For today's stable command and session behavior, refer to [Commands](/sandbox/api/commands/) and [Sessions](/sandbox/concepts/sessions/). -::: - -In the 1.0 preview, treat the sandbox as a computer you drive with explicit programs. - -Each `exec()` starts a **new supervised process** from **argv**. The call resolves when launch succeeds (you receive a process handle with `id` and `pid` properties), not when the process exits. Each launch is independent: pass `cwd` and `env` when the process needs them, or put multi-step shell syntax in one explicit shell argv. For an interactive PTY, use the [terminal](/sandbox/1-0-preview/terminals/) API. - -Long-running work often spans many short Worker requests. A process ID is enough only while the **same container** still has that process. Across idle stop, failure, or replace, store the full launch (command, options, and any app checkpoint) so you can start again. Refer to [Continue work across requests](#continue-work-across-requests). - -## Sandbox ID, container, and process - -Most applications use **one sandbox per user or task**: - - -```ts -const sandbox = getSandbox(env.Sandbox, "user-123"); -``` - - -Three different things are in play: - -| Term | Meaning | -| ---- | ------- | -| **Sandbox ID** | The stable string your app uses to find that sandbox again (for example `"user-123"`). | -| **Container** | The [Containers](/containers/) instance currently running work for that sandbox. Sandboxes run on containers. The sandbox ID is stable. The container instance behind it is not always the same one. | -| **Process** | A program you start with `exec()` **inside the current container**. The handle and `process.id` mean “this program in this container,” not “this sandbox ID forever.” | - -**Same sandbox ID does not mean the same container.** Processes live only in the container that started them. After a new container serves that ID, start new processes — you do not resume the old ones. Full sandbox model: [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/). - -## Command model - -The command model changes in the 1.0 preview compared with the current stable package: - -| Current stable package | 1.0 preview | -| ---------------------- | ----------- | -| `exec(string)` resolves when the command finishes | `exec(argv)` resolves when the process starts | -| Default session can preserve `cd` / `export` | Each launch is independent | -| `startProcess` / `execStream` for other shapes | One process handle covers short and long-running work | - -Use argv for a single binary: - - -```ts -const process = await sandbox.exec(["node", "--version"]); -const output = await process.output({ encoding: "utf8" }); -``` - - -Use an explicit shell when you need shell syntax: - - -```ts -const process = await sandbox.exec([ - "/bin/bash", - "-lc", - "cd /workspace/app && npm test", -]); -``` - - -Or pass `cwd` and `env` on the launch instead of relying on a previous command: - - -```ts -const process = await sandbox.exec(["npm", "test"], { - cwd: "/workspace/app", - env: { NODE_ENV: "test" }, -}); -``` - - -Sandbox-wide values use `setEnvVars`. Refer to [Environment variables](/sandbox/1-0-preview/environment/). - -## Process handles - -`await sandbox.exec(argv)` returns a **process handle**: - -| Capability | Members | -| ---------- | ------- | -| Identity | `id`, `pid` | -| Observe | `status()`, `logs()`, `output()`, `waitForExit()`, `waitForLog()`, `waitForPort()`, `exitCode` | -| Control | `kill(signal?)` with a numeric signal (default `15`) | - -Observation timeouts and `AbortSignal` values cancel **only that wait or stream**. They do not stop the process. Call `kill()` when you intend to stop it. - -`exec(argv, { timeout })` sets a **remote lifetime** deadline. When the supervisor stops the process for that deadline, completion can report `timedOut: true`. - -For short commands, `output()` is enough. For large or long-running output, prefer `logs({ since, replay, follow })` and keep the latest **cursor** so a later request can resume the stream while the process is still in the current container. API details: [Processes API](/sandbox/1-0-preview/api/processes/). - -## How long a process lives - -A process lives only as long as it keeps running **in the current container** for that sandbox. After the container stops, old process IDs are not valid on a later container that serves the same sandbox ID. - -### When the container stops - -The container for a sandbox is not meant to run forever. After a period with nothing to do, Cloudflare may stop it. The container can also stop after failures, or when the platform replaces it during normal operations (for example after some deploys). - -When that happens: - -- Your app still uses the same sandbox ID (`user-123`). -- Processes that were running in the old container have exited. Their process IDs and live log buffers from that container are gone. -- The next time you use the sandbox for real work, Cloudflare may start a **new** container for the same sandbox ID. You start new processes there. You do not reconnect to process IDs from the previous container. Files from the old container are not still there unless your app restored them (for example from a backup or a mounted bucket). - -Container stop and replace are not new in 1.0. The preview makes process handles fail closed after the container that owned them is gone: the SDK does not retarget an old process ID at a new container for the same sandbox ID. - -### What you see in the API - -| What you try | What happens | -| ------------ | ------------ | -| The process is still running in the current container | `getProcess(id)` returns it; you can read logs and wait as usual | -| No container is running for the sandbox yet | `getProcess` and `listProcesses` return `null` / `[]`. They do **not** start a container just to answer the lookup | -| You still hold a handle from before the container stopped | Calls on that handle fail with `StaleProcessHandleError` | -| You need the same *job* after a stop | Start a new `exec()` from the launch and checkpoint your app stored | - -Recovery procedures: [Errors and recovery](/sandbox/1-0-preview/errors/). - -### Keep the container running - -While a process or terminal is active, the container can stay running so work continues across requests. When nothing is active, the container may stop again after idle time. Long-running product flows should either keep meaningful work active or rely on checkpoints and relaunch. - -## Continue work across requests - -Worker requests are short. Sandbox processes often are not. Design the job so a later request can either **resume the same process** or **start the job again**. - -### What to store - -| Always useful | When you stream logs | -| ------------- | -------------------- | -| Sandbox ID | Latest log **cursor** from delivered events | -| Full `exec` argv | | -| `cwd` and `env` if the launch needs them | | -| Application checkpoint (repo path, step, agent state) | | - -A process ID is a resume key for the **current** container only. It is not enough to restart the job after the container may have stopped. - -### Case 1: The container still has the process - -Use this path when the work is still running and the container has not been replaced — for example another request arrives seconds later while a build or server is up. - - -```ts -const process = await sandbox.getProcess(storedProcessId); -if (process) { - const stream = await process.logs({ - since: storedCursor, - replay: true, - follow: true, - }); - // consume events; keep the latest cursor from each event - return; -} -``` - - -You can also call `status()`, `waitForPort()`, `waitForExit()`, or `kill()` on that handle. Log cursors apply only while this process still exists in this container. - -### Case 2: The process is gone — start from the stored job - -Use this path when `getProcess` returns `null`, a call throws `StaleProcessHandleError`, or enough time has passed that the container may have stopped or been replaced. - - -```ts -const process = await sandbox.exec(storedCommand, { - cwd: storedCwd, - env: storedEnv, -}); -// persist process.id (and clear any old cursor) -await process.waitForPort(3000, { timeout: 60_000 }); -``` - - -If the job also depends on files that lived only in the previous container, [back up and restore](/sandbox/guides/backup-restore/) those directories or mount durable storage before relying on the tree again. Backup and restore replace filesystem state. They do not bring back old process IDs or log buffers. - -If the container is not ready yet, you may get `ContainerUnavailableError` — back off and run the same unit of work again. Refer to [Errors and recovery](/sandbox/1-0-preview/errors/). - -### Choose a path - - -```ts -async function continueJob(sandbox: Sandbox, job: StoredJob) { - if (job.processId) { - const existing = await sandbox.getProcess(job.processId); - if (existing) { - return existing; // Case 1 — same container, same process - } - // null: no container, or this ID is not in the current container - } - - // Case 2 — relaunch from stored command and checkpoint - const process = await sandbox.exec(job.command, { - cwd: job.cwd, - env: job.env, - }); - job.processId = process.id; - job.cursor = undefined; - return process; -} -``` - - -If you still hold a handle object from before the container stopped, calls on that handle throw `StaleProcessHandleError`. Prefer `getProcess(id)` on each new request instead of reusing an old handle across requests. - -## Processes and terminals - -| | Process (`exec`) | Terminal | -| - | ---------------- | -------- | -| Role | Supervised argv process | Interactive PTY | -| Input | Launch-time argv | PTY input (`write` / browser `connect`) | -| Stop | `kill(signal?)` | `interrupt()` / `terminate()` | -| Lookup | `getProcess` / `listProcesses` | `getTerminal` / `listTerminals` | - -Both follow the same [container lifetime rules](#how-long-a-process-lives). Terminal docs: [Terminals](/sandbox/1-0-preview/terminals/). API: [Terminals API](/sandbox/1-0-preview/api/terminals/). - -## Logs and large output - -`output()` buffers stdout and stderr and may set `truncated: true`. Prefer `logs()` when output may be large or the process runs longer than one Worker request. - - -```ts -const stream = await process.logs({ follow: true, replay: true }); -// each data/terminal event includes a cursor — store the latest -``` - - -On a later request against the **same still-running container**, call `getProcess(id)` and resume with `logs({ since: cursor, replay: true, follow: true })`. After a new container starts for the sandbox, start a new process; the old cursor does not apply. - -Event shapes, wait options, and readiness checks: [Processes API](/sandbox/1-0-preview/api/processes/). - -## Related - -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Processes API](/sandbox/1-0-preview/api/processes/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [Terminals](/sandbox/1-0-preview/terminals/) -- [Migrate](/sandbox/1-0-preview/migrate/) -- [Get started](/sandbox/1-0-preview/get-started/) -- [1.0 preview overview](/sandbox/1-0-preview/) diff --git a/src/content/docs/sandbox/1-0-preview/terminals.mdx b/src/content/docs/sandbox/1-0-preview/terminals.mdx deleted file mode 100644 index eff2ffbebd2..00000000000 --- a/src/content/docs/sandbox/1-0-preview/terminals.mdx +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Terminals -pcx_content_type: concept -sidebar: - order: 4 -description: Interactive PTY terminals in the Sandbox SDK 1.0 preview — resource model and browser connect. -products: - - sandbox ---- - -import { TypeScriptExample, PackageManagers } from "~/components"; - -:::note[Path to Sandbox SDK 1.0] -This page documents terminals on `@cloudflare/sandbox@next`, the preview of Sandbox SDK 1.0. For the current stable terminal helpers, refer to [Terminal connections](/sandbox/concepts/terminal/) and [Terminal API](/sandbox/api/terminal/). -::: - -A **terminal** is an interactive PTY in the current container for a sandbox. Use it for full-duplex terminal I/O: a browser shell, resize, interrupt, and reconnect. - -Command execution uses [`exec`](/sandbox/1-0-preview/processes/) and process handles. Terminals are a separate resource type. API reference: [Terminals API](/sandbox/1-0-preview/api/terminals/). - -## Processes and terminals - -| | Process (`exec`) | Terminal | -| - | ---------------- | -------- | -| Role | Supervised argv process | Interactive PTY | -| Input | Launch-time argv (and whatever the program reads on its own) | PTY input via `write()` or browser `connect()` | -| Output | `logs()`, `output()`, waits | `output()`, snapshot, `waitForExit()` | -| Stop | `kill(signal?)` | `interrupt()` / `terminate()` | -| Lookup | `getProcess` / `listProcesses` | `getTerminal` / `listTerminals` | - -Both kinds of resource live only in the current container for a sandbox ID. Lookup methods do not start a container. Refer to [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) and [How long a process lives](/sandbox/1-0-preview/processes/#how-long-a-process-lives). - -## Create a terminal - - -```ts -const terminal = await sandbox.createTerminal({ - command: ["bash"], - cwd: "/workspace", - cols: 120, - rows: 40, -}); - -console.log(terminal.id); -``` - - -You can write to the PTY from the Worker, resize it, stream output, or end it: - - -```ts -await terminal.write(new TextEncoder().encode("uname -a\n")); -await terminal.resize(100, 30); -await terminal.terminate(); -``` - - -## Lifetime - -- A terminal exists only in the **current container** for that sandbox ID. -- `getTerminal` / `listTerminals` return `null` / `[]` when no container is running. They do not start one. -- After the container stops or is replaced, old terminal IDs are invalid. Create a new terminal if you need one again. -- An active terminal can keep the container alive across Worker requests, as an active process can. - -Store `terminal.id` to resume the same PTY while that container is still up. - -## Browser connect - -1. Create a terminal and keep `terminal.id` with the sandbox id. -2. On each WebSocket upgrade, resolve the terminal with `getTerminal`, then return `terminal.connect(request)`. -3. In the browser, use `@cloudflare/sandbox/xterm` with **`terminalId`**. - -### Worker - - -```ts -import { getSandbox } from "@cloudflare/sandbox"; - -export { Sandbox } from "@cloudflare/sandbox"; - -export default { - async fetch(request: Request, env: Env): Promise { - const url = new URL(request.url); - - if ( - url.pathname === "/ws/terminal" && - request.headers.get("Upgrade")?.toLowerCase() === "websocket" - ) { - const sandboxId = url.searchParams.get("sandboxId"); - const terminalId = url.searchParams.get("terminalId"); - if (!sandboxId || !terminalId) { - return new Response("sandboxId and terminalId are required", { - status: 400, - }); - } - - const sandbox = getSandbox(env.Sandbox, sandboxId); - const terminal = await sandbox.getTerminal(terminalId); - if (!terminal) { - return new Response("Terminal not found", { status: 404 }); - } - - return terminal.connect(request, { - cursor: url.searchParams.get("cursor") ?? undefined, - }); - } - - return new Response("Not found", { status: 404 }); - }, -}; -``` - - -Create the terminal from an application route when the UI needs one: - - -```ts -const sandboxId = "user-123"; -const sandbox = getSandbox(env.Sandbox, sandboxId); -const terminal = await sandbox.createTerminal({ command: ["bash"] }); -return Response.json({ sandboxId, terminalId: terminal.id }); -``` - - -### Browser (xterm.js) - - - - -```ts -import { Terminal } from "@xterm/xterm"; -import { FitAddon } from "@xterm/addon-fit"; -import { SandboxAddon } from "@cloudflare/sandbox/xterm"; -import "@xterm/xterm/css/xterm.css"; - -const term = new Terminal({ cursorBlink: true }); -const fitAddon = new FitAddon(); -const sandboxAddon = new SandboxAddon({ - // `origin` is already a WebSocket origin (`wss://` or `ws://`). - getWebSocketUrl: ({ sandboxId, terminalId, cursor, origin }) => { - const params = new URLSearchParams({ sandboxId }); - if (terminalId) params.set("terminalId", terminalId); - if (cursor) params.set("cursor", cursor); - return `${origin}/ws/terminal?${params}`; - }, - reconnect: true, -}); - -term.loadAddon(fitAddon); -term.loadAddon(sandboxAddon); -term.open(document.getElementById("terminal")!); -fitAddon.fit(); - -// Values returned by your create-terminal route -const sandboxId = "user-123"; -const terminalId = "term_..."; -sandboxAddon.connect({ sandboxId, terminalId }); -``` - - -| Stable package | Preview | -| -------------- | ------- | -| `sandbox.terminal(request)` | `createTerminal` + `getTerminal` + `connect` | -| xterm / URL `sessionId` | `terminalId` (and optional `cursor`) | - -## Related - -- [Terminals API](/sandbox/1-0-preview/api/terminals/) -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [Process execution](/sandbox/1-0-preview/processes/) -- [Processes API](/sandbox/1-0-preview/api/processes/) -- [Migrate](/sandbox/1-0-preview/migrate/) diff --git a/src/content/docs/sandbox/1-0-preview/troubleshooting.mdx b/src/content/docs/sandbox/1-0-preview/troubleshooting.mdx deleted file mode 100644 index 84927f2153a..00000000000 --- a/src/content/docs/sandbox/1-0-preview/troubleshooting.mdx +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Troubleshooting -pcx_content_type: how-to -sidebar: - order: 11 -description: Common failures on @cloudflare/sandbox@next and where to fix them. -products: - - sandbox ---- - -:::note[Path to Sandbox SDK 1.0] -This page is for `@cloudflare/sandbox@next`. Stable-package symptoms may differ. -::: - -Use this symptom-to-fix map. For deeper recovery, refer to [Errors and recovery](/sandbox/1-0-preview/errors/). For lifecycle behavior, refer to [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/). - -## Deploy and image - -| Symptom | What to check | -| ------- | ------------- | -| `RuntimeControlProtocolError`, control/protocol failures after deploy | Worker package and container image are on different lines. Use the same `@next` / `cloudflare/sandbox:next` (or the same exact prerelease) pair. | -| Container never becomes ready, or you see repeated `ContainerUnavailableError` | Cold start or capacity. Back off using `retryAfterMs` when set, then retry the **work**. Refer to [Errors and recovery](/sandbox/1-0-preview/errors/). | -| Works in `wrangler dev`, fails in production only | Production-only limits and cold start. Still keep package/image matched. | - -## Processes - -| Symptom | What to check | -| ------- | ------------- | -| `await exec` “finished” but the command did not | `exec` resolves on **launch**. Use `output()`, `waitForExit()`, or `exitCode`. | -| No stdout as a string | `output()` defaults to bytes. Pass `{ encoding: "utf8" }`. | -| `getProcess` is `null` / list is `[]` | No container running, or ID unknown in the **current** container. Discovery does not wake a sandbox. Relaunch from stored job state if needed. | -| `StaleProcessHandleError` | Handle was from a previous container. Start a new `exec` from checkpointed work. | -| Wait timed out / aborted but process still runs | Local wait only. Call `kill()` if you intend to stop it. | -| Port never becomes ready | Default `waitForPort` mode is **TCP**. Use `mode: "http"` for HTTP checks. Process may have exited — check status/logs. | -| Need interactive stdin | Not on the process handle. Use a [terminal](/sandbox/1-0-preview/terminals/) or non-interactive argv/`cwd`/`env`. | - -## Terminals - -| Symptom | What to check | -| ------- | ------------- | -| Browser still uses `sessionId` | Preview xterm helper expects `terminalId`. | -| `getTerminal` is `null` | Same lifetime rules as processes. Create again if the container was replaced. | -| Reconnect has no history | Pass the last `cursor` into `connect` / output options. | - -## Environment and secrets - -| Symptom | What to check | -| ------- | ------------- | -| Env from an earlier `exec` “disappeared” | No session shell. Use `setEnvVars` and/or per-launch `env`. [Environment variables](/sandbox/1-0-preview/environment/). | -| API keys leaked into the container | Do not put live secrets in sandbox env. Use [outbound traffic](/sandbox/guides/outbound-traffic/) handlers on the Worker. | - -## Interpreter - -| Symptom | What to check | -| ------- | ------------- | -| `sandbox.createCodeContext is not a function` | Attach `withInterpreter` and call `sandbox.interpreter.*`. | -| Python not available | Use the **`-python`** image variant on the same `@next` line. | - -## Bridge HTTP - -| Symptom | What to check | -| ------- | ------------- | -| Bridge `/exec`, sessions, or `/pty` behavior differs from `@next` Worker SDK docs | The self-deployed bridge is not part of the 1.0 preview. Use the [stable bridge](/sandbox/bridge/) with matching stable package and container image. | - -## Agents and long-running jobs - -For agents and long-running tools on `@next`: - -1. Launch with `exec(argv)` (often `['/bin/bash', '-lc', script]`). -2. Wait with `waitForLog`, `waitForPort`, or `logs` — not only `await exec`. -3. Persist **job state** (command, `cwd`, `env`, checkpoint), not only `process.id`. -4. On a later request: `getProcess(id)` while the same container may still hold it; otherwise `exec` again. -5. Use a [terminal](/sandbox/1-0-preview/terminals/) only when you need a human PTY, not as a session substitute. - -Refer to [Process execution](/sandbox/1-0-preview/processes/), [Migrate](/sandbox/1-0-preview/migrate/), and examples in the [sandbox-sdk](https://github.com/cloudflare/sandbox-sdk/tree/next/examples) repo (`claude-code`, `codex`, `opencode`, and others). - -## Related - -- [Errors and recovery](/sandbox/1-0-preview/errors/) -- [Errors API](/sandbox/1-0-preview/api/errors/) -- [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) -- [Process API](/sandbox/1-0-preview/api/processes/) -- [Terminal API](/sandbox/1-0-preview/api/terminals/) -- [Migrate](/sandbox/1-0-preview/migrate/) diff --git a/src/content/docs/sandbox/concepts/index.mdx b/src/content/docs/sandbox/concepts/index.mdx deleted file mode 100644 index 4e95433212a..00000000000 --- a/src/content/docs/sandbox/concepts/index.mdx +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Concepts -description: Learn how the Sandbox SDK works, including architecture, lifecycle, security, and sessions. -pcx_content_type: navigation -sidebar: - order: 7 -products: - - sandbox ---- - -These pages explain how the Sandbox SDK works, why it's designed the way it is, and the concepts you need to understand to use it effectively. - -- [Architecture](/sandbox/concepts/architecture/) - How the SDK is structured and why -- [Sandbox lifecycle](/sandbox/concepts/sandboxes/) - Understanding sandbox states and behavior -- [Container runtime](/sandbox/concepts/containers/) - How code executes in isolated containers -- [Session management](/sandbox/concepts/sessions/) - When and how to use sessions -- [Preview URLs](/sandbox/concepts/preview-urls/) - How to expose sandboxed services on the public internet. -- [Security model](/sandbox/concepts/security/) - Isolation, validation, and safety mechanisms -- [Terminal connections](/sandbox/concepts/terminal/) - How browser terminal connections work -- [Directory backups](/sandbox/concepts/backup-restore/) - Overlay restore, local extract, and cross-device renames - -## Related resources - -- [Tutorials](/sandbox/tutorials/) - Learn by building complete applications -- [How-to guides](/sandbox/guides/) - Solve specific problems -- [API reference](/sandbox/api/) - Technical details and method signatures diff --git a/src/content/docs/sandbox/index.mdx b/src/content/docs/sandbox/index.mdx index 9346194a010..5bfd8cf5b59 100644 --- a/src/content/docs/sandbox/index.mdx +++ b/src/content/docs/sandbox/index.mdx @@ -1,6 +1,6 @@ --- -title: Sandbox SDK -description: Build secure, isolated code execution environments powered by Cloudflare Workers and Containers. +title: Sandboxes on Cloudflare +description: Execute untrusted or generated code in isolated Workers or Linux virtual machines. pcx_content_type: overview sidebar: order: 1 @@ -11,311 +11,129 @@ products: - sandbox - workers - containers + - dynamic-workers + - durable-objects --- import { CardGrid, Description, - Feature, LinkTitleCard, Plan, RelatedProduct, LinkButton, - Tabs, - TabItem, + TypeScriptExample, } from "~/components"; -Build secure, isolated code execution environments +Execute untrusted or generated code away from your application -:::note[Sandbox SDK 1.0 preview] -These pages document the current stable `@cloudflare/sandbox` package. The next major release is **Sandbox SDK 1.0**, available as a preview on `@cloudflare/sandbox@next`. +A sandbox is an isolated place to run untrusted or generated work. The program you load there has its own memory and, when it needs them, its own files and processes. It cannot touch your application. You decide which APIs it can call and whether it can reach the Internet. -We recommend starting new projects on the preview, and migrating existing apps when you can, so you are ready when 1.0 becomes the stable release. Refer to the [1.0 preview](/sandbox/1-0-preview/) section for install, concepts, API reference, and migration. -::: +You can use a sandbox for agent-written code, user-uploaded applications, data analysis, development previews, build pipelines, or any other work that should not share a process with your application. -The Sandbox SDK enables you to run untrusted code securely in isolated environments. Built on [Containers](/containers/), Sandbox SDK provides a simple API for executing commands, managing files, running background processes, and exposing services — all from your [Workers](/workers/) applications. - -Sandboxes are ideal for building AI agents that need to execute code, interactive development environments, data analysis platforms, CI/CD systems, and any application that needs secure code execution at the edge. Each sandbox runs in its own isolated container with a full Linux environment, providing strong security boundaries while maintaining performance. - -With Sandbox, you can execute Python scripts, run Node.js applications, analyze data, compile code, and perform complex computations — all with a simple TypeScript API and no infrastructure to manage. - - - - ```typescript - import { getSandbox } from '@cloudflare/sandbox'; - - export { Sandbox } from '@cloudflare/sandbox'; - - export default { - async fetch(request: Request, env: Env): Promise { - const sandbox = getSandbox(env.Sandbox, 'user-123'); - - // Execute a command and get the result - const result = await sandbox.exec('python --version'); - - return Response.json({ - output: result.stdout, - exitCode: result.exitCode, - success: result.success - }); - } - }; - ``` - - - - - ```typescript - import { getSandbox } from '@cloudflare/sandbox'; - - export { Sandbox } from '@cloudflare/sandbox'; - - export default { - async fetch(request: Request, env: Env): Promise { - const sandbox = getSandbox(env.Sandbox, 'user-123'); - - // Create a Python execution context - const ctx = await sandbox.createCodeContext({ language: 'python' }); - - // Execute Python code with automatic result capture - const result = await sandbox.runCode(` - import pandas as pd - data = {'product': ['A', 'B', 'C'], 'sales': [100, 200, 150]} - df = pd.DataFrame(data) - df['sales'].sum() # Last expression is automatically returned - `, { context: ctx }); - - return Response.json({ - result: result.results?.[0]?.text, - logs: result.logs - }); - } - }; - ``` - - - - ```typescript - import { getSandbox } from '@cloudflare/sandbox'; - - export { Sandbox } from '@cloudflare/sandbox'; - - export default { - async fetch(request: Request, env: Env): Promise { - const sandbox = getSandbox(env.Sandbox, 'user-123'); - - // Create a project structure - await sandbox.mkdir('/workspace/project/src', { recursive: true }); - - // Write files - await sandbox.writeFile( - '/workspace/project/package.json', - JSON.stringify({ name: 'my-app', version: '1.0.0' }) - ); - - // Read a file back - const content = await sandbox.readFile('/workspace/project/package.json'); - - return Response.json({ content }); - } - }; - ``` - - - - ```typescript - import { getSandbox } from '@cloudflare/sandbox'; - - export { Sandbox } from '@cloudflare/sandbox'; - - export default { - async fetch(request: Request, env: Env): Promise { - const sandbox = getSandbox(env.Sandbox, 'user-123'); - - // Watch for file changes in real-time - const watcher = await sandbox.watch('/workspace/src', { - include: ['*.js', '*.ts'], - onEvent: (event) => { - console.log(`${event.type}: ${event.path}`); - if (event.type === 'modify') { - // Trigger rebuild or hot reload - console.log('Code changed, recompiling...'); - } - }, - onError: (error) => { - console.error('Watch error:', error); - } - }); - - // Stop watching when done - setTimeout(() => watcher.stop(), 60000); - - return Response.json({ message: 'File watcher started' }); - } - }; - ``` - - - - ```typescript - import { getSandbox } from '@cloudflare/sandbox'; - - export { Sandbox } from '@cloudflare/sandbox'; - - export default { - async fetch(request: Request, env: Env): Promise { - const url = new URL(request.url); - - // Terminal WebSocket connection - if (url.pathname === '/ws/terminal') { - const sandbox = getSandbox(env.Sandbox, 'user-123'); - return sandbox.terminal(request, { cols: 80, rows: 24 }); - } - - return Response.json({ message: 'Terminal endpoint' }); - } - }; - ``` - - Connect browser terminals directly to sandbox shells via WebSocket. Learn more: [Browser terminals](/sandbox/guides/browser-terminals/). - - - - ```typescript - import { getSandbox } from '@cloudflare/sandbox'; - - export { Sandbox } from '@cloudflare/sandbox'; - - export default { - async fetch(request: Request, env: Env): Promise { - // Connect to WebSocket services in sandbox - if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') { - const sandbox = getSandbox(env.Sandbox, 'user-123'); - return await sandbox.wsConnect(request, 8080); - } - - return Response.json({ message: 'WebSocket endpoint' }); - } - }; - ``` - - Connect to WebSocket servers running in sandboxes. Learn more: [WebSocket Connections](/sandbox/guides/websocket-connections/). - - - - - - Get started - - - API Reference - +Cloudflare provides two sandbox environments. Both are accessible through a [Worker](/workers/), the program that already handles your traffic. --- -## Features - - - -Deploy your Worker and keep the npm package and container image on the same release line. - - - - - -Run shell commands, Python scripts, Node.js applications, and more with streaming output support and automatic timeout handling. - - - - - -Read, write, and manipulate files in the sandbox filesystem. Run background processes, monitor output, and manage long-running operations. +## Dynamic Workers - +[Dynamic Workers](/dynamic-workers/) create a new Worker at runtime. The untrusted code can be JavaScript, TypeScript, Python, or WebAssembly. It starts in milliseconds. - +That code cannot see your application's memory. It can use only the APIs and data you pass in, and it cannot reach the Internet unless you allow it. -Expose HTTP services running in your sandbox with automatically generated preview URLs, perfect for interactive development environments and application hosting. +The isolation comes from V8, the JavaScript engine in Chrome. V8 runs the code in an isolate: a sandbox that cannot read memory outside itself. The Workers platform adds a second layer around the process and exposes only the APIs you grant. For more information, refer to the [Workers security model](/workers/reference/security-model/). - + - +```ts +export default { + async fetch(request: Request, env: Env): Promise { + const worker = env.LOADER.load({ + compatibilityDate: "$today", + mainModule: "src/index.js", + modules: { + "src/index.js": ` + export default { + fetch() { + return new Response("Hello from a sandbox"); + }, + }; + `, + }, + globalOutbound: null, + }); -Execute Python and JavaScript code with rich outputs including charts, tables, and images. Maintain persistent state between executions for AI-generated code and interactive workflows. + return worker.getEntrypoint().fetch(request); + }, +}; +``` - + - - -Create browser-based terminal interfaces that connect directly to sandbox shells via WebSocket. Build collaborative terminals, interactive development environments, and real-time shell access with automatic reconnection. - - - - - -Mount S3-compatible object storage (R2, S3, GCS, and more) as local filesystems. Access buckets using standard file operations with data that persists across sandbox lifecycles. Production deployment required. - - - - - -Monitor files and directories for changes using native filesystem events. Perfect for building hot reloading development servers, build automation systems, and configuration monitoring tools. - - - - - -Block, allow, and intercept outbound HTTP from sandboxes. Keep credentials in your Worker by injecting authorization headers in outbound handlers. - - + + Get started with Dynamic Workers + --- -## Use Cases +## Containers -Build powerful applications with Sandbox: +[Containers](/containers/) run an image you provide. The instance is a full Linux environment, so you can use any language or runtime, install packages, compile code, and keep long-running processes. Your Worker can start the instance and send it work. -### AI Code Execution +The instance does not share a process or a kernel with your Worker, so it cannot read your Worker's memory. Other instances or customers cannot reach it. HTTP traffic from the Internet reaches it only through your Worker. -Execute code generated by Large Language Models safely and reliably. Native integration with [Workers AI](/workers-ai/) models like GPT-OSS enables function calling with sandbox execution. Perfect for AI agents, code assistants, and autonomous systems that need to run untrusted code. +Each instance runs in Firecracker: a microVM with its own kernel and network. Your image is a Linux container inside that VM, and no other workload shares it. -### Data Analysis & Notebooks + -Create interactive data analysis environments with pandas, NumPy, and Matplotlib. Generate charts, tables, and visualizations with automatic rich output formatting. +```ts +import { Container, getContainer } from "@cloudflare/containers"; -### Interactive Development Environments +export class MyContainer extends Container { + defaultPort = 4000; + sleepAfter = "10m"; +} -Build cloud IDEs, coding playgrounds, and collaborative development tools with full Linux environments and preview URLs. +export default { + async fetch(request: Request, env: Env): Promise { + const { "session-id": sessionId } = await request.json(); + const container = getContainer(env.MY_CONTAINER, sessionId); + return container.fetch(request); + }, +}; +``` -### CI/CD & Build Systems + -Run tests, compile code, and execute build pipelines in isolated environments with parallel execution and streaming logs. + + Get started with Containers + --- ## Related products - + -Serverless container runtime that powers Sandbox, enabling you to run any containerized workload on the edge. +The serverless platform these sandbox environments run on. - + -Run machine learning models and LLMs on the network. Combine with Sandbox for secure AI code execution workflows. +Identity and coordination for an attached container. - + -Stateful coordination layer that enables Sandbox to maintain persistent environments with strong consistency. +Run models on Cloudflare, then execute the code they generate in a sandbox. @@ -323,83 +141,42 @@ Stateful coordination layer that enables Sandbox to maintain persistent environm ## More resources -## Coding agents - -Install [Cloudflare Skills](https://github.com/cloudflare/skills) for your agent ([Agent setup](/agent-setup/)). Use **`sandbox-stable`** with the main docs on this site while you are on the current stable package. Use **`sandbox-next`** for `@cloudflare/sandbox@next` (recommended for new projects). When you are ready to port an existing app, use **`sandbox-migrate-to-next`**. - - - Explore complete examples including AI code execution, data analysis, and - interactive environments. - - - - Deploy and keep package and image aligned. - - - - Learn how to solve specific problems and implement features with the Sandbox - SDK. - - - - Install `@cloudflare/sandbox@next` and prepare for the Sandbox SDK 1.0 - release. - - - - Explore the complete API documentation for the Sandbox SDK. + + Run model-generated JavaScript against typed tools in a sandbox. - - Learn about the key concepts and architecture of the Sandbox SDK. + + TypeScript API for commands, files, and preview URLs on Containers. - Learn about the configuration options for the Sandbox SDK. + V8 isolates, process sandboxes, and the APIs a Worker can use. - View the SDK source code, report issues, and contribute to the project. + Requests, CPU time, and unique Dynamic Workers created per day. - Understand Sandbox pricing based on the underlying Containers platform. - - - - Learn about resource limits, quotas, and best practices for working within - them. + vCPU, memory, disk, and egress for container instances. - - Connect with the community on Discord. Ask questions, share what you're - building, and get help from other developers. + + Container instance types, image size, and other platform limits. diff --git a/src/content/docs/sandbox/api/backups.mdx b/src/content/docs/sandbox/sdk/api/backups.mdx similarity index 90% rename from src/content/docs/sandbox/api/backups.mdx rename to src/content/docs/sandbox/sdk/api/backups.mdx index 1504e274d8e..09ea3ccce65 100644 --- a/src/content/docs/sandbox/api/backups.mdx +++ b/src/content/docs/sandbox/sdk/api/backups.mdx @@ -12,7 +12,7 @@ import { TypeScriptExample } from "~/components"; Create point-in-time snapshots of sandbox directories and restore them from R2. -For setup, restore workflows, and generated-cache exclusions, refer to [Backup and restore](/sandbox/guides/backup-restore/). For overlay semantics, refer to [Directory backups](/sandbox/concepts/backup-restore/). +For setup, restore workflows, and generated-cache exclusions, refer to [Backup and restore](/sandbox/sdk/guides/backup-restore/). For overlay semantics, refer to [Directory backups](/sandbox/sdk/concepts/backup-restore/). ## Methods @@ -77,11 +77,11 @@ With `localBucket: true`: - `BackupCreateError` - If archive creation or the upload to R2 fails :::note[R2 binding required] -Configure a `BACKUP_BUCKET` R2 binding in `wrangler.jsonc` before using backup methods. Production also requires `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `CLOUDFLARE_ACCOUNT_ID`, and `BACKUP_BUCKET_NAME`. Refer to [Backup and restore](/sandbox/guides/backup-restore/#prerequisites). +Configure a `BACKUP_BUCKET` R2 binding in `wrangler.jsonc` before using backup methods. Production also requires `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `CLOUDFLARE_ACCOUNT_ID`, and `BACKUP_BUCKET_NAME`. Refer to [Backup and restore](/sandbox/sdk/guides/backup-restore/#prerequisites). ::: :::caution[Path permissions] -`mksquashfs` must read every file and subdirectory in `dir`. Restrictive permissions fail with `BackupCreateError`. Refer to [Fix path permissions](/sandbox/guides/backup-restore/#fix-path-permissions). +`mksquashfs` must read every file and subdirectory in `dir`. Restrictive permissions fail with `BackupCreateError`. Refer to [Fix path permissions](/sandbox/sdk/guides/backup-restore/#fix-path-permissions). ::: :::caution[Partial writes] @@ -138,7 +138,7 @@ With `localBucket: true`: - `BackupRestoreError` - If the container fails to restore :::note[Copy-on-write] -In production, the backup is a read-only lower layer and new writes go to a writable upper layer. In local development, the directory is replaced. For overlay constraints, refer to [Directory backups](/sandbox/concepts/backup-restore/). +In production, the backup is a read-only lower layer and new writes go to a writable upper layer. In local development, the directory is replaced. For overlay constraints, refer to [Directory backups](/sandbox/sdk/concepts/backup-restore/). ::: :::caution[Ephemeral mount] @@ -181,7 +181,7 @@ interface BackupOptions { - `name` (optional) - Human-readable name. Maximum 256 characters. No control characters. - `ttl` (optional) - Time-to-live in seconds. Default: `259200` (3 days). Must be a positive number. - `gitignore` (optional) - When `true`, exclude `.gitignore` matches if `dir` is inside a git repository. Default: `false`. -- `excludes` (optional) - Glob patterns to omit. Example: `['node_modules/.cache', '*.log']`. Refer to [Exclude generated caches](/sandbox/guides/backup-restore/#exclude-generated-caches). +- `excludes` (optional) - Glob patterns to omit. Example: `['node_modules/.cache', '*.log']`. Refer to [Exclude generated caches](/sandbox/sdk/guides/backup-restore/#exclude-generated-caches). - `localBucket` (optional) - Use the `BACKUP_BUCKET` binding instead of presigned URLs. Default: `false`. - `compression` (optional) - `format` defaults to `lz4`. `threads` defaults to `8`. - `multipart` (optional) - Parallel multipart upload. Default: `true`. @@ -220,8 +220,8 @@ interface RestoreBackupResult { ## Related resources -- [Backup and restore](/sandbox/guides/backup-restore/) - Setup and restore workflows -- [Directory backups](/sandbox/concepts/backup-restore/) - Overlay restore and `EXDEV` -- [Storage API](/sandbox/api/storage/) - Mount S3-compatible buckets -- [Files API](/sandbox/api/files/) - Read and write files -- [Wrangler configuration](/sandbox/configuration/wrangler/) - Configure bindings +- [Backup and restore](/sandbox/sdk/guides/backup-restore/) - Setup and restore workflows +- [Directory backups](/sandbox/sdk/concepts/backup-restore/) - Overlay restore and `EXDEV` +- [Storage API](/sandbox/sdk/api/storage/) - Mount S3-compatible buckets +- [Files API](/sandbox/sdk/api/files/) - Read and write files +- [Wrangler configuration](/sandbox/sdk/configuration/wrangler/) - Configure bindings diff --git a/src/content/docs/sandbox/api/commands.mdx b/src/content/docs/sandbox/sdk/api/commands.mdx similarity index 92% rename from src/content/docs/sandbox/api/commands.mdx rename to src/content/docs/sandbox/sdk/api/commands.mdx index 44374911da1..43072ef67fc 100644 --- a/src/content/docs/sandbox/api/commands.mdx +++ b/src/content/docs/sandbox/sdk/api/commands.mdx @@ -12,12 +12,6 @@ import { Details, TypeScriptExample } from "~/components"; Execute commands and manage background processes in the sandbox's isolated container environment. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents today's stable `@cloudflare/sandbox` package (`exec` with string commands and buffered results, plus `startProcess` / `execStream`). - -**Sandbox SDK 1.0** (preview on `@cloudflare/sandbox@next`) makes `exec()` argv-only and returns a process handle. Start new work on the preview when you can. Refer to [Process execution](/sandbox/1-0-preview/processes/), the [Processes API](/sandbox/1-0-preview/api/processes/), or [migrate to the preview](/sandbox/1-0-preview/migrate/). -::: - ## Methods ### `exec()` @@ -81,9 +75,9 @@ await sandbox.exec('python process_login.py', { :::note[Timeout behavior] -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()`](/sandbox/api/sessions/#deletesession) or destroy the sandbox with [`destroy()`](/sandbox/api/lifecycle/#destroy). +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()`](/sandbox/sdk/api/sessions/#deletesession) or destroy the sandbox with [`destroy()`](/sandbox/sdk/api/lifecycle/#destroy). -Timeout precedence: per-command `timeout` on `exec()` > session-level `commandTimeoutMs` on [`createSession()`](/sandbox/api/sessions/#createsession) > global [`COMMAND_TIMEOUT_MS`](/sandbox/configuration/environment-variables/#command_timeout_ms) environment variable. If none are set, commands run without a timeout. +Timeout precedence: per-command `timeout` on `exec()` > session-level `commandTimeoutMs` on [`createSession()`](/sandbox/sdk/api/sessions/#createsession) > global [`COMMAND_TIMEOUT_MS`](/sandbox/sdk/configuration/environment-variables/#command_timeout_ms) environment variable. If none are set, commands run without a timeout. ::: ### `execStream()` @@ -496,5 +490,5 @@ const result = await build.waitForExit(60000); // 60 second timeout ## Related resources -- [Background processes guide](/sandbox/guides/background-processes/) - Managing long-running processes -- [Files API](/sandbox/api/files/) - File operations +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Managing long-running processes +- [Files API](/sandbox/sdk/api/files/) - File operations diff --git a/src/content/docs/sandbox/api/file-watching.mdx b/src/content/docs/sandbox/sdk/api/file-watching.mdx similarity index 92% rename from src/content/docs/sandbox/api/file-watching.mdx rename to src/content/docs/sandbox/sdk/api/file-watching.mdx index 602e8e970ca..39dcf7e3ea1 100644 --- a/src/content/docs/sandbox/api/file-watching.mdx +++ b/src/content/docs/sandbox/sdk/api/file-watching.mdx @@ -10,12 +10,6 @@ products: import { TypeScriptExample } from "~/components"; -:::note[Coming soon: Sandbox SDK 1.0] -This page documents file watching on today's stable `@cloudflare/sandbox` package, including `sessionId` and session helpers. - -On the **1.0 preview** (`@next`), `watch` remains available without sessions. Refer to [Migrate](/sandbox/1-0-preview/migrate/) for the sessionless execution model. -::: - Monitor filesystem changes in real-time using Linux's native inotify system. The `watch()` method returns a Server-Sent Events (SSE) stream of file change events that you consume with `parseSSEStream()`. ## Methods @@ -217,5 +211,5 @@ All paths must exist when starting a watch. Watching non-existent paths returns ## Related resources -- [Watch filesystem changes guide](/sandbox/guides/file-watching/) — Patterns, best practices, and real-world examples -- [Manage files guide](/sandbox/guides/manage-files/) — File operations +- [Watch filesystem changes guide](/sandbox/sdk/guides/file-watching/) — Patterns, best practices, and real-world examples +- [Manage files guide](/sandbox/sdk/guides/manage-files/) — File operations diff --git a/src/content/docs/sandbox/api/files.mdx b/src/content/docs/sandbox/sdk/api/files.mdx similarity index 88% rename from src/content/docs/sandbox/api/files.mdx rename to src/content/docs/sandbox/sdk/api/files.mdx index 89694542f8e..cbdfbf6d902 100644 --- a/src/content/docs/sandbox/api/files.mdx +++ b/src/content/docs/sandbox/sdk/api/files.mdx @@ -43,7 +43,7 @@ When using `encoding: 'base64'`, content must contain only valid base64 characte #### Large files and binary data -When using the [`rpc` transport](/sandbox/configuration/transport/) the `writeFile()` method supports passing a `ReadableStream` as the `content` parameter. This allows binary data and files greater than [32 MiB](/workers/runtime-apis/rpc/#limitations) to be written to the sandbox. It replaces the `"base64"` encoding option. +When using the [`rpc` transport](/sandbox/sdk/configuration/transport/) the `writeFile()` method supports passing a `ReadableStream` as the `content` parameter. This allows binary data and files greater than [32 MiB](/workers/runtime-apis/rpc/#limitations) to be written to the sandbox. It replaces the `"base64"` encoding option. ```js // Requires SANDBOX_TRANSPORT to be "rpc" in wrangler.jsonc @@ -67,7 +67,7 @@ const file = await sandbox.readFile(path: string, options?: ReadFileOptions): Pr **Returns**: `Promise`. :::note[Encoding] -The `"none"` encoding property was added in 0.10.1 and aims to improve support for streaming binary data. When `encoding: "none"` is provided the `content` field will be a `ReadableStream`. It is only supported with the [RPC transport](/sandbox/configuration/transport/). +The `"none"` encoding property was added in 0.10.1 and aims to improve support for streaming binary data. When `encoding: "none"` is provided the `content` field will be a `ReadableStream`. It is only supported with the [RPC transport](/sandbox/sdk/configuration/transport/). ::: @@ -211,10 +211,6 @@ await sandbox.moveFile('/tmp/download.txt', '/workspace/data.txt'); ### `gitCheckout()` -:::note[Coming soon: Sandbox SDK 1.0] -On `@next`, `gitCheckout` is **removed**. Clone and other git operations with argv `exec` (for example `['git', 'clone', url, dir]`). See the [Processes API](/sandbox/1-0-preview/api/processes/) and [Migrate](/sandbox/1-0-preview/migrate/). -::: - Clone a git repository. ```ts @@ -247,5 +243,5 @@ await sandbox.gitCheckout('https://github.com/facebook/react', { ## Related resources -- [Manage files guide](/sandbox/guides/manage-files/) - Detailed guide with best practices -- [Commands API](/sandbox/api/commands/) - Execute commands +- [Manage files guide](/sandbox/sdk/guides/manage-files/) - Detailed guide with best practices +- [Commands API](/sandbox/sdk/api/commands/) - Execute commands diff --git a/src/content/docs/sandbox/api/index.mdx b/src/content/docs/sandbox/sdk/api/index.mdx similarity index 67% rename from src/content/docs/sandbox/api/index.mdx rename to src/content/docs/sandbox/sdk/api/index.mdx index 0fcca18c702..94b5a7b63c2 100644 --- a/src/content/docs/sandbox/api/index.mdx +++ b/src/content/docs/sandbox/sdk/api/index.mdx @@ -10,35 +10,28 @@ products: import { LinkTitleCard, CardGrid } from "~/components"; -:::note[Coming soon: Sandbox SDK 1.0] -This is the API hub for today's stable `@cloudflare/sandbox` package. - -For **`@cloudflare/sandbox@next`**, use the [1.0 preview API reference](/sandbox/1-0-preview/api/). -::: - - The Sandbox SDK provides a comprehensive API for executing code, managing files, running processes, and exposing services in isolated sandboxes. - + Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources. - + Execute commands and stream output. Run scripts, manage background processes, and capture execution results. - + Read, write, and manage files in the sandbox filesystem. Includes directory operations and file metadata. Monitor real-time filesystem changes using native inotify. Build development @@ -47,39 +40,39 @@ The Sandbox SDK provides a comprehensive API for executing code, managing files, Execute Python and JavaScript code with rich outputs including charts, tables, and formatted data. - + Expose services running in the sandbox via preview URLs. Access web servers and APIs from the internet. - + Expose services on zero-config `*.trycloudflare.com` URLs via `sandbox.tunnels.get(port)`. Best for quick development and `.workers.dev` deployments. - + Mount S3-compatible buckets (R2, S3, GCS) as local filesystems for persistent data storage across sandbox lifecycles. - + Create point-in-time snapshots of directories and restore them from R2. - + Create isolated execution contexts within a sandbox. Each session maintains its own shell state, environment variables, and working directory. - + Connect browser-based terminal UIs to sandbox shells via WebSocket, with the xterm.js SandboxAddon for automatic reconnection and resize handling. diff --git a/src/content/docs/sandbox/api/interpreter.mdx b/src/content/docs/sandbox/sdk/api/interpreter.mdx similarity index 91% rename from src/content/docs/sandbox/api/interpreter.mdx rename to src/content/docs/sandbox/sdk/api/interpreter.mdx index 2b8e25f2956..751a53ab26e 100644 --- a/src/content/docs/sandbox/api/interpreter.mdx +++ b/src/content/docs/sandbox/sdk/api/interpreter.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; Execute Python, JavaScript, and TypeScript code with support for data visualizations, tables, and rich output formats. Contexts maintain state (variables, imports, functions) across executions. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents interpreter methods on today's stable `@cloudflare/sandbox` package. - -In the **1.0 preview** (`@next`), attach `withInterpreter` from `@cloudflare/sandbox/interpreter`. Refer to [Code interpreter](/sandbox/1-0-preview/interpreter/) and the [Interpreter API](/sandbox/1-0-preview/api/interpreter/). -::: - ## Methods ### `createCodeContext()` @@ -224,6 +218,6 @@ if (result.results[0]?.html) { ## Related resources -- [Build an AI Code Executor](/sandbox/tutorials/ai-code-executor/) - Complete tutorial -- [Commands API](/sandbox/api/commands/) - Lower-level command execution -- [Files API](/sandbox/api/files/) - File operations +- [Build an AI Code Executor](/sandbox/sdk/tutorials/ai-code-executor/) - Complete tutorial +- [Commands API](/sandbox/sdk/api/commands/) - Lower-level command execution +- [Files API](/sandbox/sdk/api/files/) - File operations diff --git a/src/content/docs/sandbox/api/lifecycle.mdx b/src/content/docs/sandbox/sdk/api/lifecycle.mdx similarity index 81% rename from src/content/docs/sandbox/api/lifecycle.mdx rename to src/content/docs/sandbox/sdk/api/lifecycle.mdx index 6fa08103751..b61e3b1dc8c 100644 --- a/src/content/docs/sandbox/api/lifecycle.mdx +++ b/src/content/docs/sandbox/sdk/api/lifecycle.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents lifecycle helpers on today's stable `@cloudflare/sandbox` package. - -In the **1.0 preview** (`@next`), remove transport options on `getSandbox()` and do not rely on `enableDefaultSession`. Keep `sleepAfter`, `keepAlive`, `containerTimeouts`, `normalizeId`, and `destroy` when you need them. Process and terminal handles are container-local after stop or replace. Refer to [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) and [Migrate](/sandbox/1-0-preview/migrate/). -::: - ## Methods ### `getSandbox()` @@ -35,7 +29,7 @@ const sandbox = getSandbox( **Parameters**: - `binding` - The Durable Object namespace binding from your Worker environment - `sandboxId` - Unique identifier for this sandbox. The same ID always returns the same sandbox instance. In user-facing apps, scope IDs to a single user. -- `options` (optional) - See [SandboxOptions](/sandbox/configuration/sandbox-options/) for all available options: +- `options` (optional) - See [SandboxOptions](/sandbox/sdk/configuration/sandbox-options/) for all available options: - `enableDefaultSession` - Use the default session for operations without an explicit `sessionId`. Set to `false` to evaluate each call in isolation (default: `true`) - `sleepAfter` - Duration of inactivity before automatic sleep (default: `"10m"`) - `keepAlive` - Prevent automatic sleep entirely. Persists across hibernation (default: `false`) @@ -45,7 +39,7 @@ const sandbox = getSandbox( **Returns**: `Sandbox` instance :::note -The container starts lazily on first operation. Calling `getSandbox()` returns immediately—the container only spins up when you execute a command, write a file, or perform other operations. See [Sandbox lifecycle](/sandbox/concepts/sandboxes/) for details. +The container starts lazily on first operation. Calling `getSandbox()` returns immediately—the container only spins up when you execute a command, write a file, or perform other operations. See [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) for details. ::: :::note[Implicit execution mode] @@ -146,6 +140,6 @@ Containers automatically sleep after 10 minutes of inactivity but still count to ## Related resources -- [Sandbox lifecycle concept](/sandbox/concepts/sandboxes/) - Understanding container lifecycle and state -- [Sandbox options configuration](/sandbox/configuration/sandbox-options/) - Configure `keepAlive` and other options -- [Sessions API](/sandbox/api/sessions/) - Create execution contexts within a sandbox +- [Sandbox lifecycle concept](/sandbox/sdk/concepts/sandboxes/) - Understanding container lifecycle and state +- [Sandbox options configuration](/sandbox/sdk/configuration/sandbox-options/) - Configure `keepAlive` and other options +- [Sessions API](/sandbox/sdk/api/sessions/) - Create execution contexts within a sandbox diff --git a/src/content/docs/sandbox/api/ports.mdx b/src/content/docs/sandbox/sdk/api/ports.mdx similarity index 86% rename from src/content/docs/sandbox/api/ports.mdx rename to src/content/docs/sandbox/sdk/api/ports.mdx index 33f09cd6ebd..bb49563f4a9 100644 --- a/src/content/docs/sandbox/api/ports.mdx +++ b/src/content/docs/sandbox/sdk/api/ports.mdx @@ -10,21 +10,15 @@ products: import { TypeScriptExample } from "~/components"; -:::note[Coming soon: Sandbox SDK 1.0] -This page documents ports and preview URLs on today's stable `@cloudflare/sandbox` package. - -Examples that use `startProcess` are stable-only. On **`@next`**, start services with `exec(argv)` then `waitForPort` / expose or tunnels — [Process execution](/sandbox/1-0-preview/processes/) and [Migrate](/sandbox/1-0-preview/migrate/). -::: - :::note[Production requires custom domain] -Preview URLs require a custom domain with wildcard DNS routing in production. See [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/). +Preview URLs require a custom domain with wildcard DNS routing in production. See [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/). ::: :::note[Prefer `sandbox.tunnels` for public URLs] -For most public-URL use cases — development, `.workers.dev` deployments, and production traffic — [`sandbox.tunnels`](/sandbox/api/tunnels/) is the recommended option. Use named tunnels for stable hostnames on a zone you control, or quick tunnels for zero-config `*.trycloudflare.com` URLs. `exposePort()` is appropriate when you want the Worker itself to front the request (for example, to inject authentication, rewrite responses, or call sandbox-only RPC methods on the same hostname). +For most public-URL use cases — development, `.workers.dev` deployments, and production traffic — [`sandbox.tunnels`](/sandbox/sdk/api/tunnels/) is the recommended option. Use named tunnels for stable hostnames on a zone you control, or quick tunnels for zero-config `*.trycloudflare.com` URLs. `exposePort()` is appropriate when you want the Worker itself to front the request (for example, to inject authentication, rewrite responses, or call sandbox-only RPC methods on the same hostname). ::: -Expose services running in your sandbox via public preview URLs. See [Preview URLs concept](/sandbox/concepts/preview-urls/) for details. +Expose services running in your sandbox via public preview URLs. See [Preview URLs concept](/sandbox/sdk/concepts/preview-urls/) for details. ## Module functions @@ -132,7 +126,7 @@ const frontend = await sandbox.exposePort(5173, { :::note[Local development] -When using `wrangler dev`, you must add `EXPOSE` directives to your Dockerfile for each port. See [Expose Services guide](/sandbox/guides/expose-services/#local-development) for details. +When using `wrangler dev`, you must add `EXPOSE` directives to your Dockerfile for each port. See [Expose Services guide](/sandbox/sdk/guides/expose-services/#local-development) for details. ::: ## Custom Tokens for Stable URLs @@ -257,7 +251,7 @@ Connect to WebSocket servers running in the sandbox. Use this when your Worker n - Route incoming WebSocket upgrade requests with custom authentication or authorization - Connect from your Worker to get real-time data from sandbox services -For exposing WebSocket services via public preview URLs, use `exposePort()` with `proxyToSandbox()` instead. See [WebSocket Connections guide](/sandbox/guides/websocket-connections/) for examples. +For exposing WebSocket services via public preview URLs, use `exposePort()` with `proxyToSandbox()` instead. See [WebSocket Connections guide](/sandbox/sdk/guides/websocket-connections/) for examples. ```ts const response = await sandbox.wsConnect(request: Request, port: number): Promise @@ -291,9 +285,9 @@ export default { ## Related resources -- [Preview URLs concept](/sandbox/concepts/preview-urls/) - How preview URLs work -- [Expose Services guide](/sandbox/guides/expose-services/) - Full workflow for starting services, exposing ports, and routing requests -- [WebSocket Connections guide](/sandbox/guides/websocket-connections/) - WebSocket routing via preview URLs -- [Commands API](/sandbox/api/commands/) - Start background processes -- [Tunnels API](/sandbox/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for quick development +- [Preview URLs concept](/sandbox/sdk/concepts/preview-urls/) - How preview URLs work +- [Expose Services guide](/sandbox/sdk/guides/expose-services/) - Full workflow for starting services, exposing ports, and routing requests +- [WebSocket Connections guide](/sandbox/sdk/guides/websocket-connections/) - WebSocket routing via preview URLs +- [Commands API](/sandbox/sdk/api/commands/) - Start background processes +- [Tunnels API](/sandbox/sdk/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for quick development ``` diff --git a/src/content/docs/sandbox/api/sessions.mdx b/src/content/docs/sandbox/sdk/api/sessions.mdx similarity index 72% rename from src/content/docs/sandbox/api/sessions.mdx rename to src/content/docs/sandbox/sdk/api/sessions.mdx index 37b669b03aa..42ed516627e 100644 --- a/src/content/docs/sandbox/api/sessions.mdx +++ b/src/content/docs/sandbox/sdk/api/sessions.mdx @@ -10,16 +10,10 @@ products: import { TypeScriptExample } from "~/components"; -Create shell sessions within a sandbox. Each session maintains its own shell state, environment variables, and working directory, while sharing the sandbox filesystem and process space. For more information, refer to [Session management](/sandbox/concepts/sessions/). - -:::note[Coming soon: Sandbox SDK 1.0] -This page documents today's stable `@cloudflare/sandbox` package. - -**Sandbox SDK 1.0** (preview on `@next`) removes core session execution APIs (`createSession`, `ExecutionSession`, default sessions). Pass `cwd` and `env` on each `exec`, or use one explicit shell argv script. Refer to [Process execution](/sandbox/1-0-preview/processes/) or [migrate](/sandbox/1-0-preview/migrate/#drop-session-apis). -::: +Create shell sessions within a sandbox. Each session maintains its own shell state, environment variables, and working directory, while sharing the sandbox filesystem and process space. For more information, refer to [Session management](/sandbox/sdk/concepts/sessions/). :::note -By default, for backwards compatibility, every sandbox has a default session that maintains shell state. It is recommended to set `enableDefaultSession` to `false` on `getSandbox()` so operations without an explicit `sessionId` run in isolation. Create additional sessions for separate workflows inside the same user workspace, such as development and runtime processes using the `createSession()` method. Use separate sandboxes for separate users. For sandbox-level operations like creating containers or destroying the entire sandbox, refer to the [Lifecycle API](/sandbox/api/lifecycle/). +By default, for backwards compatibility, every sandbox has a default session that maintains shell state. It is recommended to set `enableDefaultSession` to `false` on `getSandbox()` so operations without an explicit `sessionId` run in isolation. Create additional sessions for separate workflows inside the same user workspace, such as development and runtime processes using the `createSession()` method. Use separate sandboxes for separate users. For sandbox-level operations like creating containers or destroying the entire sandbox, refer to the [Lifecycle API](/sandbox/sdk/api/lifecycle/). ::: ## Methods @@ -190,14 +184,14 @@ The `ExecutionSession` object has all sandbox methods bound to the specific sess | Category | Methods | | -------- | ------- | -| **Commands** | [`exec()`](/sandbox/api/commands/#exec), [`execStream()`](/sandbox/api/commands/#execstream) | -| **Processes** | [`startProcess()`](/sandbox/api/commands/#startprocess), [`listProcesses()`](/sandbox/api/commands/#listprocesses), [`killProcess()`](/sandbox/api/commands/#killprocess), [`killAllProcesses()`](/sandbox/api/commands/#killallprocesses), [`getProcessLogs()`](/sandbox/api/commands/#getprocesslogs), [`streamProcessLogs()`](/sandbox/api/commands/#streamprocesslogs) | -| **Files** | [`writeFile()`](/sandbox/api/files/#writefile), [`readFile()`](/sandbox/api/files/#readfile), [`mkdir()`](/sandbox/api/files/#mkdir), [`deleteFile()`](/sandbox/api/files/#deletefile), [`renameFile()`](/sandbox/api/files/#renamefile), [`moveFile()`](/sandbox/api/files/#movefile), [`gitCheckout()`](/sandbox/api/files/#gitcheckout) | -| **Environment** | [`setEnvVars()`](/sandbox/api/sessions/#setenvvars) | -| **Terminal** | [`terminal()`](/sandbox/api/terminal/#terminal) | -| **Code Interpreter** | [`createCodeContext()`](/sandbox/api/interpreter/#createcodecontext), [`runCode()`](/sandbox/api/interpreter/#runcode), [`listCodeContexts()`](/sandbox/api/interpreter/#listcodecontexts), [`deleteCodeContext()`](/sandbox/api/interpreter/#deletecodecontext) | +| **Commands** | [`exec()`](/sandbox/sdk/api/commands/#exec), [`execStream()`](/sandbox/sdk/api/commands/#execstream) | +| **Processes** | [`startProcess()`](/sandbox/sdk/api/commands/#startprocess), [`listProcesses()`](/sandbox/sdk/api/commands/#listprocesses), [`killProcess()`](/sandbox/sdk/api/commands/#killprocess), [`killAllProcesses()`](/sandbox/sdk/api/commands/#killallprocesses), [`getProcessLogs()`](/sandbox/sdk/api/commands/#getprocesslogs), [`streamProcessLogs()`](/sandbox/sdk/api/commands/#streamprocesslogs) | +| **Files** | [`writeFile()`](/sandbox/sdk/api/files/#writefile), [`readFile()`](/sandbox/sdk/api/files/#readfile), [`mkdir()`](/sandbox/sdk/api/files/#mkdir), [`deleteFile()`](/sandbox/sdk/api/files/#deletefile), [`renameFile()`](/sandbox/sdk/api/files/#renamefile), [`moveFile()`](/sandbox/sdk/api/files/#movefile), [`gitCheckout()`](/sandbox/sdk/api/files/#gitcheckout) | +| **Environment** | [`setEnvVars()`](/sandbox/sdk/api/sessions/#setenvvars) | +| **Terminal** | [`terminal()`](/sandbox/sdk/api/terminal/#terminal) | +| **Code Interpreter** | [`createCodeContext()`](/sandbox/sdk/api/interpreter/#createcodecontext), [`runCode()`](/sandbox/sdk/api/interpreter/#runcode), [`listCodeContexts()`](/sandbox/sdk/api/interpreter/#listcodecontexts), [`deleteCodeContext()`](/sandbox/sdk/api/interpreter/#deletecodecontext) | ## Related resources -- [Session management concept](/sandbox/concepts/sessions/) - How sessions work -- [Commands API](/sandbox/api/commands/) - Execute commands +- [Session management concept](/sandbox/sdk/concepts/sessions/) - How sessions work +- [Commands API](/sandbox/sdk/api/commands/) - Execute commands diff --git a/src/content/docs/sandbox/api/storage.mdx b/src/content/docs/sandbox/sdk/api/storage.mdx similarity index 96% rename from src/content/docs/sandbox/api/storage.mdx rename to src/content/docs/sandbox/sdk/api/storage.mdx index e3ea08dcde3..a4429591d9f 100644 --- a/src/content/docs/sandbox/api/storage.mdx +++ b/src/content/docs/sandbox/sdk/api/storage.mdx @@ -77,7 +77,7 @@ Authentication depends on the mount mode: Endpoint-based mounts remain supported for explicit R2 endpoint configuration and for other S3-compatible providers. -See the [Mount Buckets guide](/sandbox/guides/mount-buckets/) for detailed authentication options. +See the [Mount Buckets guide](/sandbox/sdk/guides/mount-buckets/) for detailed authentication options. ::: ### `unmountBucket()` @@ -206,5 +206,5 @@ type BucketProvider = "r2" | "s3" | "gcs"; ## Related resources -- [Mount Buckets guide](/sandbox/guides/mount-buckets/) - Complete bucket mounting walkthrough -- [Files API](/sandbox/api/files/) - Read and write files +- [Mount Buckets guide](/sandbox/sdk/guides/mount-buckets/) - Complete bucket mounting walkthrough +- [Files API](/sandbox/sdk/api/files/) - Read and write files diff --git a/src/content/docs/sandbox/api/terminal.mdx b/src/content/docs/sandbox/sdk/api/terminal.mdx similarity index 88% rename from src/content/docs/sandbox/api/terminal.mdx rename to src/content/docs/sandbox/sdk/api/terminal.mdx index 3b164f90f77..f8a67d4a845 100644 --- a/src/content/docs/sandbox/api/terminal.mdx +++ b/src/content/docs/sandbox/sdk/api/terminal.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; Connect browser-based terminal UIs to sandbox shells via WebSocket. The server-side `terminal()` method proxies WebSocket connections to the container, and the client-side `SandboxAddon` integrates with xterm.js for terminal rendering. -:::note[Sandbox SDK 1.0 preview] -This page documents terminal helpers on today's stable `@cloudflare/sandbox` package. - -On **`@cloudflare/sandbox@next`**, terminals use `createTerminal`, `getTerminal`, and `terminal.connect`, with xterm `terminalId`. Refer to [Terminals](/sandbox/1-0-preview/terminals/) and [Terminals API](/sandbox/1-0-preview/api/terminals/). -::: - ## Server-side methods ### `terminal()` @@ -44,7 +38,7 @@ return await sandbox.terminal(request, { cols: 120, rows: 30 }); ``` -Works with both [default and explicitly created sessions](/sandbox/concepts/sessions/): +Works with both [default and explicitly created sessions](/sandbox/sdk/concepts/sessions/): ```ts @@ -139,7 +133,7 @@ addon.disconnect(): void ## WebSocket protocol -The `SandboxAddon` handles the WebSocket protocol automatically. These details are for building custom terminal clients without the addon. For a complete example, refer to [Connect without xterm.js](/sandbox/guides/browser-terminals/#connect-without-xtermjs). +The `SandboxAddon` handles the WebSocket protocol automatically. These details are for building custom terminal clients without the addon. For a complete example, refer to [Connect without xterm.js](/sandbox/sdk/guides/browser-terminals/#connect-without-xtermjs). ### Connection lifecycle @@ -209,7 +203,7 @@ interface SandboxAddonOptions { ## Related resources -- [Terminal connections](/sandbox/concepts/terminal/) — How terminal connections work -- [Browser terminals](/sandbox/guides/browser-terminals/) — Step-by-step setup guide -- [Sessions API](/sandbox/api/sessions/) — Session management -- [Commands API](/sandbox/api/commands/) — Non-interactive command execution +- [Terminal connections](/sandbox/sdk/concepts/terminal/) — How terminal connections work +- [Browser terminals](/sandbox/sdk/guides/browser-terminals/) — Step-by-step setup guide +- [Sessions API](/sandbox/sdk/api/sessions/) — Session management +- [Commands API](/sandbox/sdk/api/commands/) — Non-interactive command execution diff --git a/src/content/docs/sandbox/api/tunnels.mdx b/src/content/docs/sandbox/sdk/api/tunnels.mdx similarity index 96% rename from src/content/docs/sandbox/api/tunnels.mdx rename to src/content/docs/sandbox/sdk/api/tunnels.mdx index 9f2ef9805b7..fdcb819750a 100644 --- a/src/content/docs/sandbox/api/tunnels.mdx +++ b/src/content/docs/sandbox/sdk/api/tunnels.mdx @@ -18,14 +18,14 @@ Two flavors are available: - **Named tunnels** (`sandbox.tunnels.get(port, { name })`) — bind a stable hostname `.` on a zone you control. The hostname survives container restarts and is shared across sandboxes that request the same `name`. Requires a Cloudflare API token, an account, and a zone. :::note[When to use quick vs. named tunnels] -Use **quick tunnels** for local development, demos, and short-lived `.workers.dev` deployments where you do not need a stable URL. Use **named tunnels** for everything else — they are the recommended option for production traffic, webhook receivers, OAuth callbacks, and any URL that needs to be bookmarked. [`exposePort()`](/sandbox/api/ports/) remains an alternative when you want the Worker itself (rather than Cloudflare's edge) to front the request. +Use **quick tunnels** for local development, demos, and short-lived `.workers.dev` deployments where you do not need a stable URL. Use **named tunnels** for everything else — they are the recommended option for production traffic, webhook receivers, OAuth callbacks, and any URL that needs to be bookmarked. [`exposePort()`](/sandbox/sdk/api/ports/) remains an alternative when you want the Worker itself (rather than Cloudflare's edge) to front the request. ::: ## Requirements Both tunnel flavors require: -- **RPC transport.** Calling `sandbox.tunnels` on HTTP/Websocket transports throws `"RPC transport required"`. See [Transport configuration](/sandbox/configuration/transport/). +- **RPC transport.** Calling `sandbox.tunnels` on HTTP/Websocket transports throws `"RPC transport required"`. See [Transport configuration](/sandbox/sdk/configuration/transport/). Named tunnels additionally require a Cloudflare API token, account, and zone — refer to [Named tunnels: prerequisites](#prerequisites). @@ -363,7 +363,7 @@ curl "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/cfd_t ## Related resources -- [Preview URLs concept](/sandbox/concepts/preview-urls/) — Worker-fronted preview URLs and how they differ from quick tunnels. -- [Ports API](/sandbox/api/ports/) — `exposePort()` and the Worker-fronted preview URL flow. -- [Expose services guide](/sandbox/guides/expose-services/) — End-to-end walkthrough for exposing services in production. -- [Transport configuration](/sandbox/configuration/transport/) — RPC vs. route-based transport. +- [Preview URLs concept](/sandbox/sdk/concepts/preview-urls/) — Worker-fronted preview URLs and how they differ from quick tunnels. +- [Ports API](/sandbox/sdk/api/ports/) — `exposePort()` and the Worker-fronted preview URL flow. +- [Expose services guide](/sandbox/sdk/guides/expose-services/) — End-to-end walkthrough for exposing services in production. +- [Transport configuration](/sandbox/sdk/configuration/transport/) — RPC vs. route-based transport. diff --git a/src/content/docs/sandbox/bridge/http-api.mdx b/src/content/docs/sandbox/sdk/bridge/http-api.mdx similarity index 94% rename from src/content/docs/sandbox/bridge/http-api.mdx rename to src/content/docs/sandbox/sdk/bridge/http-api.mdx index c93610db41a..0f1b364e350 100644 --- a/src/content/docs/sandbox/bridge/http-api.mdx +++ b/src/content/docs/sandbox/sdk/bridge/http-api.mdx @@ -12,11 +12,7 @@ products: import { WranglerConfig } from "~/components"; -:::note[Sandbox SDK 1.0 preview] -This is the supported bridge HTTP API. The 1.0 preview covers the Worker SDK on `@next`; the bridge stays on this stable template and route surface. -::: - -This page documents every route exposed by the [sandbox bridge](/sandbox/bridge/) on the stable template. +This page documents every route exposed by the [sandbox bridge](/sandbox/sdk/bridge/) on the stable template. ## Authentication @@ -211,6 +207,6 @@ A cron trigger (`* * * * *`) primes the pool automatically after deployment. Set ## Related resources -- [Bridge overview](/sandbox/bridge/) — What the bridge is, deployment, and usage examples. -- [Sandbox API reference](/sandbox/api/) — Complete Sandbox SDK method reference. +- [Bridge overview](/sandbox/sdk/bridge/) — What the bridge is, deployment, and usage examples. +- [Sandbox API reference](/sandbox/sdk/api/) — Complete Sandbox SDK method reference. - [Bridge source on GitHub](https://github.com/cloudflare/sandbox-sdk/tree/main/bridge) — Worker, Dockerfile, and OpenAPI schema. diff --git a/src/content/docs/sandbox/bridge/index.mdx b/src/content/docs/sandbox/sdk/bridge/index.mdx similarity index 86% rename from src/content/docs/sandbox/bridge/index.mdx rename to src/content/docs/sandbox/sdk/bridge/index.mdx index f076912d483..ffd77f9d1ad 100644 --- a/src/content/docs/sandbox/bridge/index.mdx +++ b/src/content/docs/sandbox/sdk/bridge/index.mdx @@ -15,11 +15,7 @@ products: import { Details, Tabs, TabItem } from "~/components"; -:::note[Sandbox SDK 1.0 preview] -This is the supported self-deployed bridge. The 1.0 preview covers the Worker SDK on `@next`; the bridge stays on this stable template, package line, and HTTP API. -::: - -The sandbox bridge is a reference-implementation Cloudflare Worker that exposes the [Sandbox SDK](/sandbox/api/) as an HTTP API. Any HTTP client — Python script, Node.js service, CI pipeline — can create and control sandboxes without writing a Worker. You deploy the Worker in **your** account; it is not a Cloudflare-hosted shared API. +The sandbox bridge is a reference-implementation Cloudflare Worker that exposes the [Sandbox SDK](/sandbox/sdk/api/) as an HTTP API. Any HTTP client — Python script, Node.js service, CI pipeline — can create and control sandboxes without writing a Worker. You deploy the Worker in **your** account; it is not a Cloudflare-hosted shared API. ## Why use the bridge @@ -27,7 +23,7 @@ The Sandbox SDK is designed for use within Cloudflare Workers. If your applicati The bridge exposes the Sandbox SDK as a standard HTTP API so you can create and control sandboxes from any language or platform. -Key [Sandbox SDK methods](/sandbox/api/) map to individual HTTP endpoints. The bridge adds authentication, input validation, workspace path containment, and an optional [warm pool](/sandbox/bridge/http-api/#warm-pool) for instant container boot. +Key [Sandbox SDK methods](/sandbox/sdk/api/) map to individual HTTP endpoints. The bridge adds authentication, input validation, workspace path containment, and an optional [warm pool](/sandbox/sdk/bridge/http-api/#warm-pool) for instant container boot. ## Deploy @@ -311,8 +307,8 @@ The bridge source code and examples are available on GitHub: ## Related resources -- [HTTP API reference](/sandbox/bridge/http-api/) — Complete route reference for the bridge API. -- [Getting started](/sandbox/get-started/) — Build your first sandbox application directly on Workers. -- [Architecture](/sandbox/concepts/architecture/) — How the Sandbox SDK layers Workers, Durable Objects, and Containers. -- [API reference](/sandbox/api/) — Complete Sandbox SDK method reference. -- [OpenAI Agents SDK tutorial](/sandbox/tutorials/openai-agents/) — Build a Python coding agent with the bridge. +- [HTTP API reference](/sandbox/sdk/bridge/http-api/) — Complete route reference for the bridge API. +- [Getting started](/sandbox/sdk/get-started/) — Build your first sandbox application directly on Workers. +- [Architecture](/sandbox/sdk/concepts/architecture/) — How the Sandbox SDK layers Workers, Durable Objects, and Containers. +- [API reference](/sandbox/sdk/api/) — Complete Sandbox SDK method reference. +- [OpenAI Agents SDK tutorial](/sandbox/sdk/tutorials/openai-agents/) — Build a Python coding agent with the bridge. diff --git a/src/content/docs/sandbox/concepts/architecture.mdx b/src/content/docs/sandbox/sdk/concepts/architecture.mdx similarity index 92% rename from src/content/docs/sandbox/concepts/architecture.mdx rename to src/content/docs/sandbox/sdk/concepts/architecture.mdx index 96848024529..3bea91bd867 100644 --- a/src/content/docs/sandbox/concepts/architecture.mdx +++ b/src/content/docs/sandbox/sdk/concepts/architecture.mdx @@ -125,7 +125,7 @@ Enable RPC transport by setting the `SANDBOX_TRANSPORT` variable in your Worker' WebSocket transport is deprecated. Use RPC transport for new applications. -The transport layer is transparent to your application code — all SDK methods work identically regardless of transport. For details on when to use each transport and configuration examples, refer to [Transport modes](/sandbox/configuration/transport/). +The transport layer is transparent to your application code — all SDK methods work identically regardless of transport. For details on when to use each transport and configuration examples, refer to [Transport modes](/sandbox/sdk/configuration/transport/). ## Request flow @@ -153,7 +153,7 @@ The Durable Object establishes the persistent connection to the container on fir ## Related resources -- [Sandbox lifecycle](/sandbox/concepts/sandboxes/) - How sandboxes are created and managed -- [Container runtime](/sandbox/concepts/containers/) - Inside the execution environment -- [Security model](/sandbox/concepts/security/) - How isolation and validation work -- [Session management](/sandbox/concepts/sessions/) - Advanced state management +- [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) - How sandboxes are created and managed +- [Container runtime](/sandbox/sdk/concepts/containers/) - Inside the execution environment +- [Security model](/sandbox/sdk/concepts/security/) - How isolation and validation work +- [Session management](/sandbox/sdk/concepts/sessions/) - Advanced state management diff --git a/src/content/docs/sandbox/concepts/backup-restore.mdx b/src/content/docs/sandbox/sdk/concepts/backup-restore.mdx similarity index 76% rename from src/content/docs/sandbox/concepts/backup-restore.mdx rename to src/content/docs/sandbox/sdk/concepts/backup-restore.mdx index 98c26403ce1..14d41c8d50a 100644 --- a/src/content/docs/sandbox/concepts/backup-restore.mdx +++ b/src/content/docs/sandbox/sdk/concepts/backup-restore.mdx @@ -10,7 +10,7 @@ products: Backup and restore snapshot a sandbox directory into an R2 archive, then bring that tree back later. The public API is the same in production and in `wrangler dev`. The restore mechanism is not. -Use backups when you want a project directory such as `/workspace` to return later. Use [bucket mounts](/sandbox/guides/mount-buckets/) when a separate storage path such as `/data` should persist independently of the sandbox filesystem. +Use backups when you want a project directory such as `/workspace` to return later. Use [bucket mounts](/sandbox/sdk/guides/mount-buckets/) when a separate storage path such as `/data` should persist independently of the sandbox filesystem. ## Production restore @@ -33,10 +33,10 @@ Overlayfs treats the lower and upper layers as different devices. A rename that Vite does this with `node_modules/.vite/deps`. Omit that directory from the backup, or delete it after restore. -For the procedure, refer to [Exclude generated caches](/sandbox/guides/backup-restore/#exclude-generated-caches). +For the procedure, refer to [Exclude generated caches](/sandbox/sdk/guides/backup-restore/#exclude-generated-caches). ## Related resources -- [Backup and restore](/sandbox/guides/backup-restore/) - Create, restore, and exclude caches -- [Backups API](/sandbox/api/backups/) - Method signatures and options -- [Sandbox lifecycle](/sandbox/concepts/sandboxes/) - What happens when a sandbox sleeps +- [Backup and restore](/sandbox/sdk/guides/backup-restore/) - Create, restore, and exclude caches +- [Backups API](/sandbox/sdk/api/backups/) - Method signatures and options +- [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) - What happens when a sandbox sleeps diff --git a/src/content/docs/sandbox/concepts/containers.mdx b/src/content/docs/sandbox/sdk/concepts/containers.mdx similarity index 76% rename from src/content/docs/sandbox/concepts/containers.mdx rename to src/content/docs/sandbox/sdk/concepts/containers.mdx index 5c4f3a2484a..69a4c65e8e3 100644 --- a/src/content/docs/sandbox/concepts/containers.mdx +++ b/src/content/docs/sandbox/sdk/concepts/containers.mdx @@ -8,13 +8,7 @@ products: - sandbox --- -:::note[Coming soon: Sandbox SDK 1.0] -This page documents containers on today's stable `@cloudflare/sandbox` package. - -Examples that use `startProcess` apply to the stable package. On **`@next`**, long-running work uses `exec(argv)` process handles — [Process execution](/sandbox/1-0-preview/processes/). -::: - -Each sandbox runs in an isolated Linux container with Python, Node.js, and common development tools pre-installed. For a complete list of pre-installed software and how to customize the container image, see [Dockerfile reference](/sandbox/configuration/dockerfile/). +Each sandbox runs in an isolated Linux container with Python, Node.js, and common development tools pre-installed. For a complete list of pre-installed software and how to customize the container image, see [Dockerfile reference](/sandbox/sdk/configuration/dockerfile/). ## Runtime software installation @@ -82,7 +76,7 @@ console.log(exposed.url); // Public URL ``` :::note[Local development] -When using `wrangler dev`, you must add `EXPOSE` directives to your Dockerfile for each port. See [Local development with ports](/sandbox/guides/expose-services/#local-development). +When using `wrangler dev`, you must add `EXPOSE` directives to your Dockerfile for each port. See [Local development with ports](/sandbox/sdk/guides/expose-services/#local-development). ::: **Localhost** works within sandbox: @@ -114,9 +108,9 @@ const sandbox = getSandbox(env.Sandbox, `user-${userId}`); ## Related resources -- [Deploy a Sandbox application](/sandbox/guides/deploy/) - Deploy and keep package and image aligned +- [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/) - Deploy and keep package and image aligned - [Deploy Containers](/containers/guides/deploy/) - Containers deploy path -- [Architecture](/sandbox/concepts/architecture/) - How containers fit in the system -- [Security model](/sandbox/concepts/security/) - Container isolation details -- [Sandbox lifecycle](/sandbox/concepts/sandboxes/) - Container lifecycle management -- [Docker-in-Docker](/sandbox/guides/docker-in-docker/) - Run Docker containers inside a Sandbox +- [Architecture](/sandbox/sdk/concepts/architecture/) - How containers fit in the system +- [Security model](/sandbox/sdk/concepts/security/) - Container isolation details +- [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) - Container lifecycle management +- [Docker-in-Docker](/sandbox/sdk/guides/docker-in-docker/) - Run Docker containers inside a Sandbox diff --git a/src/content/docs/sandbox/sdk/concepts/index.mdx b/src/content/docs/sandbox/sdk/concepts/index.mdx new file mode 100644 index 00000000000..b447a294b78 --- /dev/null +++ b/src/content/docs/sandbox/sdk/concepts/index.mdx @@ -0,0 +1,26 @@ +--- +title: Concepts +description: Learn how the Sandbox SDK works, including architecture, lifecycle, security, and sessions. +pcx_content_type: navigation +sidebar: + order: 7 +products: + - sandbox +--- + +These pages explain how the Sandbox SDK works, why it's designed the way it is, and the concepts you need to understand to use it effectively. + +- [Architecture](/sandbox/sdk/concepts/architecture/) - How the SDK is structured and why +- [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) - Understanding sandbox states and behavior +- [Container runtime](/sandbox/sdk/concepts/containers/) - How code executes in isolated containers +- [Session management](/sandbox/sdk/concepts/sessions/) - When and how to use sessions +- [Preview URLs](/sandbox/sdk/concepts/preview-urls/) - How to expose sandboxed services on the public internet. +- [Security model](/sandbox/sdk/concepts/security/) - Isolation, validation, and safety mechanisms +- [Terminal connections](/sandbox/sdk/concepts/terminal/) - How browser terminal connections work +- [Directory backups](/sandbox/sdk/concepts/backup-restore/) - Overlay restore, local extract, and cross-device renames + +## Related resources + +- [Tutorials](/sandbox/sdk/tutorials/) - Learn by building complete applications +- [How-to guides](/sandbox/sdk/guides/) - Solve specific problems +- [API reference](/sandbox/sdk/api/) - Technical details and method signatures diff --git a/src/content/docs/sandbox/concepts/preview-urls.mdx b/src/content/docs/sandbox/sdk/concepts/preview-urls.mdx similarity index 89% rename from src/content/docs/sandbox/concepts/preview-urls.mdx rename to src/content/docs/sandbox/sdk/concepts/preview-urls.mdx index 8975df5fec3..accff49f406 100644 --- a/src/content/docs/sandbox/concepts/preview-urls.mdx +++ b/src/content/docs/sandbox/sdk/concepts/preview-urls.mdx @@ -32,14 +32,14 @@ Cloudflare Tunnel support currently has the following limitations: We are working on production deployments, custom hostnames and authentication for Cloudflare Tunnel support. In the mean time we recommend using `exposePort()` and `proxyToSandbox()` documented below under [Production usage, stable URLs and custom domains](#). ::: -See the [tunnels API reference](/sandbox/api/tunnels/) for the full API and feature set. +See the [tunnels API reference](/sandbox/sdk/api/tunnels/) for the full API and feature set. # Production usage, stable URLs & custom domains For production use we recommend using the `exposePort()` API and routing traffic through your worker. :::note[Custom domain for exposePort production URLs] -Local development does not need a custom domain or wildcard DNS for `exposePort()` preview URLs. For production, you need a custom domain with wildcard DNS routing. Refer to [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/). +Local development does not need a custom domain or wildcard DNS for `exposePort()` preview URLs. For production, you need a custom domain with wildcard DNS routing. Refer to [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/). ::: Preview URLs provide public HTTPS access to services running inside sandboxes. When you expose a port, you get a unique URL that proxies requests to your service. @@ -132,7 +132,7 @@ const sandbox = getSandbox(env.Sandbox, "MyProject-123", { Without `normalizeId: true`, `exposePort()` throws an error when the ID contains uppercase letters. -**Best practice**: Use lowercase IDs from the start (`'my-project-123'`). See [Sandbox options - normalizeId](/sandbox/configuration/sandbox-options/#normalizeid) for details. +**Best practice**: Use lowercase IDs from the start (`'my-project-123'`). See [Sandbox options - normalizeId](/sandbox/sdk/configuration/sandbox-options/#normalizeid) for details. ## Request Routing @@ -215,7 +215,7 @@ export default { }; ``` -For custom routing scenarios where your Worker needs to control which sandbox or port to connect to based on request properties, see `wsConnect()` in the [Ports API](/sandbox/api/ports/#wsconnect). +For custom routing scenarios where your Worker needs to control which sandbox or port to connect to based on request properties, see `wsConnect()` in the [Ports API](/sandbox/sdk/api/ports/#wsconnect). ## Security @@ -226,7 +226,7 @@ Preview URLs are publicly accessible by default, but require a valid access toke **Built-in security**: - **Token-based access** - Each exposed port gets a unique token in the URL (for example, `https://8080-sandbox-abc123token456.yourdomain.com`) -- **HTTPS in production** - All traffic is encrypted with TLS. Certificates are provisioned automatically for first-level wildcards (`*.yourdomain.com`). If your Worker runs on a subdomain, refer to the [TLS note for custom domains](/sandbox/guides/preview-urls-custom-domain/#subdomain-depth-matters-for-tls). +- **HTTPS in production** - All traffic is encrypted with TLS. Certificates are provisioned automatically for first-level wildcards (`*.yourdomain.com`). If your Worker runs on a subdomain, refer to the [TLS note for custom domains](/sandbox/sdk/guides/preview-urls-custom-domain/#subdomain-depth-matters-for-tls). - **Unpredictable URLs** - Auto-generated tokens are randomly generated and difficult to guess - **Token collision prevention** - Custom tokens are validated to ensure uniqueness within each sandbox @@ -273,7 +273,7 @@ app.run((host = "127.0.0.1"), (port = 3000)); ### Production Errors -For custom domain issues, refer to [preview URL custom domain troubleshooting](/sandbox/guides/preview-urls-custom-domain/#troubleshooting). +For custom domain issues, refer to [preview URL custom domain troubleshooting](/sandbox/sdk/guides/preview-urls-custom-domain/#troubleshooting). ### Local Development @@ -295,9 +295,9 @@ This is **only required for local development**. In production, all container po ## Related Resources -- [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/) - Wildcard DNS and TLS for `exposePort()` -- [Deploy a Sandbox application](/sandbox/guides/deploy/) - Worker and container image deploys -- [Expose Services](/sandbox/guides/expose-services/) - Practical patterns for exposing ports -- [Ports API](/sandbox/api/ports/) - Complete API reference -- [Tunnels API](/sandbox/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs as an alternative for development -- [Security Model](/sandbox/concepts/security/) - Security best practices +- [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/) - Wildcard DNS and TLS for `exposePort()` +- [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/) - Worker and container image deploys +- [Expose Services](/sandbox/sdk/guides/expose-services/) - Practical patterns for exposing ports +- [Ports API](/sandbox/sdk/api/ports/) - Complete API reference +- [Tunnels API](/sandbox/sdk/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs as an alternative for development +- [Security Model](/sandbox/sdk/concepts/security/) - Security best practices diff --git a/src/content/docs/sandbox/concepts/sandboxes.mdx b/src/content/docs/sandbox/sdk/concepts/sandboxes.mdx similarity index 76% rename from src/content/docs/sandbox/concepts/sandboxes.mdx rename to src/content/docs/sandbox/sdk/concepts/sandboxes.mdx index 642c4beafb1..c7e4cb0e085 100644 --- a/src/content/docs/sandbox/concepts/sandboxes.mdx +++ b/src/content/docs/sandbox/sdk/concepts/sandboxes.mdx @@ -16,12 +16,6 @@ A sandbox is an isolated execution environment where your code runs. Each sandbo - Maintains state while the container is active - Exists as a Cloudflare Durable Object -:::note[Coming soon: Sandbox SDK 1.0] -This page documents sandbox lifecycle on today's stable `@cloudflare/sandbox` package. - -The **1.0 preview** keeps the same sandbox ID / container split and makes process and terminal handles fail closed after container stop or replace. Refer to [Sandbox lifecycle (1.0 preview)](/sandbox/1-0-preview/lifecycle/) and [Errors and recovery](/sandbox/1-0-preview/errors/). -::: - ## Lifecycle states ### Creation @@ -39,9 +33,9 @@ The sandbox container is running and processing requests. All state remains avai ### Idle -After a period of inactivity (10 minutes by default, configurable via [`sleepAfter`](/sandbox/configuration/sandbox-options/)), the container stops to free resources. When the next request arrives, a fresh container starts. All previous state is lost and the environment resets to its initial state. +After a period of inactivity (10 minutes by default, configurable via [`sleepAfter`](/sandbox/sdk/configuration/sandbox-options/)), the container stops to free resources. When the next request arrives, a fresh container starts. All previous state is lost and the environment resets to its initial state. -**Note**: Containers with [`keepAlive: true`](/sandbox/configuration/sandbox-options/#keepalive) never enter the idle state. They automatically send heartbeat pings every 30 seconds to prevent eviction. +**Note**: Containers with [`keepAlive: true`](/sandbox/sdk/configuration/sandbox-options/#keepalive) never enter the idle state. They automatically send heartbeat pings every 30 seconds to prevent eviction. ### Destruction @@ -129,7 +123,7 @@ try { ### Managing keepAlive containers -Containers with [`keepAlive: true`](/sandbox/configuration/sandbox-options/#keepalive) require explicit management since they do not timeout automatically: +Containers with [`keepAlive: true`](/sandbox/sdk/configuration/sandbox-options/#keepalive) require explicit management since they do not timeout automatically: ```typescript const sandbox = getSandbox(env.Sandbox, 'persistent-task', { @@ -182,7 +176,7 @@ FROM docker.io/cloudflare/sandbox:0.7.0 FROM docker.io/cloudflare/sandbox:0.7.0-python ``` -See [Dockerfile reference](/sandbox/configuration/dockerfile/) for details on image variants and extending the base image. +See [Dockerfile reference](/sandbox/sdk/configuration/dockerfile/) for details on image variants and extending the base image. ## Best practices @@ -194,9 +188,9 @@ See [Dockerfile reference](/sandbox/configuration/dockerfile/) for details on im ## Related resources -- [Architecture](/sandbox/concepts/architecture/) - How sandboxes fit in the system -- [Container runtime](/sandbox/concepts/containers/) - What runs inside sandboxes -- [Session management](/sandbox/concepts/sessions/) - Advanced state isolation -- [Directory backups](/sandbox/concepts/backup-restore/) - Why restored files do not survive sleep unless you restore again -- [Lifecycle API](/sandbox/api/lifecycle/) - Create and manage sandboxes -- [Sessions API](/sandbox/api/sessions/) - Create and manage execution sessions +- [Architecture](/sandbox/sdk/concepts/architecture/) - How sandboxes fit in the system +- [Container runtime](/sandbox/sdk/concepts/containers/) - What runs inside sandboxes +- [Session management](/sandbox/sdk/concepts/sessions/) - Advanced state isolation +- [Directory backups](/sandbox/sdk/concepts/backup-restore/) - Why restored files do not survive sleep unless you restore again +- [Lifecycle API](/sandbox/sdk/api/lifecycle/) - Create and manage sandboxes +- [Sessions API](/sandbox/sdk/api/sessions/) - Create and manage execution sessions diff --git a/src/content/docs/sandbox/concepts/security.mdx b/src/content/docs/sandbox/sdk/concepts/security.mdx similarity index 96% rename from src/content/docs/sandbox/concepts/security.mdx rename to src/content/docs/sandbox/sdk/concepts/security.mdx index fc798aabd23..f7496393a50 100644 --- a/src/content/docs/sandbox/concepts/security.mdx +++ b/src/content/docs/sandbox/sdk/concepts/security.mdx @@ -100,7 +100,7 @@ Quick tunnels (`sandbox.tunnels.get(port)`) return a `*.trycloudflare.com` URL w await sandbox.tunnels.destroy(8080); ``` -URLs do not survive a container restart, so a restart effectively rotates the hostname. As with preview URLs, add application-level authentication for any sensitive service. See the [Tunnels API](/sandbox/api/tunnels/) for details. +URLs do not survive a container restart, so a restart effectively rotates the hostname. As with preview URLs, add application-level authentication for any sensitive service. See the [Tunnels API](/sandbox/sdk/api/tunnels/) for details. ```python from flask import Flask, request, abort @@ -162,7 +162,7 @@ Sandbox request → Outbound handler (injects real credentials) → External API The sandbox never sees the real credential. Rotate the secret in your Worker's environment and every request uses the updated value. -This pattern is useful when accessing GitHub for private repository operations, AI services, or object storage where you want to keep credentials out of the container entirely. For implementation details, refer to [Handle outbound traffic](/sandbox/guides/outbound-traffic/). +This pattern is useful when accessing GitHub for private repository operations, AI services, or object storage where you want to keep credentials out of the container entirely. For implementation details, refer to [Handle outbound traffic](/sandbox/sdk/guides/outbound-traffic/). ## What the SDK protects against @@ -210,4 +210,4 @@ try { ## Related resources - [Containers architecture](/containers/concepts/architecture/) - Underlying platform security -- [Sandbox lifecycle](/sandbox/concepts/sandboxes/) - Resource management +- [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) - Resource management diff --git a/src/content/docs/sandbox/concepts/sessions.mdx b/src/content/docs/sandbox/sdk/concepts/sessions.mdx similarity index 90% rename from src/content/docs/sandbox/concepts/sessions.mdx rename to src/content/docs/sandbox/sdk/concepts/sessions.mdx index fc2a52d4c72..491dfe3ac7a 100644 --- a/src/content/docs/sandbox/concepts/sessions.mdx +++ b/src/content/docs/sandbox/sdk/concepts/sessions.mdx @@ -15,12 +15,6 @@ Sessions are bash shell execution contexts within a sandbox. Think of them as te Sessions are useful for organizing work inside one sandbox. They are not a security boundary between users because sessions share the same filesystem and process space. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents session behavior on today's stable `@cloudflare/sandbox` package. - -**Sandbox SDK 1.0** (preview on `@next`) removes core session execution APIs. Pass `cwd` and `env` on each `exec`, or use one explicit shell argv script. Refer to [Process execution](/sandbox/1-0-preview/processes/) or [migrate](/sandbox/1-0-preview/migrate/#drop-session-apis). -::: - ## Default session By default, every sandbox has a default session that maintains shell state between commands while the container is active: @@ -115,7 +109,7 @@ const session = await sandbox.createSession({ await session.exec("npm test"); // Times out after 30s if still running ``` -Individual commands can override the session timeout with the `timeout` option on `exec()`. For more details, refer to the [Sessions API](/sandbox/api/sessions/) and the [execute commands guide](/sandbox/guides/execute-commands/#timeouts). +Individual commands can override the session timeout with the `timeout` option on `exec()`. For more details, refer to the [Sessions API](/sandbox/sdk/api/sessions/) and the [execute commands guide](/sandbox/sdk/guides/execute-commands/#timeouts). ## What is scoped to a session @@ -223,5 +217,5 @@ const userSandbox = getSandbox(env.Sandbox, `user-${userId}`); ## Related resources -- [Sandbox lifecycle](/sandbox/concepts/sandboxes/) - Understanding sandbox management -- [Sessions API](/sandbox/api/sessions/) - Complete session API reference +- [Sandbox lifecycle](/sandbox/sdk/concepts/sandboxes/) - Understanding sandbox management +- [Sessions API](/sandbox/sdk/api/sessions/) - Complete session API reference diff --git a/src/content/docs/sandbox/concepts/terminal.mdx b/src/content/docs/sandbox/sdk/concepts/terminal.mdx similarity index 81% rename from src/content/docs/sandbox/concepts/terminal.mdx rename to src/content/docs/sandbox/sdk/concepts/terminal.mdx index 7cbad77e415..ba6fe124bda 100644 --- a/src/content/docs/sandbox/concepts/terminal.mdx +++ b/src/content/docs/sandbox/sdk/concepts/terminal.mdx @@ -10,12 +10,6 @@ products: Terminal connections let browser-based UIs interact directly with sandbox shells. Instead of executing discrete commands with `exec()`, a terminal connection opens a persistent, bidirectional channel to a bash shell — the same model as SSH or a local terminal emulator. -:::note[Sandbox SDK 1.0 preview] -This page describes terminal connections on today's stable `@cloudflare/sandbox` package. - -On **`@cloudflare/sandbox@next`**, terminals use `createTerminal`, `getTerminal`, and `terminal.connect`. Refer to [Terminals](/sandbox/1-0-preview/terminals/) and [Terminals API](/sandbox/1-0-preview/api/terminals/). -::: - ## How terminal connections work Terminal connections use WebSockets to stream raw bytes between a browser terminal (like [xterm.js](https://xtermjs.org/)) and a pseudo-terminal (PTY) process running inside the sandbox container. @@ -48,11 +42,11 @@ No client-side code is needed to handle buffering — the container manages it t Network interruptions are common in browser-based applications. Terminal connections handle this through a combination of server-side buffering (described above) and client-side reconnection with exponential backoff. -The `SandboxAddon` for xterm.js implements this automatically. If you are building a custom client, you are responsible for your own reconnection logic — the server-side buffering works regardless of which client connects. Refer to the [WebSocket protocol reference](/sandbox/api/terminal/#websocket-protocol) for details on the connection lifecycle. +The `SandboxAddon` for xterm.js implements this automatically. If you are building a custom client, you are responsible for your own reconnection logic — the server-side buffering works regardless of which client connects. Refer to the [WebSocket protocol reference](/sandbox/sdk/api/terminal/#websocket-protocol) for details on the connection lifecycle. ## Session-specific terminals -Each [session](/sandbox/concepts/sessions/) can have its own terminal with independent shell state: +Each [session](/sandbox/sdk/concepts/sessions/) can have its own terminal with independent shell state: ```typescript const devSession = await sandbox.createSession({ @@ -77,7 +71,7 @@ Multiple browser clients can connect to the same session's terminal simultaneous Terminal connections use binary WebSocket frames for terminal I/O (for performance) and JSON text frames for control and status messages (for structure). This keeps the data path fast while still allowing structured communication for operations like terminal resizing. -For the full protocol specification, including the connection lifecycle and message formats, refer to the [Terminal API reference](/sandbox/api/terminal/#websocket-protocol). +For the full protocol specification, including the connection lifecycle and message formats, refer to the [Terminal API reference](/sandbox/sdk/api/terminal/#websocket-protocol). ## When to use terminals vs commands @@ -90,7 +84,7 @@ For the full protocol specification, including the connection lifecycle and mess ## Related resources -- [Terminal API reference](/sandbox/api/terminal/) — Method signatures and types -- [Browser terminals](/sandbox/guides/browser-terminals/) — Step-by-step setup guide -- [Session management](/sandbox/concepts/sessions/) — How sessions work -- [Architecture](/sandbox/concepts/architecture/) — Overall SDK design +- [Terminal API reference](/sandbox/sdk/api/terminal/) — Method signatures and types +- [Browser terminals](/sandbox/sdk/guides/browser-terminals/) — Step-by-step setup guide +- [Session management](/sandbox/sdk/concepts/sessions/) — How sessions work +- [Architecture](/sandbox/sdk/concepts/architecture/) — Overall SDK design diff --git a/src/content/docs/sandbox/configuration/dockerfile.mdx b/src/content/docs/sandbox/sdk/configuration/dockerfile.mdx similarity index 89% rename from src/content/docs/sandbox/configuration/dockerfile.mdx rename to src/content/docs/sandbox/sdk/configuration/dockerfile.mdx index 99f477ff3a2..265a14a3842 100644 --- a/src/content/docs/sandbox/configuration/dockerfile.mdx +++ b/src/content/docs/sandbox/sdk/configuration/dockerfile.mdx @@ -8,10 +8,6 @@ products: - sandbox --- -:::note[Coming soon: Sandbox SDK 1.0] -Image variant names (`-python`, `-opencode`, `-musl`) still apply on **`@next`**. Pin the container tag to the same preview line as `@cloudflare/sandbox@next` (for example `cloudflare/sandbox:next` or a matching prerelease). Do not mix a preview Worker package with a stable image tag. -::: - Customize the sandbox container image with your own packages, tools, and configurations by extending the base runtime image. ## Base images @@ -40,7 +36,7 @@ Always match the Docker image version to your npm package version. If you're usi **Why this matters**: The SDK automatically checks version compatibility on startup. Mismatched versions can cause features to break or behave unexpectedly. If versions don't match, you'll see warnings in your logs. -See [Version compatibility](/sandbox/concepts/sandboxes/#version-compatibility) for troubleshooting version mismatch warnings. +See [Version compatibility](/sandbox/sdk/concepts/sandboxes/#version-compatibility) for troubleshooting version mismatch warnings. ::: ### Default image @@ -170,6 +166,6 @@ If you have existing startup scripts that end with `exec bun /container-server/d ## Related resources - [Image Management](/containers/guides/image-management/) - Building and pushing images to Cloudflare's registry -- [Wrangler configuration](/sandbox/configuration/wrangler/) - Using custom images in wrangler.jsonc +- [Wrangler configuration](/sandbox/sdk/configuration/wrangler/) - Using custom images in wrangler.jsonc - [Docker documentation](https://docs.docker.com/reference/dockerfile/) - Complete Dockerfile syntax -- [Container concepts](/sandbox/concepts/containers/) - Understanding the runtime environment +- [Container concepts](/sandbox/sdk/concepts/containers/) - Understanding the runtime environment diff --git a/src/content/docs/sandbox/configuration/environment-variables.mdx b/src/content/docs/sandbox/sdk/configuration/environment-variables.mdx similarity index 90% rename from src/content/docs/sandbox/configuration/environment-variables.mdx rename to src/content/docs/sandbox/sdk/configuration/environment-variables.mdx index f0309b04c4d..1747a05ffe7 100644 --- a/src/content/docs/sandbox/configuration/environment-variables.mdx +++ b/src/content/docs/sandbox/sdk/configuration/environment-variables.mdx @@ -10,12 +10,6 @@ products: import { WranglerConfig } from "~/components"; -:::note[Coming soon: Sandbox SDK 1.0] -This page documents environment configuration on today's stable `@cloudflare/sandbox` package. - -For `@cloudflare/sandbox@next`, refer to [Environment variables](/sandbox/1-0-preview/environment/) in the 1.0 preview section. -::: - Pass configuration, secrets, and runtime settings to your sandboxes using environment variables. ## SDK configuration variables @@ -41,7 +35,7 @@ Controls the transport protocol for SDK-to-container communication. RPC transpor ``` -For a complete guide including valid transport modes, performance considerations, and migration instructions, refer to [Transport modes](/sandbox/configuration/transport/). +For a complete guide including valid transport modes, performance considerations, and migration instructions, refer to [Transport modes](/sandbox/sdk/configuration/transport/). ### COMMAND_TIMEOUT_MS @@ -52,7 +46,7 @@ For a complete guide including valid transport modes, performance considerations Sets a global default timeout for every `exec()` call. When set, any command that exceeds this duration raises an error on the caller side and closes the connection. -Per-command `timeout` on `exec()` and session-level `commandTimeoutMs` on [`createSession()`](/sandbox/api/sessions/#createsession) both override this value. For more details on timeout precedence, refer to [Execute commands - Timeouts](/sandbox/guides/execute-commands/#timeouts). +Per-command `timeout` on `exec()` and session-level `commandTimeoutMs` on [`createSession()`](/sandbox/sdk/api/sessions/#createsession) both override this value. For more details on timeout precedence, refer to [Execute commands - Timeouts](/sandbox/sdk/guides/execute-commands/#timeouts). ```jsonc @@ -282,7 +276,7 @@ await Promise.all([ ### Configure transport mode -Set `SANDBOX_TRANSPORT` in your Worker's `vars` to switch between HTTP, WebSocket, and RPC transport. For details on when and how to configure each transport, refer to [Transport modes](/sandbox/configuration/transport/). +Set `SANDBOX_TRANSPORT` in your Worker's `vars` to switch between HTTP, WebSocket, and RPC transport. For details on when and how to configure each transport, refer to [Transport modes](/sandbox/sdk/configuration/transport/). ### Bucket mounting credentials @@ -352,7 +346,7 @@ await sandbox.mountBucket("my-r2-bucket", "/data", { The SDK uses AWS-style credential names (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`) because bucket mounting is powered by **s3fs-fuse**, which expects S3-compatible credentials. R2's API tokens work with this format since R2 implements the S3 API. ::: -See [Mount buckets guide](/sandbox/guides/mount-buckets/) for complete bucket mounting documentation. +See [Mount buckets guide](/sandbox/sdk/guides/mount-buckets/) for complete bucket mounting documentation. ## Environment variable precedence @@ -379,9 +373,9 @@ await sandbox.exec("node app.js", { ## Related resources -- [Transport modes](/sandbox/configuration/transport/) - Configure HTTP, WebSocket, and RPC transport -- [Wrangler configuration](/sandbox/configuration/wrangler/) - Setting Worker-level environment +- [Transport modes](/sandbox/sdk/configuration/transport/) - Configure HTTP, WebSocket, and RPC transport +- [Wrangler configuration](/sandbox/sdk/configuration/wrangler/) - Setting Worker-level environment - [Secrets](/workers/configuration/secrets/) - Managing sensitive data -- [Sessions API](/sandbox/api/sessions/) - Session-level environment variables -- [Security model](/sandbox/concepts/security/) - Understanding data isolation -- [Handle outbound traffic](/sandbox/guides/outbound-traffic/) - Keep credentials out of the sandbox entirely using outbound handlers +- [Sessions API](/sandbox/sdk/api/sessions/) - Session-level environment variables +- [Security model](/sandbox/sdk/concepts/security/) - Understanding data isolation +- [Handle outbound traffic](/sandbox/sdk/guides/outbound-traffic/) - Keep credentials out of the sandbox entirely using outbound handlers diff --git a/src/content/docs/sandbox/configuration/index.mdx b/src/content/docs/sandbox/sdk/configuration/index.mdx similarity index 77% rename from src/content/docs/sandbox/configuration/index.mdx rename to src/content/docs/sandbox/sdk/configuration/index.mdx index c304aa1eb08..377f8180223 100644 --- a/src/content/docs/sandbox/configuration/index.mdx +++ b/src/content/docs/sandbox/sdk/configuration/index.mdx @@ -16,7 +16,7 @@ Configure your Sandbox SDK deployment with Wrangler, customize container images, Configure Durable Objects bindings, container images, and Worker settings in @@ -25,7 +25,7 @@ Configure your Sandbox SDK deployment with Wrangler, customize container images, Customize the sandbox container image with your own packages, tools, and @@ -34,7 +34,7 @@ Configure your Sandbox SDK deployment with Wrangler, customize container images, Pass configuration and secrets to your sandboxes using environment variables. @@ -42,7 +42,7 @@ Configure your Sandbox SDK deployment with Wrangler, customize container images, Configure HTTP or RPC transport to optimize communication and avoid subrequest limits. @@ -50,7 +50,7 @@ Configure your Sandbox SDK deployment with Wrangler, customize container images, Configure sandbox behavior with options like `keepAlive` for long-running processes. @@ -60,7 +60,7 @@ Configure your Sandbox SDK deployment with Wrangler, customize container images, ## Related resources -- [Get Started guide](/sandbox/get-started/) - Initial setup walkthrough +- [Get Started guide](/sandbox/sdk/get-started/) - Initial setup walkthrough - [Wrangler documentation](/workers/wrangler/) - Complete Wrangler reference - [Docker documentation](https://docs.docker.com/engine/reference/builder/) - Dockerfile syntax -- [Security model](/sandbox/concepts/security/) - Understanding environment isolation +- [Security model](/sandbox/sdk/concepts/security/) - Understanding environment isolation diff --git a/src/content/docs/sandbox/configuration/sandbox-options.mdx b/src/content/docs/sandbox/sdk/configuration/sandbox-options.mdx similarity index 90% rename from src/content/docs/sandbox/configuration/sandbox-options.mdx rename to src/content/docs/sandbox/sdk/configuration/sandbox-options.mdx index 6042ddf1191..156e8e3cec9 100644 --- a/src/content/docs/sandbox/configuration/sandbox-options.mdx +++ b/src/content/docs/sandbox/sdk/configuration/sandbox-options.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample, WranglerConfig } from "~/components"; Configure sandbox behavior by passing options when creating a sandbox instance with `getSandbox()`. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents options on today's stable `@cloudflare/sandbox` package. - -In the **1.0 preview** (`@next`), `enableDefaultSession` and transport selection are removed. `sleepAfter`, `keepAlive`, `containerTimeouts`, and `normalizeId` still apply. Refer to [Sandbox lifecycle](/sandbox/1-0-preview/lifecycle/) and [Migrate](/sandbox/1-0-preview/migrate/). -::: - ## Available options ```ts @@ -64,7 +58,7 @@ const statelessResult = await statelessSandbox.exec('pwd'); Keep the container alive indefinitely by preventing automatic shutdown. When `true`, the container automatically sends heartbeat pings every 30 seconds to prevent eviction and will never auto-timeout. -**How it works**: The sandbox automatically schedules lightweight ping requests to the container every 30 seconds. This prevents the container from being evicted due to inactivity while minimizing resource overhead. You can also enable/disable keepAlive dynamically using [`setKeepAlive()`](/sandbox/api/lifecycle/#setkeepalive). +**How it works**: The sandbox automatically schedules lightweight ping requests to the container every 30 seconds. This prevents the container from being evicted due to inactivity while minimizing resource overhead. You can also enable/disable keepAlive dynamically using [`setKeepAlive()`](/sandbox/sdk/api/lifecycle/#setkeepalive). The `keepAlive` flag persists across Durable Object hibernation and wakeup cycles. Once enabled, you do not need to re-set it after the sandbox wakes from hibernation. @@ -251,8 +245,8 @@ With `keepAlive`, containers send automatic heartbeat pings every 30 seconds to ## Related resources -- [Expose services guide](/sandbox/guides/expose-services/) - Using `normalizeId` with preview URLs -- [Preview URLs concept](/sandbox/concepts/preview-urls/) - Understanding DNS case-insensitivity -- [Background processes guide](/sandbox/guides/background-processes/) - Using `keepAlive` with long-running processes -- [Lifecycle API](/sandbox/api/lifecycle/) - Create and manage sandboxes with `setKeepAlive()` -- [Sandboxes concept](/sandbox/concepts/sandboxes/) - Understanding sandbox lifecycle +- [Expose services guide](/sandbox/sdk/guides/expose-services/) - Using `normalizeId` with preview URLs +- [Preview URLs concept](/sandbox/sdk/concepts/preview-urls/) - Understanding DNS case-insensitivity +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Using `keepAlive` with long-running processes +- [Lifecycle API](/sandbox/sdk/api/lifecycle/) - Create and manage sandboxes with `setKeepAlive()` +- [Sandboxes concept](/sandbox/sdk/concepts/sandboxes/) - Understanding sandbox lifecycle diff --git a/src/content/docs/sandbox/configuration/transport.mdx b/src/content/docs/sandbox/sdk/configuration/transport.mdx similarity index 90% rename from src/content/docs/sandbox/configuration/transport.mdx rename to src/content/docs/sandbox/sdk/configuration/transport.mdx index ef0983f71b0..4c3d919510d 100644 --- a/src/content/docs/sandbox/configuration/transport.mdx +++ b/src/content/docs/sandbox/sdk/configuration/transport.mdx @@ -14,12 +14,6 @@ import { WranglerConfig } from "~/components"; Configure how the Sandbox SDK communicates with containers using transport modes. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents transport selection on today's stable `@cloudflare/sandbox` package. - -**Sandbox SDK 1.0** (preview on `@next`) uses a single RPC control channel. Remove `SANDBOX_TRANSPORT`, the `transport` option on `getSandbox()`, and `setTransport()`. Refer to [Migrate to the 1.0 preview](/sandbox/1-0-preview/migrate/#remove-transport-selection). -::: - ## Overview The Sandbox SDK supports three transport modes for communication between the Durable Object and the container: @@ -214,7 +208,7 @@ Set the `SANDBOX_TRANSPORT` variable to `"rpc"`: ## Related resources -- [Wrangler configuration](/sandbox/configuration/wrangler/) - Complete Worker configuration -- [Environment variables](/sandbox/configuration/environment-variables/) - Passing configuration to sandboxes +- [Wrangler configuration](/sandbox/sdk/configuration/wrangler/) - Complete Worker configuration +- [Environment variables](/sandbox/sdk/configuration/environment-variables/) - Passing configuration to sandboxes - [Workers subrequest limits](/workers/platform/limits/#subrequests) - Understanding subrequest limits -- [Architecture](/sandbox/concepts/architecture/) - How Sandbox SDK components communicate +- [Architecture](/sandbox/sdk/concepts/architecture/) - How Sandbox SDK components communicate diff --git a/src/content/docs/sandbox/configuration/wrangler.mdx b/src/content/docs/sandbox/sdk/configuration/wrangler.mdx similarity index 79% rename from src/content/docs/sandbox/configuration/wrangler.mdx rename to src/content/docs/sandbox/sdk/configuration/wrangler.mdx index a4eee725f1c..29e8b5f2af5 100644 --- a/src/content/docs/sandbox/configuration/wrangler.mdx +++ b/src/content/docs/sandbox/sdk/configuration/wrangler.mdx @@ -59,7 +59,7 @@ The minimal configuration shown above includes all required settings. For detail ## Backup storage -To use the [backup and restore API](/sandbox/api/backups/), you need an R2 bucket binding and presigned URL credentials. The container uploads and downloads backup archives directly to/from R2 using presigned URLs, which requires R2 API token credentials. +To use the [backup and restore API](/sandbox/sdk/api/backups/), you need an R2 bucket binding and presigned URL credentials. The container uploads and downloads backup archives directly to/from R2 using presigned URLs, which requires R2 API token credentials. ### 1. Create the R2 bucket @@ -95,7 +95,7 @@ npx wrangler secret put R2_SECRET_ACCESS_KEY Create an R2 API token in the [Cloudflare dashboard](https://dash.cloudflare.com/) under **R2** > **Overview** > **Manage R2 API Tokens**. The token needs **Object Read & Write** permissions for your backup bucket. -The SDK uses these credentials to generate presigned URLs that allow the container to transfer backup archives directly to and from R2. For a complete setup walkthrough, refer to the [backup and restore guide](/sandbox/guides/backup-restore/). +The SDK uses these credentials to generate presigned URLs that allow the container to transfer backup archives directly to and from R2. For a complete setup walkthrough, refer to the [backup and restore guide](/sandbox/sdk/guides/backup-restore/). ## Troubleshooting @@ -141,11 +141,11 @@ The SDK uses these credentials to generate presigned URLs that allow the contain ## Related resources -- [Deploy a Sandbox application](/sandbox/guides/deploy/) - Deploy and keep package and image aligned +- [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/) - Deploy and keep package and image aligned - [Deploy Containers](/containers/guides/deploy/) - Containers deploy path -- [Transport modes](/sandbox/configuration/transport/) - Configure HTTP, WebSocket, and RPC transport +- [Transport modes](/sandbox/sdk/configuration/transport/) - Configure HTTP, WebSocket, and RPC transport - [Wrangler documentation](/workers/wrangler/) - Complete Wrangler reference - [Durable Objects setup](/durable-objects/get-started/) - DO-specific configuration -- [Dockerfile reference](/sandbox/configuration/dockerfile/) - Custom container images -- [Environment variables](/sandbox/configuration/environment-variables/) - Passing configuration to sandboxes -- [Get Started guide](/sandbox/get-started/) - Initial setup walkthrough +- [Dockerfile reference](/sandbox/sdk/configuration/dockerfile/) - Custom container images +- [Environment variables](/sandbox/sdk/configuration/environment-variables/) - Passing configuration to sandboxes +- [Get Started guide](/sandbox/sdk/get-started/) - Initial setup walkthrough diff --git a/src/content/docs/sandbox/get-started.mdx b/src/content/docs/sandbox/sdk/get-started.mdx similarity index 79% rename from src/content/docs/sandbox/get-started.mdx rename to src/content/docs/sandbox/sdk/get-started.mdx index 5d89a61bfe6..9d229341b21 100644 --- a/src/content/docs/sandbox/get-started.mdx +++ b/src/content/docs/sandbox/sdk/get-started.mdx @@ -12,14 +12,6 @@ import { Render, PackageManagers, Steps, WranglerConfig } from "~/components"; Build your first application with Sandbox SDK - a secure code execution environment. In this guide, you'll create a Worker that can execute Python code and work with files in isolated containers. -:::note[Coming soon: Sandbox SDK 1.0] -This guide uses today's stable `@cloudflare/sandbox` package. - -For **new projects**, we recommend the [1.0 preview](/sandbox/1-0-preview/) on `@cloudflare/sandbox@next` so you start on the APIs that become Sandbox SDK 1.0. Refer to [Get started with the 1.0 preview](/sandbox/1-0-preview/get-started/). - -Coding agents: install [Cloudflare Skills](https://github.com/cloudflare/skills) ([Agent setup](/agent-setup/)). Use **`sandbox-stable`** with this guide; use **`sandbox-next`** for `@next`; use **`sandbox-migrate-to-next`** when porting. -::: - :::note[What you're building] A simple API that can safely execute Python code and perform file operations in isolated sandbox environments. ::: @@ -205,17 +197,17 @@ Your `wrangler.jsonc` connects three pieces together: - **durable_objects** - You need not be familiar with [Durable Objects](/durable-objects) to use Sandbox SDK, but if you'd like, you can [learn more about Cloudflare Containers and Durable Objects](/containers/get-started/#each-container-is-backed-by-its-own-durable-object). This configuration creates a [binding](/workers/runtime-apis/bindings#what-is-a-binding) that makes the `Sandbox` Durable Object accessible in your Worker code. - **migrations** - Registers the `Sandbox` class, implemented by the Sandbox SDK, with [SQLite storage backend](/durable-objects/best-practices/access-durable-objects-storage) (required once) -For detailed configuration options including environment variables, secrets, and custom images, see the [Wrangler configuration reference](/sandbox/configuration/wrangler/). +For detailed configuration options including environment variables, secrets, and custom images, see the [Wrangler configuration reference](/sandbox/sdk/configuration/wrangler/). ## Next steps Now that you have a working sandbox, explore more capabilities: -- [Code interpreter with Workers AI](/sandbox/tutorials/workers-ai-code-interpreter/) - Build an AI-powered code execution system -- [Execute commands](/sandbox/guides/execute-commands/) - Run shell commands and stream output -- [Manage files](/sandbox/guides/manage-files/) - Work with files and directories -- [Deploy a Sandbox application](/sandbox/guides/deploy/) - Deploy and keep package and image aligned -- [Expose services](/sandbox/guides/expose-services/) - Get public URLs for services running in your sandbox -- [Quick tunnels](/sandbox/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for development and `.workers.dev` deployments -- [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/) - Wildcard DNS and TLS for `exposePort()` -- [API reference](/sandbox/api/) - Complete API documentation +- [Code interpreter with Workers AI](/sandbox/sdk/tutorials/workers-ai-code-interpreter/) - Build an AI-powered code execution system +- [Execute commands](/sandbox/sdk/guides/execute-commands/) - Run shell commands and stream output +- [Manage files](/sandbox/sdk/guides/manage-files/) - Work with files and directories +- [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/) - Deploy and keep package and image aligned +- [Expose services](/sandbox/sdk/guides/expose-services/) - Get public URLs for services running in your sandbox +- [Quick tunnels](/sandbox/sdk/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for development and `.workers.dev` deployments +- [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/) - Wildcard DNS and TLS for `exposePort()` +- [API reference](/sandbox/sdk/api/) - Complete API documentation diff --git a/src/content/docs/sandbox/guides/2026-deprecation.mdx b/src/content/docs/sandbox/sdk/guides/2026-deprecation.mdx similarity index 72% rename from src/content/docs/sandbox/guides/2026-deprecation.mdx rename to src/content/docs/sandbox/sdk/guides/2026-deprecation.mdx index b6222d938ff..030ce7c78cd 100644 --- a/src/content/docs/sandbox/guides/2026-deprecation.mdx +++ b/src/content/docs/sandbox/sdk/guides/2026-deprecation.mdx @@ -10,13 +10,9 @@ products: import { WranglerConfig, TypeScriptExample } from "~/components"; -:::note[Two different migration paths] -This guide is for apps that **stay on the current stable** `@cloudflare/sandbox` package and need to leave deprecated features (transports, default sessions, stream helpers, and related APIs). +This guide is for applications that stay on `@cloudflare/sandbox` and need to leave deprecated features (transports, default sessions, stream helpers, and related APIs). -To move onto **Sandbox SDK 1.0** (`@cloudflare/sandbox@next`), use [Migrate to the 1.0 preview](/sandbox/1-0-preview/migrate/) instead. That path covers argv `exec`, removed sessions, terminals, interpreter attach, and container cutover. Completing this stable-line guide first is still useful if you use the older transports or stream helpers. -::: - -This guide walks through migrating away from Sandbox SDK features deprecated in the [deprecation announcement](/changelog/sandbox/2026-06-09-deprecating-sandbox-sdk-features/). Do not build new work on these APIs. Finish this cleanup on the stable package, then move to the [1.0 preview](/sandbox/1-0-preview/) when you can. +This guide walks through migrating away from Sandbox SDK features deprecated in the [deprecation announcement](/changelog/sandbox/2026-06-09-deprecating-sandbox-sdk-features/). Do not build new work on these APIs. For the announcement and rationale, refer to the [deprecation changelog entry](/changelog/sandbox/2026-06-09-deprecating-sandbox-sdk-features/). @@ -60,11 +56,11 @@ const sandbox = getSandbox(env.Sandbox, "user-123", { ``` -For more information, refer to [Transport modes](/sandbox/configuration/transport/). +For more information, refer to [Transport modes](/sandbox/sdk/configuration/transport/). ## Desktop -The desktop feature was removed in `0.10.2`. The feature ran a full Linux desktop inside the sandbox for computer-use style automation. If you still need that shape, rebuild it with [extensions](/sandbox/1-0-preview/extensions/) rather than a built-in desktop API. Keep Sandbox SDK for isolated command execution, file operations, and runtime workflows that do not require an in-sandbox desktop. +The desktop feature was removed in `0.10.2`. The feature ran a full Linux desktop inside the sandbox for GUI automation. Keep Sandbox SDK for isolated command execution, file operations, and runtime workflows that do not require an in-sandbox desktop. ## Expose ports @@ -90,7 +86,7 @@ return Response.json({ url: tunnel.url }); If your `exposePort()` flow used `proxyToSandbox()` to inject authentication or rewrite responses, account for that behavior before moving the public URL to a tunnel. -For more information, refer to [Tunnels](/sandbox/api/tunnels/) and [Expose services](/sandbox/guides/expose-services/). +For more information, refer to [Tunnels](/sandbox/sdk/api/tunnels/) and [Expose services](/sandbox/sdk/guides/expose-services/). ## Default sessions @@ -134,7 +130,7 @@ await sandbox.exec("npm test", { ``` -For more information, refer to [Sandbox options](/sandbox/configuration/sandbox-options/#enabledefaultsession) and [Sessions](/sandbox/api/sessions/). +For more information, refer to [Sandbox options](/sandbox/sdk/configuration/sandbox-options/#enabledefaultsession) and [Sessions](/sandbox/sdk/api/sessions/). ## Streaming APIs @@ -175,7 +171,7 @@ return new Response(file.content, { ``` -For more information, refer to [Commands](/sandbox/api/commands/) and [Files](/sandbox/api/files/). +For more information, refer to [Commands](/sandbox/sdk/api/commands/) and [Files](/sandbox/sdk/api/files/). ## Verify the migration @@ -192,10 +188,4 @@ Use this checklist before you depend on a Sandbox SDK release that has removed t ## Coding agents -Coding agents with [Cloudflare Skills](https://github.com/cloudflare/skills) installed ([Agent setup](/agent-setup/)) should use **`sandbox-stable`** for work on the current stable package and follow **this guide** for deprecated-API cleanup while staying on stable. For a full move to Sandbox SDK 1.0 (`@next`), use **`sandbox-migrate-to-next`** (and the [1.0 migrate guide](/sandbox/1-0-preview/migrate/)) instead. - -## 1.0 preview - -After you finish the stable-line changes in this guide, move on to the **Sandbox SDK 1.0** preview on `@cloudflare/sandbox@next` when you can. That preview is the path to the next stable major release. - -Refer to [Sandbox SDK 1.0 preview](/sandbox/1-0-preview/) and [Migrate to the 1.0 preview](/sandbox/1-0-preview/migrate/). +Coding agents with [Cloudflare Skills](https://github.com/cloudflare/skills) installed ([Agent setup](/agent-setup/)) should follow **this guide** for deprecated-API cleanup while staying on `@cloudflare/sandbox`. diff --git a/src/content/docs/sandbox/guides/background-processes.mdx b/src/content/docs/sandbox/sdk/guides/background-processes.mdx similarity index 87% rename from src/content/docs/sandbox/guides/background-processes.mdx rename to src/content/docs/sandbox/sdk/guides/background-processes.mdx index 0e7e0932ef9..49351f5b10d 100644 --- a/src/content/docs/sandbox/guides/background-processes.mdx +++ b/src/content/docs/sandbox/sdk/guides/background-processes.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; This guide shows you how to start, monitor, and manage long-running background processes in the sandbox. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents `startProcess` and related helpers on today's stable `@cloudflare/sandbox` package. - -In the **1.0 preview** (`@next`), long-running work uses the same `exec(argv)` process handle as short commands. Refer to [Process execution](/sandbox/1-0-preview/processes/) or [migrate to the preview](/sandbox/1-0-preview/migrate/). -::: - ## When to use background processes Use `startProcess()` instead of `exec()` when: @@ -29,7 +23,7 @@ Use `startProcess()` instead of `exec()` when: - **Parallel execution** - Multiple services running simultaneously :::note -For **one-time commands, builds, or scripts that complete and exit**, use `exec()` instead. See the [Execute commands guide](/sandbox/guides/execute-commands/). +For **one-time commands, builds, or scripts that complete and exit**, use `exec()` instead. See the [Execute commands guide](/sandbox/sdk/guides/execute-commands/). ::: ## Start a background process @@ -205,7 +199,7 @@ console.log('All services running'); ## Keep containers alive for long-running processes -By default, containers automatically shut down after 10 minutes of inactivity. For long-running processes that may have idle periods (like CI/CD pipelines, batch jobs, or monitoring tasks), use the [`keepAlive` option](/sandbox/configuration/sandbox-options/#keepalive): +By default, containers automatically shut down after 10 minutes of inactivity. For long-running processes that may have idle periods (like CI/CD pipelines, batch jobs, or monitoring tasks), use the [`keepAlive` option](/sandbox/sdk/configuration/sandbox-options/#keepalive): ```ts @@ -289,10 +283,10 @@ const server = await sandbox.startProcess('node server.js'); ## Related resources -- [Commands API reference](/sandbox/api/commands/) - Complete process management API -- [Sandbox options configuration](/sandbox/configuration/sandbox-options/) - Configure `keepAlive` and other options -- [Lifecycle API](/sandbox/api/lifecycle/) - Create and manage sandboxes -- [Sessions API reference](/sandbox/api/sessions/) - Create isolated execution contexts -- [Execute commands guide](/sandbox/guides/execute-commands/) - One-time command execution -- [Expose services guide](/sandbox/guides/expose-services/) - Make processes accessible -- [Streaming output guide](/sandbox/guides/streaming-output/) - Monitor process output +- [Commands API reference](/sandbox/sdk/api/commands/) - Complete process management API +- [Sandbox options configuration](/sandbox/sdk/configuration/sandbox-options/) - Configure `keepAlive` and other options +- [Lifecycle API](/sandbox/sdk/api/lifecycle/) - Create and manage sandboxes +- [Sessions API reference](/sandbox/sdk/api/sessions/) - Create isolated execution contexts +- [Execute commands guide](/sandbox/sdk/guides/execute-commands/) - One-time command execution +- [Expose services guide](/sandbox/sdk/guides/expose-services/) - Make processes accessible +- [Streaming output guide](/sandbox/sdk/guides/streaming-output/) - Monitor process output diff --git a/src/content/docs/sandbox/guides/backup-restore.mdx b/src/content/docs/sandbox/sdk/guides/backup-restore.mdx similarity index 96% rename from src/content/docs/sandbox/guides/backup-restore.mdx rename to src/content/docs/sandbox/sdk/guides/backup-restore.mdx index c19eb4de130..599fedb4ac4 100644 --- a/src/content/docs/sandbox/guides/backup-restore.mdx +++ b/src/content/docs/sandbox/sdk/guides/backup-restore.mdx @@ -14,7 +14,7 @@ This guide shows you how to snapshot a sandbox directory to R2 and restore it la Use backup and restore when a project directory such as `/workspace` should come back after the sandbox sleeps. For a separate persisted storage path, mount a bucket instead. If you mount a bucket over `/workspace`, the mount overlays files seeded by your image in production. -For why production restore uses an overlay, refer to [Directory backups](/sandbox/concepts/backup-restore/). +For why production restore uses an overlay, refer to [Directory backups](/sandbox/sdk/concepts/backup-restore/). ## Prerequisites @@ -145,7 +145,7 @@ await sandbox.exec("rm -rf /workspace/app/node_modules/.vite"); -This failure does not occur in `wrangler dev`, which extracts the archive. For overlay restore, refer to [Directory backups](/sandbox/concepts/backup-restore/). +This failure does not occur in `wrangler dev`, which extracts the archive. For overlay restore, refer to [Directory backups](/sandbox/sdk/concepts/backup-restore/). ## Exclude gitignored files @@ -360,8 +360,8 @@ try { ## Related resources -- [Directory backups](/sandbox/concepts/backup-restore/) - Overlay restore, local extract, and `EXDEV` -- [Backups API](/sandbox/api/backups/) - Methods, options, and types -- [Storage API](/sandbox/api/storage/) - Mount S3-compatible buckets +- [Directory backups](/sandbox/sdk/concepts/backup-restore/) - Overlay restore, local extract, and `EXDEV` +- [Backups API](/sandbox/sdk/api/backups/) - Methods, options, and types +- [Storage API](/sandbox/sdk/api/storage/) - Mount S3-compatible buckets - [R2 documentation](/r2/) - R2 buckets and credentials - [R2 lifecycle rules](/r2/buckets/object-lifecycles/) - Automatic object cleanup diff --git a/src/content/docs/sandbox/guides/browser-terminals.mdx b/src/content/docs/sandbox/sdk/guides/browser-terminals.mdx similarity index 88% rename from src/content/docs/sandbox/guides/browser-terminals.mdx rename to src/content/docs/sandbox/sdk/guides/browser-terminals.mdx index 6052528e8ff..069e33bd176 100644 --- a/src/content/docs/sandbox/guides/browser-terminals.mdx +++ b/src/content/docs/sandbox/sdk/guides/browser-terminals.mdx @@ -12,15 +12,9 @@ import { TypeScriptExample, PackageManagers } from "~/components"; This guide shows you how to connect a browser-based terminal to a sandbox shell. You can use the `SandboxAddon` with xterm.js, or connect directly over WebSockets. -:::note[Sandbox SDK 1.0 preview] -This guide documents browser terminals on today's stable `@cloudflare/sandbox` package. - -On **`@cloudflare/sandbox@next`**, follow [Terminals](/sandbox/1-0-preview/terminals/) and [Terminals API](/sandbox/1-0-preview/api/terminals/). -::: - ## Prerequisites -You need an existing Cloudflare Worker with a sandbox binding. Refer to [Getting started](/sandbox/get-started/) if you do not have one. +You need an existing Cloudflare Worker with a sandbox binding. Refer to [Getting started](/sandbox/sdk/get-started/) if you do not have one. Install the terminal dependencies in your frontend project: @@ -107,7 +101,7 @@ window.addEventListener('resize', () => fitAddon.fit()); -For the full addon API, refer to the [Terminal API reference](/sandbox/api/terminal/). +For the full addon API, refer to the [Terminal API reference](/sandbox/sdk/api/terminal/). ## Connect without xterm.js @@ -166,7 +160,7 @@ Key protocol details: - Send keystrokes as binary (UTF-8). Send control messages (`resize`) as JSON text. - The PTY stays alive when a client disconnects. Reconnecting replays buffered output. -For the full protocol specification, refer to the [WebSocket protocol section](/sandbox/api/terminal/#websocket-protocol) in the API reference. +For the full protocol specification, refer to the [WebSocket protocol section](/sandbox/sdk/api/terminal/#websocket-protocol) in the API reference. ## Best practices @@ -177,6 +171,6 @@ For the full protocol specification, refer to the [WebSocket protocol section](/ ## Related resources -- [Terminal API reference](/sandbox/api/terminal/) — Method signatures, addon API, and WebSocket protocol -- [Terminal connections](/sandbox/concepts/terminal/) — How terminal connections work -- [Session management](/sandbox/concepts/sessions/) — How sessions work +- [Terminal API reference](/sandbox/sdk/api/terminal/) — Method signatures, addon API, and WebSocket protocol +- [Terminal connections](/sandbox/sdk/concepts/terminal/) — How terminal connections work +- [Session management](/sandbox/sdk/concepts/sessions/) — How sessions work diff --git a/src/content/docs/sandbox/guides/code-execution.mdx b/src/content/docs/sandbox/sdk/guides/code-execution.mdx similarity index 91% rename from src/content/docs/sandbox/guides/code-execution.mdx rename to src/content/docs/sandbox/sdk/guides/code-execution.mdx index 35a98a897d2..c417b245eda 100644 --- a/src/content/docs/sandbox/guides/code-execution.mdx +++ b/src/content/docs/sandbox/sdk/guides/code-execution.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; This guide shows you how to execute Python and JavaScript code with rich outputs using the Code Interpreter API. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents the interpreter on today's stable `@cloudflare/sandbox` package. - -In the **1.0 preview** (`@next`), the interpreter is an opt-in extension. Refer to [Code interpreter](/sandbox/1-0-preview/interpreter/) and the [Interpreter API](/sandbox/1-0-preview/api/interpreter/). -::: - ## When to use code interpreter Use the Code Interpreter API for **simple, direct code execution** with minimal setup: @@ -270,6 +264,6 @@ console.log('All contexts deleted'); ## Related resources -- [Code Interpreter API reference](/sandbox/api/interpreter/) - Complete API documentation -- [AI code executor tutorial](/sandbox/tutorials/ai-code-executor/) - Build complete AI executor -- [Execute commands guide](/sandbox/guides/execute-commands/) - Lower-level command execution +- [Code Interpreter API reference](/sandbox/sdk/api/interpreter/) - Complete API documentation +- [AI code executor tutorial](/sandbox/sdk/tutorials/ai-code-executor/) - Build complete AI executor +- [Execute commands guide](/sandbox/sdk/guides/execute-commands/) - Lower-level command execution diff --git a/src/content/docs/sandbox/guides/deploy.mdx b/src/content/docs/sandbox/sdk/guides/deploy.mdx similarity index 66% rename from src/content/docs/sandbox/guides/deploy.mdx rename to src/content/docs/sandbox/sdk/guides/deploy.mdx index cc3ac7a7559..843cd24df1c 100644 --- a/src/content/docs/sandbox/guides/deploy.mdx +++ b/src/content/docs/sandbox/sdk/guides/deploy.mdx @@ -13,17 +13,11 @@ import { PackageManagers } from "~/components"; Sandbox runs on [Containers](/containers/). For deploy commands, Workers Builds, and rollout flags, refer to [Deploy Containers](/containers/guides/deploy/) and [Rollouts](/containers/configuration/rollouts/). -To put `exposePort()` on a custom domain, refer to [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/). - -:::note[Sandbox SDK 1.0 preview] -This guide targets the stable `@cloudflare/sandbox` package. - -On **`@cloudflare/sandbox@next`**, keep the Worker package and container image on the same preview line. For a breaking cutover, refer to [Migrate](/sandbox/1-0-preview/migrate/#deploy-the-cutover). -::: +To put `exposePort()` on a custom domain, refer to [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/). ## Keep the package and image aligned -The Worker depends on `@cloudflare/sandbox` (or `@cloudflare/sandbox@next`). The container image must come from the same release line (Dockerfile and base image tags from the template or docs for that version). +The Worker depends on `@cloudflare/sandbox`. The container image must come from the same release line (Dockerfile and base image tags from the template or docs for that version). When you bump the npm package: @@ -33,9 +27,7 @@ When you bump the npm package: - Use this for stable to `@next` cutovers and other breaking package/image pairs. Refer to [Migrate](/sandbox/1-0-preview/migrate/#deploy-the-cutover) and [Rollouts](/containers/configuration/rollouts/). - -Do not mix a stable package with a `@next` image, or the reverse. + Use this for breaking package and image pairs. Refer to [Rollouts](/containers/configuration/rollouts/). ## Deploy from your machine @@ -60,5 +52,4 @@ More detail: [Before production](/containers/guides/deploy/#before-production). - [Deploy Containers](/containers/guides/deploy/) - [Rollouts](/containers/configuration/rollouts/) -- [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/) -- [Migrate to Sandbox SDK 1.0 preview](/sandbox/1-0-preview/migrate/) +- [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/) diff --git a/src/content/docs/sandbox/guides/docker-in-docker.mdx b/src/content/docs/sandbox/sdk/guides/docker-in-docker.mdx similarity index 92% rename from src/content/docs/sandbox/guides/docker-in-docker.mdx rename to src/content/docs/sandbox/sdk/guides/docker-in-docker.mdx index c70b22c0c08..638f827371d 100644 --- a/src/content/docs/sandbox/guides/docker-in-docker.mdx +++ b/src/content/docs/sandbox/sdk/guides/docker-in-docker.mdx @@ -97,6 +97,6 @@ Docker-in-Docker in Cloudflare Containers has the following limitations: ## Related resources -- [Dockerfile reference](/sandbox/configuration/dockerfile/) - Customize your sandbox image -- [Execute commands](/sandbox/guides/execute-commands/) - Run commands in the sandbox -- [Background processes](/sandbox/guides/background-processes/) - Manage long-running processes +- [Dockerfile reference](/sandbox/sdk/configuration/dockerfile/) - Customize your sandbox image +- [Execute commands](/sandbox/sdk/guides/execute-commands/) - Run commands in the sandbox +- [Background processes](/sandbox/sdk/guides/background-processes/) - Manage long-running processes diff --git a/src/content/docs/sandbox/guides/execute-commands.mdx b/src/content/docs/sandbox/sdk/guides/execute-commands.mdx similarity index 82% rename from src/content/docs/sandbox/guides/execute-commands.mdx rename to src/content/docs/sandbox/sdk/guides/execute-commands.mdx index a565b215bc1..c85f519eaff 100644 --- a/src/content/docs/sandbox/guides/execute-commands.mdx +++ b/src/content/docs/sandbox/sdk/guides/execute-commands.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; This guide shows you how to execute commands in the sandbox, handle output, and manage errors effectively. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents command execution on today's stable `@cloudflare/sandbox` package. - -**Sandbox SDK 1.0** (preview on `@cloudflare/sandbox@next`) uses argv `exec()` and process handles instead of string `exec` / `startProcess` / `execStream`. Refer to [Process execution](/sandbox/1-0-preview/processes/), the [Processes API](/sandbox/1-0-preview/api/processes/), or [migrate to the preview](/sandbox/1-0-preview/migrate/). -::: - ## Choose the right method The SDK provides multiple approaches for running commands: @@ -27,7 +21,7 @@ The SDK provides multiple approaches for running commands: - **`startProcess()`** - Start a background process. Best for web servers, databases, and services that need to keep running. :::note -For **web servers, databases, or services that need to keep running**, use `startProcess()` instead. See the [Background processes guide](/sandbox/guides/background-processes/). +For **web servers, databases, or services that need to keep running**, use `startProcess()` instead. See the [Background processes guide](/sandbox/sdk/guides/background-processes/). ::: ## Execute basic commands @@ -177,7 +171,7 @@ await session.exec('npm test', { timeout: 60000 }); // 60s for this command ### Global timeout -Set the `COMMAND_TIMEOUT_MS` [environment variable](/sandbox/configuration/environment-variables/#command_timeout_ms) to define a global default timeout for every `exec()` call across all sessions. +Set the `COMMAND_TIMEOUT_MS` [environment variable](/sandbox/sdk/configuration/environment-variables/#command_timeout_ms) to define a global default timeout for every `exec()` call across all sessions. ### Timeout precedence @@ -192,7 +186,7 @@ If none are set, commands run without a timeout. ### Timeout does not kill the process :::caution -When a command times out, the SDK raises an error and closes the connection. The underlying process **continues running** inside the container. To stop a timed-out process, delete the session with [`deleteSession()`](/sandbox/api/sessions/#deletesession) or destroy the sandbox with [`destroy()`](/sandbox/api/lifecycle/#destroy). +When a command times out, the SDK raises an error and closes the connection. The underlying process **continues running** inside the container. To stop a timed-out process, delete the session with [`deleteSession()`](/sandbox/sdk/api/sessions/#deletesession) or destroy the sandbox with [`destroy()`](/sandbox/sdk/api/lifecycle/#destroy). ::: ## Best practices @@ -200,7 +194,7 @@ When a command times out, the SDK raises an error and closes the connection. The - **Check exit codes** - Always verify `result.success` and `result.exitCode` - **Validate inputs** - Escape or validate user input to prevent injection - **Use streaming** - For long operations, use `execStream()` for real-time feedback -- **Use background processes** - For services that need to keep running (web servers, databases), use the [Background processes guide](/sandbox/guides/background-processes/) instead +- **Use background processes** - For services that need to keep running (web servers, databases), use the [Background processes guide](/sandbox/sdk/guides/background-processes/) instead - **Handle errors** - Check stderr for error details ## Troubleshooting @@ -234,7 +228,7 @@ await sandbox.exec('cd /workspace/my-app && python script.py'); ## Related resources -- [Commands API reference](/sandbox/api/commands/) - Complete method documentation -- [Background processes guide](/sandbox/guides/background-processes/) - Managing long-running processes -- [Streaming output guide](/sandbox/guides/streaming-output/) - Advanced streaming patterns -- [Code Interpreter guide](/sandbox/guides/code-execution/) - Higher-level code execution +- [Commands API reference](/sandbox/sdk/api/commands/) - Complete method documentation +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Managing long-running processes +- [Streaming output guide](/sandbox/sdk/guides/streaming-output/) - Advanced streaming patterns +- [Code Interpreter guide](/sandbox/sdk/guides/code-execution/) - Higher-level code execution diff --git a/src/content/docs/sandbox/guides/expose-services.mdx b/src/content/docs/sandbox/sdk/guides/expose-services.mdx similarity index 89% rename from src/content/docs/sandbox/guides/expose-services.mdx rename to src/content/docs/sandbox/sdk/guides/expose-services.mdx index 84a3835545f..998cda8c78f 100644 --- a/src/content/docs/sandbox/guides/expose-services.mdx +++ b/src/content/docs/sandbox/sdk/guides/expose-services.mdx @@ -10,18 +10,12 @@ products: import { TypeScriptExample } from "~/components"; -:::note[Coming soon: Sandbox SDK 1.0] -This guide documents exposing services on today's stable `@cloudflare/sandbox` package. - -On **`@next`**, start the service with `exec(argv)` (not `startProcess`), then expose or use tunnels — [Process execution](/sandbox/1-0-preview/processes/). -::: - :::note[Production requires custom domain] -Preview URLs require a custom domain with wildcard DNS routing in production. See [Configure preview URLs on a custom domain](/sandbox/guides/preview-urls-custom-domain/) for setup instructions. +Preview URLs require a custom domain with wildcard DNS routing in production. See [Configure preview URLs on a custom domain](/sandbox/sdk/guides/preview-urls-custom-domain/) for setup instructions. ::: :::note[Prefer `sandbox.tunnels` for public URLs] -[`sandbox.tunnels`](/sandbox/api/tunnels/) is the recommended option for most public-URL use cases, including production. Quick tunnels give you a zero-config `*.trycloudflare.com` URL; named tunnels bind a stable `.` hostname. Follow this guide when you specifically want the Worker itself to front the request (for example, to inject authentication or rewrite responses). +[`sandbox.tunnels`](/sandbox/sdk/api/tunnels/) is the recommended option for most public-URL use cases, including production. Quick tunnels give you a zero-config `*.trycloudflare.com` URL; named tunnels bind a stable `.` hostname. Follow this guide when you specifically want the Worker itself to front the request (for example, to inject authentication or rewrite responses). ::: This guide shows you how to expose services running in your sandbox to the internet via preview URLs. @@ -97,7 +91,7 @@ This lowercases the ID during creation so it matches preview URL routing. Withou **Best practice**: Use lowercase IDs from the start (`'my-project-123'`). -See [Sandbox options](/sandbox/configuration/sandbox-options/#normalizeid) for details. +See [Sandbox options](/sandbox/sdk/configuration/sandbox-options/#normalizeid) for details. ::: ## Stable URLs with custom tokens @@ -385,7 +379,7 @@ await sandbox.exposePort(8080, { hostname }); This creates the Durable Object with ID `"myproject-123"`, matching the preview URL routing. -See [Sandbox options - normalizeId](/sandbox/configuration/sandbox-options/#normalizeid) for details. +See [Sandbox options - normalizeId](/sandbox/sdk/configuration/sandbox-options/#normalizeid) for details. ## Preview URL Format @@ -400,7 +394,7 @@ See [Sandbox options - normalizeId](/sandbox/configuration/sandbox-options/#norm ## Related resources -- [Ports API reference](/sandbox/api/ports/) - Complete port exposure API -- [Background processes guide](/sandbox/guides/background-processes/) - Managing services -- [Execute commands guide](/sandbox/guides/execute-commands/) - Starting services -- [Tunnels API reference](/sandbox/api/tunnels/) - Recommended alternative for most public-URL use cases (quick or named tunnels) +- [Ports API reference](/sandbox/sdk/api/ports/) - Complete port exposure API +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Managing services +- [Execute commands guide](/sandbox/sdk/guides/execute-commands/) - Starting services +- [Tunnels API reference](/sandbox/sdk/api/tunnels/) - Recommended alternative for most public-URL use cases (quick or named tunnels) diff --git a/src/content/docs/sandbox/guides/file-watching.mdx b/src/content/docs/sandbox/sdk/guides/file-watching.mdx similarity index 97% rename from src/content/docs/sandbox/guides/file-watching.mdx rename to src/content/docs/sandbox/sdk/guides/file-watching.mdx index 972feed1c33..1bee59454aa 100644 --- a/src/content/docs/sandbox/guides/file-watching.mdx +++ b/src/content/docs/sandbox/sdk/guides/file-watching.mdx @@ -502,7 +502,7 @@ File watchers are automatically stopped when the sandbox sleeps or shuts down. I ## Related resources -- [File Watching API reference](/sandbox/api/file-watching/) — Complete API documentation and types -- [Manage files guide](/sandbox/guides/manage-files/) — File operations -- [Background processes guide](/sandbox/guides/background-processes/) — Long-running processes -- [Stream output guide](/sandbox/guides/streaming-output/) — Real-time output handling +- [File Watching API reference](/sandbox/sdk/api/file-watching/) — Complete API documentation and types +- [Manage files guide](/sandbox/sdk/guides/manage-files/) — File operations +- [Background processes guide](/sandbox/sdk/guides/background-processes/) — Long-running processes +- [Stream output guide](/sandbox/sdk/guides/streaming-output/) — Real-time output handling diff --git a/src/content/docs/sandbox/guides/git-workflows.mdx b/src/content/docs/sandbox/sdk/guides/git-workflows.mdx similarity index 83% rename from src/content/docs/sandbox/guides/git-workflows.mdx rename to src/content/docs/sandbox/sdk/guides/git-workflows.mdx index 3bdee312e43..d76c8fe7cd0 100644 --- a/src/content/docs/sandbox/guides/git-workflows.mdx +++ b/src/content/docs/sandbox/sdk/guides/git-workflows.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; This guide shows you how to clone repositories, manage branches, and automate Git operations in the sandbox. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents `sandbox.gitCheckout()` on today's stable `@cloudflare/sandbox` package. - -On the **1.0 preview** (`@next`), `gitCheckout` is removed. Run `git` with argv `exec` — for example `sandbox.exec(['git', 'clone', url, dir])` then `await process.output()`. See the [Processes API](/sandbox/1-0-preview/api/processes/) and [Migrate](/sandbox/1-0-preview/migrate/). -::: - ## Clone repositories @@ -60,7 +54,7 @@ await sandbox.gitCheckout(repoUrl); :::note[More secure alternative] -Embedding a token in the URL passes the credential directly into the sandbox. For better access control, use an outbound handler that injects the real token at request time — the sandbox never holds the credential. Refer to [Handle outbound traffic](/sandbox/guides/outbound-traffic/). +Embedding a token in the URL passes the credential directly into the sandbox. For better access control, use an outbound handler that injects the real token at request time — the sandbox never holds the credential. Refer to [Handle outbound traffic](/sandbox/sdk/guides/outbound-traffic/). ::: ## Clone and build @@ -150,6 +144,6 @@ await sandbox.gitCheckout('https://github.com/user/large-repo', { ## Related resources -- [Files API reference](/sandbox/api/files/) - File operations after cloning -- [Execute commands guide](/sandbox/guides/execute-commands/) - Run git commands -- [Manage files guide](/sandbox/guides/manage-files/) - Work with cloned files +- [Files API reference](/sandbox/sdk/api/files/) - File operations after cloning +- [Execute commands guide](/sandbox/sdk/guides/execute-commands/) - Run git commands +- [Manage files guide](/sandbox/sdk/guides/manage-files/) - Work with cloned files diff --git a/src/content/docs/sandbox/guides/index.mdx b/src/content/docs/sandbox/sdk/guides/index.mdx similarity index 67% rename from src/content/docs/sandbox/guides/index.mdx rename to src/content/docs/sandbox/sdk/guides/index.mdx index 114fee0fff3..f4feea9cc3a 100644 --- a/src/content/docs/sandbox/guides/index.mdx +++ b/src/content/docs/sandbox/sdk/guides/index.mdx @@ -12,9 +12,9 @@ import { ResourcesBySelector } from "~/components"; These guides show you how to solve specific problems and implement features with the Sandbox SDK. Each guide focuses on a particular task and provides practical, production-ready solutions. - + ## Related resources -- [Tutorials](/sandbox/tutorials/) - Step-by-step learning paths -- [API reference](/sandbox/api/) - Complete method documentation +- [Tutorials](/sandbox/sdk/tutorials/) - Step-by-step learning paths +- [API reference](/sandbox/sdk/api/) - Complete method documentation diff --git a/src/content/docs/sandbox/guides/manage-files.mdx b/src/content/docs/sandbox/sdk/guides/manage-files.mdx similarity index 92% rename from src/content/docs/sandbox/guides/manage-files.mdx rename to src/content/docs/sandbox/sdk/guides/manage-files.mdx index 77da730d99e..146f688fa32 100644 --- a/src/content/docs/sandbox/guides/manage-files.mdx +++ b/src/content/docs/sandbox/sdk/guides/manage-files.mdx @@ -76,7 +76,7 @@ return new Response(imageFile.content, { :::note -For more details on the `rpc` transport please see the [Transport](/sandbox/configuration/transport/) docs. +For more details on the `rpc` transport please see the [Transport](/sandbox/sdk/configuration/transport/) docs. ::: ## Organize files @@ -213,7 +213,7 @@ try { ## Related resources -- [Files API reference](/sandbox/api/files/) - Complete method documentation -- [Execute commands guide](/sandbox/guides/execute-commands/) - Run file operations with commands -- [Git workflows guide](/sandbox/guides/git-workflows/) - Clone and manage repositories -- [Code Interpreter guide](/sandbox/guides/code-execution/) - Generate and execute code files +- [Files API reference](/sandbox/sdk/api/files/) - Complete method documentation +- [Execute commands guide](/sandbox/sdk/guides/execute-commands/) - Run file operations with commands +- [Git workflows guide](/sandbox/sdk/guides/git-workflows/) - Clone and manage repositories +- [Code Interpreter guide](/sandbox/sdk/guides/code-execution/) - Generate and execute code files diff --git a/src/content/docs/sandbox/guides/mount-buckets.mdx b/src/content/docs/sandbox/sdk/guides/mount-buckets.mdx similarity index 95% rename from src/content/docs/sandbox/guides/mount-buckets.mdx rename to src/content/docs/sandbox/sdk/guides/mount-buckets.mdx index c02539a2980..3ea300d9612 100644 --- a/src/content/docs/sandbox/guides/mount-buckets.mdx +++ b/src/content/docs/sandbox/sdk/guides/mount-buckets.mdx @@ -13,7 +13,7 @@ import { TypeScriptExample, WranglerConfig } from "~/components"; Mount S3-compatible object storage buckets as local filesystem paths. Access object storage using standard file operations. For Cloudflare R2 in production, you can also mount by Worker R2 binding name so credentials stay in the Worker runtime. :::caution[Mounting `/workspace`] -Mounting a bucket at `/workspace` or a subpath under it can be confusing in app or project setups. In production, the mount overlays that path instead of merging with files already in the image or template. If you want `/workspace` itself to persist over time, [Backup and restore](/sandbox/guides/backup-restore/) is often a better fit. +Mounting a bucket at `/workspace` or a subpath under it can be confusing in app or project setups. In production, the mount overlays that path instead of merging with files already in the image or template. If you want `/workspace` itself to persist over time, [Backup and restore](/sandbox/sdk/guides/backup-restore/) is often a better fit. ::: :::note[S3-compatible providers] @@ -449,10 +449,10 @@ await sandbox.exec('cp', { args: ['/workspace/results.json', '/data/results/outp ## Related resources -- [Persistent storage tutorial](/sandbox/tutorials/persistent-storage/) - Complete R2 example -- [Backup and restore](/sandbox/guides/backup-restore/) - Persist a project directory such as `/workspace` -- [Storage API reference](/sandbox/api/storage/) - Full method documentation -- [Environment variables](/sandbox/configuration/environment-variables/) - Credential configuration for remote endpoint mounts -- [Wrangler configuration](/sandbox/configuration/wrangler/) - Configure R2 bindings and compatibility flags +- [Persistent storage tutorial](/sandbox/sdk/tutorials/persistent-storage/) - Complete R2 example +- [Backup and restore](/sandbox/sdk/guides/backup-restore/) - Persist a project directory such as `/workspace` +- [Storage API reference](/sandbox/sdk/api/storage/) - Full method documentation +- [Environment variables](/sandbox/sdk/configuration/environment-variables/) - Credential configuration for remote endpoint mounts +- [Wrangler configuration](/sandbox/sdk/configuration/wrangler/) - Configure R2 bindings and compatibility flags - [R2 documentation](/r2/) - Learn about Cloudflare R2 -- [Outbound traffic](/sandbox/guides/outbound-traffic/) - Learn how `ContainerProxy` and outbound interception work +- [Outbound traffic](/sandbox/sdk/guides/outbound-traffic/) - Learn how `ContainerProxy` and outbound interception work diff --git a/src/content/docs/sandbox/guides/outbound-traffic.mdx b/src/content/docs/sandbox/sdk/guides/outbound-traffic.mdx similarity index 95% rename from src/content/docs/sandbox/guides/outbound-traffic.mdx rename to src/content/docs/sandbox/sdk/guides/outbound-traffic.mdx index e3da306c4a5..630bfe8c59e 100644 --- a/src/content/docs/sandbox/guides/outbound-traffic.mdx +++ b/src/content/docs/sandbox/sdk/guides/outbound-traffic.mdx @@ -18,7 +18,7 @@ Use them to: - Safely inject authorization headers or tokens - Transparently reroute traffic - Add custom policy on outbound traffic (such as denying specific HTTP requests) -- [Connect to Workers bindings](/sandbox/guides/workers-connections/) like KV, R2, and Durable Objects +- [Connect to Workers bindings](/sandbox/sdk/guides/workers-connections/) like KV, R2, and Durable Objects ## Block outbound traffic @@ -288,7 +288,7 @@ Requests are evaluated in this order: ## Related resources -- [Connect to Workers bindings](/sandbox/guides/workers-connections/) — Access KV, R2, Durable Objects, and other bindings from a sandbox +- [Connect to Workers bindings](/sandbox/sdk/guides/workers-connections/) — Access KV, R2, Durable Objects, and other bindings from a sandbox - [Handle outbound traffic (Containers)](/containers/guides/outbound-traffic/) — Container SDK API for outbound handlers -- [Sandbox options](/sandbox/configuration/sandbox-options/) — Configure sandbox behavior -- [Environment variables](/sandbox/configuration/environment-variables/) — Configure secrets and environment variables +- [Sandbox options](/sandbox/sdk/configuration/sandbox-options/) — Configure sandbox behavior +- [Environment variables](/sandbox/sdk/configuration/environment-variables/) — Configure secrets and environment variables diff --git a/src/content/docs/sandbox/guides/preview-urls-custom-domain.mdx b/src/content/docs/sandbox/sdk/guides/preview-urls-custom-domain.mdx similarity index 81% rename from src/content/docs/sandbox/guides/preview-urls-custom-domain.mdx rename to src/content/docs/sandbox/sdk/guides/preview-urls-custom-domain.mdx index a32360e0d60..565ffa1efbb 100644 --- a/src/content/docs/sandbox/guides/preview-urls-custom-domain.mdx +++ b/src/content/docs/sandbox/sdk/guides/preview-urls-custom-domain.mdx @@ -10,16 +10,12 @@ products: import { WranglerConfig } from "~/components"; -Set up wildcard DNS, routes, and TLS so `exposePort()` preview URLs work on your domain. To deploy the Worker and sandbox image, refer to [Deploy a Sandbox application](/sandbox/guides/deploy/). +Set up wildcard DNS, routes, and TLS so `exposePort()` preview URLs work on your domain. To deploy the Worker and sandbox image, refer to [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/). :::note[Only required for preview URLs] Custom domain setup is only needed if you use `exposePort()` to expose services from sandboxes. If your application does not use `exposePort()`, you can deploy to `.workers.dev` without this configuration. -For public URLs without custom-domain setup, [`sandbox.tunnels`](/sandbox/api/tunnels/) is an alternative: quick tunnels for development, named tunnels for stable hostnames in production. -::: - -:::note[Sandbox SDK 1.0 preview] -Command examples that use `startProcess` are stable-only. On **`@next`**, use argv `exec` process handles. Refer to [Process execution](/sandbox/1-0-preview/processes/). Package and image still must match on the same release line. +For public URLs without custom-domain setup, [`sandbox.tunnels`](/sandbox/sdk/api/tunnels/) is an alternative: quick tunnels for development, named tunnels for stable hostnames in production. ::: Preview URLs need wildcard DNS because each exposed port gets a unique subdomain: `https://8080-abc123.yourdomain.com`. @@ -41,7 +37,7 @@ You have three options: - Active Cloudflare zone with a domain - Worker that uses `exposePort()` - [Wrangler CLI](/workers/wrangler/install-and-update/) installed -- Sandbox app already [deployable](/sandbox/guides/deploy/) (Worker + image) +- Sandbox app already [deployable](/sandbox/sdk/guides/deploy/) (Worker + image) ## Setup @@ -87,7 +83,7 @@ Redeploy the Worker so the route configuration takes effect: npx wrangler deploy ``` -If this deploy also changes your sandbox image or package, follow [Deploy a Sandbox application](/sandbox/guides/deploy/) for rollout and package/image pairing. For route-only changes you can still use a normal deploy. Use `--containers-rollout=none` only when you intentionally skip container image and instance updates. +If this deploy also changes your sandbox image or package, follow [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/) for rollout and package/image pairing. For route-only changes you can still use a normal deploy. Use `--containers-rollout=none` only when you intentionally skip container image and instance updates. ## Verify @@ -118,9 +114,9 @@ For detailed troubleshooting, see the [Workers routing documentation](/workers/c ## Related -- [Deploy a Sandbox application](/sandbox/guides/deploy/) - Deploy Worker and image -- [Preview URLs](/sandbox/concepts/preview-urls/) - How preview URLs work -- [Expose services](/sandbox/guides/expose-services/) - Patterns for exposing ports -- [Tunnels API](/sandbox/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for development +- [Deploy a Sandbox application](/sandbox/sdk/guides/deploy/) - Deploy Worker and image +- [Preview URLs](/sandbox/sdk/concepts/preview-urls/) - How preview URLs work +- [Expose services](/sandbox/sdk/guides/expose-services/) - Patterns for exposing ports +- [Tunnels API](/sandbox/sdk/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for development - [Workers routing](/workers/configuration/routing/) - Advanced routing configuration - [Cloudflare DNS](/dns/) - DNS management diff --git a/src/content/docs/sandbox/guides/proxy-requests.mdx b/src/content/docs/sandbox/sdk/guides/proxy-requests.mdx similarity index 85% rename from src/content/docs/sandbox/guides/proxy-requests.mdx rename to src/content/docs/sandbox/sdk/guides/proxy-requests.mdx index 96cfcf3e0f4..1c994e4f1b3 100644 --- a/src/content/docs/sandbox/guides/proxy-requests.mdx +++ b/src/content/docs/sandbox/sdk/guides/proxy-requests.mdx @@ -11,5 +11,5 @@ noindex: true --- :::caution[Outdated guide] -This guide is outdated. For the current guidance, refer to [Handle outbound traffic](/sandbox/guides/outbound-traffic/). +This guide is outdated. For the current guidance, refer to [Handle outbound traffic](/sandbox/sdk/guides/outbound-traffic/). ::: diff --git a/src/content/docs/sandbox/guides/streaming-output.mdx b/src/content/docs/sandbox/sdk/guides/streaming-output.mdx similarity index 84% rename from src/content/docs/sandbox/guides/streaming-output.mdx rename to src/content/docs/sandbox/sdk/guides/streaming-output.mdx index b1571686513..29e91457dc0 100644 --- a/src/content/docs/sandbox/guides/streaming-output.mdx +++ b/src/content/docs/sandbox/sdk/guides/streaming-output.mdx @@ -12,12 +12,6 @@ import { TypeScriptExample } from "~/components"; This guide shows you how to handle real-time output from commands, processes, and code execution. -:::note[Coming soon: Sandbox SDK 1.0] -This page documents streaming helpers on today's stable `@cloudflare/sandbox` package. - -In the **1.0 preview** (`@next`), stream with process handle methods such as `logs()` after `exec(argv)`. Refer to [Process execution](/sandbox/1-0-preview/processes/) or the [Processes API](/sandbox/1-0-preview/api/processes/). -::: - ## When to use streaming Use streaming when you need: @@ -174,7 +168,7 @@ for await (const event of parseSSEStream(stream)) { ## Related resources -- [Commands API reference](/sandbox/api/commands/) - Complete streaming API -- [Execute commands guide](/sandbox/guides/execute-commands/) - Command execution patterns -- [Background processes guide](/sandbox/guides/background-processes/) - Process log streaming -- [Code Interpreter guide](/sandbox/guides/code-execution/) - Stream code execution output +- [Commands API reference](/sandbox/sdk/api/commands/) - Complete streaming API +- [Execute commands guide](/sandbox/sdk/guides/execute-commands/) - Command execution patterns +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Process log streaming +- [Code Interpreter guide](/sandbox/sdk/guides/code-execution/) - Stream code execution output diff --git a/src/content/docs/sandbox/guides/websocket-connections.mdx b/src/content/docs/sandbox/sdk/guides/websocket-connections.mdx similarity index 94% rename from src/content/docs/sandbox/guides/websocket-connections.mdx rename to src/content/docs/sandbox/sdk/guides/websocket-connections.mdx index f63858ba22b..c85c77912fa 100644 --- a/src/content/docs/sandbox/guides/websocket-connections.mdx +++ b/src/content/docs/sandbox/sdk/guides/websocket-connections.mdx @@ -248,7 +248,7 @@ Port exposure in Dockerfile is only required for local development. In productio ## Related resources -- [Ports API reference](/sandbox/api/ports/) - Complete API documentation -- [Preview URLs concept](/sandbox/concepts/preview-urls/) - How preview URLs work -- [Tunnels API](/sandbox/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for WebSocket services in development -- [Background processes guide](/sandbox/guides/background-processes/) - Managing long-running services +- [Ports API reference](/sandbox/sdk/api/ports/) - Complete API documentation +- [Preview URLs concept](/sandbox/sdk/concepts/preview-urls/) - How preview URLs work +- [Tunnels API](/sandbox/sdk/api/tunnels/) - Zero-config `*.trycloudflare.com` URLs for WebSocket services in development +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Managing long-running services diff --git a/src/content/docs/sandbox/guides/workers-connections.mdx b/src/content/docs/sandbox/sdk/guides/workers-connections.mdx similarity index 80% rename from src/content/docs/sandbox/guides/workers-connections.mdx rename to src/content/docs/sandbox/sdk/guides/workers-connections.mdx index 4b20890c316..13ea764578c 100644 --- a/src/content/docs/sandbox/guides/workers-connections.mdx +++ b/src/content/docs/sandbox/sdk/guides/workers-connections.mdx @@ -13,7 +13,7 @@ products: import { TypeScriptExample } from "~/components"; -Sandboxes can access [Workers bindings](/workers/runtime-apis/bindings/) — KV, R2, D1, Durable Objects, and others — through [outbound handlers](/sandbox/guides/outbound-traffic/#define-outbound-handlers). An outbound handler intercepts HTTP requests from the sandbox and runs inside the Workers runtime, where all of your configured bindings are available. +Sandboxes can access [Workers bindings](/workers/runtime-apis/bindings/) — KV, R2, D1, Durable Objects, and others — through [outbound handlers](/sandbox/sdk/guides/outbound-traffic/#define-outbound-handlers). An outbound handler intercepts HTTP requests from the sandbox and runs inside the Workers runtime, where all of your configured bindings are available. The sandbox makes a plain HTTP request to a virtual hostname (for example, `http://my.kv/some-key`), and the outbound handler resolves it using the bound resource. No SDK or client library is required inside the sandbox. @@ -78,6 +78,6 @@ MySandbox.outboundByHost = { ## Related resources -- [Handle outbound traffic](/sandbox/guides/outbound-traffic/) — Block, allow, and intercept all outbound HTTP from a sandbox -- [Sandbox options](/sandbox/configuration/sandbox-options/) — Configure sandbox behavior -- [Environment variables](/sandbox/configuration/environment-variables/) — Configure secrets and environment variables +- [Handle outbound traffic](/sandbox/sdk/guides/outbound-traffic/) — Block, allow, and intercept all outbound HTTP from a sandbox +- [Sandbox options](/sandbox/sdk/configuration/sandbox-options/) — Configure sandbox behavior +- [Environment variables](/sandbox/sdk/configuration/environment-variables/) — Configure secrets and environment variables diff --git a/src/content/docs/sandbox/sdk/index.mdx b/src/content/docs/sandbox/sdk/index.mdx new file mode 100644 index 00000000000..63cb4cc8bf3 --- /dev/null +++ b/src/content/docs/sandbox/sdk/index.mdx @@ -0,0 +1,395 @@ +--- +title: Sandbox SDK +description: Build secure, isolated code execution environments powered by Cloudflare Workers and Containers. +pcx_content_type: overview +sidebar: + order: 2 + label: Sandbox SDK +head: + - tag: title + content: Sandbox SDK +products: + - sandbox + - workers + - containers +--- + +import { + CardGrid, + Description, + Feature, + LinkTitleCard, + Plan, + RelatedProduct, + LinkButton, + Tabs, + TabItem, +} from "~/components"; + + + +Build secure, isolated code execution environments + + + + + +The Sandbox SDK enables you to run untrusted code securely in isolated environments. Built on [Containers](/containers/), Sandbox SDK provides a simple API for executing commands, managing files, running background processes, and exposing services — all from your [Workers](/workers/) applications. + +Sandboxes are ideal for building AI agents that need to execute code, interactive development environments, data analysis platforms, CI/CD systems, and any application that needs secure code execution at the edge. Each sandbox runs in its own isolated container with a full Linux environment, providing strong security boundaries while maintaining performance. + +With Sandbox, you can execute Python scripts, run Node.js applications, analyze data, compile code, and perform complex computations — all with a simple TypeScript API and no infrastructure to manage. + + + + ```typescript + import { getSandbox } from '@cloudflare/sandbox'; + + export { Sandbox } from '@cloudflare/sandbox'; + + export default { + async fetch(request: Request, env: Env): Promise { + const sandbox = getSandbox(env.Sandbox, 'user-123'); + + // Execute a command and get the result + const result = await sandbox.exec('python --version'); + + return Response.json({ + output: result.stdout, + exitCode: result.exitCode, + success: result.success + }); + } + }; + ``` + + + + + ```typescript + import { getSandbox } from '@cloudflare/sandbox'; + + export { Sandbox } from '@cloudflare/sandbox'; + + export default { + async fetch(request: Request, env: Env): Promise { + const sandbox = getSandbox(env.Sandbox, 'user-123'); + + // Create a Python execution context + const ctx = await sandbox.createCodeContext({ language: 'python' }); + + // Execute Python code with automatic result capture + const result = await sandbox.runCode(` + import pandas as pd + data = {'product': ['A', 'B', 'C'], 'sales': [100, 200, 150]} + df = pd.DataFrame(data) + df['sales'].sum() # Last expression is automatically returned + `, { context: ctx }); + + return Response.json({ + result: result.results?.[0]?.text, + logs: result.logs + }); + } + }; + ``` + + + + ```typescript + import { getSandbox } from '@cloudflare/sandbox'; + + export { Sandbox } from '@cloudflare/sandbox'; + + export default { + async fetch(request: Request, env: Env): Promise { + const sandbox = getSandbox(env.Sandbox, 'user-123'); + + // Create a project structure + await sandbox.mkdir('/workspace/project/src', { recursive: true }); + + // Write files + await sandbox.writeFile( + '/workspace/project/package.json', + JSON.stringify({ name: 'my-app', version: '1.0.0' }) + ); + + // Read a file back + const content = await sandbox.readFile('/workspace/project/package.json'); + + return Response.json({ content }); + } + }; + ``` + + + + ```typescript + import { getSandbox } from '@cloudflare/sandbox'; + + export { Sandbox } from '@cloudflare/sandbox'; + + export default { + async fetch(request: Request, env: Env): Promise { + const sandbox = getSandbox(env.Sandbox, 'user-123'); + + // Watch for file changes in real-time + const watcher = await sandbox.watch('/workspace/src', { + include: ['*.js', '*.ts'], + onEvent: (event) => { + console.log(`${event.type}: ${event.path}`); + if (event.type === 'modify') { + // Trigger rebuild or hot reload + console.log('Code changed, recompiling...'); + } + }, + onError: (error) => { + console.error('Watch error:', error); + } + }); + + // Stop watching when done + setTimeout(() => watcher.stop(), 60000); + + return Response.json({ message: 'File watcher started' }); + } + }; + ``` + + + + ```typescript + import { getSandbox } from '@cloudflare/sandbox'; + + export { Sandbox } from '@cloudflare/sandbox'; + + export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + + // Terminal WebSocket connection + if (url.pathname === '/ws/terminal') { + const sandbox = getSandbox(env.Sandbox, 'user-123'); + return sandbox.terminal(request, { cols: 80, rows: 24 }); + } + + return Response.json({ message: 'Terminal endpoint' }); + } + }; + ``` + + Connect browser terminals directly to sandbox shells via WebSocket. Learn more: [Browser terminals](/sandbox/sdk/guides/browser-terminals/). + + + + ```typescript + import { getSandbox } from '@cloudflare/sandbox'; + + export { Sandbox } from '@cloudflare/sandbox'; + + export default { + async fetch(request: Request, env: Env): Promise { + // Connect to WebSocket services in sandbox + if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') { + const sandbox = getSandbox(env.Sandbox, 'user-123'); + return await sandbox.wsConnect(request, 8080); + } + + return Response.json({ message: 'WebSocket endpoint' }); + } + }; + ``` + + Connect to WebSocket servers running in sandboxes. Learn more: [WebSocket Connections](/sandbox/sdk/guides/websocket-connections/). + + + + + + Get started + + + API Reference + + +--- + +## Features + + + +Deploy your Worker and keep the npm package and container image on the same release line. + + + + + +Run shell commands, Python scripts, Node.js applications, and more with streaming output support and automatic timeout handling. + + + + + +Read, write, and manipulate files in the sandbox filesystem. Run background processes, monitor output, and manage long-running operations. + + + + + +Expose HTTP services running in your sandbox with automatically generated preview URLs, perfect for interactive development environments and application hosting. + + + + + +Execute Python and JavaScript code with rich outputs including charts, tables, and images. Maintain persistent state between executions for AI-generated code and interactive workflows. + + + + + +Create browser-based terminal interfaces that connect directly to sandbox shells via WebSocket. Build collaborative terminals, interactive development environments, and real-time shell access with automatic reconnection. + + + + + +Mount S3-compatible object storage (R2, S3, GCS, and more) as local filesystems. Access buckets using standard file operations with data that persists across sandbox lifecycles. Production deployment required. + + + + + +Monitor files and directories for changes using native filesystem events. Perfect for building hot reloading development servers, build automation systems, and configuration monitoring tools. + + + + + +Block, allow, and intercept outbound HTTP from sandboxes. Keep credentials in your Worker by injecting authorization headers in outbound handlers. + + + +--- + +## Use Cases + +Build powerful applications with Sandbox: + +### AI Code Execution + +Execute code generated by Large Language Models safely and reliably. Native integration with [Workers AI](/workers-ai/) models like GPT-OSS enables function calling with sandbox execution. Perfect for AI agents, code assistants, and autonomous systems that need to run untrusted code. + +### Data Analysis & Notebooks + +Create interactive data analysis environments with pandas, NumPy, and Matplotlib. Generate charts, tables, and visualizations with automatic rich output formatting. + +### Interactive Development Environments + +Build cloud IDEs, coding playgrounds, and collaborative development tools with full Linux environments and preview URLs. + +### CI/CD & Build Systems + +Run tests, compile code, and execute build pipelines in isolated environments with parallel execution and streaming logs. + +--- + +## Related products + + + +Serverless container runtime that powers Sandbox, enabling you to run any containerized workload on the edge. + + + + + +Run machine learning models and LLMs on the network. Combine with Sandbox for secure AI code execution workflows. + + + + + +Stateful coordination layer that enables Sandbox to maintain persistent environments with strong consistency. + + + +--- + +## More resources + +## Coding agents + +Install [Cloudflare Skills](https://github.com/cloudflare/skills) for your agent ([Agent setup](/agent-setup/)). Use **`sandbox-stable`** with these Sandbox SDK docs. + + + + + Explore complete examples including AI code execution, data analysis, and + interactive environments. + + + + Deploy and keep package and image aligned. + + + + Learn how to solve specific problems and implement features with the Sandbox + SDK. + + + + Explore the complete API documentation for the Sandbox SDK. + + + + Learn about the key concepts and architecture of the Sandbox SDK. + + + + Learn about the configuration options for the Sandbox SDK. + + + + View the SDK source code, report issues, and contribute to the project. + + + + Understand Sandbox pricing based on the underlying Containers platform. + + + + Learn about resource limits, quotas, and best practices for working within + them. + + + + Connect with the community on Discord. Ask questions, share what you're + building, and get help from other developers. + + + diff --git a/src/content/docs/sandbox/platform/index.mdx b/src/content/docs/sandbox/sdk/platform/index.mdx similarity index 73% rename from src/content/docs/sandbox/platform/index.mdx rename to src/content/docs/sandbox/sdk/platform/index.mdx index d53b91d2d10..31512aacc06 100644 --- a/src/content/docs/sandbox/platform/index.mdx +++ b/src/content/docs/sandbox/sdk/platform/index.mdx @@ -12,7 +12,7 @@ Information about the Sandbox SDK platform, including pricing and limits. ## Available resources -- [Pricing](/sandbox/platform/pricing/) - Understand costs based on the Containers platform -- [Limits](/sandbox/platform/limits/) - Resource limits and best practices +- [Pricing](/sandbox/sdk/platform/pricing/) - Understand costs based on the Containers platform +- [Limits](/sandbox/sdk/platform/limits/) - Resource limits and best practices Since Sandbox SDK is built on [Containers](/containers/), it shares the same underlying platform characteristics. Refer to these pages to understand how pricing and limits work for your sandbox deployments. diff --git a/src/content/docs/sandbox/platform/limits.mdx b/src/content/docs/sandbox/sdk/platform/limits.mdx similarity index 94% rename from src/content/docs/sandbox/platform/limits.mdx rename to src/content/docs/sandbox/sdk/platform/limits.mdx index d5cd7e74497..ed51da34b05 100644 --- a/src/content/docs/sandbox/platform/limits.mdx +++ b/src/content/docs/sandbox/sdk/platform/limits.mdx @@ -53,7 +53,7 @@ With RPC transport enabled: - All subsequent SDK operations use the existing connection (no additional subrequests) - Ideal for workflows with many SDK operations per request -See [Transport modes](/sandbox/configuration/transport/) for a complete guide. +See [Transport modes](/sandbox/sdk/configuration/transport/) for a complete guide. ## Best practices @@ -61,5 +61,5 @@ To work within these limits: - **Right-size your instances** - Choose the appropriate [instance type](/containers/platform/limits/#instance-types) based on your workload requirements - **Clean up unused sandboxes** - Terminate sandbox sessions when they are no longer needed to free up resources -- **Optimize images** - Keep your [custom Dockerfiles](/sandbox/configuration/dockerfile/) lean to reduce image size +- **Optimize images** - Keep your [custom Dockerfiles](/sandbox/sdk/configuration/dockerfile/) lean to reduce image size - **Use RPC transport for high-frequency operations** - Enable `SANDBOX_TRANSPORT=rpc` to avoid subrequest limits when making many SDK calls per request diff --git a/src/content/docs/sandbox/platform/pricing.mdx b/src/content/docs/sandbox/sdk/platform/pricing.mdx similarity index 100% rename from src/content/docs/sandbox/platform/pricing.mdx rename to src/content/docs/sandbox/sdk/platform/pricing.mdx diff --git a/src/content/docs/sandbox/tutorials/ai-code-executor.mdx b/src/content/docs/sandbox/sdk/tutorials/ai-code-executor.mdx similarity index 92% rename from src/content/docs/sandbox/tutorials/ai-code-executor.mdx rename to src/content/docs/sandbox/sdk/tutorials/ai-code-executor.mdx index 992afa80321..e55368fbcfb 100644 --- a/src/content/docs/sandbox/tutorials/ai-code-executor.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/ai-code-executor.mdx @@ -235,11 +235,11 @@ You created an AI code execution system that: ## Next steps -- [Code interpreter with Workers AI](/sandbox/tutorials/workers-ai-code-interpreter/) - Use Cloudflare's native AI models with official packages -- [Analyze data with AI](/sandbox/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for data analysis -- [Code Interpreter API](/sandbox/api/interpreter/) - Use the built-in code interpreter instead of exec -- [Streaming output](/sandbox/guides/streaming-output/) - Show real-time execution progress -- [API reference](/sandbox/api/) - Explore all available methods +- [Code interpreter with Workers AI](/sandbox/sdk/tutorials/workers-ai-code-interpreter/) - Use Cloudflare's native AI models with official packages +- [Analyze data with AI](/sandbox/sdk/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for data analysis +- [Code Interpreter API](/sandbox/sdk/api/interpreter/) - Use the built-in code interpreter instead of exec +- [Streaming output](/sandbox/sdk/guides/streaming-output/) - Show real-time execution progress +- [API reference](/sandbox/sdk/api/) - Explore all available methods ## Related resources diff --git a/src/content/docs/sandbox/tutorials/analyze-data-with-ai.mdx b/src/content/docs/sandbox/sdk/tutorials/analyze-data-with-ai.mdx similarity index 96% rename from src/content/docs/sandbox/tutorials/analyze-data-with-ai.mdx rename to src/content/docs/sandbox/sdk/tutorials/analyze-data-with-ai.mdx index 5497b602e6f..4410d92be4b 100644 --- a/src/content/docs/sandbox/tutorials/analyze-data-with-ai.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/analyze-data-with-ai.mdx @@ -293,6 +293,6 @@ An AI data analysis system that: ## Next steps -- [Code Interpreter API](/sandbox/api/interpreter/) - Use the built-in code interpreter -- [File operations](/sandbox/guides/manage-files/) - Advanced file handling -- [Streaming output](/sandbox/guides/streaming-output/) - Real-time progress updates +- [Code Interpreter API](/sandbox/sdk/api/interpreter/) - Use the built-in code interpreter +- [File operations](/sandbox/sdk/guides/manage-files/) - Advanced file handling +- [Streaming output](/sandbox/sdk/guides/streaming-output/) - Real-time progress updates diff --git a/src/content/docs/sandbox/tutorials/automated-testing-pipeline.mdx b/src/content/docs/sandbox/sdk/tutorials/automated-testing-pipeline.mdx similarity index 95% rename from src/content/docs/sandbox/tutorials/automated-testing-pipeline.mdx rename to src/content/docs/sandbox/sdk/tutorials/automated-testing-pipeline.mdx index 8eb71e18f8c..72807f93705 100644 --- a/src/content/docs/sandbox/tutorials/automated-testing-pipeline.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/automated-testing-pipeline.mdx @@ -232,6 +232,6 @@ An automated testing pipeline that: ## Next steps -- [Streaming output](/sandbox/guides/streaming-output/) - Add real-time test output -- [Background processes](/sandbox/guides/background-processes/) - Handle long-running tests -- [Sessions API](/sandbox/api/sessions/) - Cache dependencies between runs +- [Streaming output](/sandbox/sdk/guides/streaming-output/) - Add real-time test output +- [Background processes](/sandbox/sdk/guides/background-processes/) - Handle long-running tests +- [Sessions API](/sandbox/sdk/api/sessions/) - Cache dependencies between runs diff --git a/src/content/docs/sandbox/tutorials/claude-code.mdx b/src/content/docs/sandbox/sdk/tutorials/claude-code.mdx similarity index 88% rename from src/content/docs/sandbox/tutorials/claude-code.mdx rename to src/content/docs/sandbox/sdk/tutorials/claude-code.mdx index ffe141ec6cf..d07b27652ed 100644 --- a/src/content/docs/sandbox/tutorials/claude-code.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/claude-code.mdx @@ -117,10 +117,10 @@ You created an API that: ## Next steps -- [Analyze data with AI](/sandbox/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for data analysis -- [Code Interpreter API](/sandbox/api/interpreter/) - Use the built-in code interpreter instead of exec -- [Streaming output](/sandbox/guides/streaming-output/) - Show real-time execution progress -- [API reference](/sandbox/api/) - Explore all available methods +- [Analyze data with AI](/sandbox/sdk/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for data analysis +- [Code Interpreter API](/sandbox/sdk/api/interpreter/) - Use the built-in code interpreter instead of exec +- [Streaming output](/sandbox/sdk/guides/streaming-output/) - Show real-time execution progress +- [API reference](/sandbox/sdk/api/) - Explore all available methods ## Related resources diff --git a/src/content/docs/sandbox/tutorials/claude-managed-agents.mdx b/src/content/docs/sandbox/sdk/tutorials/claude-managed-agents.mdx similarity index 100% rename from src/content/docs/sandbox/tutorials/claude-managed-agents.mdx rename to src/content/docs/sandbox/sdk/tutorials/claude-managed-agents.mdx diff --git a/src/content/docs/sandbox/tutorials/code-review-bot.mdx b/src/content/docs/sandbox/sdk/tutorials/code-review-bot.mdx similarity index 98% rename from src/content/docs/sandbox/tutorials/code-review-bot.mdx rename to src/content/docs/sandbox/sdk/tutorials/code-review-bot.mdx index daeeff91090..5d75355ad32 100644 --- a/src/content/docs/sandbox/tutorials/code-review-bot.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/code-review-bot.mdx @@ -358,6 +358,6 @@ A GitHub code review bot that: ## Next steps -- [Git operations](/sandbox/api/files/#gitcheckout) - Advanced repository handling -- [Sessions API](/sandbox/api/sessions/) - Manage long-running sandbox operations +- [Git operations](/sandbox/sdk/api/files/#gitcheckout) - Advanced repository handling +- [Sessions API](/sandbox/sdk/api/sessions/) - Manage long-running sandbox operations - [GitHub Apps](https://docs.github.com/en/apps) - Build a proper GitHub App diff --git a/src/content/docs/sandbox/tutorials/cursor-cloud-agents.mdx b/src/content/docs/sandbox/sdk/tutorials/cursor-cloud-agents.mdx similarity index 100% rename from src/content/docs/sandbox/tutorials/cursor-cloud-agents.mdx rename to src/content/docs/sandbox/sdk/tutorials/cursor-cloud-agents.mdx diff --git a/src/content/docs/sandbox/tutorials/devin-outposts.mdx b/src/content/docs/sandbox/sdk/tutorials/devin-outposts.mdx similarity index 100% rename from src/content/docs/sandbox/tutorials/devin-outposts.mdx rename to src/content/docs/sandbox/sdk/tutorials/devin-outposts.mdx diff --git a/src/content/docs/sandbox/sdk/tutorials/index.mdx b/src/content/docs/sandbox/sdk/tutorials/index.mdx new file mode 100644 index 00000000000..70b392eb732 --- /dev/null +++ b/src/content/docs/sandbox/sdk/tutorials/index.mdx @@ -0,0 +1,28 @@ +--- +title: Tutorials +description: Step-by-step Sandbox SDK tutorials for building AI agents, code executors, and testing pipelines. +pcx_content_type: navigation +sidebar: + order: 4 +products: + - sandbox +--- + +import { ResourcesBySelector } from "~/components"; + +Learn how to build applications with Sandbox SDK through step-by-step tutorials. Each tutorial takes 20-30 minutes. + + + +## Before you start + +All tutorials assume you have: + +- Completed the [Get Started guide](/sandbox/sdk/get-started/) +- Basic familiarity with [Workers](/workers/) +- [Docker](https://www.docker.com/) installed and running + +## Related resources + +- [How-to guides](/sandbox/sdk/guides/) - Solve specific problems +- [API reference](/sandbox/sdk/api/) - Complete SDK reference diff --git a/src/content/docs/sandbox/tutorials/openai-agents.mdx b/src/content/docs/sandbox/sdk/tutorials/openai-agents.mdx similarity index 92% rename from src/content/docs/sandbox/tutorials/openai-agents.mdx rename to src/content/docs/sandbox/sdk/tutorials/openai-agents.mdx index f3f71779b9d..36b602fcb04 100644 --- a/src/content/docs/sandbox/tutorials/openai-agents.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/openai-agents.mdx @@ -15,11 +15,6 @@ products: import { Details } from "~/components"; -:::note[Sandbox SDK 1.0 preview] -This tutorial uses the supported stable bridge template and HTTP API. The 1.0 preview covers the Worker SDK on `@next`; bridge deployments stay on the [stable bridge](/sandbox/bridge/). -::: - - The [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/) is a lightweight Python framework for building multi-agent workflows. A Cloudflare Sandbox integration is provided out of the box and ensures that the SDK includes a first-class Cloudflare backend that gives your agents isolated containers for running code, installing packages, and managing files. In this tutorial, you will deploy a sandbox bridge Worker and build a Python agent that accepts a coding task, executes it inside a Cloudflare Sandbox, and copies the output files to your local machine. @@ -34,7 +29,7 @@ In this tutorial, you will deploy a sandbox bridge Worker and build a Python age ## 1. Deploy the sandbox bridge -The [sandbox bridge](/sandbox/bridge/) is a Cloudflare Worker that exposes the Sandbox API over HTTP so non-Worker clients — such as a Python script using the OpenAI Agents SDK — can create and control sandboxes. +The [sandbox bridge](/sandbox/sdk/bridge/) is a Cloudflare Worker that exposes the Sandbox API over HTTP so non-Worker clients — such as a Python script using the OpenAI Agents SDK — can create and control sandboxes. The Sandbox environment comes pre-configured for Node.js and Python development, so your agents can start writing and running code immediately. @@ -138,7 +133,6 @@ The sandbox has bun, node, npm, and python available on the PATH. Implement the user's task in /workspace, test it, then copy deliverable files to /workspace/output/. """.strip() - async def copy_output(session, dest: Path) -> list[Path]: """Download files from /workspace/output/ in the sandbox to a local directory.""" dest.mkdir(parents=True, exist_ok=True) @@ -154,7 +148,6 @@ async def copy_output(session, dest: Path) -> list[Path]: copied.append(local) return copied - async def run(prompt: str, output_dir: Path) -> None: worker_url = os.environ.get("CLOUDFLARE_SANDBOX_WORKER_URL", "") if not worker_url: @@ -197,7 +190,6 @@ async def run(prompt: str, output_dir: Path) -> None: finally: await client.delete(session) - if __name__ == "__main__": prompt = sys.argv[1] if len(sys.argv) > 1 else "Create a hello world HTTP server using Bun.serve" asyncio.run(run(prompt, Path("output"))) @@ -257,6 +249,6 @@ The Cloudflare Sandbox provides more capabilities you can integrate into your ag - [Workspace chat example](https://github.com/cloudflare/sandbox-sdk/tree/main/bridge/examples/workspace-chat) — A full-stack chat application with a file browser sidebar, built with the OpenAI Agents SDK and Cloudflare Sandbox. - [OpenAI Agents SDK documentation](https://openai.github.io/openai-agents-python/) — Learn about multi-agent handoffs, guardrails, tracing, and more. -- [Sandbox bridge](/sandbox/bridge/) — Overview of the bridge Worker, usage examples, and configuration. -- [HTTP API reference](/sandbox/bridge/http-api/) — Complete route reference for the bridge API. -- [Sandbox tutorials](/sandbox/tutorials/) — More tutorials covering code execution, data analysis, and CI/CD pipelines. +- [Sandbox bridge](/sandbox/sdk/bridge/) — Overview of the bridge Worker, usage examples, and configuration. +- [HTTP API reference](/sandbox/sdk/bridge/http-api/) — Complete route reference for the bridge API. +- [Sandbox tutorials](/sandbox/sdk/tutorials/) — More tutorials covering code execution, data analysis, and CI/CD pipelines. diff --git a/src/content/docs/sandbox/tutorials/persistent-storage.mdx b/src/content/docs/sandbox/sdk/tutorials/persistent-storage.mdx similarity index 93% rename from src/content/docs/sandbox/tutorials/persistent-storage.mdx rename to src/content/docs/sandbox/sdk/tutorials/persistent-storage.mdx index 7e0b0049a40..d36042bac02 100644 --- a/src/content/docs/sandbox/tutorials/persistent-storage.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/persistent-storage.mdx @@ -15,7 +15,7 @@ import { Render, PackageManagers, TypeScriptExample } from "~/components"; Mount object storage buckets as local filesystem paths to persist data across sandbox lifecycles. This tutorial uses Cloudflare R2, but the same approach works with any S3-compatible provider. -This tutorial shows how to persist an external data directory mounted at `/data`. If you want the working project in `/workspace` to persist, refer to [Backup and restore](/sandbox/guides/backup-restore/). +This tutorial shows how to persist an external data directory mounted at `/data`. If you want the working project in `/workspace` to persist, refer to [Backup and restore](/sandbox/sdk/guides/backup-restore/). **Time to complete:** 20 minutes @@ -246,12 +246,12 @@ In this tutorial, you built a data pipeline that demonstrates filesystem persist ## Next steps -- [Mount buckets guide](/sandbox/guides/mount-buckets/) - Comprehensive mounting reference -- [Storage API](/sandbox/api/storage/) - Complete API documentation -- [Environment variables](/sandbox/configuration/environment-variables/) - Credential configuration options +- [Mount buckets guide](/sandbox/sdk/guides/mount-buckets/) - Comprehensive mounting reference +- [Storage API](/sandbox/sdk/api/storage/) - Complete API documentation +- [Environment variables](/sandbox/sdk/configuration/environment-variables/) - Credential configuration options ## Related resources - [R2 documentation](/r2/) - Learn about Cloudflare R2 -- [Background processes guide](/sandbox/guides/background-processes/) - Long-running data processing -- [Sandboxes concept](/sandbox/concepts/sandboxes/) - Understanding sandbox lifecycle +- [Background processes guide](/sandbox/sdk/guides/background-processes/) - Long-running data processing +- [Sandboxes concept](/sandbox/sdk/concepts/sandboxes/) - Understanding sandbox lifecycle diff --git a/src/content/docs/sandbox/tutorials/workers-ai-code-interpreter.mdx b/src/content/docs/sandbox/sdk/tutorials/workers-ai-code-interpreter.mdx similarity index 93% rename from src/content/docs/sandbox/tutorials/workers-ai-code-interpreter.mdx rename to src/content/docs/sandbox/sdk/tutorials/workers-ai-code-interpreter.mdx index bfb4f060ecf..6f0420d5822 100644 --- a/src/content/docs/sandbox/tutorials/workers-ai-code-interpreter.mdx +++ b/src/content/docs/sandbox/sdk/tutorials/workers-ai-code-interpreter.mdx @@ -212,10 +212,10 @@ You deployed a sophisticated code interpreter that: ## Next steps -- [Analyze data with AI](/sandbox/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for advanced data analysis -- [Code Interpreter API](/sandbox/api/interpreter/) - Use the built-in code interpreter with structured outputs -- [Streaming output](/sandbox/guides/streaming-output/) - Show real-time execution progress -- [API reference](/sandbox/api/) - Explore all available sandbox methods +- [Analyze data with AI](/sandbox/sdk/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for advanced data analysis +- [Code Interpreter API](/sandbox/sdk/api/interpreter/) - Use the built-in code interpreter with structured outputs +- [Streaming output](/sandbox/sdk/guides/streaming-output/) - Show real-time execution progress +- [API reference](/sandbox/sdk/api/) - Explore all available sandbox methods ## Related resources diff --git a/src/content/docs/sandbox/tutorials/index.mdx b/src/content/docs/sandbox/tutorials/index.mdx deleted file mode 100644 index 24fe5041c52..00000000000 --- a/src/content/docs/sandbox/tutorials/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Tutorials -description: Step-by-step Sandbox SDK tutorials for building AI agents, code executors, and testing pipelines. -pcx_content_type: navigation -sidebar: - order: 4 -products: - - sandbox ---- - -:::note[Coming soon: Sandbox SDK 1.0] -These tutorials target today's stable `@cloudflare/sandbox` package and may use sessions, string `exec`, `startProcess`, `gitCheckout`, or the stable bridge template. - -For **`@next`** Worker SDK work, start from [1.0 preview](/sandbox/1-0-preview/) and [Migrate](/sandbox/1-0-preview/migrate/). Bridge deployments stay on the [stable bridge](/sandbox/bridge/). -::: - -import { ResourcesBySelector } from "~/components"; - -Learn how to build applications with Sandbox SDK through step-by-step tutorials. Each tutorial takes 20-30 minutes. - - - -## Before you start - -All tutorials assume you have: - -- Completed the [Get Started guide](/sandbox/get-started/) -- Basic familiarity with [Workers](/workers/) -- [Docker](https://www.docker.com/) installed and running - -## Related resources - -- [How-to guides](/sandbox/guides/) - Solve specific problems -- [API reference](/sandbox/api/) - Complete SDK reference