/** * Railway Sandbox Provider * * A Railway sandbox implementation for Mastra workspaces. Provisions an * ephemeral, isolated Linux VM on Railway, runs commands in it via the * Railway TypeScript SDK, and destroys it on teardown. * * @see https://docs.railway.com/sandboxes */ import type { CommandResult, ExecuteCommandOptions, InstructionsOption, MastraSandboxOptions, ProviderStatus, SandboxCloneOptions, SandboxInfo, SandboxStartResult } from '@mastra/core/workspace'; import { MastraSandbox } from '@mastra/core/workspace'; import { Sandbox } from 'railway'; import type { SandboxNetworkIsolation, SandboxTemplate } from 'railway'; import { RailwayProcessManager } from './process-manager.js'; /** * Outcome of a {@link RailwaySandbox.captureCheckpoint} call. * * `captured` and `coalesced` both represent a successful capture the caller can * persist against — they carry the checkpoint name inline so callers don't have * to reach back into the sandbox instance to learn what they just wrote. * `skipped` carries a machine-readable reason so the set stays extensible * without another breaking change. */ export type CaptureCheckpointResult = { status: 'captured'; checkpointName: string; } | { status: 'coalesced'; checkpointName: string; } | { status: 'skipped'; reason: 'no-checkpoint-name-configured' | 'sandbox-not-running'; }; /** * Railway sandbox provider configuration. */ export interface RailwaySandboxOptions extends Omit { /** Unique identifier for this sandbox instance. */ id?: string; /** Railway API token. Falls back to the RAILWAY_API_TOKEN env var. */ token?: string; /** Railway environment ID. Falls back to the RAILWAY_ENVIRONMENT_ID env var. */ environmentId?: string; /** * Reattach to an existing Railway sandbox by its Railway ID instead of * creating a new one. When set, `start()` calls `Sandbox.connect()`. */ sandboxId?: string; /** * What `start()` does when `sandboxId` is set but Railway reports that * sandbox no longer exists. * * - `'best-effort'` (default): provision a replacement sandbox. * - `'required'`: throw a `SandboxError` with code `SANDBOX_REATTACH_FAILED` * instead of provisioning, so the caller can surface the lost VM. */ reattach?: 'best-effort' | 'required'; /** * Reuse a saved Railway sandbox checkpoint as the baseline filesystem for * new sandboxes. When the named checkpoint is missing, the sandbox is created * normally and a checkpoint is captured after setup succeeds. */ checkpointName?: string; /** * Fallback checkpoint used to seed a new sandbox when `checkpointName` has * no stored state. Snapshots continue writing to `checkpointName`. */ seedCheckpointName?: string; /** * How long the sandbox can sit idle (no `exec` interaction) before Railway * destroys it automatically. Range depends on plan (1–120 minutes on * Hobby/Pro, 1–5 on Trial/Free). Defaults to the plan default when omitted. */ idleTimeoutMinutes?: number; /** * Network isolation mode. * - `ISOLATED` (default): outbound internet only, no private network access. * - `PRIVATE`: joins the environment's private network. */ networkIsolation?: SandboxNetworkIsolation; /** Environment variables baked into the sandbox, available to every command. */ env?: Record; /** * Provision the sandbox from a custom base image built with the Railway * template builder. Use this to pre-install packages or run setup steps so * every sandbox created from it starts ready. * * - Builder callback — receives the base `Sandbox.template()` and returns the * configured template. Railway builds the template when `Sandbox.create()` * runs during `start()`. * ```ts * template: t => t.withPackages('git', 'curl').run('npm i -g pnpm') * ``` * - Pre-built `SandboxTemplate` — pass a template to reuse it across * sandboxes. Railway still builds the image during sandbox creation. * * Ignored when `sandboxId` is set (reattach) or when forking. */ template?: SandboxTemplate | ((base: SandboxTemplate) => SandboxTemplate); /** * Default execution timeout in milliseconds applied to commands that don't * specify their own timeout. When omitted, commands run until they exit. */ timeout?: number; /** * 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; } /** * Railway sandbox provider for Mastra workspaces. * * Features: * - Ephemeral, isolated Linux VM via the Railway TypeScript SDK * - Command execution with streaming output and timeouts * - Configurable idle timeout and network isolation * - Reattach to an existing sandbox by Railway ID * * @example Basic usage * ```typescript * import { Workspace } from '@mastra/core/workspace'; * import { RailwaySandbox } from '@mastra/railway'; * * const sandbox = new RailwaySandbox({ * // token + environmentId read from RAILWAY_API_TOKEN / RAILWAY_ENVIRONMENT_ID * idleTimeoutMinutes: 30, * }); * * const workspace = new Workspace({ sandbox }); * const result = await workspace.executeCode('console.log("Hello!")'); * ``` * * @example Private networking * ```typescript * const sandbox = new RailwaySandbox({ * networkIsolation: 'PRIVATE', * env: { NODE_ENV: 'production' }, * }); * ``` */ export declare class RailwaySandbox extends MastraSandbox { readonly id: string; readonly name = "RailwaySandbox"; readonly provider = "railway"; status: ProviderStatus; readonly processes: RailwayProcessManager; private _sandbox; private _createdAt; private _checkpointRefreshTimer; private _checkpointRefreshInFlight; private _sandboxId?; private _restoredCheckpointName?; private readonly _token?; private readonly _environmentId?; private readonly _checkpointName?; private readonly _seedCheckpointName?; private readonly _idleTimeoutMinutes?; private readonly _networkIsolation?; private readonly _env; private readonly _timeout?; private readonly _instructionsOverride?; private readonly _templateOption?; private readonly _reattach; constructor(options?: RailwaySandboxOptions); private generateId; /** * Get the underlying Railway Sandbox instance for direct SDK access. * * @throws {SandboxNotReadyError} If the sandbox has not been started. */ get railway(): Sandbox; /** * The Railway provider sandbox id — the physical, reattachable VM id, as * distinct from the logical `id`. Resolved after connect or create; also * reflects a configured reattach id before start. Persist this to reattach * deterministically later via the `sandboxId` option. Undefined until the * sandbox has been started (or configured to reattach) in this process. */ get sandboxId(): string | undefined; /** * Start the Railway sandbox. * * Reattaches to an existing sandbox when `sandboxId` is configured, * otherwise provisions a new one. Resolves once the sandbox is RUNNING. * * Concurrent-caller coalescing lives in the `MastraSandbox` base class * (constructor-wrapped `start()`); a failed attempt is never latched. * * Reports `outcome: 'connected'` on reattach and `outcome: 'created'` when a new * sandbox was provisioned (including checkpoint-seeded fresh VMs). */ start(): Promise; /** * Create a new Railway sandbox. */ private _createNewSandbox; /** * Reconnect to an existing Railway sandbox, creating a fresh one when */ private _reconnectSandbox; private _clientConfig; private _createOptions; /** Persist the configured recovery checkpoint when available. */ snapshot(): Promise; /** Snapshots persist real checkpoints that can seed future sandboxes. */ readonly supportsCheckpoints: boolean; /** * Capture the sandbox's checkpoint on demand, outside the idle-timer schedule. * * Intended for callers (e.g. a factory-side scheduler) that want to refresh * the recovery checkpoint at semantic moments — turn end, session-idle, * pre-teardown — rather than only just before Railway's idle destroy. * * Coalesces with any in-flight timer-driven refresh: concurrent callers join * the same underlying `Sandbox.checkpoint` call and receive * `{ status: 'coalesced', checkpointName }`. Both `captured` and `coalesced` * carry the checkpoint name inline so callers can persist a session→ * checkpoint binding without a second, non-atomic read against the sandbox. * Returns `{ status: 'skipped', reason }` when there's nothing to capture * (no `checkpointName` configured, or the sandbox isn't running yet). * * On successful capture, restarts the idle-timer countdown so the next * timer-driven refresh is scheduled from this capture. * * Never captures without a `checkpointName` and never mutates status — safe * to invoke concurrently with `executeCommand`, `restart`, or `stop`. */ captureCheckpoint(): Promise; private _checkpointSandbox; private _scheduleCheckpointRefresh; private _cancelCheckpointRefresh; /** * Stop the Railway sandbox. * * Railway sandboxes have no separate "stopped" state — they're either * running or destroyed — so stopping destroys the sandbox but we keep a checkpoint of the filesystem. */ stop(): Promise; /** * Destroy the Railway sandbox and release its resources including the checkpoint. */ destroy(): Promise; private _flushCheckpointRefresh; private _teardown; /** * Fork this running sandbox into a new, independent `RailwaySandbox`. * * Clones the filesystem (a fresh boot, not live processes) into the same * environment. The returned sandbox is already started and reattached to the * forked Railway sandbox; it inherits this sandbox's credentials and defaults * unless overridden via `options`. * * @throws {SandboxNotReadyError} If this sandbox has not been started. */ fork(options?: Pick): Promise; /** * Construct a sibling `RailwaySandbox` that inherits this sandbox's * credentials and defaults (token, environment, checkpoint, network * isolation, timeout, template, instructions) with per-instance overrides. * * Unlike {@link fork}, `clone` performs no I/O and does not require this * sandbox to be started — the returned sandbox is not started and provisions * (or reattaches, when `sandboxId` is set) on its own `start()`. Use it when * one configured sandbox acts as the template for a fleet of independent * sandboxes (e.g. one per project). */ clone(options?: SandboxCloneOptions): RailwaySandbox; /** * Whether a Railway API token was resolved at construction (explicit option * or the `RAILWAY_API_TOKEN` env fallback). Lets callers gate features on a * usable configuration without provisioning a sandbox. */ get hasCredentials(): boolean; /** The configured idle teardown window in minutes, if any. */ get idleTimeoutMinutes(): number | undefined; getInfo(): Promise; getInstructions(): string; private _buildDefaultInstructions; /** * Execute a command in the sandbox and return the result. */ executeCommand(command: string, args?: string[], options?: ExecuteCommandOptions): Promise; } //# sourceMappingURL=index.d.ts.map