@mastra/core
Version:
349 lines • 15.1 kB
TypeScript
/**
* Local Sandbox Provider
*
* A sandbox implementation that executes commands on the local machine.
* This is the default sandbox for development and local agents.
*
* Supports optional native OS sandboxing:
* - macOS: Uses seatbelt (sandbox-exec) for filesystem and network isolation
* - Linux: Uses bubblewrap (bwrap) for namespace isolation
*/
import type { RequestContext } from '../../request-context/index.js';
import type { WorkspaceFilesystem } from '../filesystem/filesystem.js';
import type { MountResult } from '../filesystem/mount.js';
import type { ProviderStatus } from '../lifecycle.js';
import type { InstructionsOption } from '../types.js';
import { LocalProcessManager } from './local-process-manager.js';
import { MastraSandbox } from './mastra-sandbox.js';
import type { MastraSandboxOptions } from './mastra-sandbox.js';
import type { MountManager } from './mount-manager.js';
import type { IsolationBackend, NativeSandboxConfig } from './native-sandbox/index.js';
import type { SandboxCloneOptions } from './sandbox.js';
import type { SandboxInfo } from './types.js';
/**
* Directory for mount marker files used to detect config changes across restarts.
*
* Resolved lazily so `os.tmpdir()` is never invoked at module-load time. The
* Agent/evals runtime (which transitively imports this module) is bundled into
* the Studio client, where `node:os` is shimmed to an empty object and
* `os.tmpdir` is `undefined`. Evaluating it at import time crashes Studio boot.
* See https://github.com/mastra-ai/mastra/issues/18519.
*/
export declare function getMarkerDir(): string;
/**
* Local sandbox provider configuration.
*/
export interface LocalSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {
/** Unique identifier for this sandbox instance */
id?: string;
/** Working directory for command execution */
workingDirectory?: string;
/**
* Environment variables to set for command execution.
* PATH is included by default unless overridden (needed for finding executables).
* Other host environment variables are not inherited unless explicitly passed.
*
* @example
* ```typescript
* // Default - only PATH is available
* env: undefined
*
* // Add specific variables
* env: { NODE_ENV: 'production', HOME: process.env.HOME }
*
* // Full host environment (less secure)
* env: process.env
* ```
*/
env?: NodeJS.ProcessEnv;
/**
* Encoding used to decode command stdout/stderr (any WHATWG encoding label, e.g. 'gbk').
* Useful on Windows systems whose native commands emit a legacy code page. Default: 'utf-8'.
*/
outputEncoding?: string;
/**
* Default timeout for executeCommand in ms (default: 30000).
* Use 0 to disable. Does not apply to processes.spawn.
*/
timeout?: number;
/**
* Isolation backend for sandboxed execution.
* - 'none': No sandboxing (direct execution on host) - default
* - 'seatbelt': macOS sandbox-exec (built-in on macOS)
* - 'bwrap': Linux bubblewrap (requires installation)
*
* Use `LocalSandbox.detectIsolation()` to get the recommended backend.
* @default 'none'
*/
isolation?: IsolationBackend;
/**
* Configuration for native sandboxing.
* Only used when isolation is 'seatbelt' or 'bwrap'.
*/
nativeSandbox?: NativeSandboxConfig;
/**
* Custom instructions that override the default instructions
* returned by `getInstructions()`.
*
* - `string` — Fully replaces the default instructions.
* Pass an empty string to suppress instructions entirely.
* - `(opts) => string` — Receives the default instructions and
* optional request context so you can extend or customise per-request.
*/
instructions?: InstructionsOption;
/**
* Named checkpoint to seed the working directory from on `start()` and to
* persist to on `snapshot()`. When set and a matching checkpoint exists
* under `checkpointsDirectory`, an empty/missing working directory is seeded
* from it before start. A missing checkpoint falls back to a normal empty
* working directory.
*/
checkpointName?: string;
/**
* Fallback checkpoint used to seed the working directory when
* `checkpointName` has no stored checkpoint yet (e.g. a repo-level warm base
* image for a brand-new session). Boot-only: `snapshot()` keeps writing to
* `checkpointName`.
*/
seedCheckpointName?: string;
/**
* Directory where named checkpoints are stored.
* Defaults to `<parent of workingDirectory>/.checkpoints`.
*/
checkpointsDirectory?: string;
}
/**
* Executes workspace commands on the host machine for development and trusted
* local execution. Isolation requires explicit configuration.
*
* @example
* ```typescript
* import { Workspace, LocalSandbox } from '@mastra/core/workspace';
*
* const workspace = new Workspace({
* sandbox: new LocalSandbox({ workingDirectory: './my-workspace' }),
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Local sandbox documentation](https://mastra.ai/reference/workspace/local-sandbox)
* if packaged docs are unavailable.
*/
export declare class LocalSandbox extends MastraSandbox<string> {
readonly id: string;
readonly name = "LocalSandbox";
readonly provider = "local";
status: ProviderStatus;
readonly isolation: IsolationBackend;
readonly processes: LocalProcessManager;
readonly mounts: MountManager;
private readonly env;
private readonly _outputEncoding?;
private readonly timeout;
private _nativeSandboxConfig;
/**
* SBPL the user wrote, read from `seatbeltProfilePath` at start. Set only when that file
* already existed and does not carry our generated-profile marker. While it is undefined,
* `wrapCommand()` generates the profile from the live `_nativeSandboxConfig` on every call,
* so the profile always tracks the allowlist.
*/
private _customSeatbeltProfile?;
/** Where the profile file lives on disk: the configured path, or one we generated. */
private _seatbeltProfilePath?;
private _sandboxFolderPath?;
private readonly _createdAt;
private readonly _instructionsOverride?;
private _activeMountPaths;
/** Snapshot of `readWritePaths` from ctor; entries here are never removed on unmount. */
private readonly _initialReadWritePaths;
/** Refcount for isolation paths added by mounts (not present in `_initialReadWritePaths`). */
private _mountIsolationRefCount;
/** Normalized mount path → canonical isolation path recorded for that mount. */
private _mountPathToIsolationPath;
/** Named checkpoint to seed from on start and persist to on snapshot. */
private readonly _checkpointName?;
/** Boot-only fallback checkpoint used when `_checkpointName` has no state. */
private readonly _seedCheckpointName?;
/** Directory where named checkpoints live. */
private readonly _checkpointsDirectory;
/** Chains snapshot() calls so concurrent captures never interleave. */
private _snapshotChain;
/**
* The effective working directory. Narrowed to `string`: the constructor
* always computes a value (the option, expanded, or `<cwd>/.sandbox`), so
* unlike the base getter this never returns `undefined`.
*/
get workingDirectory(): string;
constructor(options?: LocalSandboxOptions);
/**
* Construct a sibling `LocalSandbox` that inherits this sandbox's
* configuration (isolation, native sandbox config, instructions) with
* per-instance overrides.
*
* Performs no I/O — the sandbox clone creates its working directory on its
* own `start()`. `sandboxId` and `idleTimeoutMinutes` have no local
* equivalent and are ignored: local sandboxes reattach by logical `id` and
* have no provider-managed idle teardown.
*/
clone(options?: SandboxCloneOptions): LocalSandbox;
/**
* Acquisition primitives (base-orchestrated start): an existing working
* directory is the "found sandbox" — reattaching reports `outcome: 'connected'`,
* a missing directory means a fresh sandbox (`outcome: 'created'`).
*
* This stat and the `mkdir` in `create()` are not atomic, so `'created'` is
* best-effort: two processes starting on the same working directory can both
* report it. Keep onStart setup idempotent.
*/
protected find(): Promise<string | undefined>;
protected connect(_handle: string): Promise<void>;
protected create(): Promise<void>;
/**
* Shared start body for both branches: ensure the working directory
* exists, seed it from a checkpoint when empty, and set up the seatbelt
* profile on macOS. Everything here is idempotent.
*/
private _prepareWorkspace;
/** LocalSandbox persists real filesystem-backed checkpoints. */
readonly supportsCheckpoints = true;
/** Resolve the on-disk directory for a named checkpoint, rejecting unsafe names. */
private _checkpointPath;
/**
* Seed an empty/missing working directory from the configured checkpoint.
* Missing checkpoint or already-populated workdir → no-op (normal start).
*/
private _seedFromCheckpoint;
/**
* Identity of the directory currently at `checkpointDir`, or undefined if no
* directory is there. Retries briefly to cover the instant in
* `_captureCheckpoint` where the old checkpoint has been renamed away but the
* replacement has not yet been renamed into place. The window is two atomic
* renames, so a couple of short retries close it.
*/
private _checkpointIdentity;
/**
* Persist the working directory as the configured named checkpoint.
* Copies to a temp sibling, then swaps it into place with rename so a
* concurrent boot always observes a complete checkpoint. No-op when no
* checkpoint name is set.
*/
snapshot(): Promise<void>;
private _captureCheckpoint;
/**
* Stop the local sandbox.
* Kills background processes and unmounts all active mounts. Unlike remote
* providers, a local sandbox has no suspend/resume — its background
* processes ARE the runtime state, so a stopped sandbox must not leave them
* running. Files in the working directory are untouched and `start()` works
* again afterwards.
* Status management is handled by the base class.
*/
stop(): Promise<void>;
/**
* Destroy the local sandbox and clean up resources.
* Unmounts all filesystems, clears mount state, and cleans up seatbelt profile.
* Status management is handled by the base class.
*/
destroy(): Promise<void>;
/** @deprecated Use `status === 'running'` instead. */
isReady(): Promise<boolean>;
getInfo(): Promise<SandboxInfo>;
getInstructions(opts?: {
requestContext?: RequestContext;
}): string;
private _getDefaultInstructions;
private generateId;
/**
* Build the environment object for execution.
* Always includes PATH by default (needed for finding executables).
* Merges the sandbox's configured env with any additional env from the command.
* @internal Used by LocalProcessManager.
*/
buildEnv(additionalEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
/**
* Mount a filesystem at a path on the local host.
*
* - **local** — Creates a symlink from `<workingDir>/<mount>` to the basePath.
*
* Virtual mount paths (e.g. `/s3`) are resolved under the sandbox's workingDirectory.
* Other mount types can be handled via the `onMount` hook.
*/
mount(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult>;
/**
* Unmount a filesystem from a path.
*/
unmount(mountPath: string): Promise<void>;
/**
* Write a marker file for detecting config changes.
* Uses hostPath (resolved OS path) for the marker filename and content,
* and mountPath (virtual path) for looking up the entry.
*/
private writeMarkerFile;
/**
* Check if a path is already mounted and if the config matches.
* Uses hostPath (resolved OS path) for checking the actual mount point.
*/
private checkExistingMount;
/**
* Check if a marker file exists for a given host path (regardless of content).
* Returns true if we previously created a mount here.
*/
private hasMarkerFile;
/**
* Check if a marker file matches the given config.
* Returns 'matching' if hash matches, 'mismatched' if hash differs,
* or 'foreign' if no marker exists (we didn't create this mount).
*/
private checkMarkerFile;
/**
* Dynamically add a mount path to the sandbox isolation allowlist.
*
* - Seatbelt: pushes to readWritePaths (wrapCommand reads config each call)
* - Bwrap: pushes to readWritePaths (buildBwrapCommand reads config each call)
*
* Local mounts are symlinks under `workingDirectory`. Bubblewrap cannot
* `--bind` a symlink (it fails with "Unable to mount source on destination"),
* so we store the canonical path (`realpath`) of the mount point — the same
* directory the symlink refers to.
*/
private addMountPathToIsolation;
/**
* Reverse {@link addMountPathToIsolation}: drop refcounted paths from the allowlist on unmount
* while preserving user-provided `readWritePaths` from construction.
*/
private removeMountIsolationForPath;
/**
* Resolve a virtual mount path to a host filesystem path.
*
* Virtual paths like "/s3" become `<workingDir>/s3`. This differs from E2B
* where root-level paths like `/s3` are used directly (E2B runs in a VM with sudo).
* LocalSandbox runs on the host, so mounts are scoped under workingDirectory.
*/
private resolveHostPath;
/**
* Wrap a command with the configured isolation backend.
* @internal Used by LocalProcessManager for background process isolation.
*/
wrapCommandForIsolation(command: string): {
command: string;
args: string[];
};
/**
* Detect the best available isolation backend for this platform.
* Returns detection result with backend recommendation and availability.
*
* @example
* ```typescript
* const result = LocalSandbox.detectIsolation();
* const sandbox = new LocalSandbox({
* isolation: result.available ? result.backend : 'none',
* });
* ```
*/
static detectIsolation(): import("./native-sandbox").SandboxDetectionResult;
}
//# sourceMappingURL=local-sandbox.d.ts.map