샌드박스프로세스 관리자
추가된 항목: @mastra/core@1.7.0
샌드박스에서 백그라운드 프로세스를 관리하기 위한 추상 기본 클래스입니다. 프로세스를 생성하고, 나열하고, PID로 핸들을 가져오고, 종료하는 방법을 제공합니다.
BlaxelSandbox, DaytonaSandbox, E2BSandbox, ModalSandbox, 그리고LocalSandbox모두 내장된 프로세스 관리자를 포함합니다. 사용자 정의 샌드박스 공급자를 구축하지 않는 한 이 클래스를 직접 인스턴스화할 필요는 없습니다.
사용예사용예에 대한 직접 링크
샌드박스를 통해 프로세스 관리자에 액세스합니다.processes property:
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?)spawncommand-options에 대한 직접 링크
백그라운드 프로세스를 생성합니다. 프로세스가 완료될 때까지 기다리지 않고 즉시 ProcessHandle을 반환합니다.
const handle = await sandbox.processes.spawn('npm run dev', {
cwd: '/app',
env: { NODE_ENV: 'development' },
onStdout: data => console.log(data),
})
매개변수:
command:
options?:
timeout?:
env?:
cwd?:
onStdout?:
onStderr?:
abortSignal?:
보고: Promise<ProcessHandle>
list()list에 대한 직접 링크
추적된 모든 프로세스를 나열합니다. PID, 실행 상태 및 종료 코드를 포함하여 각 프로세스에 대한 정보를 반환합니다.
const procs = await sandbox.processes.list()
for (const proc of procs) {
console.log(proc.pid, proc.running, proc.exitCode)
}
보고: Promise<ProcessInfo[]>
get(pid)getpid에 대한 직접 링크
PID로 프로세스 핸들을 가져옵니다. 프로세스를 찾을 수 없거나 이미 해제된 경우 undefined를 반환합니다.
const handle = await sandbox.processes.get(1234)
if (handle) {
console.log(handle.stdout)
await handle.kill()
}
보고: Promise<ProcessHandle | undefined>
kill(pid)killpid에 대한 직접 링크
PID로 프로세스를 종료합니다. 반환하기 전에 프로세스가 종료될 때까지 기다립니다. 프로세스를 종료했으면 true, 찾지 못했으면 false를 반환합니다.
const killed = await sandbox.processes.kill(handle.pid)
보고: Promise<boolean>
ProcessInfoprocessinfo에 대한 직접 링크
추적된 프로세스에 대한 정보(다음에서 반환)list().
pid:
command?:
running:
exitCode?:
ProcessHandleprocesshandle에 대한 직접 링크
생성된 백그라운드 프로세스를 처리합니다. 출력을 읽고, stdin을 보내고, 완료를 기다리고, 프로세스를 종료하는 메서드를 제공합니다.
ProcessHandle 인스턴스를 직접 생성하지 않습니다. spawn()과 get()이 이를 반환합니다.
사용예사용예에 대한 직접 링크
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:
stdout:
stderr:
exitCode:
command:
reader:
writer:
행동 양식행동 양식에 대한 직접 링크
wait(options?)waitoptions에 대한 직접 링크
프로세스가 종료될 때까지 기다린 후 결과를 반환합니다. 기다리는 동안 출력을 스트리밍하려면 선택적으로 onStdout/onStderr 콜백을 전달합니다. 콜백은 wait()가 완료되면 자동으로 제거됩니다.
// 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?:
onStdout?:
onStderr?:
보고: Promise<CommandResult>
그만큼CommandResult object contains:
success:
exitCode:
stdout:
stderr:
executionTimeMs:
timedOut?:
killed?:
kill()kill에 대한 직접 링크
프로세스를 종료합니다. 프로세스를 종료했으면 true, 이미 종료된 상태였으면 false를 반환합니다.
const killed = await handle.kill()
보고: Promise<boolean>
sendStdin(data)sendstdindata에 대한 직접 링크
프로세스의 stdin으로 데이터를 보냅니다. 프로세스가 이미 종료되었거나 stdin을 사용할 수 없는 경우 발생합니다.
await handle.sendStdin('console.log("hello")\n')
보고: Promise<void>
스트림 상호 운용성스트림 상호 운용성에 대한 직접 링크
ProcessHandle은 LSP 또는 JSON-RPC 같은 Node.js 스트림 기반 프로토콜과 통합할 수 있도록 reader 및 writer 속성을 노출합니다.
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가 시작됩니다.
import { SandboxProcessManager, ProcessHandle } from '@mastra/core/workspace'
import type { ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace'
class MyProcessManager extends SandboxProcessManager<MySandbox> {
async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {
// Your spawn implementation
const handle = new MyProcessHandle(/* ... */)
this._tracked.set(handle.pid, handle)
return handle
}
async list(): Promise<ProcessInfo[]> {
return Array.from(this._tracked.values()).map(handle => ({
pid: handle.pid,
running: handle.exitCode === undefined,
exitCode: handle.exitCode,
}))
}
}
MastraSandbox의 processes 옵션을 통해 프로세스 관리자를 Sandbox에 전달합니다.
class MySandbox extends MastraSandbox {
constructor() {
super({
name: 'MySandbox',
processes: new MyProcessManager(),
})
}
}
프로세스 관리자가 제공되면 MastraSandbox가 spawn() + wait()를 사용하는 기본 executeCommand 구현을 자동으로 생성하므로 둘 다 구현할 필요가 없습니다.