Skip to content

Commit 587c938

Browse files
committed
Improve sandbox lifecycle documentation
Separate sandbox-level operations (getSandbox, destroy) from session-level operations by creating a new Lifecycle API page. Previously destroy() was misplaced in the Sessions API despite operating on the entire container. Add missing deleteSession() documentation and document auto-session creation behavior. Remove unnecessary comparisons between methods.
1 parent 90bba41 commit 587c938

File tree

11 files changed

+220
-72
lines changed

11 files changed

+220
-72
lines changed

src/content/docs/sandbox/api/commands.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Commands
33
pcx_content_type: concept
44
sidebar:
5-
order: 1
5+
order: 2
66
---
77

88
import { Details, TypeScriptExample } from "~/components";

src/content/docs/sandbox/api/files.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Files
33
pcx_content_type: concept
44
sidebar:
5-
order: 2
5+
order: 3
66
---
77

88
import { TypeScriptExample } from "~/components";

src/content/docs/sandbox/api/index.mdx

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,30 +7,24 @@ sidebar:
77

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

10-
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()`.
11-
12-
## Getting a sandbox instance
13-
14-
```typescript
15-
import { getSandbox } from '@cloudflare/sandbox';
16-
17-
const sandbox = getSandbox(env.Sandbox, 'user-123');
18-
```
19-
20-
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.
21-
22-
## API organization
23-
24-
The Sandbox SDK is organized into focused APIs:
10+
The Sandbox SDK provides a comprehensive API for executing code, managing files, running processes, and exposing services in isolated sandboxes.
2511

2612
<CardGrid>
2713

14+
<LinkTitleCard
15+
title="Lifecycle"
16+
href="/sandbox/api/lifecycle/"
17+
icon="rocket"
18+
>
19+
Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources.
20+
</LinkTitleCard>
21+
2822
<LinkTitleCard
2923
title="Commands"
3024
href="/sandbox/api/commands/"
3125
icon="seti:shell"
3226
>
33-
Execute commands and stream output. Includes `exec()`, `execStream()`, and background process management.
27+
Execute commands and stream output. Run scripts, manage background processes, and capture execution results.
3428
</LinkTitleCard>
3529

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

6862
</CardGrid>

src/content/docs/sandbox/api/interpreter.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Code Interpreter
33
pcx_content_type: concept
44
sidebar:
5-
order: 3
5+
order: 4
66
---
77

88
import { TypeScriptExample } from "~/components";
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
---
2+
title: Lifecycle
3+
pcx_content_type: configuration
4+
sidebar:
5+
order: 1
6+
---
7+
8+
import { TypeScriptExample } from "~/components";
9+
10+
Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources.
11+
12+
:::note
13+
For session-specific operations like `createSession()` and `deleteSession()`, see the [Sessions API](/sandbox/api/sessions/).
14+
:::
15+
16+
## Methods
17+
18+
### `getSandbox()`
19+
20+
Get or create a sandbox instance by ID.
21+
22+
```ts
23+
const sandbox = getSandbox(
24+
binding: DurableObjectNamespace<Sandbox>,
25+
sandboxId: string,
26+
options?: SandboxOptions
27+
): Sandbox
28+
```
29+
30+
**Parameters**:
31+
- `binding` - The Durable Object namespace binding from your Worker environment
32+
- `sandboxId` - Unique identifier for this sandbox. The same ID always returns the same sandbox instance
33+
- `options` (optional):
34+
- `keepAlive` - Set to `true` to prevent automatic container timeout after 10 minutes of inactivity
35+
36+
**Returns**: `Sandbox` instance
37+
38+
:::note
39+
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.
40+
:::
41+
42+
<TypeScriptExample>
43+
```
44+
import { getSandbox } from '@cloudflare/sandbox';
45+
46+
export default {
47+
async fetch(request: Request, env: Env): Promise<Response> {
48+
const sandbox = getSandbox(env.Sandbox, 'user-123');
49+
const result = await sandbox.exec('python script.py');
50+
return Response.json(result);
51+
}
52+
};
53+
```
54+
</TypeScriptExample>
55+
56+
:::caution
57+
When using `keepAlive: true`, you **must** call `destroy()` when finished to prevent containers running indefinitely.
58+
:::
59+
60+
---
61+
62+
### `destroy()`
63+
64+
Destroy the sandbox container and free up resources.
65+
66+
```ts
67+
await sandbox.destroy(): Promise<void>
68+
```
69+
70+
Immediately terminates the container and permanently deletes all state:
71+
- All files in `/workspace`, `/tmp`, and `/home`
72+
- All running processes
73+
- All sessions (including the default session)
74+
- Network connections and exposed ports
75+
76+
<TypeScriptExample>
77+
```
78+
async function executeCode(code: string): Promise<string> {
79+
const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
80+
81+
try {
82+
await sandbox.writeFile('/tmp/code.py', code);
83+
const result = await sandbox.exec('python /tmp/code.py');
84+
return result.stdout;
85+
} finally {
86+
await sandbox.destroy();
87+
}
88+
}
89+
```
90+
</TypeScriptExample>
91+
92+
:::note
93+
Containers automatically sleep after 10 minutes of inactivity but still count toward account limits. Use `destroy()` to immediately free up resources.
94+
:::
95+
96+
---
97+
98+
## Related resources
99+
100+
- [Sandbox lifecycle concept](/sandbox/concepts/sandboxes/) - Understanding container lifecycle and state
101+
- [Sandbox options configuration](/sandbox/configuration/sandbox-options/) - Configure `keepAlive` and other options
102+
- [Sessions API](/sandbox/api/sessions/) - Create isolated execution contexts within a sandbox

src/content/docs/sandbox/api/ports.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Ports
33
pcx_content_type: concept
44
sidebar:
5-
order: 4
5+
order: 5
66
---
77

88
import { TypeScriptExample } from "~/components";

src/content/docs/sandbox/api/sessions.mdx

Lines changed: 48 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,15 @@
22
title: Sessions
33
pcx_content_type: configuration
44
sidebar:
5-
order: 5
5+
order: 6
66
---
77

88
import { TypeScriptExample } from "~/components";
99

1010
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.
1111

1212
:::note
13-
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.
14-
:::
15-
16-
:::note
17-
For sandbox-level configuration options like `keepAlive`, refer to the [Sandbox options configuration](/sandbox/configuration/sandbox-options/).
13+
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/).
1814
:::
1915

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

83+
---
84+
85+
### `deleteSession()`
86+
87+
Delete a session and clean up its resources.
88+
89+
```ts
90+
const result = await sandbox.deleteSession(sessionId: string): Promise<SessionDeleteResult>
91+
```
92+
93+
**Parameters**:
94+
- `sessionId` - ID of the session to delete (cannot be `"default"`)
95+
96+
**Returns**: `Promise<SessionDeleteResult>` containing:
97+
- `success` - Whether deletion succeeded
98+
- `sessionId` - ID of the deleted session
99+
- `timestamp` - Deletion timestamp
100+
101+
<TypeScriptExample>
102+
```
103+
// Create a temporary session for a specific task
104+
const tempSession = await sandbox.createSession({ id: 'temp-task' });
105+
106+
try {
107+
await tempSession.exec('npm run heavy-task');
108+
} finally {
109+
// Clean up the session when done
110+
await sandbox.deleteSession('temp-task');
111+
}
112+
```
113+
</TypeScriptExample>
114+
115+
:::caution
116+
Deleting a session immediately terminates all running commands. The default session cannot be deleted.
117+
:::
118+
119+
---
120+
87121
### `setEnvVars()`
88122

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

118-
### `destroy()`
119-
120-
Destroy the sandbox container and free up resources.
121-
122-
```ts
123-
await sandbox.destroy(): Promise<void>
124-
```
125-
126-
:::note
127-
Containers automatically sleep after 10 minutes of inactivity, but still count toward account limits. Use `destroy()` to immediately free up resources.
128-
129-
**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.
130-
:::
131-
132-
<TypeScriptExample>
133-
```
134-
async function executeCode(code: string): Promise<string> {
135-
const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
136-
137-
try {
138-
await sandbox.writeFile('/tmp/code.py', code);
139-
const result = await sandbox.exec('python /tmp/code.py');
140-
return result.stdout;
141-
} finally {
142-
await sandbox.destroy();
143-
}
144-
}
145-
```
146-
</TypeScriptExample>
152+
---
147153

148154
## ExecutionSession methods
149155

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

152-
**Commands**: [`exec()`](/sandbox/api/commands/#exec), [`execStream()`](/sandbox/api/commands/#execstream)
153-
**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)
154-
**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)
155-
**Environment**: [`setEnvVars()`](/sandbox/api/sessions/#setenvvars)
156-
**Code Interpreter**: [`createCodeContext()`](/sandbox/api/interpreter/#createcodecontext), [`runCode()`](/sandbox/api/interpreter/#runcode), [`listCodeContexts()`](/sandbox/api/interpreter/#listcodecontexts), [`deleteCodeContext()`](/sandbox/api/interpreter/#deletecodecontext)
158+
| Category | Methods |
159+
| -------- | ------- |
160+
| **Commands** | [`exec()`](/sandbox/api/commands/#exec), [`execStream()`](/sandbox/api/commands/#execstream) |
161+
| **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) |
162+
| **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) |
163+
| **Environment** | [`setEnvVars()`](/sandbox/api/sessions/#setenvvars) |
164+
| **Code Interpreter** | [`createCodeContext()`](/sandbox/api/interpreter/#createcodecontext), [`runCode()`](/sandbox/api/interpreter/#runcode), [`listCodeContexts()`](/sandbox/api/interpreter/#listcodecontexts), [`deleteCodeContext()`](/sandbox/api/interpreter/#deletecodecontext) |
157165

158166
## Related resources
159167

src/content/docs/sandbox/concepts/sandboxes.mdx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,5 @@ await sandbox.exec("python process.py");
144144
- [Architecture](/sandbox/concepts/architecture/) - How sandboxes fit in the system
145145
- [Container runtime](/sandbox/concepts/containers/) - What runs inside sandboxes
146146
- [Session management](/sandbox/concepts/sessions/) - Advanced state isolation
147-
- [Sessions API](/sandbox/api/sessions/) - Programmatic lifecycle control
147+
- [Lifecycle API](/sandbox/api/lifecycle/) - Create and manage sandboxes
148+
- [Sessions API](/sandbox/api/sessions/) - Create and manage execution sessions

0 commit comments

Comments
 (0)