跳到主要内容

LocalSandbox

添加于: @mastra/core@1.1.0

在本地系统上执行命令。有关接口详情,请参阅 WorkspaceSandbox 接口

用法
用法的直接链接

LocalSandbox 添加到 Workspace,并将其分配给 Agent。之后,Agent 便可在执行任务的过程中运行 shell 命令:

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 实例的唯一标识符

workingDirectory?:

string
= process.cwd()/.sandbox/
执行命令的目录。默认为 process.cwd() 中的 .sandbox/,以便与 seatbelt profile 隔离。

env?:

NodeJS.ProcessEnv
要设置的环境变量。除非被覆盖,否则默认包含 PATH。

timeout?:

number
= 30000
操作的默认超时时间(毫秒)

isolation?:

'none' | 'seatbelt' | 'bwrap'
= 'none'
原生 OS sandboxing 后端。macOS 使用 'seatbelt',Linux 使用 'bwrap'。

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
自定义指令,用于覆盖 getInstructions() 返回的默认指令。传入字符串可完全替换默认指令;传入函数则可扩展默认指令,并访问当前 requestContext 以便按请求进行自定义。

nativeSandbox?:

NativeSandboxConfig
原生 sandboxing 配置(请参阅下方 NativeSandboxConfig)。

NativeSandboxConfig
nativesandboxconfig的直接链接

原生 OS sandboxing 的配置选项(与 isolation: 'seatbelt''bwrap' 一起使用)。

allowNetwork?:

boolean
= false
允许经过 Sandbox 隔离的命令访问网络。

readOnlyPaths?:

string[]
允许只读访问的其他路径(系统路径始终可读)。

readWritePaths?:

string[]
除 Workspace 目录之外,允许读写访问的其他路径。

seatbeltProfilePath?:

string
自定义 seatbelt profile 文件的路径(仅限 macOS)。如果该文件由你编写,Mastra 会原样使用:它不会向文件中添加挂载路径,因此 profile 必须已经允许你挂载的每条路径。如果文件不存在,系统会生成默认 profile 并将其写入此路径,生成的 profile 会允许挂载路径。Mastra 会标记自己生成的 profile,因此后续运行会重新生成,而不会将其当作你的文件读回。若要编辑生成的 profile 并保留修改,请删除其中的标记注释:此后该文件会被视为你编写的文件,系统也不再向其中添加挂载路径。

bwrapArgs?:

string[]
传给 bwrap 的其他参数(仅限 Linux)。

allowSystemBinaries?:

boolean
= true
允许读取标准系统二进制路径(/bin、/usr/bin 等)。

属性
属性的直接链接

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
直接运行脚本运行命令的位置相对于该位置

当同一个相对路径解析到不同位置时,可能造成困惑。

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

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 作为本地计算机上的子进程运行。

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()

启用原生隔离(seatbeltbwrap)后,生成的进程也会由同一个隔离后端包装。

如需完整 API,请参阅 SandboxProcessManager 参考

静态方法
静态方法的直接链接

detectIsolation()
detectisolation的直接链接

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

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

环境隔离
环境隔离的直接链接

默认情况下,LocalSandbox 的环境中只包含 PATH。这样既能正常运行命令,又能防止意外泄露 API 密钥和 secret。

// 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
原生 OS sandboxing的直接链接

LocalSandbox 支持原生 OS 级 sandboxing,以增强安全性:

  • macOS:使用 Seatbelt(sandbox-exec)隔离文件系统和网络
  • Linux:使用 Bubblewrap(bwrap)进行 namespace 隔离
// 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 位置
Sandbox profile 位置的直接链接

在 macOS 上使用 seatbelt 隔离时,LocalSandbox 会在 process.cwd() 中的 .sandbox-profiles/ 文件夹内生成 profile 文件,该文件夹与工作目录分开:

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 启动时创建,并在销毁时清理。