{"version":3,"file":"index.cjs","names":["ProcessHandle","UnsupportedStdinCloseError","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","SandboxNotFoundError","SandboxError","Sandbox"],"sources":["../src/utils/shell-quote.ts","../src/sandbox/process-manager.ts","../src/sandbox/index.ts","../src/provider.ts"],"sourcesContent":["/**\n * Shell-quote a single argument for safe use in a command string.\n *\n * Arguments containing only safe characters are returned as-is.\n * All others are wrapped in single quotes with embedded single quotes escaped.\n */\nexport function shellQuote(arg: string): string {\n  // Safe characters that don't need quoting\n  if (/^[a-zA-Z0-9._\\-/@:=]+$/.test(arg)) return arg;\n  // Wrap in single quotes, escaping any embedded single quotes\n  return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n","/**\n * Railway Process Manager\n *\n * Implements SandboxProcessManager for Railway sandboxes.\n * Wraps the Railway SDK's `Sandbox.exec()` API.\n *\n * Railway's `exec(command, options)` accepts per-call `cwd` and `env` options\n * (since SDK v3.3.1) and returns an `ExecHandle` that runs the command\n * server-side, independently of the client. Each spawn() starts one exec.\n * The handle streams output via `onStdout`/`onStderr` callbacks wired to\n * `emitStdout`/`emitStderr`, exposes a durable `sessionName`, and can be\n * terminated with `kill(signal)`.\n */\n\nimport { ProcessHandle, UnsupportedStdinCloseError, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { ExecHandle, ExecResult } from 'railway';\nimport type { RailwaySandbox } from './index';\n\nexport const LOG_PREFIX = '[RailwaySandbox]';\n\n// =============================================================================\n// Railway Process Handle\n// =============================================================================\n\n/**\n * Wraps a Railway ExecHandle to conform to Mastra's ProcessHandle.\n * Not exported — internal to this module.\n */\nclass RailwayProcessHandle extends ProcessHandle {\n  readonly pid: string;\n\n  private readonly _execHandle: ExecHandle;\n  private readonly _startTime: number;\n  private _exitCode: number | undefined;\n  private _waitPromise: Promise<CommandResult> | null = null;\n  private _killed = false;\n\n  constructor(pid: string, execHandle: ExecHandle, startTime: number, options?: SpawnProcessOptions) {\n    super(options);\n    this.pid = pid;\n    this._execHandle = execHandle;\n    this._startTime = startTime;\n\n    // Resolve exit code once the command completes so exitCode is available\n    // without an explicit wait().\n    void this._execHandle.then(\n      (result: ExecResult) => {\n        // -1 means terminated by a signal (e.g. after kill()).\n        this._exitCode = result.exitCode ?? (this._killed ? 137 : -1);\n      },\n      () => {\n        if (this._exitCode === undefined) {\n          this._exitCode = 1;\n        }\n      },\n    );\n  }\n\n  get exitCode(): number | undefined {\n    return this._exitCode;\n  }\n\n  async wait(): Promise<CommandResult> {\n    // Idempotent — cache the promise so repeated calls return the same result.\n    if (!this._waitPromise) {\n      this._waitPromise = this._doWait();\n    }\n    return this._waitPromise;\n  }\n\n  private async _doWait(): Promise<CommandResult> {\n    try {\n      const result = await this._execHandle;\n      const exitCode = result.exitCode ?? (this._killed ? 137 : -1);\n      this._exitCode = exitCode;\n\n      // Railway captures output server-side; surface it through the base buffers\n      // if streaming callbacks didn't already populate them.\n      if (result.stdout && !this.stdout) this.emitStdout(result.stdout);\n      if (result.stderr && !this.stderr) this.emitStderr(result.stderr);\n\n      return {\n        success: exitCode === 0,\n        exitCode,\n        stdout: this.stdout,\n        stderr: this.stderr,\n        executionTimeMs: Date.now() - this._startTime,\n        killed: this._killed,\n        timedOut: result.timedOut,\n      };\n    } catch (error) {\n      const exitCode = this._exitCode ?? 1;\n      this._exitCode = exitCode;\n      return {\n        success: false,\n        exitCode,\n        stdout: this.stdout,\n        stderr: this.stderr || (error instanceof Error ? error.message : String(error)),\n        executionTimeMs: Date.now() - this._startTime,\n        killed: this._killed,\n      };\n    }\n  }\n\n  async kill(): Promise<boolean> {\n    if (this._exitCode !== undefined) return false;\n    this._killed = true;\n    try {\n      return await this._execHandle.kill('TERM');\n    } catch {\n      // Command may already be gone.\n      return false;\n    }\n  }\n\n  async sendStdin(_data: string): Promise<void> {\n    // Railway's exec API does not expose stdin streaming.\n    throw new Error(`${LOG_PREFIX} sending stdin is not supported by the Railway sandbox provider`);\n  }\n\n  async closeStdin(): Promise<void> {\n    throw new UnsupportedStdinCloseError(\n      `${LOG_PREFIX} closing stdin is not supported by the Railway sandbox provider`,\n    );\n  }\n}\n\n// =============================================================================\n// Railway Process Manager\n// =============================================================================\n\n/**\n * Railway implementation of SandboxProcessManager.\n * Uses the Railway SDK's `Sandbox.exec()` with one exec per spawned process.\n */\nexport class RailwayProcessManager extends SandboxProcessManager<RailwaySandbox> {\n  private _spawnCounter = 0;\n\n  async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n    const railway = this.sandbox.railway;\n\n    // The base spawn wrapper already merged the sandbox env into options.env\n    const mergedEnv = { ...options.env };\n    const env = Object.fromEntries(\n      Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n    );\n\n    const pid = `railway-proc-${Date.now().toString(36)}-${(this._spawnCounter++).toString(36)}`;\n\n    // Deferred reference — callbacks fire asynchronously after the handle is\n    // assigned, so `handle` is always defined by the time they run.\n    let handle: RailwayProcessHandle;\n\n    const cwd = options.cwd ?? this.sandbox.workingDirectory;\n    const execHandle = railway.exec(command, {\n      ...(options.timeout !== undefined && { timeoutSec: Math.ceil(options.timeout / 1000) }),\n      ...(cwd !== undefined && { cwd }),\n      ...(Object.keys(env).length > 0 && { env }),\n      onStdout: (chunk: string) => handle.emitStdout(chunk),\n      onStderr: (chunk: string) => handle.emitStderr(chunk),\n    });\n\n    handle = new RailwayProcessHandle(pid, execHandle, Date.now(), options);\n    this._tracked.set(handle.pid, handle);\n    return handle;\n  }\n\n  /**\n   * List tracked processes.\n   *\n   * Railway has no API to enumerate running exec sessions by sandbox, so this\n   * reports the processes this manager spawned.\n   */\n  async list(): Promise<ProcessInfo[]> {\n    return Array.from(this._tracked.values()).map(handle => ({\n      pid: handle.pid,\n      command: handle.command,\n      running: handle.exitCode === undefined,\n      ...(handle.exitCode !== undefined && { exitCode: handle.exitCode }),\n    }));\n  }\n}\n","/**\n * Railway Sandbox Provider\n *\n * A Railway sandbox implementation for Mastra workspaces. Provisions an\n * ephemeral, isolated Linux VM on Railway, runs commands in it via the\n * Railway TypeScript SDK, and destroys it on teardown.\n *\n * @see https://docs.railway.com/sandboxes\n */\n\nimport type {\n  CommandResult,\n  ExecuteCommandOptions,\n  InstructionsOption,\n  MastraSandboxOptions,\n  ProviderStatus,\n  SandboxCloneOptions,\n  SandboxInfo,\n  SandboxStartOutcome,\n  SandboxStartResult,\n} from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxError, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { Sandbox, SandboxFailedError, SandboxNotFoundError, SandboxTimeoutError } from 'railway';\nimport type { SandboxNetworkIsolation, SandboxTemplate } from 'railway';\nimport { shellQuote } from '../utils/shell-quote';\nimport { LOG_PREFIX, RailwayProcessManager } from './process-manager';\n\n/**\n * Safety margin subtracted from the sandbox's idle timeout when scheduling the\n * pre-reap checkpoint refresh. Sized to comfortably exceed Cloud Run cold-start\n * / recycle windows so a scale event during the refresh doesn't cause the timer\n * to lose the race with Railway's idle destroy. If a caller reduces the idle\n * timeout below this margin, the refresh falls back to the 1-second floor and\n * fires almost immediately after start — surfacing the misconfiguration rather\n * than silently skipping the refresh.\n */\nconst CHECKPOINT_REFRESH_MARGIN_MS = 180_000;\n\n// =============================================================================\n// Public capture result\n// =============================================================================\n\n/**\n * Outcome of a {@link RailwaySandbox.captureCheckpoint} call.\n *\n * `captured` and `coalesced` both represent a successful capture the caller can\n * persist against — they carry the checkpoint name inline so callers don't have\n * to reach back into the sandbox instance to learn what they just wrote.\n * `skipped` carries a machine-readable reason so the set stays extensible\n * without another breaking change.\n */\nexport type CaptureCheckpointResult =\n  | { status: 'captured'; checkpointName: string }\n  | { status: 'coalesced'; checkpointName: string }\n  | { status: 'skipped'; reason: 'no-checkpoint-name-configured' | 'sandbox-not-running' };\n\n// =============================================================================\n// Railway Sandbox Options\n// =============================================================================\n\n/**\n * Railway sandbox provider configuration.\n */\nexport interface RailwaySandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n  /** Unique identifier for this sandbox instance. */\n  id?: string;\n  /** Railway API token. Falls back to the RAILWAY_API_TOKEN env var. */\n  token?: string;\n  /** Railway environment ID. Falls back to the RAILWAY_ENVIRONMENT_ID env var. */\n  environmentId?: string;\n  /**\n   * Reattach to an existing Railway sandbox by its Railway ID instead of\n   * creating a new one. When set, `start()` calls `Sandbox.connect()`.\n   */\n  sandboxId?: string;\n  /**\n   * What `start()` does when `sandboxId` is set but Railway reports that\n   * sandbox no longer exists.\n   *\n   * - `'best-effort'` (default): provision a replacement sandbox.\n   * - `'required'`: throw a `SandboxError` with code `SANDBOX_REATTACH_FAILED`\n   *   instead of provisioning, so the caller can surface the lost VM.\n   */\n  reattach?: 'best-effort' | 'required';\n  /**\n   * Reuse a saved Railway sandbox checkpoint as the baseline filesystem for\n   * new sandboxes. When the named checkpoint is missing, the sandbox is created\n   * normally and a checkpoint is captured after setup succeeds.\n   */\n  checkpointName?: string;\n  /**\n   * Fallback checkpoint used to seed a new sandbox when `checkpointName` has\n   * no stored state. Snapshots continue writing to `checkpointName`.\n   */\n  seedCheckpointName?: string;\n  /**\n   * How long the sandbox can sit idle (no `exec` interaction) before Railway\n   * destroys it automatically. Range depends on plan (1–120 minutes on\n   * Hobby/Pro, 1–5 on Trial/Free). Defaults to the plan default when omitted.\n   */\n  idleTimeoutMinutes?: number;\n  /**\n   * Network isolation mode.\n   * - `ISOLATED` (default): outbound internet only, no private network access.\n   * - `PRIVATE`: joins the environment's private network.\n   */\n  networkIsolation?: SandboxNetworkIsolation;\n  /** Environment variables baked into the sandbox, available to every command. */\n  env?: Record<string, string>;\n  /**\n   * Provision the sandbox from a custom base image built with the Railway\n   * template builder. Use this to pre-install packages or run setup steps so\n   * every sandbox created from it starts ready.\n   *\n   * - Builder callback — receives the base `Sandbox.template()` and returns the\n   *   configured template. Railway builds the template when `Sandbox.create()`\n   *   runs during `start()`.\n   *   ```ts\n   *   template: t => t.withPackages('git', 'curl').run('npm i -g pnpm')\n   *   ```\n   * - Pre-built `SandboxTemplate` — pass a template to reuse it across\n   *   sandboxes. Railway still builds the image during sandbox creation.\n   *\n   * Ignored when `sandboxId` is set (reattach) or when forking.\n   */\n  template?: SandboxTemplate | ((base: SandboxTemplate) => SandboxTemplate);\n  /**\n   * Default execution timeout in milliseconds applied to commands that don't\n   * specify their own timeout. When omitted, commands run until they exit.\n   */\n  timeout?: number;\n  /**\n   * Custom instructions that override the default instructions returned by\n   * `getInstructions()`.\n   *\n   * - `string` — Fully replaces the default instructions. Pass an empty string\n   *   to suppress instructions entirely.\n   * - `(opts) => string` — Receives the default instructions and optional\n   *   request context so you can extend or customise per-request.\n   */\n  instructions?: InstructionsOption;\n}\n\n// =============================================================================\n// Railway Sandbox Implementation\n// =============================================================================\n\n/**\n * Railway sandbox provider for Mastra workspaces.\n *\n * Features:\n * - Ephemeral, isolated Linux VM via the Railway TypeScript SDK\n * - Command execution with streaming output and timeouts\n * - Configurable idle timeout and network isolation\n * - Reattach to an existing sandbox by Railway ID\n *\n * @example Basic usage\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { RailwaySandbox } from '@mastra/railway';\n *\n * const sandbox = new RailwaySandbox({\n *   // token + environmentId read from RAILWAY_API_TOKEN / RAILWAY_ENVIRONMENT_ID\n *   idleTimeoutMinutes: 30,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCode('console.log(\"Hello!\")');\n * ```\n *\n * @example Private networking\n * ```typescript\n * const sandbox = new RailwaySandbox({\n *   networkIsolation: 'PRIVATE',\n *   env: { NODE_ENV: 'production' },\n * });\n * ```\n */\nexport class RailwaySandbox extends MastraSandbox {\n  readonly id: string;\n  readonly name = 'RailwaySandbox';\n  readonly provider = 'railway';\n  status: ProviderStatus = 'pending';\n\n  declare readonly processes: RailwayProcessManager;\n\n  private _sandbox: Sandbox | null = null;\n  private _createdAt: Date | null = null;\n  private _checkpointRefreshTimer: ReturnType<typeof setTimeout> | null = null;\n  private _checkpointRefreshInFlight: Promise<void> | null = null;\n  private _sandboxId?: string;\n  private _restoredCheckpointName?: string;\n\n  private readonly _token?: string;\n  private readonly _environmentId?: string;\n  private readonly _checkpointName?: string;\n  private readonly _seedCheckpointName?: string;\n  private readonly _idleTimeoutMinutes?: number;\n  private readonly _networkIsolation?: SandboxNetworkIsolation;\n  private readonly _env: Record<string, string>;\n  private readonly _timeout?: number;\n  private readonly _instructionsOverride?: InstructionsOption;\n  private readonly _templateOption?: RailwaySandboxOptions['template'];\n  private readonly _reattach: 'best-effort' | 'required';\n\n  constructor(options: RailwaySandboxOptions = {}) {\n    super({\n      ...options,\n      name: 'RailwaySandbox',\n      processes: new RailwayProcessManager(),\n    });\n\n    this.id = options.id ?? this.generateId();\n    this._token = options.token ?? process.env.RAILWAY_API_TOKEN;\n    this._environmentId = options.environmentId ?? process.env.RAILWAY_ENVIRONMENT_ID;\n    this._sandboxId = options.sandboxId;\n    this._checkpointName = options.checkpointName;\n    this._seedCheckpointName = options.seedCheckpointName;\n    this._idleTimeoutMinutes = options.idleTimeoutMinutes;\n    this._networkIsolation = options.networkIsolation;\n    this._env = options.env ?? {};\n    this._timeout = options.timeout;\n    this._instructionsOverride = options.instructions;\n    this._templateOption = options.template;\n    this._reattach = options.reattach ?? 'best-effort';\n  }\n\n  private generateId(): string {\n    return `railway-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n  }\n\n  /**\n   * Get the underlying Railway Sandbox instance for direct SDK access.\n   *\n   * @throws {SandboxNotReadyError} If the sandbox has not been started.\n   */\n  get railway(): Sandbox {\n    if (!this._sandbox) {\n      throw new SandboxNotReadyError(this.id);\n    }\n    return this._sandbox;\n  }\n\n  /**\n   * The Railway provider sandbox id — the physical, reattachable VM id, as\n   * distinct from the logical `id`. Resolved after connect or create; also\n   * reflects a configured reattach id before start. Persist this to reattach\n   * deterministically later via the `sandboxId` option. Undefined until the\n   * sandbox has been started (or configured to reattach) in this process.\n   */\n  get sandboxId(): string | undefined {\n    return this._sandbox?.id ?? this._sandboxId;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Lifecycle\n  // ---------------------------------------------------------------------------\n\n  /**\n   * Start the Railway sandbox.\n   *\n   * Reattaches to an existing sandbox when `sandboxId` is configured,\n   * otherwise provisions a new one. Resolves once the sandbox is RUNNING.\n   *\n   * Concurrent-caller coalescing lives in the `MastraSandbox` base class\n   * (constructor-wrapped `start()`); a failed attempt is never latched.\n   *\n   * Reports `outcome: 'connected'` on reattach and `outcome: 'created'` when a new\n   * sandbox was provisioned (including checkpoint-seeded fresh VMs).\n   */\n  async start(): Promise<SandboxStartResult> {\n    if (this._sandbox) {\n      return { outcome: 'connected' };\n    }\n\n    const clientConfig = this._clientConfig();\n    const createOptions = this._createOptions(clientConfig);\n\n    let outcome: SandboxStartOutcome = 'connected';\n    if (this._sandboxId) {\n      this._restoredCheckpointName = undefined;\n      try {\n        this._sandbox = await this._reconnectSandbox(this._sandboxId, clientConfig);\n      } catch (error) {\n        if (!(error instanceof SandboxNotFoundError)) {\n          throw error;\n        }\n        if (this._reattach === 'required') {\n          throw new SandboxError(\n            `Railway sandbox ${this._sandboxId} could not be reattached (not found); refusing to provision a replacement because reattach is 'required'. Clear the persisted sandboxId to start a fresh sandbox.`,\n            'SANDBOX_REATTACH_FAILED',\n            { provider: 'railway', sandboxId: this._sandboxId, logicalId: this.id, cause: error },\n          );\n        }\n        this._sandbox = await this._createNewSandbox(createOptions);\n        outcome = 'created';\n      }\n    } else {\n      this._sandbox = await this._createNewSandbox(createOptions);\n      outcome = 'created';\n    }\n\n    const sandbox = this._sandbox;\n    this._sandboxId = sandbox.id;\n\n    this._createdAt = sandbox.createdAt ? new Date(sandbox.createdAt) : new Date();\n    this.logger.debug(`${LOG_PREFIX} Railway sandbox ${sandbox.id} ready for logical ID: ${this.id}`);\n    this._scheduleCheckpointRefresh();\n    return { outcome };\n  }\n\n  /**\n   * Create a new Railway sandbox.\n   */\n  private async _createNewSandbox(createOptions: ReturnType<RailwaySandbox['_createOptions']>): Promise<Sandbox> {\n    this.logger.debug(`${LOG_PREFIX} Creating Railway sandbox for: ${this.id}`);\n    let checkpointToRestore: string | undefined;\n    if (this._checkpointName || this._seedCheckpointName) {\n      const checkpoints = await Sandbox.checkpoints(this._clientConfig());\n      const checkpointNames = new Set(checkpoints.map(checkpoint => checkpoint.key));\n      checkpointToRestore = checkpointNames.has(this._checkpointName ?? '')\n        ? this._checkpointName\n        : checkpointNames.has(this._seedCheckpointName ?? '')\n          ? this._seedCheckpointName\n          : undefined;\n    }\n\n    const sandbox = checkpointToRestore\n      ? await Sandbox.create(checkpointToRestore, createOptions)\n      : await Sandbox.create(createOptions);\n    this._restoredCheckpointName = checkpointToRestore;\n    return sandbox;\n  }\n\n  /**\n   * Reconnect to an existing Railway sandbox, creating a fresh one when\n   */\n  private async _reconnectSandbox(\n    reconnectSandboxId: string,\n    clientConfig: { token?: string; environmentId?: string },\n  ): Promise<Sandbox> {\n    this.logger.debug(`${LOG_PREFIX} Reconnecting to Railway sandbox ${reconnectSandboxId}...`);\n\n    let connectedSandbox: Sandbox = await Sandbox.connect(reconnectSandboxId, clientConfig);\n\n    if (connectedSandbox.status !== 'RUNNING') {\n      throw new SandboxNotFoundError({\n        id: reconnectSandboxId,\n        environmentId: clientConfig.environmentId ?? '',\n      });\n    }\n\n    return connectedSandbox;\n  }\n\n  private _clientConfig(): { token?: string; environmentId?: string } {\n    return {\n      ...(this._token !== undefined && { token: this._token }),\n      ...(this._environmentId !== undefined && { environmentId: this._environmentId }),\n    };\n  }\n\n  private _createOptions(clientConfig: { token?: string; environmentId?: string }) {\n    return {\n      ...clientConfig,\n      ...(this._idleTimeoutMinutes !== undefined && { idleTimeoutMinutes: this._idleTimeoutMinutes }),\n      ...(this._networkIsolation !== undefined && { networkIsolation: this._networkIsolation }),\n      ...(Object.keys(this._env).length > 0 && { env: this._env }),\n    };\n  }\n\n  /** Persist the configured recovery checkpoint when available. */\n  async snapshot(): Promise<void> {\n    await this.captureCheckpoint();\n  }\n\n  /** Snapshots persist real checkpoints that can seed future sandboxes. */\n  readonly supportsCheckpoints: boolean = true;\n\n  /**\n   * Capture the sandbox's checkpoint on demand, outside the idle-timer schedule.\n   *\n   * Intended for callers (e.g. a factory-side scheduler) that want to refresh\n   * the recovery checkpoint at semantic moments — turn end, session-idle,\n   * pre-teardown — rather than only just before Railway's idle destroy.\n   *\n   * Coalesces with any in-flight timer-driven refresh: concurrent callers join\n   * the same underlying `Sandbox.checkpoint` call and receive\n   * `{ status: 'coalesced', checkpointName }`. Both `captured` and `coalesced`\n   * carry the checkpoint name inline so callers can persist a session→\n   * checkpoint binding without a second, non-atomic read against the sandbox.\n   * Returns `{ status: 'skipped', reason }` when there's nothing to capture\n   * (no `checkpointName` configured, or the sandbox isn't running yet).\n   *\n   * On successful capture, restarts the idle-timer countdown so the next\n   * timer-driven refresh is scheduled from this capture.\n   *\n   * Never captures without a `checkpointName` and never mutates status — safe\n   * to invoke concurrently with `executeCommand`, `restart`, or `stop`.\n   */\n  async captureCheckpoint(): Promise<CaptureCheckpointResult> {\n    const checkpointName = this._checkpointName;\n    if (!checkpointName) {\n      return { status: 'skipped', reason: 'no-checkpoint-name-configured' };\n    }\n\n    const sandbox = this._sandbox;\n    if (!sandbox) {\n      return { status: 'skipped', reason: 'sandbox-not-running' };\n    }\n\n    if (this._checkpointRefreshInFlight) {\n      await this._checkpointRefreshInFlight;\n      return { status: 'coalesced', checkpointName };\n    }\n\n    const capture = this._checkpointSandbox(sandbox).finally(() => {\n      if (this._checkpointRefreshInFlight === capture) {\n        this._checkpointRefreshInFlight = null;\n      }\n    });\n    this._checkpointRefreshInFlight = capture;\n\n    await capture;\n    this._scheduleCheckpointRefresh();\n\n    return { status: 'captured', checkpointName };\n  }\n\n  private async _checkpointSandbox(sandbox: Sandbox): Promise<void> {\n    if (!this._checkpointName) {\n      return;\n    }\n\n    this.logger.debug(`${LOG_PREFIX} Capturing Railway sandbox checkpoint ${this._checkpointName} for: ${this.id}`);\n\n    const checkpoints = await Sandbox.checkpoints(this._clientConfig());\n    const checkpointAlreadyExists = checkpoints.some(checkpoint => checkpoint.key === this._checkpointName);\n\n    // Remove first so we can re-create a checkpoint with the same name.\n    if (checkpointAlreadyExists) {\n      await Sandbox.deleteCheckpoint(this._checkpointName, this._clientConfig());\n    }\n\n    await sandbox.checkpoint(this._checkpointName);\n  }\n\n  private _scheduleCheckpointRefresh(): void {\n    if (!this._checkpointName || !this._sandbox) {\n      return;\n    }\n\n    const idleTimeoutMinutes = this._idleTimeoutMinutes ?? this._sandbox.idleTimeoutMinutes;\n    if (!idleTimeoutMinutes) {\n      return;\n    }\n\n    this._cancelCheckpointRefresh();\n\n    const delayMs = Math.max(1_000, idleTimeoutMinutes * 60_000 - CHECKPOINT_REFRESH_MARGIN_MS);\n    this._checkpointRefreshTimer = setTimeout(() => {\n      this._checkpointRefreshTimer = null;\n      const sandbox = this._sandbox;\n      if (!sandbox || this._checkpointRefreshInFlight) {\n        return;\n      }\n\n      const refresh = this._checkpointSandbox(sandbox).finally(() => {\n        if (this._checkpointRefreshInFlight === refresh) {\n          this._checkpointRefreshInFlight = null;\n        }\n      });\n      this._checkpointRefreshInFlight = refresh;\n      refresh.catch(error => {\n        this.logger.warn(`${LOG_PREFIX} Failed to refresh Railway sandbox checkpoint ${this._checkpointName}:`, error);\n      });\n    }, delayMs);\n    this._checkpointRefreshTimer.unref?.();\n  }\n\n  private _cancelCheckpointRefresh(): void {\n    if (this._checkpointRefreshTimer) {\n      clearTimeout(this._checkpointRefreshTimer);\n      this._checkpointRefreshTimer = null;\n    }\n  }\n\n  /**\n   * Stop the Railway sandbox.\n   *\n   * Railway sandboxes have no separate \"stopped\" state — they're either\n   * running or destroyed — so stopping destroys the sandbox but we keep a checkpoint of the filesystem.\n   */\n  async stop(): Promise<void> {\n    if (this._checkpointName) {\n      await this._flushCheckpointRefresh().catch(error => {\n        this.logger.warn(`${LOG_PREFIX} Failed to checkpoint Railway sandbox ${this._sandbox?.id}:`, error);\n      });\n    }\n\n    await this._teardown();\n  }\n\n  /**\n   * Destroy the Railway sandbox and release its resources including the checkpoint.\n   */\n  async destroy(): Promise<void> {\n    this._cancelCheckpointRefresh();\n    if (this._checkpointName) {\n      await this._checkpointRefreshInFlight;\n      await Sandbox.deleteCheckpoint(this._checkpointName, this._clientConfig()).catch(error => {\n        this.logger.warn(`${LOG_PREFIX} Failed to delete Railway checkpoint ${this._checkpointName}:`, error);\n      });\n    }\n\n    await this._teardown();\n  }\n\n  private async _flushCheckpointRefresh(): Promise<void> {\n    this._cancelCheckpointRefresh();\n\n    if (this._checkpointRefreshInFlight) {\n      await this._checkpointRefreshInFlight;\n      return;\n    }\n\n    if (this._sandbox) {\n      await this._checkpointSandbox(this._sandbox);\n    }\n  }\n\n  private async _teardown(): Promise<void> {\n    this._cancelCheckpointRefresh();\n    if (!this._sandbox) {\n      return;\n    }\n    await this._checkpointRefreshInFlight;\n\n    const sandbox = this._sandbox;\n    this._sandbox = null;\n    try {\n      await sandbox.destroy();\n    } catch (error) {\n      this.logger.warn(`${LOG_PREFIX} Failed to destroy Railway sandbox ${sandbox.id}:`, error);\n    }\n  }\n\n  /**\n   * Fork this running sandbox into a new, independent `RailwaySandbox`.\n   *\n   * Clones the filesystem (a fresh boot, not live processes) into the same\n   * environment. The returned sandbox is already started and reattached to the\n   * forked Railway sandbox; it inherits this sandbox's credentials and defaults\n   * unless overridden via `options`.\n   *\n   * @throws {SandboxNotReadyError} If this sandbox has not been started.\n   */\n  async fork(\n    options: Pick<RailwaySandboxOptions, 'id' | 'idleTimeoutMinutes' | 'networkIsolation' | 'env'> = {},\n  ): Promise<RailwaySandbox> {\n    const source = this.railway;\n    const forked = await source.fork({\n      ...(options.idleTimeoutMinutes !== undefined && { idleTimeoutMinutes: options.idleTimeoutMinutes }),\n      ...(options.networkIsolation !== undefined && { networkIsolation: options.networkIsolation }),\n      ...(options.env !== undefined && { env: options.env }),\n    });\n\n    const child = new RailwaySandbox({\n      ...(options.id !== undefined && { id: options.id }),\n      ...(this._token !== undefined && { token: this._token }),\n      ...(this._environmentId !== undefined && { environmentId: this._environmentId }),\n      idleTimeoutMinutes: options.idleTimeoutMinutes ?? this._idleTimeoutMinutes,\n      networkIsolation: options.networkIsolation ?? this._networkIsolation,\n      env: options.env ?? this._env,\n      timeout: this._timeout,\n    });\n    await child._start();\n    return child;\n  }\n\n  /**\n   * Construct a sibling `RailwaySandbox` that inherits this sandbox's\n   * credentials and defaults (token, environment, checkpoint, network\n   * isolation, timeout, template, instructions) with per-instance overrides.\n   *\n   * Unlike {@link fork}, `clone` performs no I/O and does not require this\n   * sandbox to be started — the returned sandbox is not started and provisions\n   * (or reattaches, when `sandboxId` is set) on its own `start()`. Use it when\n   * one configured sandbox acts as the template for a fleet of independent\n   * sandboxes (e.g. one per project).\n   */\n  clone(options: SandboxCloneOptions = {}): RailwaySandbox {\n    return new RailwaySandbox({\n      ...(options.id !== undefined && { id: options.id }),\n      ...(this._token !== undefined && { token: this._token }),\n      ...(this._environmentId !== undefined && { environmentId: this._environmentId }),\n      ...((options.checkpointName ?? this._checkpointName) !== undefined && {\n        checkpointName: options.checkpointName ?? this._checkpointName,\n      }),\n      ...(options.seedCheckpointName !== undefined && { seedCheckpointName: options.seedCheckpointName }),\n      idleTimeoutMinutes: options.idleTimeoutMinutes ?? this._idleTimeoutMinutes,\n      ...(this._networkIsolation !== undefined && { networkIsolation: this._networkIsolation }),\n      env: options.env ?? this._env,\n      ...(this._templateOption !== undefined && { template: this._templateOption }),\n      ...(this._timeout !== undefined && { timeout: this._timeout }),\n      ...(this._instructionsOverride !== undefined && { instructions: this._instructionsOverride }),\n      ...(options.sandboxId !== undefined && { sandboxId: options.sandboxId }),\n      reattach: this._reattach,\n    });\n  }\n\n  /**\n   * Whether a Railway API token was resolved at construction (explicit option\n   * or the `RAILWAY_API_TOKEN` env fallback). Lets callers gate features on a\n   * usable configuration without provisioning a sandbox.\n   */\n  get hasCredentials(): boolean {\n    return this._token !== undefined && this._token !== '';\n  }\n\n  /** The configured idle teardown window in minutes, if any. */\n  get idleTimeoutMinutes(): number | undefined {\n    return this._idleTimeoutMinutes;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Info & Instructions\n  // ---------------------------------------------------------------------------\n\n  async getInfo(): Promise<SandboxInfo> {\n    return {\n      id: this.id,\n      name: this.name,\n      provider: this.provider,\n      status: this.status,\n      createdAt: this._createdAt ?? new Date(),\n      metadata: {\n        ...(this._sandbox && {\n          railwaySandboxId: this._sandbox.id,\n          environmentId: this._sandbox.environmentId,\n          region: this._sandbox.region,\n          networkIsolation: this._sandbox.networkIsolation,\n          ...(this._sandbox.idleTimeoutMinutes != null && {\n            idleTimeoutMinutes: this._sandbox.idleTimeoutMinutes,\n          }),\n          ...(this._restoredCheckpointName && { restoredCheckpointName: this._restoredCheckpointName }),\n        }),\n      },\n    };\n  }\n\n  getInstructions(): string {\n    const defaultInstructions = this._buildDefaultInstructions();\n\n    if (typeof this._instructionsOverride === 'string') {\n      return this._instructionsOverride;\n    }\n    if (typeof this._instructionsOverride === 'function') {\n      return this._instructionsOverride({ defaultInstructions });\n    }\n    return defaultInstructions;\n  }\n\n  private _buildDefaultInstructions(): string {\n    const parts: string[] = [];\n    parts.push('Railway cloud sandbox: an isolated Debian Linux VM with outbound internet access.');\n\n    if (this._networkIsolation === 'PRIVATE') {\n      parts.push('Joined to the environment private network.');\n    }\n\n    if (this._timeout !== undefined) {\n      parts.push(`Default command timeout: ${Math.ceil(this._timeout / 1000)}s.`);\n    } else {\n      parts.push('Commands run until they exit unless a timeout is set.');\n    }\n\n    if (this._idleTimeoutMinutes !== undefined) {\n      parts.push(`Idle timeout: ${this._idleTimeoutMinutes} minute(s).`);\n    }\n\n    return parts.join(' ');\n  }\n\n  // ---------------------------------------------------------------------------\n  // Command Execution\n  // ---------------------------------------------------------------------------\n\n  /**\n   * Execute a command in the sandbox and return the result.\n   */\n  async executeCommand(\n    command: string,\n    args: string[] = [],\n    options: ExecuteCommandOptions = {},\n  ): Promise<CommandResult> {\n    const status = this._sandbox?.status;\n\n    if (status !== 'RUNNING') {\n      if (!this._checkpointName) {\n        throw new SandboxNotReadyError(this.id);\n      }\n\n      // TODO: this reconstructs \"am I inside the current start?\" from base\n      // internals because status flips to 'running' before the onStart hook.\n      // If the base ever gates commands on start re-entrancy directly, delete\n      // this branch and let it decide.\n      if (this._startPromise) {\n        if (this.status === 'running') {\n          // status flips to 'running' before the base class runs the\n          // bootstrap/onStart phase of the CURRENT start attempt — an\n          // executeCommand arriving here is running inside that attempt, and\n          // joining the in-flight promise would await itself forever. Fail\n          // loudly instead of hanging.\n          throw new SandboxNotReadyError(this.id);\n        }\n        // Concurrent with someone else's in-flight start — join it.\n        await this.start();\n      } else {\n        // The VM is provably down — reset local state so the base-class start\n        // wrapper (which early-returns while status is 'running') actually\n        // re-runs the reconnect/provision logic.\n        this._sandbox = null;\n        this.status = 'stopped';\n        await this.start();\n      }\n    }\n\n    const fullCommand = args.length > 0 ? `${command} ${args.map(shellQuote).join(' ')}` : command;\n    const timeout = options.timeout ?? this._timeout;\n    const mergedEnv = { ...this.getEnv(), ...options.env };\n    const env = Object.keys(mergedEnv).length\n      ? Object.fromEntries(\n          Object.entries(mergedEnv).filter((entry): entry is [string, string] => entry[1] !== undefined),\n        )\n      : undefined;\n    const startedAt = Date.now();\n    const cwd = options.cwd ?? this.workingDirectory;\n    const result = await this.railway.exec(fullCommand, {\n      ...(timeout !== undefined && { timeoutSec: Math.ceil(timeout / 1000) }),\n      ...(cwd !== undefined && { cwd }),\n      ...(env !== undefined && { env }),\n    });\n    const exitCode = result.exitCode ?? -1;\n    return {\n      success: exitCode === 0,\n      exitCode,\n      stdout: result.stdout,\n      stderr: result.stderr,\n      executionTimeMs: Date.now() - startedAt,\n      command,\n      args,\n      timedOut: result.timedOut,\n    };\n  }\n}\n","/**\n * Railway sandbox provider descriptor for MastraEditor.\n *\n * @example\n * ```typescript\n * import { railwaySandboxProvider } from '@mastra/railway';\n *\n * const editor = new MastraEditor({\n *   sandboxes: { [railwaySandboxProvider.id]: railwaySandboxProvider },\n * });\n * ```\n */\nimport type { SandboxProvider } from '@mastra/core/editor';\nimport { RailwaySandbox } from './sandbox';\n\n/**\n * Serializable subset of RailwaySandboxOptions for editor storage.\n */\ninterface RailwayProviderConfig {\n  token?: string;\n  environmentId?: string;\n  sandboxId?: string;\n  idleTimeoutMinutes?: number;\n  networkIsolation?: 'ISOLATED' | 'PRIVATE';\n  env?: Record<string, string>;\n  timeout?: number;\n}\n\nexport const railwaySandboxProvider: SandboxProvider<RailwayProviderConfig> = {\n  id: 'railway',\n  name: 'Railway Sandbox',\n  description: 'Ephemeral, isolated Linux VM powered by Railway',\n  configSchema: {\n    type: 'object',\n    properties: {\n      token: { type: 'string', description: 'Railway API token (falls back to RAILWAY_API_TOKEN)' },\n      environmentId: {\n        type: 'string',\n        description: 'Railway environment ID (falls back to RAILWAY_ENVIRONMENT_ID)',\n      },\n      sandboxId: { type: 'string', description: 'Reattach to an existing Railway sandbox by ID' },\n      idleTimeoutMinutes: {\n        type: 'number',\n        description: 'Minutes a sandbox can sit idle before Railway destroys it',\n      },\n      networkIsolation: {\n        type: 'string',\n        description: 'Network isolation mode',\n        enum: ['ISOLATED', 'PRIVATE'],\n        default: 'ISOLATED',\n      },\n      env: {\n        type: 'object',\n        description: 'Environment variables',\n        additionalProperties: { type: 'string' },\n      },\n      timeout: { type: 'number', description: 'Default command timeout in ms' },\n    },\n  },\n  createSandbox: config => new RailwaySandbox(config),\n};\n"],"mappings":";;;;;;;;;;AAMA,SAAgB,WAAW,KAAqB;CAE9C,IAAI,yBAAyB,KAAK,GAAG,GAAG,OAAO;CAE/C,OAAO,MAAM,IAAI,QAAQ,MAAM,OAAO,IAAI;AAC5C;;;;;;;;;;;;;;;ACQA,MAAa,aAAa;;;;;AAU1B,IAAM,uBAAN,cAAmCA,uBAAAA,cAAc;CAC/C;CAEA;CACA;CACA;CAC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