@mastra/core
Version:
410 lines • 18.1 kB
TypeScript
/**
* MastraSandbox Base Class
*
* Abstract base class for sandbox providers that want automatic logger integration.
* Extends MastraBase to receive the Mastra logger when registered with a Mastra instance.
*
* MountManager is automatically created if the subclass implements `mount()`.
* Use `declare readonly mounts: MountManager` to get non-optional typing.
*
* ## Lifecycle Management
*
* The base class provides race-condition-safe lifecycle wrappers:
* - `_start()` - Handles concurrent calls, status management, and mount processing
* - `_stop()` - Handles concurrent calls and status management
* - `_destroy()` - Handles concurrent calls and status management
*
* Subclasses override the plain `start()`, `stop()`, and `destroy()` methods
* to provide their implementation. Callers use the `_`-prefixed wrappers
* (or `callLifecycle()`) which add status tracking and race-condition safety.
*
* External providers can extend this class to get logger support, or implement
* the WorkspaceSandbox interface directly if they don't need logging.
*/
import { MastraBase } from '../../base.js';
import type { IMastraLogger } from '../../logger/index.js';
import type { WorkspaceFilesystem } from '../filesystem/filesystem.js';
import type { MountResult } from '../filesystem/mount.js';
import type { ProviderStatus, SandboxStartOutcome, SandboxStartResult } from '../lifecycle.js';
import { MountManager } from './mount-manager.js';
import type { SandboxProcessManager } from './process-manager/index.js';
import type { SandboxComputer, SandboxFileInput, SandboxNetworking, WorkspaceSandbox, WriteFilesOptions } from './sandbox.js';
import type { CommandResult, ExecuteCommandOptions, SandboxInfo } from './types.js';
/**
* Lifecycle hook that fires during sandbox state transitions.
* Receives the sandbox instance so users can call `executeCommand`, read files, etc.
*/
export type SandboxLifecycleHook = (args: {
sandbox: WorkspaceSandbox;
}) => void | Promise<void>;
/**
* Start hook: a {@link SandboxLifecycleHook} that additionally receives the
* provider's {@link SandboxStartResult} `outcome`: `'created'` = this start
* provisioned a fresh VM, `'connected'` = reconnected/resumed an existing
* one, `undefined` = the provider doesn't report (not yet migrated).
*/
export type SandboxStartHook = (args: {
sandbox: WorkspaceSandbox;
outcome?: SandboxStartOutcome;
}) => void | Promise<void>;
/** Options forwarded to a provider's sandbox start implementation. */
export interface SandboxStartOptions {
abortSignal?: AbortSignal;
}
/**
* Options for the MastraSandbox base class constructor.
* Providers extend this to add their own options while inheriting lifecycle hooks.
*/
export interface MastraSandboxOptions {
/**
* Called after the sandbox reaches 'running' status, before pending mounts
* are processed. Fires on EVERY start regardless of trigger (explicit,
* `ensureRunning()` from a lazy command, a revival after the VM was
* replaced), which makes it the seam for once-per-VM setup: branch on
* `outcome` and probe/run whatever the environment needs.
*
* A thrown error is FATAL: `start()` rejects and the sandbox is marked
* `error`, and the next start retries the hook. (`onStop`/`onDestroy` stay
* non-fatal, since teardown proceeds best-effort.)
*/
onStart?: SandboxStartHook;
/** Called before the sandbox stops */
onStop?: SandboxLifecycleHook;
/** Called before the sandbox is destroyed */
onDestroy?: SandboxLifecycleHook;
/**
* Initial values for the sandbox's runtime environment overlay.
*
* These values are made visible to every command and spawned process
* routed through the sandbox's process manager (which also backs the
* built-in `executeCommand`), merged per spawn. This is an overlay, not
* VM-level environment — providers may additionally consume their own
* env options for creation-time semantics, and providers with custom
* execution transports that bypass the process manager must consume the
* overlay themselves. Update at runtime with `setEnv`.
*/
env?: Record<string, string | undefined>;
/**
* Default directory for command execution and process spawns when a
* per-command `cwd` is not provided. A per-command `cwd` always wins.
*
* The value is passed to the provider as-is — absolute paths are
* recommended; `~`-prefixed paths work only where the provider documents
* expansion. The sandbox does not create the directory. Providers without
* the concept in their runtime fall back to their prior default.
*/
workingDirectory?: string;
/**
* Process manager for this sandbox.
*
* When provided, the base class automatically:
* 1. Sets the sandbox back-reference on the process manager
* 2. Exposes it via `this.processes`
* 3. Creates a default `executeCommand` implementation (spawn + wait)
*
* @example
* ```typescript
* class MySandbox extends MastraSandbox {
* constructor() {
* super({
* name: 'MySandbox',
* processes: new MyProcessManager({ env: myEnv }),
* });
* }
* }
* ```
*/
processes?: SandboxProcessManager;
}
/**
* Abstract base class for sandbox providers with logger support.
*
* Providers that extend this class automatically receive the Mastra logger
* when the sandbox is used with a Mastra instance. MountManager is also
* automatically created if the subclass implements `mount()`.
*
* @example
* ```typescript
* class MyCustomSandbox extends MastraSandbox {
* declare readonly mounts: MountManager; // Non-optional type
* readonly id = 'my-sandbox';
* readonly name = 'MyCustomSandbox';
* readonly provider = 'custom';
* status: ProviderStatus = 'pending';
*
* constructor() {
* super({
* name: 'MyCustomSandbox',
* processes: new MyProcessManager({ env: myEnv }),
* });
* }
*
* async start(): Promise<void> { /* startup logic *\/ }
* async mount(filesystem, mountPath) { ... }
* async unmount(mountPath) { ... }
* }
* ```
*/
export declare abstract class MastraSandbox<THandle = unknown> extends MastraBase implements WorkspaceSandbox {
#private;
/** Unique identifier for this sandbox instance */
abstract readonly id: string;
/** Human-readable name (e.g., 'E2B Sandbox', 'Docker') */
abstract readonly name: string;
/** Provider type identifier */
abstract readonly provider: string;
/** Current status of the sandbox */
abstract status: ProviderStatus;
/**
* Execute a shell command and wait for completion.
*
* Method syntax (not property syntax) is intentional — it prevents
* `useDefineForClassFields` from emitting `this.executeCommand = undefined`
* which would shadow prototype methods defined by subclasses.
*/
executeCommand?(command: string, args?: string[], options?: ExecuteCommandOptions): Promise<CommandResult>;
/** Default timeout for foreground commands; background spawns are unaffected. */
protected defaultCommandTimeout?: number;
/** Optional networking capability - implement to expose public port URLs */
readonly networking?: SandboxNetworking;
/** Optional computer-use (desktop) capability - implement to enable workspace computer tools */
readonly computer?: SandboxComputer;
/**
* Optional bulk file upload into the sandbox's own filesystem.
*
* Method syntax (not property syntax) is intentional — it prevents
* `useDefineForClassFields` from emitting `this.writeFiles = undefined`
* which would shadow prototype methods defined by subclasses.
*/
writeFiles?(files: SandboxFileInput[], options?: WriteFilesOptions): Promise<void>;
/** Process manager */
readonly processes?: SandboxProcessManager;
/** Mount manager - automatically created if subclass implements mount() */
readonly mounts?: MountManager;
/** Optional mount method - implement to enable mounting support */
mount?(filesystem: WorkspaceFilesystem, mountPath: string): Promise<MountResult>;
/** Optional unmount method */
unmount?(mountPath: string): Promise<void>;
/** Get instructions describing how this sandbox works */
getInstructions?(): string;
/** Get sandbox status and metadata */
getInfo?(): SandboxInfo | Promise<SandboxInfo>;
/**
* Persist the sandbox's current state when supported.
*
* The default implementation is a no-op for providers without snapshot support.
*/
snapshot(): Promise<void>;
/**
* Whether `snapshot()` persists real checkpoints. Providers overriding
* `snapshot()` with a real implementation should also override this to true.
*/
readonly supportsCheckpoints: boolean;
/** Promise for _start() to prevent race conditions from concurrent calls */
protected _startPromise?: Promise<SandboxStartResult | void>;
/** The subclass's `start()`, captured before the constructor shadows it. */
private readonly _implStart;
/** Whether acquisition runs through {@link find}/{@link connect}/{@link create}. */
private readonly _useAcquisitionPrimitives;
/** Promise for _stop() to prevent race conditions from concurrent calls */
protected _stopPromise?: Promise<void>;
/** Promise for _destroy() to prevent race conditions from concurrent calls */
protected _destroyPromise?: Promise<void>;
/** Lifecycle callbacks */
private _onStart?;
private readonly _onStop?;
private readonly _onDestroy?;
/**
* Effective default working directory, exposed via the
* {@link workingDirectory} getter. Protected so providers that compute or
* probe their effective value (e.g. a default like `/workspace`, or a
* runtime probe) can write it back with {@link setWorkingDirectory} and
* keep the getter truthful.
*/
protected _workingDirectory?: string;
constructor(options: {
name: string;
} & MastraSandboxOptions);
/**
* Update the sandbox's runtime environment overlay.
*
* The updater receives a copy of the current overlay and returns the new
* one, so a single call can set, unset, or batch-update variables:
*
* ```typescript
* sandbox.setEnv(env => ({ ...env, GH_TOKEN: token }));
* ```
*
* Changes apply immediately to subsequent commands and processes routed
* through the sandbox's process manager (including the built-in
* `executeCommand`), survive provider pause/resume and VM replacement,
* and are never written into the VM — the overlay is merged per spawn,
* not persisted. Removing a key removes it from the overlay only;
* env values a provider supplies on its own still apply.
*/
setEnv(update: (env: Record<string, string | undefined>) => Record<string, string | undefined>): void;
/**
* Snapshot of the current runtime environment overlay.
*
* Returns a fresh copy — mutating it never affects the stored overlay; use
* {@link setEnv} to change it. The process manager reads this per spawn to
* merge the overlay into command environments.
*/
getEnv(): Record<string, string | undefined>;
/**
* The sandbox's default working directory, when one is configured.
*
* Commands and process spawns without a per-command `cwd` run here;
* per-command `cwd` always wins. `undefined` means the provider's own
* default applies (typically the home directory).
*/
get workingDirectory(): string | undefined;
/**
* Set the effective working directory after construction. For providers
* that resolve the value themselves — a computed default, or a runtime
* probe that needs a running VM — so the {@link workingDirectory} getter
* stays truthful.
*/
protected setWorkingDirectory(dir: string): void;
/**
* Attach or replace the start hook after construction. The updater receives
* the installed hook and returns its replacement, so callers compose instead
* of clobbering a hook they didn't know about; ignoring `prev` replaces it.
*
* ```typescript
* sandbox.setOnStart(prev => async args => {
* await prev?.(args); // whatever prepared the sandbox runs first
* await mySetup(args);
* });
* ```
*
* Errors stay FATAL, so a throw stops the hooks after it. Each call wraps
* the current hook, so attach once per sandbox or the work stacks.
*/
setOnStart(update: (previous: SandboxStartHook | undefined) => SandboxStartHook): void;
/**
* Start the sandbox (wrapper with status management and race-condition safety).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management and automatically processes pending mounts after startup.
*
* Subclasses override `start()` to provide their startup logic.
*/
_start(options?: SandboxStartOptions): Promise<SandboxStartResult | void>;
/**
* Internal start execution - handles status, the onStart hook, and mount
* processing.
*/
private _executeStart;
/**
* Locate an existing VM/environment for this sandbox's logical id. Returns
* a provider-native handle for {@link connect} to adopt, or `undefined` when
* nothing usable exists. Avoid side effects where the provider's API allows.
*/
protected find?(options?: SandboxStartOptions): Promise<THandle | undefined>;
/**
* Adopt/wake/resume the handle {@link find} returned. Throwing fails
* `start()`: a provider that should fall back to creating fresh puts that
* policy in `find` (return `undefined` for an unusable handle) instead.
*/
protected connect?(handle: THandle, options?: SandboxStartOptions): Promise<void> | void;
/**
* Provision a fresh VM/environment for this sandbox's logical id.
* Implementing this without overriding `start()` opts into base-orchestrated
* acquisition, which derives the outcome from the branch that ran: find then
* connect reports 'connected', create reports 'created'.
*/
protected create?(options?: SandboxStartOptions): Promise<void> | void;
/** Base-orchestrated acquisition (rung 1 — see {@link start}). */
private _acquire;
/**
* Sandbox startup. Providers plug in at one of three rungs (best available
* wins); either way the base owns coalescing, status management, the
* onStart setup hook, and mount processing:
*
* 1. Implement the {@link find}/{@link connect}/{@link create} primitives
* (and do NOT override `start()`) — the base orchestrates acquisition
* and derives the outcome structurally. For providers whose API
* decomposes into lookup/wake/provision.
* 2. Override `start()` returning {@link SandboxStartResult} — for
* providers with a fused getOrCreate-style API where decomposition
* would add round-trips.
* 3. Override `start()` returning void — the outcome is unknown.
*
* The base constructor wraps `start()` so direct calls are routed through
* `_start()`. Use METHOD syntax when overriding — a class-field `start`
* initializer would overwrite the wrapper. Implementing neither rung throws:
* a sandbox with nothing to start says so with an empty `async start() {}`.
*
* Id-keyed getOrCreate contract: a sandbox constructed with a known `id`
* resolves that id on start — reconnect/resume when the provider finds an
* existing VM for it, create otherwise.
*/
start(_options?: SandboxStartOptions): Promise<SandboxStartResult | void>;
/**
* Ensure the sandbox is running.
*
* Calls `_start()` if status is not 'running'. Useful for lazy initialization
* where operations should automatically start the sandbox if needed.
*
* This is the lazy entry point into the id-keyed getOrCreate contract
* described on {@link start}.
*
* @throws {SandboxNotReadyError} if the sandbox fails to reach 'running' status
*
* @example
* ```typescript
* async executeCommand(command: string): Promise<CommandResult> {
* await this.ensureRunning();
* // Now safe to use the sandbox
* }
* ```
*/
ensureRunning(): Promise<void>;
/**
* Stop the sandbox (wrapper with status management and race-condition safety).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management.
*
* Subclasses override `stop()` to provide their stop logic.
*/
_stop(): Promise<void>;
/**
* Internal stop execution - handles status.
*/
private _executeStop;
/**
* Override this method to implement sandbox stop logic.
*
* Called by `_stop()` after status is set to 'stopping'.
* Status will be set to 'stopped' on success, 'error' on failure.
*/
stop(): Promise<void>;
/**
* Destroy the sandbox and clean up all resources (wrapper with status management).
*
* This method is race-condition-safe - concurrent calls will return the same promise.
* Handles status management.
*
* Subclasses override `destroy()` to provide their destroy logic.
*/
_destroy(): Promise<void>;
/**
* Internal destroy execution - handles status.
*/
private _executeDestroy;
/**
* Override this method to implement sandbox destroy logic.
*
* Called by `_destroy()` after status is set to 'destroying'.
* Status will be set to 'destroyed' on success, 'error' on failure.
*/
destroy(): Promise<void>;
/**
* Override to propagate logger to MountManager.
* @internal
*/
__setLogger(logger: IMastraLogger): void;
}
//# sourceMappingURL=mastra-sandbox.d.ts.map