> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # E2BSandbox 在隔离的 [E2B](https://e2b.dev) 云端 Sandbox 中执行命令。提供安全的临时环境,并支持挂载云存储。有关接口详情,请参阅 [WorkspaceSandbox 接口](https://mastra.zisheng.pro/reference/workspace/sandbox)。 ## 安装 **npm**: ```bash npm install @mastra/e2b ``` **pnpm**: ```bash pnpm add @mastra/e2b ``` **Yarn**: ```bash yarn add @mastra/e2b ``` **Bun**: ```bash bun add @mastra/e2b ``` ## 用法 将 `E2BSandbox` 添加到 Workspace,并将其分配给 Agent: ```typescript import { Agent } from '@mastra/core/agent' import { Workspace } from '@mastra/core/workspace' import { E2BSandbox } from '@mastra/e2b' const workspace = new Workspace({ sandbox: new E2BSandbox({ id: 'dev-sandbox', timeout: 60_000, // 60 second timeout (default: 5 minutes) }), }) const agent = new Agent({ id: 'dev-agent', name: 'dev-agent', model: 'anthropic/claude-opus-4-7', workspace, }) ``` ## 构造函数参数 **apiKey** (`string`): E2B API key。未提供时使用 E2B\_API\_KEY 环境变量。 **timeout** (`number`): 以毫秒为单位的执行超时时间 (Default: `300000(5 分钟)`) **template** (`string | TemplateBuilder | function`): Sandbox template 规范。可以是 template ID 字符串、TemplateBuilder 或自定义默认 template 的函数。 **env** (`Record`): 要在 Sandbox 中设置的环境变量 **id** (`string`): 此 Sandbox 实例的唯一标识符 (Default: `自动生成`) **domain** (`string`): 自托管 E2B 的域名。未提供时使用 E2B\_DOMAIN 环境变量。 **apiUrl** (`string`): 自托管 E2B 的 API URL。未提供时使用 E2B\_API\_URL 环境变量。 **accessToken** (`string`): 用于身份验证的 access token。未提供时使用 E2B\_ACCESS\_TOKEN 环境变量。 **metadata** (`Record`): 附加到 Sandbox 实例的自定义元数据。 **instructions** (`string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)`): 由 getInstructions() 返回的自定义 instructions。字符串会完全替换默认值;函数会接收默认值,并可根据每个请求进行扩展或自定义。传入空字符串可完全禁止 instructions。 ## 属性 **id** (`string`): Sandbox 实例标识符 **name** (`string`): Provider 名称('E2BSandbox') **provider** (`string`): Provider 标识符('e2b') **status** (`ProviderStatus`): 'pending' | 'initializing' | 'ready' | 'starting' | 'running' | 'stopping' | 'stopped' | 'destroying' | 'destroyed' | 'error' **processes** (`E2BProcessManager`): 后台进程管理器。请参阅 SandboxProcessManager 参考。 ## 后台进程 `E2BSandbox` 内置了用于生成和管理后台进程的进程管理器。进程使用 E2B SDK 的 `commands.run()` 并设置 `background: true`,在 E2B 云端 Sandbox 中运行。 ```typescript const sandbox = new E2BSandbox({ id: 'dev-sandbox' }) await sandbox.start() // Spawn a background process const handle = await sandbox.processes.spawn('node server.js', { env: { PORT: '3000' }, onStdout: data => console.log(data), }) // Interact with the process console.log(handle.stdout) await handle.sendStdin('input\n') await handle.kill() ``` E2B 进程管理器支持重新连接到外部生成或重新连接前生成的进程。使用 PID 调用 `get(pid)`,即可连接到现有进程: ```typescript const handle = await sandbox.processes.get(existingPid) if (handle) { console.log(handle.stdout) } ``` 有关完整 API,请参阅 [`SandboxProcessManager` 参考](https://mastra.zisheng.pro/reference/workspace/process-manager)。 ## 挂载云存储 E2B Sandbox 可以挂载 S3、GCS 和 Azure Blob 文件系统,使云存储可以作为 Sandbox 内的本地目录访问。这适用于: - 处理存储在云端 bucket 中的大型数据集 - 将输出文件直接写入云存储 - 在不同 Sandbox Session 之间共享数据 ### 使用 mounts 配置 挂载文件系统最简单的方式是使用 Workspace 的 `mounts` 配置: ```typescript import { Workspace } from '@mastra/core/workspace' import { S3Filesystem } from '@mastra/s3' import { GCSFilesystem } from '@mastra/gcs' import { E2BSandbox } from '@mastra/e2b' const workspace = new Workspace({ mounts: { '/s3-data': new S3Filesystem({ bucket: 'my-s3-bucket', region: 'us-east-1', accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }), '/gcs-data': new GCSFilesystem({ bucket: 'my-gcs-bucket', projectId: 'my-project', credentials: JSON.parse(process.env.GCS_SERVICE_ACCOUNT_KEY), }), }, sandbox: new E2BSandbox({ id: 'dev-sandbox' }), }) ``` Sandbox 启动时,文件系统会自动挂载到指定路径。随后,Sandbox 中运行的代码可以像访问本地目录一样访问 `/s3-data` 和 `/gcs-data` 中的文件。 ### 挂载的工作原理 E2B Sandbox 使用 FUSE(Filesystem in Userspace)挂载云存储: - **S3/R2**:通过 [s3fs-fuse](https://github.com/s3fs-fuse/s3fs-fuse) 挂载 - **GCS**:通过 [gcsfuse](https://github.com/GoogleCloudPlatform/gcsfuse) 挂载 - **Azure Blob**:通过 [blobfuse2](https://github.com/Azure/azure-storage-fuse) 挂载 使用挂载功能时,E2B Sandbox 会自动安装所需的 FUSE Tool。为获得最佳性能,请预先构建已安装这些 Tool 的自定义 template。 ## 自定义 template 默认情况下,如果未指定 template,E2BSandbox 会自动构建一个已安装 `s3fs`、支持挂载 S3 的 template。该 template 会缓存并在不同 Sandbox 实例之间复用。 挂载 GCS 时,如果尚未安装 `gcsfuse`,系统会在挂载时自动安装。若需要其他 Tool 或更快的冷启动,请使用自定义 template。 ### 使用现有 template 如果已有预先构建的 template,请传入其 ID: ```typescript const workspace = new Workspace({ sandbox: new E2BSandbox({ id: 'dev-sandbox', template: 'my-custom-template', }), }) ``` ### 自定义默认 template 传入函数来自定义默认的可挂载 template。该函数接收 `TemplateBuilder`,并应返回修改后的 template: ```typescript const workspace = new Workspace({ sandbox: new E2BSandbox({ template: base => base .aptInstall(['ffmpeg', 'imagemagick', 'poppler-utils']) .pipInstall(['pandas', 'numpy']) .npmInstall(['sharp']), }), }) ``` Template builder 支持链式调用以下操作: - `aptInstall(packages)` - 安装系统软件包 - `pipInstall(packages)` - 安装 Python 软件包 - `npmInstall(packages)` - 安装 Node.js 软件包 - `runCmd(command)` - 运行 shell 命令 - `setEnvs(vars)` - 设置环境变量 - `copy(src, dest)` - 将文件复制到 template 中 有关可用方法的完整列表,请参阅 [E2B template 文档](https://e2b.dev/docs/template/defining-template)。 ### 预先构建 template 默认 template 会在首次使用时构建并缓存。为了加快冷启动或加入 GCS 支持,可以预先构建 template: ```typescript import { createDefaultMountableTemplate } from '@mastra/e2b' import { Template } from 'e2b' // Get the default mountable template (includes s3fs) const { template, id } = createDefaultMountableTemplate() // Build and save to E2B const result = await Template.build(template, id) console.log('Template ID:', result.templateId) // Use this ID in your E2BSandbox config for instant startup const sandbox = new E2BSandbox({ template: result.templateId, }) ``` 为加快 GCS 冷启动,请在自定义 template 中预先安装 `gcsfuse`: ```typescript const workspace = new Workspace({ sandbox: new E2BSandbox({ id: 'dev-sandbox', template: base => base.aptInstall(['gcsfuse']), }), }) ``` 此步骤可选:如果不存在 `gcsfuse`,系统会在挂载时自动安装。 ## 与 Code Mode 配合使用 [Code Mode](https://mastra.zisheng.pro/docs/agents/code-mode) 允许 Agent 编写一个用于编排其 Tool 的 TypeScript 程序。由于 E2B 会在远程 micro-VM 中运行该程序,因此需要一种 transport 将程序写入 Sandbox 文件系统,而不是宿主文件系统。`@mastra/e2b` 为此提供了 `E2BCodeModeTransport`。将其作为第二个参数传给 `createCodeMode`: ```typescript import { createCodeMode } from '@mastra/core/tools' import { E2BSandbox, E2BCodeModeTransport } from '@mastra/e2b' const { tool, instructions } = createCodeMode( { tools: { getWeather, getForecast }, sandbox: new E2BSandbox({ timeout: 60_000 }), }, new E2BCodeModeTransport(), ) ``` 如果 Sandbox 尚未运行,`E2BCodeModeTransport` 会自动启动它;随后使用宿主上的 esbuild 移除 TypeScript 类型(因此不受 Sandbox Node 版本影响),在 VM 中运行 `node`,并在结束后清理程序文件。`@mastra/core` 中默认的 `StdioCodeModeTransport` 仅适用于与宿主共享文件系统的 Sandbox,例如 `LocalSandbox`。 ## 相关内容 - [SandboxProcessManager 参考](https://mastra.zisheng.pro/reference/workspace/process-manager) - [WorkspaceSandbox 接口](https://mastra.zisheng.pro/reference/workspace/sandbox) - [LocalSandbox 参考](https://mastra.zisheng.pro/reference/workspace/local-sandbox) - [S3Filesystem 参考](https://mastra.zisheng.pro/reference/workspace/s3-filesystem) - [GCSFilesystem 参考](https://mastra.zisheng.pro/reference/workspace/gcs-filesystem) - [Azure Blob Filesystem 参考](https://mastra.zisheng.pro/reference/workspace/azure-blob-filesystem) - [Workspace 概览](https://mastra.zisheng.pro/docs/workspace/overview)