跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Modal

Executes commands in isolated Modal cloud sandboxes. Provides secure, ephemeral environments backed by Modal's infrastructure. For interface details, see WorkspaceSandbox interface.

Installation
Installation的直接链接

npm install @mastra/modal

Usage
Usage的直接链接

Add a ModalSandbox to a workspace and assign it to an agent:

import { Agent } from '@mastra/core/agent'
import { Workspace } from '@mastra/core/workspace'
import { ModalSandbox } from '@mastra/modal'

const workspace = new Workspace({
sandbox: new ModalSandbox({
id: 'dev-sandbox',
baseImage: 'ubuntu:22.04',
timeoutMs: 60_000,
}),
})

const agent = new Agent({
id: 'dev-agent',
model: 'anthropic/claude-opus-4-7',
workspace,
})

Authentication
Authentication的直接链接

Set Modal credentials via environment variables or constructor options:

MODAL_TOKEN_ID=ak-...
MODAL_TOKEN_SECRET=as-...

Or pass them directly:

const sandbox = new ModalSandbox({
tokenId: process.env.MODAL_TOKEN_ID,
tokenSecret: process.env.MODAL_TOKEN_SECRET,
})

Get your credentials from the Modal dashboard.

Constructor parameters
Constructor parameters的直接链接

id?:

string
= Auto-generated
Unique identifier / name for this sandbox. Used as the Modal sandbox name so the sandbox can be reconnected on subsequent start() calls.

appName?:

string
= 'mastra'
Modal App name to associate sandboxes with.

baseImage?:

string
= 'ubuntu:22.04'
Docker image to use for the sandbox.

timeoutMs?:

number
= 300000 (5 minutes)
Wall-clock max lifetime in milliseconds. The sandbox is terminated when this expires, regardless of activity. Modal's maximum is 24 hours (86_400_000).

env?:

Record<string, string>
Environment variables baked into the sandbox at create time.

workingDirectory?:

string
Default working directory inside the sandbox, used for command execution when no per-command cwd is given. A per-command cwd always wins.

workdir?:

string
Deprecated alias for workingDirectory. When both are set, workingDirectory wins.

tokenId?:

string
Modal token ID. Falls back to MODAL_TOKEN_ID environment variable.

tokenSecret?:

string
Modal token secret. Falls back to MODAL_TOKEN_SECRET environment variable.

instructions?:

string | function
Custom instructions returned by getInstructions(). Pass a string to fully replace the default, or a function to extend it.

onStart?:

function
Lifecycle hook called after the sandbox reaches running status.

volumes?:

Record<string, Volume>
Modal Volumes to mount into the sandbox, keyed by absolute mount path. The working directory must not be at or inside a mount path.

onStop?:

function
Lifecycle hook called before the sandbox stops.

onDestroy?:

function
Lifecycle hook called before the sandbox is destroyed.

Properties
Properties的直接链接

id:

string
Sandbox instance identifier.

name:

string
Provider name ('ModalSandbox')

provider:

string
Provider identifier ('modal')

status:

ProviderStatus
'pending' | 'starting' | 'running' | 'stopping' | 'stopped' | 'destroying' | 'destroyed' | 'error'

processes:

ModalProcessManager
Background process manager. See SandboxProcessManager reference.

Sandbox lifecycle
Sandbox lifecycle的直接链接

  • _start(): Attempts to reconnect to an existing running sandbox. If none is found, creates a sandbox from the latest snapshot (if available from a previous _stop()), or from the baseImage.
  • _stop(): Snapshots the filesystem, then terminates the sandbox. Snapshot is kept in memory on the same instance for future starts.
  • _destroy(): Terminates the sandbox and discards any snapshot.
const sandbox = new ModalSandbox({
id: 'dev-sandbox',
baseImage: 'ubuntu:22.04',
timeoutMs: 300_000,
})

await sandbox._start()
await sandbox.processes.spawn('npm install')
await sandbox._stop()
await sandbox._start()

Volumes and persistent files
Volumes and persistent files的直接链接

Mount Modal Volumes with the volumes option, then use ModalFilesystem to expose a mounted path to the agent's workspace file tools. Files written under the mount persist across sandbox restarts.

import { Workspace } from '@mastra/core/workspace'
import { ModalFilesystem, ModalSandbox } from '@mastra/modal'
import { ModalClient } from 'modal'

const modal = new ModalClient()
const privateVolume = await modal.volumes.fromName('agent-user-123', { createIfMissing: true })
const teamVolume = await modal.volumes.fromName('agent-team', { createIfMissing: true })

const sandbox = new ModalSandbox({
id: 'agent-sandbox',
workingDirectory: '/workspace',
volumes: {
'/mnt/agent': privateVolume,
'/mnt/team': teamVolume,
},
})

const workspace = new Workspace({
sandbox,
filesystem: new ModalFilesystem({ sandbox, basePath: '/mnt/agent' }),
})

ModalFilesystem runs file operations inside the sandbox and confines all paths to basePath. Set readOnly: true to reject writes.

Writes made by other sandboxes to the same Volume are only visible after a reload. Call reloadVolumes() on a long-lived sandbox to pick them up:

await sandbox.reloadVolumes()
备注

Keep the working directory outside every Volume mount (for example /workspace). Modal can't reload a Volume that is the current working directory, so ModalSandbox throws if workingDirectory is at or inside a mount path.

Background processes
Background processes的直接链接

ModalSandbox includes a built-in process manager for spawning and managing background processes. Each spawn() call creates a new ContainerProcess via the Modal SDK's Sandbox.exec() API.

const sandbox = new ModalSandbox({ id: 'dev-sandbox' })
await sandbox._start()

// Spawn a background process
const handle = await sandbox.processes.spawn('node script.js', {
env: { PORT: '3000' },
onStdout: data => console.log(data),
})

// Wait for the process to complete
const result = await handle.wait()
console.log(result.exitCode)

// Kill the process
await handle.kill()
备注

sendStdin() isn't supported. The Modal JS SDK doesn't expose stdin on Sandbox.exec().

See SandboxProcessManager reference for the full API.