> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # E2B샌드박스 격리된 상태에서 명령을 실행합니다.[E2B](https://e2b.dev)클라우드 샌드박스. 클라우드 스토리지 마운트를 지원하여 안전한 임시 환경을 제공합니다. 인터페이스에 대한 자세한 내용은 다음을 참조하세요.[WorkspaceSandbox 인터페이스](https://mastra.zisheng.pro/ko/reference/workspace/sandbox). ## 설치 **npm**: ```bash npm install @mastra/e2b ``` **pnpm**: ```bash pnpm add @mastra/e2b ``` **Yarn**: ```bash yarn add @mastra/e2b ``` **Bun**: ```bash bun add @mastra/e2b ``` ## 용법 Workspace에 `E2BSandbox`를 추가하고 Agent에 할당합니다: ```typescript import { Agent } from '@mastra/core/agent' import { Workspace } from '@mastra/core/workspace' import { E2BSandbox } from '@mastra/e2b' const workspace = new Workspace({ sandbox: new E2BSandbox({ id: 'dev-sandbox', timeout: 60_000, // 60 second timeout (default: 5 minutes) }), }) const agent = new Agent({ id: 'dev-agent', name: 'dev-agent', model: 'anthropic/claude-opus-4-7', workspace, }) ``` ## 생성자 매개변수 **apiKey** (`string`): E2B API 키입니다. 지정하지 않으면 E2B\_API\_KEY 환경 변수를 사용합니다. **timeout** (`number`): 밀리초 단위의 실행 제한 시간 (Default: `300000(5분)`) **template** (`string | TemplateBuilder | function`): Sandbox 템플릿 사양입니다. 템플릿 ID 문자열, TemplateBuilder 또는 기본 템플릿을 사용자 지정하는 함수일 수 있습니다. **env** (`Record`): Sandbox에 설정할 환경 변수 **id** (`string`): 이 Sandbox 인스턴스의 고유 식별자 (Default: `자동 생성`) **domain** (`string`): 자체 호스팅 E2B의 도메인입니다. 지정하지 않으면 E2B\_DOMAIN 환경 변수를 사용합니다. **apiUrl** (`string`): 자체 호스팅 E2B의 API URL입니다. 지정하지 않으면 E2B\_API\_URL 환경 변수를 사용합니다. **accessToken** (`string`): 인증용 액세스 토큰입니다. 지정하지 않으면 E2B\_ACCESS\_TOKEN 환경 변수를 사용합니다. **metadata** (`Record`): Sandbox 인스턴스에 연결할 사용자 지정 메타데이터입니다. **instructions** (`string | ((opts: { defaultInstructions: string; requestContext?: RequestContext }) => string)`): getInstructions()가 반환하는 사용자 지정 지침입니다. 문자열은 기본값을 완전히 대체합니다. 함수는 기본값을 전달받으며 요청별로 이를 확장하거나 사용자 지정할 수 있습니다. 지침을 완전히 표시하지 않으려면 빈 문자열을 전달합니다. ## 속성 **id** (`string`): Sandbox 인스턴스 식별자 **name** (`string`): Provider 이름('E2BSandbox') **provider** (`string`): Provider 식별자('e2b') **status** (`ProviderStatus`): 'pending' | 'initializing' | 'ready' | 'starting' | 'running' | 'stopping' | 'stopped' | 'destroying' | 'destroyed' | 'error' **processes** (`E2BProcessManager`): 백그라운드 프로세스 관리자입니다. SandboxProcessManager 레퍼런스를 참조하세요. ## 백그라운드 프로세스 `E2BSandbox`에는 백그라운드 프로세스를 생성하고 관리하는 내장 프로세스 관리자가 포함되어 있습니다. 프로세스는 `background: true`가 지정된 E2B SDK의 `commands.run()`을 사용하여 E2B 클라우드 Sandbox에서 실행됩니다. ```typescript const sandbox = new E2BSandbox({ id: 'dev-sandbox' }) 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() ``` E2B 프로세스 관리자는 외부에서 생성되었거나 재연결 전에 생성된 프로세스에 대한 재연결을 지원합니다. 기존 프로세스에 연결하려면 PID를 사용해 `get(pid)`를 호출합니다: ```typescript const handle = await sandbox.processes.get(existingPid) if (handle) { console.log(handle.stdout) } ``` 전체 API는 [`SandboxProcessManager` 레퍼런스](https://mastra.zisheng.pro/ko/reference/workspace/process-manager)를 참조하세요. ## 클라우드 스토리지 마운트 E2B 샌드박스는 S3, GCS 및 Azure Blob 파일 시스템을 마운트할 수 있으므로 클라우드 스토리지를 샌드박스 내부의 로컬 디렉터리로 액세스할 수 있습니다. 이는 다음과 같은 경우에 유용합니다. - 클라우드 버킷에 저장된 대규모 데이터 세트 처리 - 출력 파일을 클라우드 스토리지에 직접 쓰기 - 샌드박스 세션 간 데이터 공유 ### 마운트 구성 사용 파일 시스템을 마운트하는 가장 간단한 방법은 작업 공간을 이용하는 것입니다.`mounts` config: ```typescript import { Workspace } from '@mastra/core/workspace' import { S3Filesystem } from '@mastra/s3' import { GCSFilesystem } from '@mastra/gcs' import { E2BSandbox } from '@mastra/e2b' const workspace = new Workspace({ mounts: { '/s3-data': new S3Filesystem({ bucket: 'my-s3-bucket', region: 'us-east-1', accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }), '/gcs-data': new GCSFilesystem({ bucket: 'my-gcs-bucket', projectId: 'my-project', credentials: JSON.parse(process.env.GCS_SERVICE_ACCOUNT_KEY), }), }, sandbox: new E2BSandbox({ id: 'dev-sandbox' }), }) ``` Sandbox가 시작되면 파일 시스템이 지정된 경로에 자동으로 마운트됩니다. Sandbox에서 실행되는 코드는 `/s3-data` 및 `/gcs-data`의 파일에 로컬 디렉터리처럼 액세스할 수 있습니다. ### 장착 작동 방식 E2B 샌드박스는 FUSE(사용자 공간의 파일 시스템)를 사용하여 클라우드 스토리지를 마운트합니다. - **S3/R2**: 다음을 통해 장착됨[s3fs-fuse](https://github.com/s3fs-fuse/s3fs-fuse) - **GCS**: 다음을 통해 장착됨[gcsfuse](https://github.com/GoogleCloudPlatform/gcsfuse) - **Azure 블롭**: 다음을 통해 장착됨[blobfuse2](https://github.com/Azure/azure-storage-fuse) E2B 샌드박스는 마운팅을 사용할 때 필요한 FUSE Tool을 자동으로 설치합니다. 최상의 성능을 위해서는 Tool이 설치된 사용자 정의 템플릿을 미리 구축하십시오. ## 맞춤 템플릿 기본적으로 템플릿을 지정하지 않으면 E2BSandbox는 S3 마운트 지원을 위해 `s3fs`가 설치된 템플릿을 자동으로 빌드합니다. 이 템플릿은 캐시되어 Sandbox 인스턴스 간에 재사용됩니다. GCS 마운트의 경우 `gcsfuse`가 아직 없으면 마운트할 때 자동으로 설치됩니다. Tool을 추가하거나 콜드 스타트를 단축하려면 사용자 지정 템플릿을 사용하세요. ### 기존 템플릿 사용 사전 구축된 템플릿이 있는 경우 해당 ID를 전달합니다. ```typescript const workspace = new Workspace({ sandbox: new E2BSandbox({ id: 'dev-sandbox', template: 'my-custom-template', }), }) ``` ### 기본 템플릿 사용자 정의 기본 마운트 지원 템플릿을 사용자 지정하는 함수를 전달합니다. 함수는 `TemplateBuilder`를 전달받아 수정된 템플릿을 반환해야 합니다: ```typescript const workspace = new Workspace({ sandbox: new E2BSandbox({ template: base => base .aptInstall(['ffmpeg', 'imagemagick', 'poppler-utils']) .pipInstall(['pandas', 'numpy']) .npmInstall(['sharp']), }), }) ``` 템플릿 빌더는 다음과 같은 작업을 통해 메소드 체이닝을 지원합니다. - `aptInstall(packages)`- 시스템 패키지 설치 - `pipInstall(packages)`- Python 패키지 설치 - `npmInstall(packages)`- Node.js 패키지 설치 - `runCmd(command)`- 쉘 명령 실행 - `setEnvs(vars)`- 환경변수 설정 - `copy(src, dest)`- 템플릿에 파일 복사 사용 가능한 메서드의 전체 목록은 [E2B 템플릿 문서](https://e2b.dev/docs/template/defining-template)를 참조하세요. ### 사전 구축 템플릿 기본 템플릿은 처음 사용할 때 작성되고 캐시됩니다. 더 빠른 콜드 스타트를 원하거나 GCS 지원을 포함하려면 템플릿을 사전 빌드할 수 있습니다. ```typescript import { createDefaultMountableTemplate } from '@mastra/e2b' import { Template } from 'e2b' // Get the default mountable template (includes s3fs) const { template, id } = createDefaultMountableTemplate() // Build and save to E2B const result = await Template.build(template, id) console.log('Template ID:', result.templateId) // Use this ID in your E2BSandbox config for instant startup const sandbox = new E2BSandbox({ template: result.templateId, }) ``` GCS 콜드 스타트를 단축하려면 사용자 지정 템플릿에 `gcsfuse`를 미리 설치합니다: ```typescript const workspace = new Workspace({ sandbox: new E2BSandbox({ id: 'dev-sandbox', template: base => base.aptInstall(['gcsfuse']), }), }) ``` 이는 선택 사항입니다. `gcsfuse`가 없으면 마운트할 때 자동으로 설치됩니다. ## 코드 모드와 함께 사용 [코드 모드](https://mastra.zisheng.pro/ko/docs/agents/code-mode)를 사용하면 Agent가 Tool을 조율하는 단일 TypeScript 프로그램을 작성할 수 있습니다. E2B는 원격 마이크로 VM에서 해당 프로그램을 실행하므로, 호스트가 아닌 Sandbox 파일 시스템에 프로그램을 쓰는 전송 계층이 필요합니다. `@mastra/e2b`는 이를 위한 `E2BCodeModeTransport`를 제공합니다. 이를 `createCodeMode`의 두 번째 인수로 전달합니다: ```typescript import { createCodeMode } from '@mastra/core/tools' import { E2BSandbox, E2BCodeModeTransport } from '@mastra/e2b' const { tool, instructions } = createCodeMode( { tools: { getWeather, getForecast }, sandbox: new E2BSandbox({ timeout: 60_000 }), }, new E2BCodeModeTransport(), ) ``` `E2BCodeModeTransport`는 Sandbox가 실행 중이 아니면 자동으로 시작하고, Sandbox의 Node 버전과 관계없이 작동하도록 esbuild를 사용해 호스트에서 TypeScript를 변환한 다음 VM 내부에서 `node`로 실행하며, 이후 프로그램 파일을 정리합니다. `@mastra/core`의 기본 `StdioCodeModeTransport`는 `LocalSandbox`처럼 호스트 파일 시스템을 공유하는 Sandbox에서만 작동합니다. ## 관련된 - [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) - [Azure Blob 파일 시스템 참조](https://mastra.zisheng.pro/ko/reference/workspace/azure-blob-filesystem) - [작업공간 개요](https://mastra.zisheng.pro/ko/docs/workspace/overview)