> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 샌드박스프로세스 관리자 **추가된 항목:** `@mastra/core@1.7.0` 샌드박스에서 백그라운드 프로세스를 관리하기 위한 추상 기본 클래스입니다. 프로세스를 생성하고, 나열하고, PID로 핸들을 가져오고, 종료하는 방법을 제공합니다. [`BlaxelSandbox`](https://mastra.zisheng.pro/ko/reference/workspace/blaxel-sandbox), [`DaytonaSandbox`](https://mastra.zisheng.pro/ko/reference/workspace/daytona-sandbox), [`E2BSandbox`](https://mastra.zisheng.pro/ko/reference/workspace/e2b-sandbox), [`ModalSandbox`](https://mastra.zisheng.pro/ko/reference/workspace/modal-sandbox), 그리고[`LocalSandbox`](https://mastra.zisheng.pro/ko/reference/workspace/local-sandbox)모두 내장된 프로세스 관리자를 포함합니다. 사용자 정의 샌드박스 공급자를 구축하지 않는 한 이 클래스를 직접 인스턴스화할 필요는 없습니다. ## 사용예 샌드박스를 통해 프로세스 관리자에 액세스합니다.`processes` property: ```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`): 실행할 명령입니다. 셸에서 해석됩니다. **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`): 프로세스를 중단하는 신호입니다. 중단되면 프로세스가 종료됩니다. **보고:** `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로 프로세스 핸들을 가져옵니다. 프로세스를 찾을 수 없거나 이미 해제된 경우 `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` 생성된 백그라운드 프로세스를 처리합니다. 출력을 읽고, 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의 읽기 가능 스트림입니다. stdio를 통해 통신하는 LSP 또는 JSON-RPC 같은 프로토콜에 유용합니다. **writer** (`Writable`): stdin으로 연결되는 쓰기 가능 스트림입니다. stdio를 통해 통신하는 LSP 또는 JSON-RPC 같은 프로토콜에 유용합니다. ### 행동 양식 #### `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` object contains: **success** (`boolean`): 종료 코드가 0이면 true입니다. **exitCode** (`number`): 숫자 형식의 종료 코드입니다. **stdout** (`string`): 전체 stdout 출력입니다. **stderr** (`string`): 전체 stderr 출력입니다. **executionTimeMs** (`number`): 실행 시간(밀리초)입니다. **timedOut** (`boolean`): 제한 시간 초과로 프로세스가 종료되었으면 true입니다. **killed** (`boolean`): 신호로 프로세스가 종료되었으면 true입니다. #### `kill()` 프로세스를 종료합니다. 프로세스를 종료했으면 `true`, 이미 종료된 상태였으면 `false`를 반환합니다. ```typescript const killed = await handle.kill() ``` **보고:** `Promise` #### `sendStdin(data)` 프로세스의 stdin으로 데이터를 보냅니다. 프로세스가 이미 종료되었거나 stdin을 사용할 수 없는 경우 발생합니다. ```typescript await handle.sendStdin('console.log("hello")\n') ``` **보고:** `Promise` ## 스트림 상호 운용성 `ProcessHandle`은 LSP 또는 JSON-RPC 같은 Node.js 스트림 기반 프로토콜과 통합할 수 있도록 `reader` 및 `writer` 속성을 노출합니다. ```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` 구현을 자동으로 생성하므로 둘 다 구현할 필요가 없습니다. ## 관련된 - [모래 상자](https://mastra.zisheng.pro/ko/docs/workspace/sandbox) - [WorkspaceSandbox 인터페이스](https://mastra.zisheng.pro/ko/reference/workspace/sandbox) - [로컬샌드박스 참조](https://mastra.zisheng.pro/ko/reference/workspace/local-sandbox) - [E2B샌드박스 참조](https://mastra.zisheng.pro/ko/reference/workspace/e2b-sandbox) - [Daytona샌드박스 참조](https://mastra.zisheng.pro/ko/reference/workspace/daytona-sandbox)