본문으로 건너뛰기

플랫폼샌드박스

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 install @mastra/platform-workspace

플랫폼 자격 증명을 구성합니다. 액세스 토큰, 프로젝트 ID 및 환경 ID는 환경 변수로 대체되므로 Mastra 플랫폼 배포는 생성자 옵션을 0으로 전달할 수 있습니다.

MASTRA_PLATFORM_ACCESS_TOKEN=your-platform-access-token
MASTRA_PROJECT_ID=your-project-id
MASTRA_ENVIRONMENT_ID=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 환경에서 실행되는 다른 서비스에 접근할 수 있도록 networkIsolationPRIVATE으로 설정하여 환경의 사설 네트워크에 연결합니다.

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?:

string
플랫폼 액세스 토큰입니다. 지정하지 않으면 MASTRA_PLATFORM_ACCESS_TOKEN 환경 변수를 사용합니다.

projectId?:

string
플랫폼 프로젝트 ID입니다. 지정하지 않으면 MASTRA_PROJECT_ID 환경 변수를 사용합니다.

environmentId?:

string
Sandbox가 속한 플랫폼 환경 ID입니다. 지정하지 않으면 MASTRA_ENVIRONMENT_ID 환경 변수를 사용합니다. sandboxId를 전달하지 않은 경우 필수입니다.

sandboxId?:

string
새 Sandbox를 생성하는 대신 다시 연결할 기존 Sandbox ID입니다. 설정하면 environmentId가 필요하지 않습니다.

idleTimeoutMinutes?:

number
활동이 없을 때 플랫폼이 Sandbox를 제거하기 전까지 Sandbox가 유지되는 시간입니다.

networkIsolation?:

'ISOLATED' | 'PRIVATE'
네트워크 모드입니다. 'ISOLATED'(기본값)는 아웃바운드 인터넷만 허용합니다. 'PRIVATE'은 플랫폼 환경의 사설 네트워크에 연결합니다.

env?:

Record<string, string>
Sandbox 생성 시 포함되는 환경 변수입니다. 명령별 환경 변수도 executeCommand에 전달할 수 있습니다.

timeout?:

number
기본 명령 실행 제한 시간(밀리초)입니다. 호출별로 ExecuteCommandOptions.timeout을 통해 재정의할 수 있습니다.

instructions?:

string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)
getInstructions()가 반환할 사용자 지정 지침입니다. 문자열은 기본값을 완전히 대체하며, 함수는 기본값을 받아 요청별로 확장하거나 맞춤 설정할 수 있습니다.

id?:

string
= 자동 생성
이 Sandbox 인스턴스의 고유 식별자입니다. 권고용 복구 키로 플랫폼에 전송됩니다. 플랫폼이 이전 Sandbox의 id를 인식하면 새 Sandbox는 기본 레시피 대신 해당 Sandbox의 최신 체크포인트에서 부팅됩니다. 알 수 없는 id는 새 Sandbox 생성으로 이어집니다. 생략하면 자동 생성되며 체크포인트 복구가 비활성화됩니다.

fetch?:

typeof fetch
주로 테스트에 사용하는 사용자 지정 fetch 구현입니다.

속성
속성에 대한 직접 링크

id:

string
Sandbox 인스턴스 식별자입니다.

name:

string
Provider 이름('PlatformSandbox').

provider:

string
Provider 식별자('platform').

status:

ProviderStatus
'pending' | 'initializing' | 'ready' | 'starting' | 'running' | 'stopping' | 'stopped' | 'destroying' | 'destroyed' | 'error'.

processes:

PlatformProcessManager
백그라운드 프로세스 관리자입니다. SandboxProcessManager 레퍼런스를 참조하세요.

행동 양식
행동 양식에 대한 직접 링크

start:

() => Promise<void>
원격 Sandbox를 프로비저닝하거나 생성자에 sandboxId가 전달된 경우 다시 연결합니다. Sandbox가 실행된 후에는 멱등성을 보장합니다. 재연결 대상이 제거된 경우 새로 프로비저닝합니다.

destroy:

() => Promise<void>
원격 Sandbox를 해제하고 캐시된 exec 리스를 지웁니다. 이후 start()를 호출하면 새 Sandbox를 프로비저닝합니다(안정적인 id가 설정된 경우 체크포인트에서 복원).

stop:

() => Promise<void>
destroy()의 별칭입니다.

executeCommand:

(command: string, args?: string[], options?: ExecuteCommandOptions) => Promise<CommandResult>
원격 Sandbox에서 명령을 실행하고 stdout, stderr, exitCode, executionTimeMs를 반환합니다. command는 셸 문자열이며 args는 안전하게 셸 인용됩니다.

clone:

(options?: SandboxCloneOptions) => PlatformSandbox
자격 증명과 기본값을 상속하면서 인스턴스별 재정의(id, sandboxId, env, idleTimeoutMinutes)를 적용하는, 시작되지 않은 형제 PlatformSandbox를 생성합니다. I/O는 수행하지 않습니다. 구성된 하나의 템플릿에서 독립적인 Sandbox 집합을 구축할 때 사용합니다.

getInfo:

() => Promise<SandboxInfo>
Sandbox의 플랫폼 id, provider, status, createdAt 및 메타데이터(sandboxId, providerResourceId, platformStatus)를 반환합니다.

getInstructions:

(opts?: { requestContext?: RequestContext }) => string
Workspace가 Tool 설명에 표시하는 Sandbox 지침을 반환합니다. 생성자의 instructions 옵션을 따르며, 옵션이 없으면 실행 중인 원격 Sandbox의 현재 id가 포함된 플랫폼 기본 지침을 반환합니다.

오류
오류에 대한 직접 링크

플랫폼 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) codeproxyMessageundefined입니다. 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, wsEndpointsandboxId, command, attempts)를 제공하므로 운영자는 Railway 데이터 플레인 장애와 명령 실패를 구분할 수 있습니다.