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.
Create a new shell session.
const session = await sandbox.createSession(options?: SessionOptions): Promise<ExecutionSession>Parameters:
options(optional):id- Custom session ID (auto-generated if not provided)env- Environment variables for this session:Record<string, string | undefined>cwd- Working directory (default:"/workspace")commandTimeoutMs- Maximum time in milliseconds that any command in this session can run before timing out. Individual commands can override this with thetimeoutoption onexec().
Returns: Promise<ExecutionSession> with all sandbox methods bound to this session
// Separate workflow environments
const prodSession = await sandbox.createSession({
id: "prod",
env: { NODE_ENV: "production", API_URL: "https://api.example.com" },
cwd: "/workspace/prod",
});
const testSession = await sandbox.createSession({
id: "test",
env: {
NODE_ENV: "test",
API_URL: "http://localhost:3000",
DEBUG_MODE: undefined, // Skipped, not set in this session
},
cwd: "/workspace/test",
});
// Run in parallel
const [prodResult, testResult] = await Promise.all([
prodSession.exec("npm run build"),
testSession.exec("npm run build"),
]);
// Session with a default command timeout
const session = await sandbox.createSession({
commandTimeoutMs: 5000, // 5s timeout for all commands
});
await session.exec("sleep 10"); // Times out after 5s
// Per-command timeout overrides session-level timeout
await session.exec("sleep 10", { timeout: 3000 }); // Times out after 3s// Separate workflow environments
const prodSession = await sandbox.createSession({
id: 'prod',
env: { NODE_ENV: 'production', API_URL: 'https://api.example.com' },
cwd: '/workspace/prod'
});
const testSession = await sandbox.createSession({
id: 'test',
env: {
NODE_ENV: 'test',
API_URL: 'http://localhost:3000',
DEBUG_MODE: undefined // Skipped, not set in this session
},
cwd: '/workspace/test'
});
// Run in parallel
const [prodResult, testResult] = await Promise.all([
prodSession.exec('npm run build'),
testSession.exec('npm run build')
]);
// Session with a default command timeout
const session = await sandbox.createSession({
commandTimeoutMs: 5000 // 5s timeout for all commands
});
await session.exec('sleep 10'); // Times out after 5s
// Per-command timeout overrides session-level timeout
await session.exec('sleep 10', { timeout: 3000 }); // Times out after 3sRetrieve an existing session by ID.
const session = await sandbox.getSession(sessionId: string): Promise<ExecutionSession>Parameters:
sessionId- ID of an existing session
Returns: Promise<ExecutionSession> bound to the specified session
// First request - create a task-specific session
const session = await sandbox.createSession({ id: "build" });
await session.exec("git clone https://github.com/user/repo.git");
await session.exec("cd repo && npm install");
// Second request - resume session (environment and cwd preserved)
const session = await sandbox.getSession("build");
const result = await session.exec("cd repo && npm run build");// First request - create a task-specific session
const session = await sandbox.createSession({ id: 'build' });
await session.exec('git clone https://github.com/user/repo.git');
await session.exec('cd repo && npm install');
// Second request - resume session (environment and cwd preserved)
const session = await sandbox.getSession('build');
const result = await session.exec('cd repo && npm run build');Delete a session and clean up its resources.
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 succeededsessionId- ID of the deleted sessiontimestamp- Deletion timestamp
// 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");
}// 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');
}Set environment variables in the sandbox.
await sandbox.setEnvVars(envVars: Record<string, string | undefined>): Promise<void>Parameters:
envVars- Key-value pairs of environment variables to set or unsetstringvalues: Set the environment variableundefinedornullvalues: Unset the environment variable
const sandbox = getSandbox(env.Sandbox, "user-123");
// Set environment variables first
await sandbox.setEnvVars({
API_KEY: env.OPENAI_API_KEY,
DATABASE_URL: env.DATABASE_URL,
NODE_ENV: "production",
OLD_TOKEN: undefined, // Unsets OLD_TOKEN if previously set
});
// Now commands can access these variables
await sandbox.exec("python script.py");const sandbox = getSandbox(env.Sandbox, 'user-123');
// Set environment variables first
await sandbox.setEnvVars({
API_KEY: env.OPENAI_API_KEY,
DATABASE_URL: env.DATABASE_URL,
NODE_ENV: 'production',
OLD_TOKEN: undefined // Unsets OLD_TOKEN if previously set
});
// Now commands can access these variables
await sandbox.exec('python script.py');The ExecutionSession object has all sandbox methods bound to the specific session:
| Category | Methods |
|---|---|
| Commands | exec(), execStream() |
| Processes | startProcess(), listProcesses(), killProcess(), killAllProcesses(), getProcessLogs(), streamProcessLogs() |
| Files | writeFile(), readFile(), mkdir(), deleteFile(), renameFile(), moveFile(), gitCheckout() |
| Environment | setEnvVars() |
| Terminal | terminal() |
| Code Interpreter | createCodeContext(), runCode(), listCodeContexts(), deleteCodeContext() |
- Session management concept - How sessions work
- Commands API - Execute commands