> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # LocalSandbox **添加于:** `@mastra/core@1.1.0` 在本地系统上执行命令。有关接口详情,请参阅 [WorkspaceSandbox 接口](https://mastra.zisheng.pro/reference/workspace/sandbox)。 ## 用法 将 `LocalSandbox` 添加到 Workspace,并将其分配给 Agent。之后,Agent 便可在执行任务的过程中运行 shell 命令: ```typescript import { Agent } from '@mastra/core/agent' import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace' const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: './workspace' }), sandbox: new LocalSandbox({ workingDirectory: './workspace', env: { NODE_ENV: 'development', }, }), }) const agent = new Agent({ id: 'dev-agent', model: 'openai/gpt-5.6-sol', workspace, }) // The agent now has the execute_command tool available const response = await agent.generate('Run npm install') ``` ### 自动启动行为 如果 `LocalSandbox` 尚未运行,它会在首次执行命令时自动启动。你也可以在应用启动时调用 `workspace.init()` 来显式启动 Sandbox,以避免首条命令的延迟。 ## 构造函数参数 **id** (`string`): 此 Sandbox 实例的唯一标识符 (Default: `自动生成`) **workingDirectory** (`string`): 执行命令的目录。默认为 process.cwd() 中的 .sandbox/,以便与 seatbelt profile 隔离。 (Default: `process.cwd()/.sandbox/`) **env** (`NodeJS.ProcessEnv`): 要设置的环境变量。除非被覆盖,否则默认包含 PATH。 **timeout** (`number`): 操作的默认超时时间(毫秒) (Default: `30000`) **isolation** (`'none' | 'seatbelt' | 'bwrap'`): 原生 OS sandboxing 后端。macOS 使用 'seatbelt',Linux 使用 'bwrap'。 (Default: `'none'`) **instructions** (`string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)`): 自定义指令,用于覆盖 getInstructions() 返回的默认指令。传入字符串可完全替换默认指令;传入函数则可扩展默认指令,并访问当前 requestContext 以便按请求进行自定义。 **nativeSandbox** (`NativeSandboxConfig`): 原生 sandboxing 配置(请参阅下方 NativeSandboxConfig)。 ## `NativeSandboxConfig` 原生 OS sandboxing 的配置选项(与 `isolation: 'seatbelt'` 或 `'bwrap'` 一起使用)。 **allowNetwork** (`boolean`): 允许经过 Sandbox 隔离的命令访问网络。 (Default: `false`) **readOnlyPaths** (`string[]`): 允许只读访问的其他路径(系统路径始终可读)。 **readWritePaths** (`string[]`): 除 Workspace 目录之外,允许读写访问的其他路径。 **seatbeltProfilePath** (`string`): 自定义 seatbelt profile 文件的路径(仅限 macOS)。如果该文件由你编写,Mastra 会原样使用:它不会向文件中添加挂载路径,因此 profile 必须已经允许你挂载的每条路径。如果文件不存在,系统会生成默认 profile 并将其写入此路径,生成的 profile 会允许挂载路径。Mastra 会标记自己生成的 profile,因此后续运行会重新生成,而不会将其当作你的文件读回。若要编辑生成的 profile 并保留修改,请删除其中的标记注释:此后该文件会被视为你编写的文件,系统也不再向其中添加挂载路径。 **bwrapArgs** (`string[]`): 传给 bwrap 的其他参数(仅限 Linux)。 **allowSystemBinaries** (`boolean`): 允许读取标准系统二进制路径(/bin、/usr/bin 等)。 (Default: `true`) ## 属性 **id** (`string`): Sandbox 实例标识符 **name** (`string`): Provider 名称('LocalSandbox') **provider** (`string`): Provider 标识符('local') **status** (`ProviderStatus`): 'starting' | 'running' | 'stopped' | 'error' **workingDirectory** (`string`): 已配置的工作目录 **processes** (`LocalProcessManager`): 后台进程管理器。请参阅 SandboxProcessManager 参考。 ## 路径解析 ### 相对路径和执行上下文 为 `workingDirectory` 使用相对路径时,该路径会从 `process.cwd()` 开始解析。在 Mastra 项目中,cwd 会根据代码的运行方式发生变化: | 上下文 | 工作目录 | `./workspace` 解析为 | | -------------- | ---------------------- | ------------------------------- | | `mastra dev` | `./src/mastra/public/` | `./src/mastra/public/workspace` | | `mastra start` | `./.mastra/output/` | `./.mastra/output/workspace` | | 直接运行脚本 | 运行命令的位置 | 相对于该位置 | 当同一个相对路径解析到不同位置时,可能造成困惑。 ### 建议:使用绝对路径 为了让所有执行上下文中的路径保持一致,请使用包含绝对路径的环境变量: ```typescript import { LocalSandbox } from '@mastra/core/workspace' const sandbox = new LocalSandbox({ workingDirectory: process.env.WORKSPACE_PATH!, }) ``` 在环境中将 `WORKSPACE_PATH` 设置为绝对路径,例如 `/home/user/my-project/workspace`。这样无论以何种方式运行代码,命令都会从一致的目录中执行。 ## 后台进程 `LocalSandbox` 包含用于生成和管理后台进程的内置进程管理器。进程通过 `child_process.spawn` 作为本地计算机上的子进程运行。 ```typescript const sandbox = new LocalSandbox({ workingDirectory: './workspace' }) await sandbox.start() // Spawn a background process const handle = await sandbox.processes.spawn('node server.js') // Read output, send stdin, kill console.log(handle.stdout) await handle.sendStdin('input\n') await handle.kill() ``` 启用原生隔离(`seatbelt` 或 `bwrap`)后,生成的进程也会由同一个隔离后端包装。 如需完整 API,请参阅 [`SandboxProcessManager` 参考](https://mastra.zisheng.pro/reference/workspace/process-manager)。 ## 静态方法 ### `detectIsolation()` 检测当前平台上最佳的可用隔离后端。 ```typescript const detection = LocalSandbox.detectIsolation() // { backend: 'seatbelt', available: true, message: 'Seatbelt available on macOS' } ``` ## 环境隔离 默认情况下,`LocalSandbox` 的环境中只包含 `PATH`。这样既能正常运行命令,又能防止意外泄露 API 密钥和 secret。 ```typescript // Default: only PATH is available (commands work, secrets protected) const secureSandbox = new LocalSandbox({ workingDirectory: './workspace', }) // Explicit: pass specific variables const sandbox = new LocalSandbox({ workingDirectory: './workspace', env: { NODE_ENV: 'development', API_URL: 'https://api.example.com', }, }) // Full access (use with caution) const devSandbox = new LocalSandbox({ workingDirectory: './workspace', env: process.env, }) ``` ## 原生 OS sandboxing `LocalSandbox` 支持原生 OS 级 sandboxing,以增强安全性: - **macOS**:使用 Seatbelt(`sandbox-exec`)隔离文件系统和网络 - **Linux**:使用 Bubblewrap(`bwrap`)进行 namespace 隔离 ```typescript // Detect the best available backend for this platform const detection = LocalSandbox.detectIsolation() console.log(detection) // { backend: 'seatbelt', available: true, message: '...' } // Enable native sandboxing const sandbox = new LocalSandbox({ workingDirectory: './workspace', isolation: 'seatbelt', // or 'bwrap' on Linux nativeSandbox: { allowNetwork: false, // Block network access (default) readWritePaths: ['/tmp/extra'], // Additional writable paths }, }) ``` 启用隔离后: - 文件写入仅限于 Workspace 目录(以及已配置的路径) - 可从任意位置读取文件(系统二进制文件需要此权限) - 默认阻止网络访问 - 进程隔离可防止影响宿主系统 ### Sandbox profile 位置 在 macOS 上使用 seatbelt 隔离时,`LocalSandbox` 会在 `process.cwd()` 中的 `.sandbox-profiles/` 文件夹内生成 profile 文件,该文件夹与工作目录分开: ```text project/ ├── .sandbox/ # Default working directory (sandboxed) │ └── ... files created by sandbox ├── .sandbox-profiles/ # Seatbelt profiles (outside sandbox) │ └── seatbelt-a1b2c3d4.sb # Hash based on workspace + config └── ... your project files ``` Profile 文件名是 Workspace 路径和配置的哈希值,因此设置相同的 Sandbox 会共享同一个 profile,而不同配置会获得单独的文件。这样可防止同时运行多个 Sandbox 时发生冲突。 这种分离方式可防止经过 Sandbox 隔离的进程读取或修改自己的安全 profile。Profile 会在 Sandbox 启动时创建,并在销毁时清理。 ## 相关内容 - [SandboxProcessManager 参考](https://mastra.zisheng.pro/reference/workspace/process-manager) - [WorkspaceSandbox 接口](https://mastra.zisheng.pro/reference/workspace/sandbox) - [Workspace 类](https://mastra.zisheng.pro/reference/workspace/workspace-class) - [Workspace 概览](https://mastra.zisheng.pro/docs/workspace/overview)