跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

LocalSandbox

Added in: @mastra/core@1.1.0

Executes commands on the local system. For interface details, see WorkspaceSandbox interface.

Usage
Usage的直接链接

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-5.6-sol',
workspace,
})

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

Auto-start behavior
Auto-start behavior的直接链接

LocalSandbox automatically starts on the first command execution if not already running. You can also explicitly start the sandbox by calling workspace.init() at application startup to avoid first-command latency.

Constructor parameters
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.

outputEncoding?:

string
= 'utf-8'
Encoding used to decode command stdout and stderr. Accepts any WHATWG encoding label, such as 'gbk' for native Windows commands on a Chinese (code page 936) system.

timeout?:

number
= 30000
Default timeout for operations in milliseconds

isolation?:

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

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
Custom instructions that override the default instructions returned by getInstructions(). Pass a string to fully replace them, or a function to extend them with access to the current requestContext for per-request customization.

nativeSandbox?:

NativeSandboxConfig
Configuration for native sandboxing (see NativeSandboxConfig below).

start() reports { outcome: 'created' } when the working directory didn't exist yet and { outcome: 'connected' } when it reattaches to an existing directory. See start() for the shared contract.

NativeSandboxConfig
nativesandboxconfig的直接链接

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 you wrote the file, it's used exactly as written: Mastra doesn't add mounted paths to it, so the profile must already allow every path you mount. If the file doesn't exist, a default profile is generated and written to this path, and that generated profile allows mounted paths. Mastra marks the profiles it generates, so a later run regenerates them instead of reading them back as your own. To edit a generated profile and keep your edits, delete its marker comment: the file then counts as yours, and mounted paths are no longer added to it.

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

Properties
Properties的直接链接

id:

string
Sandbox instance identifier

name:

string
Provider name ('LocalSandbox')

provider:

string
Provider identifier ('local')

status:

ProviderStatus
'pending' | 'initializing' | 'ready' | 'starting' | 'running' | 'stopping' | 'stopped' | 'destroying' | 'destroyed' | 'error'

workingDirectory:

string
The configured working directory

processes:

LocalProcessManager
Background process manager. See SandboxProcessManager reference.

Path Resolution
Path Resolution的直接链接

Relative paths and execution context
Relative paths and execution context的直接链接

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

ContextWorking directory./workspace resolves to
mastra dev./src/mastra/public/./src/mastra/public/workspace
mastra start./.mastra/output/./.mastra/output/workspace
Direct scriptWhere you ran the commandRelative to that location

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

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!,
})

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

Background processes
Background processes的直接链接

LocalSandbox includes a built-in process manager for spawning and managing background processes. Processes run as child processes on the local machine using 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, signal EOF, and wait for completion
console.log(handle.stdout)
await handle.sendStdin('input\n')
await handle.closeStdin()
await handle.wait()

When native isolation is enabled (seatbelt or bwrap), spawned processes are also wrapped with the same isolation backend.

See SandboxProcessManager reference for the full API.

Static methods
Static methods的直接链接

detectIsolation()
detectisolation的直接链接

Detect the best available isolation backend for the current platform.

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

Environment isolation
Environment isolation的直接链接

By default, LocalSandbox only includes PATH in the environment. Commands can run without 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,
})

Native OS sandboxing
Native OS sandboxing的直接链接

LocalSandbox supports native OS-level sandboxing for additional security:

  • macOS: Uses Seatbelt (sandbox-exec) for filesystem and network isolation
  • Linux: Uses Bubblewrap (bwrap) for namespace isolation
// 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:

  • File writes are restricted to the workspace directory (and configured paths)
  • File reads are allowed everywhere (needed for system binaries)
  • Network access is blocked by default
  • Process isolation prevents affecting the host system

Sandbox profile location
Sandbox profile location的直接链接

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.