> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # SandboxProcessManager **新增於:** `@mastra/core@1.7.0` 用於管理 Sandbox 背景處理程序的抽象基底類別。提供產生處理程序、列出處理程序、透過 PID 取得 handle,以及終止處理程序的方法。 [`BlaxelSandbox`](https://mastra.zisheng.pro/zh-TW/reference/workspace/blaxel-sandbox)、[`DaytonaSandbox`](https://mastra.zisheng.pro/zh-TW/reference/workspace/daytona-sandbox)、[`E2BSandbox`](https://mastra.zisheng.pro/zh-TW/reference/workspace/e2b-sandbox)、[`ModalSandbox`](https://mastra.zisheng.pro/zh-TW/reference/workspace/modal-sandbox) 與 [`LocalSandbox`](https://mastra.zisheng.pro/zh-TW/reference/workspace/local-sandbox) 都內建處理程序管理器。除非你正在建立自訂 Sandbox Provider,否則不需要直接建立此類別的執行個體。 ## 使用範例 透過 Sandbox 的 `processes` 屬性存取處理程序管理器: ```typescript import { LocalSandbox } from '@mastra/core/workspace' const sandbox = new LocalSandbox({ workingDirectory: './workspace' }) await sandbox.start() // Spawn a background process const handle = await sandbox.processes.spawn('node server.js', { env: { PORT: '3000' }, onStdout: data => console.log(data), }) // List all tracked processes const procs = await sandbox.processes.list() // Get a handle by PID const proc = await sandbox.processes.get(handle.pid) // Kill a process await sandbox.processes.kill(handle.pid) ``` ## 方法 ### `spawn(command, options?)` 產生背景處理程序。不會等待處理程序完成,而會立即回傳 `ProcessHandle`。 ```typescript const handle = await sandbox.processes.spawn('npm run dev', { cwd: '/app', env: { NODE_ENV: 'development' }, onStdout: data => console.log(data), }) ``` **參數:** **command** (`string`): 要執行的指令。由 shell 解譯。 **options** (`SpawnProcessOptions`): 產生處理程序的選用設定。 **options.timeout** (`number`): 逾時時間,單位為毫秒。超過時會終止處理程序。 **options.env** (`NodeJS.ProcessEnv`): 處理程序的環境變數。 **options.cwd** (`string`): 處理程序的工作目錄。 **options.onStdout** (`(data: string) => void`): stdout 資料塊的回呼函式。資料到達時呼叫。 **options.onStderr** (`(data: string) => void`): stderr 資料塊的回呼函式。資料到達時呼叫。 **options.abortSignal** (`AbortSignal`): 用於中止處理程序的 signal。中止時會終止處理程序。 **回傳值:** `Promise` ### `list()` 列出所有追蹤中的處理程序。回傳每個處理程序的資訊,包含 PID、執行狀態與結束程式碼。 ```typescript const procs = await sandbox.processes.list() for (const proc of procs) { console.log(proc.pid, proc.running, proc.exitCode) } ``` **回傳值:** `Promise` ### `get(pid)` 透過 PID 取得處理程序的 handle。若找不到該處理程序或已將其移除,則回傳 `undefined`。 ```typescript const handle = await sandbox.processes.get(1234) if (handle) { console.log(handle.stdout) await handle.kill() } ``` **回傳值:** `Promise` ### `kill(pid)` 透過 PID 終止處理程序。回傳前會等待處理程序終止。如果處理程序已終止,則回傳 `true`;如果找不到,則回傳 `false`。 ```typescript const killed = await sandbox.processes.kill(handle.pid) ``` **回傳值:** `Promise` ## `ProcessInfo` 追蹤中處理程序的資訊,由 `list()` 回傳。 **pid** (`number`): 處理程序 ID。 **command** (`string`): 已執行的指令。 **running** (`boolean`): 處理程序是否仍在執行。 **exitCode** (`number`): 處理程序已完成時的結束程式碼。 *** ## `ProcessHandle` 已產生背景處理程序的 handle。提供讀取輸出、傳送 stdin、等待完成與終止處理程序的方法。 不需要直接建立 `ProcessHandle` 執行個體;它們由 `spawn()` 與 `get()` 回傳。 ### 使用範例 ```typescript const handle = await sandbox.processes.spawn('npm run dev', { onStdout: data => console.log(data), }) // Read accumulated output console.log(handle.pid) console.log(handle.stdout) console.log(handle.stderr) console.log(handle.exitCode) // undefined while running // Wait for completion const result = await handle.wait() // Send stdin await handle.sendStdin('input data\n') // Kill the process await handle.kill() ``` ### 屬性 **pid** (`number`): 處理程序 ID。 **stdout** (`string`): 目前累積的 stdout 輸出。 **stderr** (`string`): 目前累積的 stderr 輸出。 **exitCode** (`number | undefined`): 結束程式碼。處理程序仍在執行時為 undefined。 **command** (`string | undefined`): 產生處理程序時使用的指令。由處理程序管理器自動設定。 **reader** (`Readable`): stdout 的可讀 stream。適用於 LSP 或 JSON-RPC 等透過 stdio 通訊的協定。 **writer** (`Writable`): 寫入 stdin 的可寫 stream。適用於 LSP 或 JSON-RPC 等透過 stdio 通訊的協定。 ### 方法 #### `wait(options?)` 等待處理程序結束並回傳結果。可選擇傳入 `onStdout`/`onStderr` 回呼函式,以便在等待時串流傳輸輸出。`wait()` 完成後,會自動移除回呼函式。 ```typescript // Simple wait const result = await handle.wait() console.log(result.success, result.exitCode, result.stdout) // Wait with streaming const result = await handle.wait({ onStdout: data => process.stdout.write(data), onStderr: data => process.stderr.write(data), }) ``` **參數:** **options** (`WaitOptions`): 等待時的選用設定。 **options.onStdout** (`(data: string) => void`): 等待期間 stdout 資料塊的回呼函式。 **options.onStderr** (`(data: string) => void`): 等待期間 stderr 資料塊的回呼函式。 **回傳值:** `Promise` `CommandResult` 物件包含: **success** (`boolean`): 結束程式碼為 0 時是 true。 **exitCode** (`number`): 數值形式的結束程式碼。 **stdout** (`string`): 完整的 stdout 輸出。 **stderr** (`string`): 完整的 stderr 輸出。 **executionTimeMs** (`number`): 執行時間,單位為毫秒。 **timedOut** (`boolean`): 處理程序因逾時而被終止時是 true。 **killed** (`boolean`): 處理程序因 signal 而被終止時是 true。 #### `kill()` 終止處理程序。如果處理程序已終止,則回傳 `true`;如果早已結束,則回傳 `false`。 ```typescript const killed = await handle.kill() ``` **回傳值:** `Promise` #### `sendStdin(data)` 將資料傳送至處理程序的 stdin。如果處理程序已結束或 stdin 不可用,則拋出錯誤。 ```typescript await handle.sendStdin('console.log("hello")\n') ``` **回傳值:** `Promise` ## Stream 互通性 `ProcessHandle` 公開 `reader` 與 `writer` 屬性,用來與 LSP 或 JSON-RPC 等以 Node.js stream 為基礎的協定整合: ```typescript import { createMessageConnection, StreamMessageReader, StreamMessageWriter, } from 'vscode-jsonrpc/node' const handle = await sandbox.processes.spawn('typescript-language-server --stdio') const connection = createMessageConnection( new StreamMessageReader(handle.reader), new StreamMessageWriter(handle.writer), ) connection.listen() ``` ## 建立自訂處理程序管理器 若要為自訂 Sandbox Provider 建立處理程序管理器,請擴充 `SandboxProcessManager` 並實作 `spawn()` 與 `list()`。基底類別會自動使用 `ensureRunning()` 包裝你的方法,讓 Sandbox 在任何處理程序操作前啟動。 ```typescript import { SandboxProcessManager, ProcessHandle } from '@mastra/core/workspace' import type { ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace' class MyProcessManager extends SandboxProcessManager { async spawn(command: string, options: SpawnProcessOptions = {}): Promise { // Your spawn implementation const handle = new MyProcessHandle(/* ... */) this._tracked.set(handle.pid, handle) return handle } async list(): Promise { return Array.from(this._tracked.values()).map(handle => ({ pid: handle.pid, running: handle.exitCode === undefined, exitCode: handle.exitCode, })) } } ``` 透過 `MastraSandbox` 的 `processes` 選項,將處理程序管理器傳給 Sandbox: ```typescript class MySandbox extends MastraSandbox { constructor() { super({ name: 'MySandbox', processes: new MyProcessManager(), }) } } ``` 提供處理程序管理器後,`MastraSandbox` 會自動建立使用 `spawn()` + `wait()` 的預設 `executeCommand` 實作,因此不需要兩者都實作。 ## 相關內容 - [Sandbox](https://mastra.zisheng.pro/zh-TW/docs/workspace/sandbox) - [WorkspaceSandbox 介面](https://mastra.zisheng.pro/zh-TW/reference/workspace/sandbox) - [LocalSandbox 參考](https://mastra.zisheng.pro/zh-TW/reference/workspace/local-sandbox) - [E2BSandbox 參考](https://mastra.zisheng.pro/zh-TW/reference/workspace/e2b-sandbox) - [DaytonaSandbox 參考](https://mastra.zisheng.pro/zh-TW/reference/workspace/daytona-sandbox)