Skip to main content

LocalSandbox

在本地系统上执行命令。

🌐 Executes commands on the local system.

info

有关接口详情,请参见 WorkspaceSandbox 接口

🌐 For interface details, see WorkspaceSandbox interface.

用法
Direct link to 用法

🌐 Usage

向工作区添加 LocalSandbox 并将其分配给代理。然后代理可以作为其任务的一部分执行 shell 命令:

🌐 Add a LocalSandbox to a workspace and assign it to an agent. The agent can then execute shell commands as part of its tasks:

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-4o',
workspace,
});

// The agent now has the execute_command tool available
const response = await agent.generate('Run npm install');

自动启动行为
Direct link to 自动启动行为

🌐 Auto-start behavior

LocalSandbox 会在第一次命令执行时自动启动(如果尚未运行)。你也可以通过在应用启动时调用 workspace.init() 来显式启动沙箱,从而避免首次命令的延迟。

构造函数参数
Direct link to 构造函数参数

🌐 Constructor parameters

id?:

string
= Auto-generated
Unique identifier for this sandbox instance

workingDirectory?:

string
= process.cwd()/.sandbox/
Directory for command execution. Defaults to .sandbox/ in process.cwd() for isolation from seatbelt profiles.

env?:

NodeJS.ProcessEnv
Environment variables to set. PATH is included by default unless overridden.

timeout?:

number
= 30000
Default timeout for operations in milliseconds

isolation?:

'none' | 'seatbelt' | 'bwrap'
= 'none'
Native OS sandboxing backend. 'seatbelt' for macOS, 'bwrap' for Linux.

nativeSandbox?:

NativeSandboxConfig
Configuration for native sandboxing (see NativeSandboxConfig below).

NativeSandboxConfig
Direct link to NativeSandboxConfig

本地操作系统沙箱的配置选项(用于 isolation: 'seatbelt''bwrap')。

🌐 Configuration options for native OS sandboxing (used with isolation: 'seatbelt' or 'bwrap').

allowNetwork?:

boolean
= false
Allow network access from sandboxed commands.

readOnlyPaths?:

string[]
Additional paths to allow read-only access (system paths are always readable).

readWritePaths?:

string[]
Additional paths to allow read-write access beyond the workspace directory.

seatbeltProfilePath?:

string
Path to a custom seatbelt profile file (macOS only). If the file exists, it's used; if not, a default profile is generated and written to this path.

bwrapArgs?:

string[]
Additional arguments to pass to bwrap (Linux only).

allowSystemBinaries?:

boolean
= true
Allow read access to standard system binary paths (/bin, /usr/bin, etc.).

属性
Direct link to 属性

🌐 Properties

id:

string
Sandbox instance identifier

name:

string
Provider name ('LocalSandbox')

provider:

string
Provider identifier ('local')

status:

ProviderStatus
'starting' | 'running' | 'stopped' | 'error'

workingDirectory:

string
The configured working directory

方法
Direct link to 方法

🌐 Methods

start()
Direct link to start

初始化并启动沙箱。创建工作目录,并在使用本地隔离时设置安全配置文件。

🌐 Initialize and start the sandbox. Creates the working directory and sets up seatbelt profiles if using native isolation.

await sandbox.start();

workspace.init() 自动调用,或在第一次 executeCommand() 调用时调用。

🌐 Called automatically by workspace.init() or on first executeCommand() call.

stop()
Direct link to stop

停止沙盒。

🌐 Stop the sandbox.

await sandbox.stop();

destroy()
Direct link to destroy

清理沙箱资源。如果安全带配置文件是自动生成的,则将其删除。

🌐 Clean up sandbox resources. Removes seatbelt profiles if they were auto-generated.

await sandbox.destroy();

workspace.destroy() 调用。

🌐 Called by workspace.destroy().

isReady()
Direct link to isready

检查沙箱是否已准备好进行操作。

🌐 Check if the sandbox is ready for operations.

const ready = await sandbox.isReady();
// true if status is 'running'

executeCommand(command, args?, options?)
Direct link to executecommandcommand-args-options

在沙箱中执行一个 shell 命令。

🌐 Execute a shell command in the sandbox.

const listResult = await sandbox.executeCommand('ls', ['-la']);
const installResult = await sandbox.executeCommand('npm', ['install', 'lodash'], {
timeout: 60000,
env: { NODE_ENV: 'development' },
});

参数:

command:

string
Command to execute

args?:

string[]
Command arguments

options.timeout?:

number
Execution timeout in milliseconds

options.cwd?:

string
Working directory for the command

options.env?:

Record<string, string>
Additional environment variables

options.onStdout?:

(data: string) => void
Callback for stdout streaming

