# DaytonaSandbox Executes commands in isolated [Daytona](https://www.daytona.io) cloud sandboxes. Supports multiple runtimes, resource configuration, volumes, snapshots, network isolation, and mounting cloud storage (S3, GCS) via FUSE. > **Info:** For interface details, see [WorkspaceSandbox interface](https://mastra.ai/reference/workspace/sandbox). ## Installation ```bash npm install @mastra/daytona ``` Set your Daytona API key in one of three ways: ```bash # Shell export export DAYTONA_API_KEY=your-api-key ``` ```bash # .env file DAYTONA_API_KEY=your-api-key ``` ```typescript // Passed directly as constructor argument new DaytonaSandbox({ apiKey: 'your-api-key' }) ``` ## Usage Add a `DaytonaSandbox` to a workspace and assign it to an agent: ```typescript import { Agent } from '@mastra/core/agent' import { Workspace } from '@mastra/core/workspace' import { DaytonaSandbox } from '@mastra/daytona' const sandbox = new DaytonaSandbox({ language: 'typescript', timeout: 120_000, }) const workspace = new Workspace({ sandbox }) 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! ``` ### With a snapshot Use a pre-built snapshot to skip environment setup time: ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ snapshot: 'my-snapshot-id', timeout: 60_000, }), }) ``` ### Custom image with resources Use a custom Docker image with specific resource allocation: ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ image: 'node:20-slim', resources: { cpu: 2, memory: 4, disk: 6 }, language: 'typescript', }), }) ``` ### Ephemeral sandbox For one-shot tasks — sandbox is deleted immediately on stop: ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ ephemeral: true, language: 'python', }), }) ``` ### Streaming output Stream command output in real time via `onStdout` and `onStderr` callbacks: ```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), }) ``` Both callbacks are optional and can be used independently. ### Network isolation Restrict outbound network access: ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ networkBlockAll: true, networkAllowList: '10.0.0.0/8,192.168.0.0/16', }), }) ``` ## Constructor parameters **id?:** (`string`): Unique identifier for this sandbox instance. (Default: `Auto-generated`) **apiKey?:** (`string`): Daytona API key for authentication. Falls back to DAYTONA\_API\_KEY environment variable. **apiUrl?:** (`string`): Daytona API endpoint. Falls back to DAYTONA\_API\_URL environment variable. **target?:** (`string`): Runner region. Falls back to DAYTONA\_TARGET environment variable. **timeout?:** (`number`): Default execution timeout in milliseconds. (Default: `300000 (5 minutes)`) **language?:** (`'typescript' | 'javascript' | 'python'`): Runtime language for the sandbox. (Default: `'typescript'`) **snapshot?:** (`string`): Pre-built snapshot ID to create the sandbox from. Takes precedence over image. **image?:** (`string`): Docker image for sandbox creation. Triggers image-based creation when set. Can be combined with resources. Ignored when snapshot is set. **resources?:** (`{ cpu?: number; memory?: number; disk?: number }`): Resource allocation for the sandbox (CPU cores, memory in GiB, disk in GiB). Only used when image is set. **env?:** (`Record`): Environment variables to set in the sandbox. (Default: `{}`) **labels?:** (`Record`): Custom metadata labels. (Default: `{}`) **name?:** (`string`): Sandbox display name. (Default: `Sandbox id`) **user?:** (`string`): OS user to run commands as. (Default: `'daytona'`) **public?:** (`boolean`): Make port previews public. (Default: `false`) **ephemeral?:** (`boolean`): Delete sandbox immediately on stop. (Default: `false`) **autoStopInterval?:** (`number`): Auto-stop interval in minutes. Set to 0 to disable. (Default: `15`) **autoArchiveInterval?:** (`number`): Auto-archive interval in minutes. Set to 0 for the maximum interval (7 days). (Default: `7 days`) **autoDeleteInterval?:** (`number`): Auto-delete interval in minutes. Negative values disable auto-delete. Set to 0 to delete on stop. (Default: `disabled`) **volumes?:** (`Array<{ volumeId: string; mountPath: string }>`): Daytona volumes to attach at sandbox creation time. **networkBlockAll?:** (`boolean`): Block all outbound network access from the sandbox. (Default: `false`) **networkAllowList?:** (`string`): Comma-separated list of allowed CIDR addresses when network access is restricted. ## Properties **id:** (`string`): Sandbox instance identifier. **name:** (`string`): Provider name ('DaytonaSandbox'). **provider:** (`string`): Provider identifier ('daytona'). **status:** (`ProviderStatus`): 'pending' | 'initializing' | 'ready' | 'stopped' | 'destroyed' | 'error' **mounts:** (`MountManager`): Mount manager for tracking FUSE-mounted cloud filesystems (S3, GCS). **instance:** (`Sandbox`): The underlying Daytona Sandbox instance. Throws SandboxNotReadyError if the sandbox has not been started. ## Methods ### `start()` Create and start the Daytona sandbox. ```typescript await sandbox.start() ``` Called automatically on first command execution or by `workspace.init()`. ### `stop()` Stop the sandbox. The sandbox can be restarted later — files and state persist. ```typescript await sandbox.stop() ``` ### `destroy()` Delete the sandbox and clean up all resources. ```typescript await sandbox.destroy() ``` ### `executeCommand(command, args?, options?)` Execute a shell command in the sandbox. Automatically starts the sandbox if not already running, and retries once if the sandbox has timed out. ```typescript const result = await sandbox.executeCommand('node', ['-e', 'console.log("Hello!")']) const output = await sandbox.executeCommand('pip', ['install', 'requests'], { timeout: 60_000, cwd: '/workspace', }) // Stream output in real time 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), }) ``` **Parameters:** **command:** (`string`): Command to execute. **args?:** (`string[]`): Command arguments. **options.timeout?:** (`number`): Execution timeout in milliseconds. Overrides the instance default. **options.cwd?:** (`string`): Working directory for the command. **options.env?:** (`Record`): Additional environment variables for this command. Merged with instance-level env. **options.onStdout?:** (`(data: string) => void`): Callback for stdout streaming. **options.onStderr?:** (`(data: string) => void`): Callback for stderr streaming. ### `mount(filesystem, mountPath)` Mount a filesystem into the sandbox at the specified path. ```typescript await sandbox.mount(s3Filesystem, '/mnt/data') ``` ### `unmount(mountPath)` Unmount a previously mounted filesystem. ```typescript await sandbox.unmount('/mnt/data') ``` ### `getInfo()` Get sandbox status and resource information. ```typescript const info = await sandbox.getInfo() // { // id: 'daytona-sandbox-abc123', // name: 'DaytonaSandbox', // provider: 'daytona', // status: 'running', // createdAt: Date, // mounts: [], // resources: { // cpuCores: 2, // vCPU count from the running sandbox // memoryMB: 4096, // converted from GB (×1024) // diskMB: 20480, // converted from GiB (×1024) // }, // metadata: { // language: 'typescript', // ephemeral: false, // snapshot: 'my-snapshot-id', // only when snapshot is set // image: 'node:20-slim', // only when image is set // target: 'us', // only when sandbox is running // }, // } ``` ### `getInstructions()` Get a description of the sandbox environment. Used in tool descriptions so agents understand the execution context. ```typescript // Default (no options) new DaytonaSandbox().getInstructions() // 'Cloud sandbox with isolated execution (typescript runtime). Default working directory: /home/daytona. Command timeout: 300s. Running as user: daytona.' // All options set new DaytonaSandbox({ language: 'python', timeout: 60_000, user: 'app', volumes: [{ volumeId: 'vol-123', mountPath: '/data' }], networkBlockAll: true, }).getInstructions() // 'Cloud sandbox with isolated execution (python runtime). Default working directory: /home/daytona. Command timeout: 60s. Running as user: app. 1 volume(s) attached. Network access is blocked.' ``` ## Direct SDK access Access the underlying Daytona `Sandbox` instance for filesystem, git, and other operations not exposed through the `WorkspaceSandbox` interface: ```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') ``` The `instance` getter throws `SandboxNotReadyError` if the sandbox has not been started yet. ## Sandbox creation modes `DaytonaSandbox` selects a creation mode based on the options provided: | Options | Creation mode | | ------------------------- | ----------------------------------------------------- | | `snapshot` set | Snapshot-based (snapshot takes precedence over image) | | `image` set (no snapshot) | Image-based (optionally with `resources`) | | Neither set | Default snapshot-based | Resources are only applied when `image` is set. Passing `resources` without `image` has no effect. ## Mounting Cloud Storage Daytona sandboxes can mount S3 or GCS filesystems, making cloud storage accessible as local directories inside the sandbox. This is useful for: - Processing large datasets stored in cloud buckets - Writing output files directly to cloud storage - Sharing data between sandbox sessions ### Using the mounts config The simplest way to mount filesystems is through the workspace `mounts` config: ```typescript import { Workspace } from '@mastra/core/workspace' import { S3Filesystem } from '@mastra/s3' import { GCSFilesystem } from '@mastra/gcs' import { DaytonaSandbox } from '@mastra/daytona' 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 DaytonaSandbox({ id: 'dev-sandbox' }), }) ``` When the sandbox starts, the filesystems are automatically mounted at the specified paths. Code running in the sandbox can then access files at `/s3-data` and `/gcs-data` as if they were local directories. ### How mounting works Daytona sandboxes use FUSE (Filesystem in Userspace) to mount cloud storage: - **S3/R2**: Mounted via [s3fs-fuse](https://github.com/s3fs-fuse/s3fs-fuse) - **GCS**: Mounted via [gcsfuse](https://github.com/GoogleCloudPlatform/gcsfuse) The required FUSE tools are installed automatically at mount time if not already present in the sandbox image. For faster startup, pre-install them in a custom image: ```dockerfile FROM ubuntu:22.04 RUN apt-get update && apt-get install -y s3fs fuse gcsfuse ``` ```typescript const workspace = new Workspace({ sandbox: new DaytonaSandbox({ image: 'my-registry/my-image:latest', }), mounts: { '/data': new S3Filesystem({ /* ... */ }), }, }) ``` ## Related - [WorkspaceSandbox interface](https://mastra.ai/reference/workspace/sandbox) - [LocalSandbox reference](https://mastra.ai/reference/workspace/local-sandbox) - [S3Filesystem reference](https://mastra.ai/reference/workspace/s3-filesystem) - [GCSFilesystem reference](https://mastra.ai/reference/workspace/gcs-filesystem) - [Workspace overview](https://mastra.ai/docs/workspace/overview)