> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # LocalSandbox **新增於:** `@mastra/core@1.1.0` 在本機系統上執行指令。介面詳情請參閱 [WorkspaceSandbox 介面](https://mastra.zisheng.pro/zh-TW/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: `Auto-generated`) **workingDirectory** (`string`): 執行指令的目錄。預設為 process.cwd() 中的 .sandbox/,以便與 seatbelt profile 隔離。 (Default: `process.cwd()/.sandbox/`) **env** (`NodeJS.ProcessEnv`): 要設定的環境變數。除非覆寫,否則預設會包含 PATH。 **timeout** (`number`): 操作的預設逾時時間,單位為毫秒。 (Default: `30000`) **isolation** (`'none' | 'seatbelt' | 'bwrap'`): 原生作業系統 Sandbox 後端。macOS 使用 'seatbelt',Linux 使用 'bwrap'。 (Default: `'none'`) **instructions** (`string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)`): 自訂指示,用於覆寫 getInstructions() 傳回的預設指示。傳入字串可完全取代預設指示;傳入函式則可存取目前的 requestContext 並擴充指示,以便針對每個要求自訂。 **nativeSandbox** (`NativeSandboxConfig`): 原生 Sandbox 的設定(請參閱下方的 NativeSandboxConfig)。 ## `NativeSandboxConfig` 原生作業系統 Sandbox 的設定選項(搭配 `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/zh-TW/reference/workspace/process-manager)。 ## 靜態方法 ### `detectIsolation()` 偵測目前平台可用的最佳隔離後端。 ```typescript const detection = LocalSandbox.detectIsolation() // { backend: 'seatbelt', available: true, message: 'Seatbelt available on macOS' } ``` ## 環境隔離 根據預設,`LocalSandbox` 的環境只會包含 `PATH`。這能讓指令正常執行,同時防止意外暴露 API 金鑰與機密資訊。 ```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, }) ``` ## 原生作業系統 Sandbox `LocalSandbox` 支援作業系統層級的原生 Sandbox,可提供額外安全性: - **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 路徑與設定的 hash,因此設定相同的 Sandbox 會共用同一個 profile,而設定不同時則會使用個別檔案。這可避免同時執行多個 Sandbox 時發生衝突。 此分隔方式可防止 Sandbox 中的處理程序讀取或修改自己的安全性 profile。Profile 會在 Sandbox 啟動時建立,並在銷毀時清除。 ## 相關內容 - [SandboxProcessManager 參考](https://mastra.zisheng.pro/zh-TW/reference/workspace/process-manager) - [WorkspaceSandbox 介面](https://mastra.zisheng.pro/zh-TW/reference/workspace/sandbox) - [Workspace 類別](https://mastra.zisheng.pro/zh-TW/reference/workspace/workspace-class) - [Workspace 概觀](https://mastra.zisheng.pro/zh-TW/docs/workspace/overview)