会话是沙箱内的 bash shell 执行上下文。可以把它们想象成同一台计算机上的终端标签页。
- Sandbox = 用户或任务的工作区
- Session = 该工作区内的一个 shell
会话适用于在同一个沙箱中组织工作。它们不是用户之间的安全边界,因为会话共享同一文件系统与进程空间。
默认情况下,每个沙箱都有一个默认会话,在容器处于活动状态期间会在命令之间维护 shell 状态:
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// These commands run in the default session
await sandbox.exec("cd /app");
await sandbox.exec("pwd"); // Output: /app
await sandbox.exec("export MY_VAR=hello");
await sandbox.exec("echo $MY_VAR"); // Output: hello工作目录、环境变量与导出的变量会在命令之间保留。如果容器因不活动而重启,此状态会重置。
如果在调用 getSandbox() 时将 enableDefaultSession: false 设为 false,则没有显式 sessionId 的操作会在隔离环境中运行,而不是使用默认会话:
const sandbox = getSandbox(env.Sandbox, 'my-sandbox', {
enableDefaultSession: false
});
await sandbox.exec("cd /app");
await sandbox.exec("pwd"); // Output: /workspace (cd was not inherited)没有默认会话时,第二条命令不会继承第一条命令的 shell 状态。建议你始终应用此设置,因为它将在未来的 Sandbox SDK 版本中成为默认行为。当你希望命令共享 shell 状态时,请创建或检索显式会话。
容器会在首次使用时自动创建会话。如果引用不存在的会话 ID,容器会使用默认设置创建它:
// This session does not exist yet
const result = await sandbox.exec('echo hello', { sessionId: 'new-session' });
// Container automatically creates 'new-session' with defaults:
// - cwd: '/workspace'
// - env: {} (empty)此行为在删除会话后尤其相关:
// Create and configure a session
const session = await sandbox.createSession({
id: 'temp',
env: { MY_VAR: 'value' }
});
// Delete the session
await sandbox.deleteSession('temp');
// Using the same session ID again works - auto-created with defaults
const result = await sandbox.exec('echo $MY_VAR', { sessionId: 'temp' });
// Output: (empty) - MY_VAR is not set in the freshly created session这种自动创建意味着当命令引用不存在的会话时仍会运行。但自定义配置(环境变量、工作目录)在删除后会丢失。
在同一沙箱中为不同工作流创建额外会话:
const buildSession = await sandbox.createSession({
id: "build",
env: { NODE_ENV: "production" },
cwd: "/build"
});
const testSession = await sandbox.createSession({
id: "test",
env: { NODE_ENV: "test" },
cwd: "/test"
});
// Different shell contexts
await buildSession.exec("npm run build");
await testSession.exec("npm test");你也可以为会话中的所有命令设置默认命令超时:
const session = await sandbox.createSession({
id: "ci",
commandTimeoutMs: 30000 // 30s timeout for all commands
});
await session.exec("npm test"); // Times out after 30s if still running单条命令可通过 exec() 上的 timeout 选项覆盖会话超时。更多详情请参阅 Sessions API 与执行命令指南。
每个会话拥有自己的:
Shell 环境:
await session1.exec("export MY_VAR=hello");
await session2.exec("echo $MY_VAR"); // Empty - different shell工作目录:
await session1.exec("cd /workspace/project1");
await session2.exec("pwd"); // Different working directory环境变量(通过 createSession 选项设置):
const session1 = await sandbox.createSession({
env: { API_KEY: 'key-1' }
});
const session2 = await sandbox.createSession({
env: { API_KEY: 'key-2' }
});沙箱中的所有会话共享:
文件系统:
await session1.writeFile('/workspace/file.txt', 'data');
await session2.readFile('/workspace/file.txt'); // Can read it进程:
await session1.startProcess('node server.js');
await session2.listProcesses(); // Sees the server在以下情况下使用会话:
- 你需要为同一用户的任务使用独立的 shell 状态
- 在不同环境下并行运行操作
- 将 AI agent 凭据与应用运行时分离
示例 - 分离开发与运行时环境:
// Phase 1: AI agent writes code (with API keys)
const devSession = await sandbox.createSession({
id: "dev",
env: { ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY }
});
await devSession.exec('ai-tool "build a web server"');
// Phase 2: Run the code (without API keys)
const appSession = await sandbox.createSession({
id: "app",
env: { PORT: "3000" }
});
await appSession.exec("node server.js");在以下情况下使用独立沙箱:
- 你需要对不受信任的代码进行完全隔离
- 不同用户需要独立的工作区
- 用户数据必须保持分离
- 需要独立的资源分配
清理临时会话以释放资源,同时保持沙箱运行:
try {
const session = await sandbox.createSession({ id: 'temp' });
await session.exec('command');
} finally {
await sandbox.deleteSession('temp');
}默认会话无法删除:
// This throws an error
await sandbox.deleteSession('default');
// Error: Cannot delete default session. Use sandbox.destroy() instead.会话共享沙箱文件系统 - 文件操作会影响所有会话:
// Bad - affects all sessions
await session.exec('rm -rf /workspace/*');
// For user data or untrusted code, use a separate sandbox
const userSandbox = getSandbox(env.Sandbox, `user-${userId}`);- 沙箱生命周期 - 理解沙箱管理
- Sessions API - 完整会话 API 参考