options.onStderr?:

(data: string) => void
Callback for stderr streaming

getInfo()
Direct link to getinfo

获取沙盒状态和资源信息。

🌐 Get sandbox status and resource information.

const info = await sandbox.getInfo();
// { status: 'running', resources: { ... } }

getInstructions()
Direct link to getinstructions

返回此沙箱的工作原理描述。用于工具说明中。

🌐 Returns a description of how this sandbox works. Used in tool descriptions.

const instructions = sandbox.getInstructions();
// 'Local command execution. Working directory: "/workspace".'

路径解析
Direct link to 路径解析

🌐 Path Resolution

相对路径和执行上下文
Direct link to 相对路径和执行上下文

🌐 Relative paths and execution context

当你为 workingDirectory 使用相对路径时,它会从 process.cwd() 解析。在 Mastra 项目中,cwd 会根据你运行代码的方式而有所不同:

🌐 When you use a relative path for workingDirectory, it resolves from process.cwd(). In Mastra projects, cwd varies depending on how you run your code:

上下文工作目录./workspace 解析为
mastra dev./src/mastra/public/./src/mastra/public/workspace
mastra start./.mastra/output/./.mastra/output/workspace
直接脚本运行命令的位置相对于该位置

当相同的相对路径解析到不同位置时,这可能会导致混淆。

🌐 This can cause confusion when the same relative path resolves to different locations.

🌐 Recommended: Use absolute paths

为了在所有执行环境中保持路径一致,请使用包含绝对路径的环境变量:

🌐 For consistent paths across all execution contexts, use an environment variable with an absolute path:

import { LocalSandbox } from '@mastra/core/workspace';

const sandbox = new LocalSandbox({
workingDirectory: process.env.WORKSPACE_PATH!,
});

在你的环境中将 WORKSPACE_PATH 设置为像 /home/user/my-project/workspace 这样的绝对路径。这可以确保无论你如何运行代码,命令都能从一致的目录执行。

🌐 Set WORKSPACE_PATH in your environment to an absolute path like /home/user/my-project/workspace. This ensures commands run from a consistent directory regardless of how you run your code.

静态方法
Direct link to 静态方法

🌐 Static Methods

detectIsolation()
Direct link to detectisolation

检测当前平台上可用的最佳隔离后端。

🌐 Detect the best available isolation backend for the current platform.

const detection = LocalSandbox.detectIsolation();
// { backend: 'seatbelt', available: true, message: 'Seatbelt available on macOS' }

环境隔离
Direct link to 环境隔离

🌐 Environment Isolation

默认情况下,LocalSandbox 仅在环境中包含 PATH。这样可以在命令运行的同时,防止意外暴露 API 密钥和机密信息。

🌐 By default, LocalSandbox only includes PATH in the environment. This allows commands to run while preventing accidental exposure of API keys and secrets.

// 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,
});

原生操作系统沙箱
Direct link to 原生操作系统沙箱

🌐 Native OS Sandboxing

LocalSandbox 支持原生操作系统级别的沙箱以提供额外的安全性:

  • macOS:使用 Seatbelt(sandbox-exec)进行文件系统和网络隔离
  • Linux:使用 Bubblewrap (bwrap) 进行命名空间隔离
// 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
},
});

启用隔离时:

🌐 When isolation is enabled:

  • 文件写入仅限于工作区目录(和已配置的路径)
  • 文件读取在任何地方都是允许的(系统二进制文件需要)
  • 网络访问默认被阻止
  • 进程隔离可以防止影响主机系统

沙盒配置文件位置
Direct link to 沙盒配置文件位置

🌐 Sandbox profile location

在 macOS 上使用安全带隔离时,LocalSandbox 会在 process.cwd() 中的 .sandbox-profiles/ 文件夹中生成一个配置文件,与工作目录分开:

🌐 When using seatbelt isolation on macOS, LocalSandbox generates a profile file in a .sandbox-profiles/ folder in process.cwd(), separate from the working directory:

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

配置文件的文件名是工作区路径和配置的哈希值,因此具有相同设置的沙箱共享相同的配置文件,而不同配置的沙箱会得到不同的文件。这可以在同时运行多个沙箱时防止冲突。

🌐 The profile filename is a hash of the workspace path and configuration, so sandboxes with identical settings share the same profile while different configurations get separate files. This prevents collisions when running multiple sandboxes concurrently.

这种分离可以防止沙箱进程读取或修改自身的安全配置文件。配置文件在沙箱启动时创建,在销毁时清理。

🌐 This separation prevents sandboxed processes from reading or modifying their own security profiles. The profile is created when the sandbox starts and cleaned up when destroyed.

🌐 Related