> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 데이토나샌드박스 격리된 상태에서 명령을 실행합니다.[Daytona](https://www.daytona.io)클라우드 샌드박스. 다중 런타임, 리소스 구성, 볼륨, 스냅샷, 스트리밍 출력, 샌드박스 재연결, 파일 시스템 마운트(S3, GCS) 및 네트워크 격리를 지원합니다. 인터페이스에 대한 자세한 내용은 다음을 참조하세요.[WorkspaceSandbox 인터페이스](https://mastra.zisheng.pro/ko/reference/workspace/sandbox). ## 설치 **npm**: ```bash npm install @mastra/daytona ``` **pnpm**: ```bash pnpm add @mastra/daytona ``` **Yarn**: ```bash yarn add @mastra/daytona ``` **Bun**: ```bash bun add @mastra/daytona ``` 세 가지 방법 중 하나로 Daytona API 키를 설정하세요. **Shell export**: ```bash export DAYTONA_API_KEY=your-api-key ``` **.env file**: ```bash DAYTONA_API_KEY=your-api-key ``` **Constructor**: ```typescript new DaytonaSandbox({ apiKey: 'your-api-key' }) ``` ## 용법 Workspace에 `DaytonaSandbox`를 추가하고 Agent에 할당합니다: ```typescript import { Agent } from '@mastra/core/agent' import { Workspace } from '@mastra/core/workspace' import { DaytonaSandbox } from '@mastra/daytona' const workspace = new Workspace({ sandbox: new DaytonaSandbox({ language: 'typescript', timeout: 120_000, }), }) 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) // I'll run both commands simultaneously! // // Here are the results: // // 1. **Hello, world!** — Successfully printed the message. // 2. **Current Working Directory** — `/home/daytona` // // Both commands ran in parallel and completed successfully! ``` ### 스냅샷 포함 사전 빌드된 스냅샷을 사용하여 환경 설정 시간을 건너뜁니다. ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ snapshot: 'my-snapshot-id', timeout: 60_000, }), }) ``` ### 리소스가 포함된 커스텀 이미지 특정 리소스 할당이 포함된 사용자 지정 Docker 이미지를 사용합니다. ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ image: 'node:20-slim', resources: { cpu: 2, memory: 4, disk: 6 }, language: 'typescript', }), }) ``` ### 임시 샌드박스 일회성 작업의 경우: 중지 시 샌드박스가 즉시 삭제됩니다. ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ ephemeral: true, language: 'python', }), }) ``` ### 스트리밍 출력 `onStdout` 및 `onStderr` 콜백을 통해 명령 출력을 실시간으로 스트리밍합니다: ```typescript await sandbox.executeCommand('bash', ['-c', 'for i in 1 2 3; do echo "line $i"; sleep 1; done'], { onStdout: chunk => process.stdout.write(chunk), onStderr: chunk => process.stderr.write(chunk), }) ``` 두 콜백 모두 선택 사항이며 독립적으로 사용할 수 있습니다. ### 재연결 동일한 `id`를 제공하여 기존 Sandbox에 다시 연결합니다. Sandbox는 파일과 상태가 그대로 유지된 채 재개됩니다: ```typescript const sandbox = new DaytonaSandbox({ id: 'my-persistent-sandbox' }) // First session await sandbox._start() await sandbox.executeCommand('sh', ['-c', 'echo "session 1" > /tmp/state.txt']) await sandbox._stop() // Later — reconnects to the same sandbox const sandbox2 = new DaytonaSandbox({ id: 'my-persistent-sandbox' }) await sandbox2._start() const result = await sandbox2.executeCommand('cat', ['/tmp/state.txt']) console.log(result.stdout) // "session 1" ``` 샌드박스가 중지되거나 보관된 상태인 경우 자동으로 다시 시작됩니다. 작동 불능 상태(파괴, 오류 발생)인 경우 대신 새로운 샌드박스가 생성됩니다. ### 파일 시스템 마운트 S3 또는 GCS 버킷을 샌드박스 내부의 로컬 디렉터리로 마운트합니다. #### 작업 공간 마운트 구성을 통해 가장 간단한 방법: 샌드박스가 시작될 때 파일 시스템이 자동으로 마운트됩니다. ```typescript import { Workspace } from '@mastra/core/workspace' import { DaytonaSandbox } from '@mastra/daytona' import { GCSFilesystem } from '@mastra/gcs' import { S3Filesystem } from '@mastra/s3' const workspace = new Workspace({ mounts: { '/s3-data': new S3Filesystem({ bucket: process.env.S3_BUCKET!, region: 'auto', accessKeyId: process.env.S3_ACCESS_KEY_ID, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY, endpoint: process.env.S3_ENDPOINT, // e.g. https://.r2.cloudflarestorage.com }), '/gcs-data': new GCSFilesystem({ bucket: process.env.GCS_BUCKET!, projectId: 'my-project-id', credentials: JSON.parse(process.env.GCS_SERVICE_ACCOUNT_KEY!), }), }, sandbox: new DaytonaSandbox({ language: 'python' }), }) ``` Workspace가 시작되면 파일 시스템이 지정된 경로에 자동으로 마운트됩니다. Sandbox에서 실행되는 코드는 `/s3-data` 및 `/gcs-data`의 파일에 로컬 디렉터리처럼 액세스할 수 있습니다. #### 을 통해`sandbox.mount()` 샌드박스가 시작된 후 언제든지 수동으로 마운트합니다. #### S3 ```typescript import { S3Filesystem } from '@mastra/s3' await sandbox.mount( new S3Filesystem({ bucket: process.env.S3_BUCKET!, region: 'us-east-1', accessKeyId: process.env.S3_ACCESS_KEY_ID, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY, }), '/data', ) ``` #### S3 호환(Cloudflare R2, MinIO) ```typescript import { S3Filesystem } from '@mastra/s3' await sandbox.mount( new S3Filesystem({ bucket: process.env.S3_BUCKET!, region: 'auto', accessKeyId: process.env.S3_ACCESS_KEY_ID, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY, endpoint: process.env.S3_ENDPOINT, // e.g. https://.r2.cloudflarestorage.com }), '/data', ) ``` #### GCS ```typescript import { GCSFilesystem } from '@mastra/gcs' await sandbox.mount( new GCSFilesystem({ bucket: process.env.GCS_BUCKET!, projectId: 'my-project-id', credentials: JSON.parse(process.env.GCS_SERVICE_ACCOUNT_KEY!), }), '/data', ) ``` ### 네트워크 격리 아웃바운드 네트워크 액세스를 제한합니다. ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ networkBlockAll: true, networkAllowList: '10.0.0.0/8,192.168.0.0/16', }), }) ``` 패키지 레지스트리 및 호스팅 API처럼 IP 주소가 변경되는 서비스에는 `domainAllowList`를 사용합니다: ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ networkBlockAll: true, domainAllowList: 'registry.npmjs.org,*.githubusercontent.com', }), }) ``` 두 허용 목록은 모두 Sandbox 생성 시 적용되며 `clone()`에서도 유지됩니다. Sandbox가 시작된 후 정책을 변경하려면 기본 Daytona Sandbox를 사용합니다: ```typescript await sandbox.instance.updateNetworkSettings({ domainAllowList: 'api.example.com', }) ``` ## 생성자 매개변수 **id** (`string`): 이 Sandbox 인스턴스의 고유 식별자입니다. (Default: `자동 생성`) **apiKey** (`string`): 인증에 사용할 Daytona API 키입니다. 지정하지 않으면 DAYTONA\_API\_KEY 환경 변수를 사용합니다. **apiUrl** (`string`): Daytona API 엔드포인트입니다. 지정하지 않으면 DAYTONA\_API\_URL 환경 변수를 사용합니다. **target** (`string`): Runner 리전입니다. 지정하지 않으면 DAYTONA\_TARGET 환경 변수를 사용합니다. **timeout** (`number`): 밀리초 단위의 기본 실행 제한 시간입니다. (Default: `300000(5분)`) **language** (`'typescript' | 'javascript' | 'python'`): Sandbox의 런타임 언어입니다. (Default: `'typescript'`) **snapshot** (`string`): Sandbox 생성에 사용할 사전 빌드된 스냅샷 ID입니다. image보다 우선합니다. **image** (`string`): Sandbox 생성에 사용할 Docker 이미지입니다. 설정하면 이미지 기반 생성을 실행합니다. resources와 함께 사용할 수 있습니다. snapshot이 설정되어 있으면 무시됩니다. **resources** (`{ cpu?: number; memory?: number; disk?: number }`): Sandbox의 리소스 할당량입니다(CPU 코어, GiB 단위 Memory, GiB 단위 디스크). image가 설정된 경우에만 사용됩니다. **env** (`Record`): Sandbox에 설정할 환경 변수입니다. (Default: `{}`) **labels** (`Record`): 사용자 지정 메타데이터 레이블입니다. (Default: `{}`) **name** (`string`): Sandbox 표시 이름입니다. (Default: `Sandbox id`) **user** (`string`): 명령을 실행할 OS 사용자입니다. (Default: `'daytona'`) **public** (`boolean`): 포트 미리 보기를 공개합니다. (Default: `false`) **ephemeral** (`boolean`): 중지 시 Sandbox를 즉시 삭제합니다. (Default: `false`) **autoStopInterval** (`number`): 분 단위 자동 중지 간격입니다. 비활성화하려면 0으로 설정합니다. (Default: `15`) **autoArchiveInterval** (`number`): 분 단위 자동 보관 간격입니다. 최대 간격(7일)을 사용하려면 0으로 설정합니다. (Default: `7일`) **autoDeleteInterval** (`number`): 분 단위 자동 삭제 간격입니다. 음수 값은 자동 삭제를 비활성화합니다. 중지 시 삭제하려면 0으로 설정합니다. (Default: `비활성화됨`) **volumes** (`Array<{ volumeId: string; mountPath: string }>`): Sandbox 생성 시 연결할 Daytona 볼륨입니다. **networkBlockAll** (`boolean`): Sandbox에서 나가는 모든 네트워크 액세스를 차단합니다. (Default: `false`) **networkAllowList** (`string`): 네트워크 액세스가 제한될 때 허용할 CIDR 주소의 쉼표로 구분된 목록입니다. **domainAllowList** (`string`): 네트워크 액세스가 제한될 때 허용할 도메인의 쉼표로 구분된 목록입니다. \*.githubusercontent.com과 같은 와일드카드를 지원합니다. IP 주소가 변경되는 서비스에는 networkAllowList 대신 이 옵션을 사용합니다. ## 속성 **id** (`string`): Sandbox 인스턴스 식별자입니다. **name** (`string`): Provider 이름입니다('DaytonaSandbox'). **provider** (`string`): Provider 식별자입니다('daytona'). **status** (`ProviderStatus`): 'pending' | 'initializing' | 'ready' | 'stopped' | 'destroyed' | 'error' **instance** (`Sandbox`): 기본 Daytona Sandbox 인스턴스입니다. Sandbox가 시작되지 않았으면 SandboxNotReadyError를 발생시킵니다. **processes** (`DaytonaProcessManager`): 백그라운드 프로세스 관리자입니다. SandboxProcessManager 레퍼런스를 참조하세요. ## 백그라운드 프로세스 `DaytonaSandbox`백그라운드 프로세스 생성 및 관리를 위한 내장 프로세스 관리자가 포함되어 있습니다. 프로세스는 세션 기반 명령 실행을 사용하여 Daytona 클라우드 샌드박스에서 실행됩니다. ```typescript const sandbox = new DaytonaSandbox({ language: 'typescript' }) await sandbox.start() // Spawn a background process const handle = await sandbox.processes.spawn('node server.js', { env: { PORT: '3000' }, onStdout: data => console.log(data), }) // Interact with the process console.log(handle.stdout) await handle.sendStdin('input\n') await handle.kill() ``` 전체 API는 [`SandboxProcessManager` 레퍼런스](https://mastra.zisheng.pro/ko/reference/workspace/process-manager)를 참조하세요. ## 클라우드 스토리지 마운트 Daytona 샌드박스는 S3 또는 GCS 버킷을 마운트할 수 있으므로 샌드박스 내부의 로컬 디렉터리로 클라우드 스토리지에 액세스할 수 있습니다. 이는 다음과 같은 경우에 유용합니다. - 클라우드 버킷에 저장된 대규모 데이터 세트 처리 - 출력 파일을 클라우드 스토리지에 직접 쓰기 - 샌드박스 세션 간 데이터 공유 사용 예는 다음을 참조하세요.[Filesystem mounting](#filesystem-mounting). Daytona 샌드박스는 FUSE(사용자 공간의 파일 시스템)를 사용하여 클라우드 스토리지를 탑재합니다. - **S3/R2**: 다음을 통해 장착됨[s3fs-fuse](https://github.com/s3fs-fuse/s3fs-fuse) - **GCS**: 다음을 통해 장착됨[gcsfuse](https://github.com/GoogleCloudPlatform/gcsfuse) 필수 FUSE Tool은 샌드박스 이미지에 아직 없는 경우 마운트 시 자동으로 설치됩니다. ### S3 환경 변수 | 변수 | 설명 | | ---------------------- | -------------------------- | | `S3_BUCKET` | 버킷 이름 | | `S3_REGION` | AWS 리전 또는 R2/MinIO용 `auto` | | `S3_ACCESS_KEY_ID` | 액세스 키 ID | | `S3_SECRET_ACCESS_KEY` | 비밀 액세스 키 | | `S3_ENDPOINT` | 엔드포인트 URL(S3 호환 스토리지만 해당) | ### GCS 환경 변수 | 변수 | 설명 | | ------------------------- | --------------------------------- | | `GCS_BUCKET` | 버킷 이름 | | `GCS_SERVICE_ACCOUNT_KEY` | 서비스 계정 키 JSON(경로가 아닌 전체 JSON 문자열) | ### 스냅샷으로 콜드 스타트 ​​대기 시간 줄이기 기본적으로 `s3fs`와 `gcsfuse`는 처음 마운트할 때 `apt`를 통해 설치되므로 시작 시간이 늘어납니다. 이를 방지하려면 Daytona 스냅샷에 미리 포함하고 `snapshot` 옵션을 통해 스냅샷 이름을 전달하세요. **옵션 1: 선언적 이미지 빌드** ```typescript import { Daytona, Image } from '@daytonaio/sdk' const template = Image.base('daytonaio/sandbox') .runCommands('sudo apt-get update -qq') .runCommands('sudo apt-get install -y s3fs') // gcsfuse requires the Google Cloud apt repository .runCommands( 'sudo mkdir -p /etc/apt/keyrings && ' + 'curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg -o /tmp/gcsfuse-key.gpg && ' + 'sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/gcsfuse.gpg /tmp/gcsfuse-key.gpg && ' + // Use gcsfuse-jammy for Ubuntu, gcsfuse-bookworm for Debian 'echo "deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-jammy main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list', ) .runCommands('sudo apt-get update -qq && sudo apt-get install -y gcsfuse') const daytona = new Daytona() await daytona.snapshot.create( { name: 'cloud-fs-mounting', image: template, }, { onLogs: console.log }, ) ``` **옵션 2: Dockerfile:**사용[`Image.fromDockerfile()`](https://www.daytona.io/docs/typescript-sdk/image#fromdockerfile) ```dockerfile FROM daytonaio/sandbox RUN sudo apt-get update -qq RUN sudo apt-get install -y s3fs # Use gcsfuse-jammy for Ubuntu, gcsfuse-bookworm for Debian RUN sudo mkdir -p /etc/apt/keyrings && curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg -o /tmp/gcsfuse-key.gpg && sudo gpg --batch --yes --dearmor -o /etc/apt/keyrings/gcsfuse.gpg /tmp/gcsfuse-key.gpg && echo "deb [signed-by=/etc/apt/keyrings/gcsfuse.gpg] https://packages.cloud.google.com/apt gcsfuse-jammy main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list RUN sudo apt-get update -qq && sudo apt-get install -y gcsfuse ``` ```typescript import { Daytona, Image } from '@daytonaio/sdk' const daytona = new Daytona() await daytona.snapshot.create( { name: 'cloud-fs-mounting', image: Image.fromDockerfile('./Dockerfile'), }, { onLogs: console.log }, ) ``` 그런 다음 샌드박스 구성에서 스냅샷 이름을 사용합니다. ```typescript const workspace = new Workspace({ mounts: { '/s3-data': new S3Filesystem({/* ... */}), '/gcs-data': new GCSFilesystem({/* ... */}), }, sandbox: new DaytonaSandbox({ snapshot: 'cloud-fs-mounting' }), }) ``` ## 직접 SDK 액세스 파일 시스템, git 및 `WorkspaceSandbox` 인터페이스를 통해 노출되지 않는 기타 작업을 위해 기본 Daytona `Sandbox` 인스턴스에 액세스합니다: ```typescript const daytonaSandbox = sandbox.instance // Upload a file await daytonaSandbox.fs.uploadFile(Buffer.from('hello'), '/tmp/hello.txt') // Run git operations await daytonaSandbox.git.clone('https://github.com/org/repo', '/workspace/repo') ``` Sandbox가 아직 시작되지 않았으면 `instance` getter가 `SandboxNotReadyError`를 발생시킵니다. ## 샌드박스 생성 모드 `DaytonaSandbox`제공된 옵션에 따라 생성 모드를 선택합니다. | 옵션 | 생성 모드 | | ----------------------------------------------------------------------- | -------------------------------- | | `snapshot` 설정 | 스냅샷 기반(snapshot이 image보다 우선) | | `image` 설정(snapshot 없음) | 이미지 기반(선택적으로 `resources`와 함께 사용) | | 둘 다 설정하지 않음 | 기본 스냅샷 기반 | | 리소스는 `image`가 설정된 경우에만 적용됩니다. `image` 없이 `resources`를 전달하면 아무 효과가 없습니다. | | ## 관련된 - [SandboxProcessManager 참조](https://mastra.zisheng.pro/ko/reference/workspace/process-manager) - [WorkspaceSandbox 인터페이스](https://mastra.zisheng.pro/ko/reference/workspace/sandbox) - [로컬샌드박스 참조](https://mastra.zisheng.pro/ko/reference/workspace/local-sandbox) - [S3파일 시스템 참조](https://mastra.zisheng.pro/ko/reference/workspace/s3-filesystem) - [GCS파일 시스템 참조](https://mastra.zisheng.pro/ko/reference/workspace/gcs-filesystem) - [작업공간 개요](https://mastra.zisheng.pro/ko/docs/workspace/overview)