Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/content/docs/sandbox/api/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Commands
pcx_content_type: concept
sidebar:
order: 1
order: 2
---

import { Details, TypeScriptExample } from "~/components";
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/sandbox/api/files.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Files
pcx_content_type: concept
sidebar:
order: 2
order: 3
---

import { TypeScriptExample } from "~/components";
Expand Down
28 changes: 11 additions & 17 deletions src/content/docs/sandbox/api/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,24 @@ sidebar:

import { LinkTitleCard, CardGrid } from "~/components";

The Sandbox SDK provides a comprehensive API for executing code, managing files, running processes, and exposing services in isolated sandboxes. All operations are performed through the `Sandbox` instance you obtain via `getSandbox()`.

## Getting a sandbox instance

```typescript
import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(env.Sandbox, 'user-123');
```

The same sandbox ID will always return the same sandbox instance. You can architect your application to use a single sandbox ID for multiple users, or use unique IDs per user or session. Using unique sandbox IDs per user is recommended if you are providing code generation or execution capabilities directly to your users.

## API organization

The Sandbox SDK is organized into focused APIs:
The Sandbox SDK provides a comprehensive API for executing code, managing files, running processes, and exposing services in isolated sandboxes.

<CardGrid>

<LinkTitleCard
title="Lifecycle"
href="/sandbox/api/lifecycle/"
icon="rocket"
>
Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources.
</LinkTitleCard>

<LinkTitleCard
title="Commands"
href="/sandbox/api/commands/"
icon="seti:shell"
>
Execute commands and stream output. Includes `exec()`, `execStream()`, and background process management.
Execute commands and stream output. Run scripts, manage background processes, and capture execution results.
</LinkTitleCard>

<LinkTitleCard
Expand Down Expand Up @@ -62,7 +56,7 @@ The Sandbox SDK is organized into focused APIs:
href="/sandbox/api/sessions/"
icon="seti:plan"
>
Advanced: Create isolated execution contexts with persistent shell state. Configure environment variables and manage container lifecycle.
Create isolated execution contexts within a sandbox. Each session maintains its own shell state, environment variables, and working directory.
</LinkTitleCard>

</CardGrid>
2 changes: 1 addition & 1 deletion src/content/docs/sandbox/api/interpreter.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Code Interpreter
pcx_content_type: concept
sidebar:
order: 3
order: 4
---

import { TypeScriptExample } from "~/components";
Expand Down
102 changes: 102 additions & 0 deletions src/content/docs/sandbox/api/lifecycle.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
title: Lifecycle
pcx_content_type: configuration
sidebar:
order: 1
---

import { TypeScriptExample } from "~/components";

Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources.

:::note
For session-specific operations like `createSession()` and `deleteSession()`, see the [Sessions API](/sandbox/api/sessions/).
:::

## Methods

### `getSandbox()`

Get or create a sandbox instance by ID.

```ts
const sandbox = getSandbox(
binding: DurableObjectNamespace<Sandbox>,
sandboxId: string,
options?: SandboxOptions
): Sandbox
```

**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
- `options` (optional):
- `keepAlive` - Set to `true` to prevent automatic container timeout after 10 minutes of inactivity

**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.
:::

<TypeScriptExample>
```
import { getSandbox } from '@cloudflare/sandbox';

export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python script.py');
return Response.json(result);
}
};
```
</TypeScriptExample>

:::caution
When using `keepAlive: true`, you **must** call `destroy()` when finished to prevent containers running indefinitely.
:::

---

### `destroy()`

Destroy the sandbox container and free up resources.

```ts
await sandbox.destroy(): Promise<void>
```

Immediately terminates the container and permanently deletes all state:
- All files in `/workspace`, `/tmp`, and `/home`
- All running processes
- All sessions (including the default session)
- Network connections and exposed ports

<TypeScriptExample>
```
async function executeCode(code: string): Promise<string> {
const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);

try {
await sandbox.writeFile('/tmp/code.py', code);
const result = await sandbox.exec('python /tmp/code.py');
return result.stdout;
} finally {
await sandbox.destroy();
}
}
```
</TypeScriptExample>

:::note
Containers automatically sleep after 10 minutes of inactivity but still count toward account limits. Use `destroy()` to immediately free up resources.
:::

---

## 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 isolated execution contexts within a sandbox
2 changes: 1 addition & 1 deletion src/content/docs/sandbox/api/ports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Ports
pcx_content_type: concept
sidebar:
order: 4
order: 5
---

