在 sandbox 内创建 shell 会话。每个会话维护各自的 shell 状态、环境变量和工作目录,同时共享 sandbox 文件系统与进程空间。更多信息请参阅 Session management。
创建新的 shell 会话。
const session = await sandbox.createSession(options?: SessionOptions): Promise<ExecutionSession>参数:
options(可选):id- 自定义会话 ID(未提供时自动生成)env- 此会话的环境变量:Record<string, string | undefined>cwd- 工作目录(默认:"/workspace")commandTimeoutMs- 此会话中任何命令在超时前可运行的最长时间(毫秒)。单个命令可通过exec()上的timeout选项覆盖该值。
返回:绑定到此会话的所有 sandbox 方法的 Promise<ExecutionSession>
// 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 3s按 ID 检索现有会话。
const session = await sandbox.getSession(sessionId: string): Promise<ExecutionSession>参数:
sessionId- 现有会话的 ID
返回:绑定到指定会话的 Promise<ExecutionSession>
// 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');删除会话并清理其资源。
const result = await sandbox.deleteSession(sessionId: string): Promise<SessionDeleteResult>参数:
sessionId- 要删除的会话 ID(不能为"default")
返回:包含以下内容的 Promise<SessionDeleteResult>:
success- 删除是否成功sessionId- 已删除会话的 IDtimestamp- 删除时间戳
// 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');
}在 sandbox 中设置环境变量。
await sandbox.setEnvVars(envVars: Record<string, string | undefined>): Promise<void>参数:
envVars- 要设置或取消设置的环境变量键值对string值:设置环境变量undefined或null值:取消设置环境变量
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');ExecutionSession 对象具有绑定到特定会话的所有 sandbox 方法:
| 类别 | 方法 |
|---|---|
| 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 概念 - 会话如何工作
- Commands API - 执行命令