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

IsolatedVmCodeModeTransport

The IsolatedVmCodeModeTransport class runs Code mode programs in an in-process V8 isolate, backed by isolated-vm. The isolate is the execution boundary, so no workspace sandbox is required: the program has no filesystem, network, process, or module access. Its only capabilities are the external_* functions, which call back into the real tools on the host.

Compared to the default StdioCodeModeTransport, this transport spawns no processes and writes no temp files, which makes it a good fit for serverless and multi-tenant hosts where OS-level sandboxing isn't available.

Installation
Installation的直接链接

npm install @mastra/isolated-vm

isolated-vm is a native addon. It provides prebuilt binaries for common platforms, so installation usually needs no extra setup. A C++ toolchain is only needed on platforms without a matching prebuild, where it falls back to compiling from source.

On Node.js 20 and later, creating an isolate crashes unless the host process starts with --no-node-snapshot. The constructor reports the missing flag as an error. Pass it when starting the server or through NODE_OPTIONS:

NODE_OPTIONS=--no-node-snapshot npm run dev

Usage
Usage的直接链接

Pass the transport as the second argument to createCodeMode(). No sandbox is needed:

import { createCodeMode } from '@mastra/core/tools'
import { IsolatedVmCodeModeTransport } from '@mastra/isolated-vm'

const { tool, instructions } = createCodeMode(
{ tools: { getTopProducts, getProductRatings } },
new IsolatedVmCodeModeTransport({ memoryLimitMb: 128 }),
)

Constructor parameters
Constructor parameters的直接链接

options?:

IsolatedVmCodeModeTransportOptions
Configuration for the isolate.
IsolatedVmCodeModeTransportOptions

memoryLimitMb?:

number
V8 isolate heap limit in MiB. A program that exceeds the limit is terminated and the tool returns an error result.

How it works
How it works的直接链接

Each run creates a fresh isolate with its own heap. TypeScript is stripped on the host with esbuild, then the program is evaluated inside the isolate. Every external_* call crosses the isolate boundary as JSON strings in both directions, so no host object references leak into model-authored code. The allow-list, tool validation, request context, and tracing all run on the host, the same as with other transports.

The timeout configured on createCodeMode() applies to both asynchronous hangs and synchronous infinite loops, and the isolate is disposed after every run.