import { TypeScriptExample } from "~/components";
Expand Down
88 changes: 48 additions & 40 deletions src/content/docs/sandbox/api/sessions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,15 @@
title: Sessions
pcx_content_type: configuration
sidebar:
order: 5
order: 6
---

import { TypeScriptExample } from "~/components";

Create isolated execution contexts within a sandbox. Each session maintains its own shell state, environment variables, and working directory. See [Session management concept](/sandbox/concepts/sessions/) for details.

:::note
Every sandbox has a default session that automatically maintains shell state. Create additional sessions when you need isolated shell contexts for different environments or parallel workflows.
:::

:::note
For sandbox-level configuration options like `keepAlive`, refer to the [Sandbox options configuration](/sandbox/configuration/sandbox-options/).
Every sandbox has a default session that automatically maintains shell state. Create additional sessions when you need isolated shell contexts for different environments or parallel workflows. For sandbox-level operations like creating containers or destroying the entire sandbox, see the [Lifecycle API](/sandbox/api/lifecycle/).
:::

## Methods
Expand Down Expand Up @@ -84,6 +80,44 @@ const result = await session.exec('cd repo && npm run build');
```
</TypeScriptExample>

---

### `deleteSession()`

Delete a session and clean up its resources.

```ts
const result = await sandbox.deleteSession(sessionId: string): Promise<SessionDeleteResult>
```

**Parameters**:
- `sessionId` - ID of the session to delete (cannot be `"default"`)

**Returns**: `Promise<SessionDeleteResult>` containing:
- `success` - Whether deletion succeeded
- `sessionId` - ID of the deleted session
- `timestamp` - Deletion timestamp

<TypeScriptExample>
```
// Create a temporary session for a specific task
const tempSession = await sandbox.createSession({ id: 'temp-task' });
try {
await tempSession.exec('npm run heavy-task');
} finally {
// Clean up the session when done
await sandbox.deleteSession('temp-task');
}
```
</TypeScriptExample>

:::caution
Deleting a session immediately terminates all running commands. The default session cannot be deleted.
:::

---

### `setEnvVars()`

Set environment variables in the sandbox.
Expand Down Expand Up @@ -115,45 +149,19 @@ await sandbox.exec('python script.py');
```
</TypeScriptExample>

### `destroy()`

Destroy the sandbox container and free up resources.

```ts
await sandbox.destroy(): Promise<void>
```

:::note
Containers automatically sleep after 10 minutes of inactivity, but still count toward account limits. Use `destroy()` to immediately free up resources.

**Important**: When using [`keepAlive: true`](/sandbox/configuration/sandbox-options/#keepalive), containers will not automatically timeout, so calling `destroy()` is **required** to prevent containers running indefinitely.
:::

<TypeScriptExample>
```
async function executeCode(code: string): Promise<string> {
const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
try {
await sandbox.writeFile('/tmp/code.py', code);
const result = await sandbox.exec('python /tmp/code.py');
return result.stdout;
} finally {
await sandbox.destroy();
}
}
```
</TypeScriptExample>
---

## ExecutionSession methods

The `ExecutionSession` object has all sandbox methods bound to the specific session:

**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)
**Code Interpreter**: [`createCodeContext()`](/sandbox/api/interpreter/#createcodecontext), [`runCode()`](/sandbox/api/interpreter/#runcode), [`listCodeContexts()`](/sandbox/api/interpreter/#listcodecontexts), [`deleteCodeContext()`](/sandbox/api/interpreter/#deletecodecontext)
| 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) |
| **Code Interpreter** | [`createCodeContext()`](/sandbox/api/interpreter/#createcodecontext), [`runCode()`](/sandbox/api/interpreter/#runcode), [`listCodeContexts()`](/sandbox/api/interpreter/#listcodecontexts), [`deleteCodeContext()`](/sandbox/api/interpreter/#deletecodecontext) |

## Related resources

Expand Down
3 changes: 2 additions & 1 deletion src/content/docs/sandbox/concepts/sandboxes.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,5 @@ await sandbox.exec("python process.py");
- [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
- [Sessions API](/sandbox/api/sessions/) - Programmatic lifecycle control
- [Lifecycle API](/sandbox/api/lifecycle/) - Create and manage sandboxes
- [Sessions API](/sandbox/api/sessions/) - Create and manage execution sessions
Loading
Loading