跳至主要內容

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 設定檔隔離。

env?:

NodeJS.ProcessEnv
要設定的環境變數。除非遭覆寫,否則預設會包括 PATH。

timeout?:

number
= 30000
操作的預設逾時時間(以毫秒為單位)

isolation?:

'none' | 'seatbelt' | 'bwrap'
= 'none'
原生作業系統 Sandbox 後端。macOS 使用 'seatbelt',Linux 使用 'bwrap'。

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
覆寫 getInstructions() 傳回之預設指示的自訂指示。傳入字串以完全取代指示,或傳入函數以擴充指示,並可存取目前的 requestContext,按個別請求自訂。

nativeSandbox?:

NativeSandboxConfig
原生 Sandbox 的設定(請參閱下方的 NativeSandboxConfig)。

NativeSandboxConfig
nativesandboxconfig 的直接連結

原生作業系統 Sandbox 的設定選項(與 isolation: 'seatbelt''bwrap' 配合使用)。

allowNetwork?:

boolean
= false
允許 Sandbox 內的指令存取網絡。

readOnlyPaths?:

string[]
允許唯讀存取的其他路徑(系統路徑一律可供讀取)。

readWritePaths?:

string[]
Workspace 目錄以外允許讀寫存取的其他路徑。

seatbeltProfilePath?:

string
自訂 seatbelt 設定檔的路徑(只適用於 macOS)。如果檔案由你編寫,系統會原樣使用:Mastra 不會將已掛載路徑加入其中,因此設定檔必須已經允許你掛載的每個路徑。如果檔案不存在,系統會產生預設設定檔並寫入此路徑,而該設定檔會允許已掛載路徑。Mastra 會標記其產生的設定檔,因此日後運行時會重新產生檔案,而不會視為由你編寫並讀回。如要編輯已產生的設定檔並保留修改,請刪除其標記註解:檔案隨後便會視為由你編寫,系統亦不會再加入已掛載路徑。

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 項目中,目前工作目錄會因程式碼的運行方式而異:

內容工作目錄./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 金鑰及機密資料。

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

原生作業系統 Sandbox
原生作業系統 Sandbox 的直接連結

LocalSandbox 支援原生作業系統層級的 Sandbox,以提供額外保安:

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

啟用隔離時:

  • 檔案寫入只限 Workspace 目錄(及已設定的路徑)
  • 所有位置均可讀取檔案(系統二進制檔案需要此權限)
  • 預設封鎖網絡存取
  • 程序隔離可防止影響主機系統

Sandbox 設定檔位置
Sandbox 設定檔位置 的直接連結

在 macOS 上使用 seatbelt 隔離時,LocalSandbox 會在 process.cwd() 內的 .sandbox-profiles/ 資料夾產生設定檔,並與工作目錄分開:

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

設定檔名稱是 Workspace 路徑及設定的雜湊值,因此設定相同的 Sandbox 會共用同一份設定檔,而不同設定則會使用不同檔案。這可防止同時運行多個 Sandbox 時發生衝突。

這種分隔方式可防止 Sandbox 內的程序讀取或修改本身的保安設定檔。設定檔會在 Sandbox 啟動時建立,並在銷毀時清除。