플랫폼샌드박스
Mastra 플랫폼 환경에서 샌드박스를 프로비저닝하기 위한 클라이언트입니다. 각PlatformSandbox인스턴스는 하나의 원격 샌드박스를 소유합니다.start()그것을 규정하고,executeCommand()그것에 맞서 달리고,destroy()그것을 찢어 버리십시오. 추가 원격 샌드박스를 소유하려면 추가 인스턴스를 구성하세요. 사용clone()구성된 템플릿에서 이를 파생시킵니다(참조:복제).
Sandbox는 Python 3, Node 22, TypeScript, tsx 및 일반적인 빌드 Tool이 이미 설치된 사전 구축 레시피 체크포인트에서 부팅됩니다. 안정적인 id를 전달하여 체크포인트 복구를 사용하면 새 Sandbox가 이전 Sandbox의 파일 시스템에서 부팅됩니다.
관련 Provider: 자체 호스팅 Railway Sandbox용 RailwaySandbox, 로컬 Sandbox용 LocalSandbox.
인터페이스에 대한 자세한 내용은 다음을 참조하세요.WorkspaceSandbox interface.
설치설치에 대한 직접 링크
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/platform-workspace
pnpm add @mastra/platform-workspace
yarn add @mastra/platform-workspace
bun add @mastra/platform-workspace
플랫폼 자격 증명을 구성합니다. 액세스 토큰, 프로젝트 ID 및 환경 ID는 환경 변수로 대체되므로 Mastra 플랫폼 배포는 생성자 옵션을 0으로 전달할 수 있습니다.
- .env file
- Constructor
MASTRA_PLATFORM_ACCESS_TOKEN=your-platform-access-token
MASTRA_PROJECT_ID=your-project-id
MASTRA_ENVIRONMENT_ID=your-environment-id
new PlatformSandbox({
accessToken: 'your-platform-access-token',
projectId: 'your-project-id',
environmentId: 'your-environment-id',
})
Mastra 플랫폼 배포에서는 MASTRA_PLATFORM_ACCESS_TOKEN, MASTRA_PROJECT_ID, MASTRA_ENVIRONMENT_ID가 자동으로 주입되므로 옵션 없이 생성자를 호출할 수 있습니다. 로컬 개발 환경에서는 MASTRA_PLATFORM_ACCESS_TOKEN에 조직 설정 페이지의 API Tokens에서 가져온 sk_ API 토큰을 사용할 수 있습니다.
용법용법에 대한 직접 링크
Workspace에 PlatformSandbox를 추가하고 Agent에 할당합니다.
import { Agent } from '@mastra/core/agent'
import { Workspace } from '@mastra/core/workspace'
import { PlatformSandbox } from '@mastra/platform-workspace'
const workspace = new Workspace({
sandbox: new PlatformSandbox({
// accessToken, projectId, environmentId all fall back to env vars
idleTimeoutMinutes: 30,
}),
})
const agent = new Agent({
id: 'code-agent',
name: 'Code Agent',
instructions: 'You are a coding assistant working in this workspace.',
model: 'anthropic/claude-sonnet-4-6',
workspace,
})
const response = await agent.generate(
'Print "Hello, world!" and show the current working directory.',
)
console.log(response.text)
비공개 네트워킹비공개 네트워킹에 대한 직접 링크
같은 Mastra Platform 환경에서 실행되는 다른 서비스에 접근할 수 있도록 networkIsolation을 PRIVATE으로 설정하여 환경의 사설 네트워크에 연결합니다.
const workspace = new Workspace({
sandbox: new PlatformSandbox({
networkIsolation: 'PRIVATE',
}),
})
기본 ISOLATED 모드에서는 아웃바운드 인터넷 액세스만 허용되며 사설 네트워크에는 연결할 수 없습니다.
실행 중인 샌드박스에 다시 연결실행 중인 샌드박스에 다시 연결에 대한 직접 링크
새 Sandbox를 생성하는 대신 실행 중인 Sandbox에 다시 연결하려면 기존 sandboxId를 전달합니다.
const sandbox = new PlatformSandbox({
sandboxId: 'sbx_abc123',
})
await sandbox.start()
const result = await sandbox.executeCommand('cat', ['/workspace/state.json'])
Sandbox가 이미 존재하므로 sandboxId가 설정된 경우 environmentId는 필요하지 않습니다.
체크포인트 복구체크포인트 복구에 대한 직접 링크
생성자의 id(명시적으로 지정하거나 자동 생성)는 권고용 복구 키로 POST /sandbox 요청을 통해 플랫폼에 전송됩니다.
- 플랫폼이 이전 세션의
id를 인식하면 새 Sandbox는 기본 레시피 대신 이전 Sandbox 파일 시스템의 최신 체크포인트에서 부팅됩니다. id가 인식되지 않으면 플랫폼은 기본 레시피에서 새 Sandbox를 시작합니다. 자동 생성된 ID는 일치하지 않으므로id를 생략하면 체크포인트 복구가 비활성화됩니다. 세션 간 또는destroy()/start()주기 간에 Sandbox의 파일 시스템을 유지하려면 안정적인id를 전달합니다.
const sandbox = new PlatformSandbox({
id: `project-${projectId}`,
})
await sandbox.start() // Boots from the most recent checkpoint for this id, or fresh if unknown
체크포인트 복구는 sandboxId 재연결보다 단위가 큽니다. sandboxId를 통한 재연결은 실행 중인 동일한 Sandbox와 그 프로세스에 다시 연결합니다. 체크포인트 복구는 완전히 새로운 Sandbox를 생성하고, 해당 id를 사용했던 이전 Sandbox에 대해 플랫폼이 캡처한 최신 체크포인트에서 파일 시스템을 복원합니다. 실행 중이던 프로세스와 마지막 체크포인트 이후에 이루어진 파일 시스템 쓰기는 복원되지 않습니다.
각 id는 하나의 독립된 파일 시스템에 매핑됩니다. 관련 없는 Sandbox에서 같은 id를 재사용하면 서로의 체크포인트에서 부팅됩니다.
일련의 샌드박스에 대한 복제일련의 샌드박스에 대한 복제에 대한 직접 링크
clone()은 자격 증명과 기본값(액세스 토큰, 프로젝트, 환경, 네트워크 격리, 제한 시간, 지침, 환경 변수, 유휴 제한 시간)을 상속하면서 인스턴스별로 재정의할 수 있는 독립적인 형제 PlatformSandbox를 반환합니다. 반환된 Sandbox는 시작되지 않은 상태이며 자체 start() 호출 시 프로비저닝되므로 clone()은 I/O를 수행하지 않습니다.
const template = new PlatformSandbox({
networkIsolation: 'PRIVATE',
idleTimeoutMinutes: 30,
})
const perProject = template.clone({ id: `project-${projectId}` })
await perProject.start()
각 복제본에 안정적인 id를 지정해 clone()과 함께 사용하면 복제본별로 독립적인 체크포인트 복구를 사용할 수 있습니다.
명령 실행명령 실행에 대한 직접 링크
executeCommand는 원격 Sandbox에서 명령을 실행하고 출력을 반환합니다. 인수가 안전하게 셸 인용되도록 args를 전달합니다.
const result = await sandbox.executeCommand('python', ['analyze.py'], {
timeout: 30_000,
cwd: '/workspace',
env: { INPUT: 'repo' },
})
console.log(result.stdout)
console.log(result.exitCode)
command 인수는 셸 문자열이며 원격 셸에 그대로 연결됩니다. 따라서 파이프, 리디렉션, 명령 연결(ls -la | grep foo)을 사용할 수 있지만, 신뢰할 수 없는 입력은 args를 통해 전달하거나(안전하게 인용됨) 호출자가 셸 인용해야 합니다. 신뢰할 수 없는 command 값은 Sandbox에서 임의의 셸 명령 실행을 허용합니다.
생성자 매개변수생성자 매개변수에 대한 직접 링크
accessToken?:
projectId?:
environmentId?:
sandboxId?:
idleTimeoutMinutes?:
networkIsolation?:
env?:
timeout?:
instructions?:
id?:
fetch?:
속성속성에 대한 직접 링크
id:
name:
provider:
status:
processes:
행동 양식행동 양식에 대한 직접 링크
start:
destroy:
stop:
executeCommand:
clone:
getInfo:
getInstructions:
오류오류에 대한 직접 링크
플랫폼 API 오류는 PlatformApiError를 발생시킵니다. 구조화된 { error: { message, type } } 응답은 .code(머신 판독 가능한 유형)와 .proxyMessage(사람이 읽을 수 있는 문자열)로 파싱되며 원시 응답 본문은 .body에서 계속 사용할 수 있습니다.
import { PlatformApiError } from '@mastra/platform-workspace'
try {
await sandbox.executeCommand('cat', ['/missing.txt'])
} catch (err) {
if (err instanceof PlatformApiError) {
if (err.code === 'not_found') {
// handle missing resource
} else if (err.code === 'authentication_error') {
// refresh token
}
console.error(err.status, err.code, err.proxyMessage)
}
}
응답 본문이 JSON이 아닌 경우(예: 로드 밸런서가 반환한 HTML 502) code와 proxyMessage는 undefined입니다.
executeCommand직접 실행 데이터 플레인(철도 tcp-proxy에 대한 WebSocket)을 통해 실행되며 복구할 수 없는 오류가 발생하면 두 가지 유형의 샌드박스 오류가 발생할 수도 있습니다.
import { SandboxDestroyedError, SandboxExecTransportError } from '@mastra/platform-workspace'
try {
await sandbox.executeCommand('pytest')
} catch (err) {
if (err instanceof SandboxDestroyedError) {
// /exec-lease returned 410; the sandbox has been destroyed.
// The cached sandbox id and lease have already been cleared,
// so reusing the instance will reprovision on the next call.
} else if (err instanceof SandboxExecTransportError) {
// Both the initial WebSocket attempt and the built-in retry
// closed without an exit frame against a live sandbox.
console.error(err.closeCode, err.closeReason, err.wsEndpoint)
}
}
SandboxExecTransportError는 진단 필드(opened, closeCode, closeReason, wsEndpoint와 sandboxId, command, attempts)를 제공하므로 운영자는 Railway 데이터 플레인 장애와 명령 실패를 구분할 수 있습니다.