@mastra/modal 0.7.2-alpha.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -550,34 +550,34 @@ var ModalFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
550
550
  if (relative === ".." || relative.startsWith("../")) throw new _mastra_core_workspace.PermissionError(path$1, "access outside filesystem base path");
551
551
  return relative === "." ? this.basePath : path.posix.join(this.basePath, relative);
552
552
  }
553
- async readFile(path$2, options) {
554
- const { stdout } = await this.run("read", [this.resolvePath(path$2)], path$2);
553
+ async readFile(path, options) {
554
+ const { stdout } = await this.run("read", [this.resolvePath(path)], path);
555
555
  const buffer = Buffer.from(stdout);
556
556
  return options?.encoding ? buffer.toString(options.encoding) : buffer;
557
557
  }
558
- async writeFile(path$3, content, options) {
558
+ async writeFile(path, content, options) {
559
559
  this.assertWritable("writeFile");
560
560
  if (options?.expectedMtime) {
561
- const current = await this.stat(path$3).catch((error) => {
561
+ const current = await this.stat(path).catch((error) => {
562
562
  if (error instanceof _mastra_core_workspace.FileNotFoundError) return void 0;
563
563
  throw error;
564
564
  });
565
- if (current && current.modifiedAt.getTime() !== options.expectedMtime.getTime()) throw new _mastra_core_workspace.StaleFileError(path$3, options.expectedMtime, current.modifiedAt);
565
+ if (current && current.modifiedAt.getTime() !== options.expectedMtime.getTime()) throw new _mastra_core_workspace.StaleFileError(path, options.expectedMtime, current.modifiedAt);
566
566
  }
567
567
  const args = [
568
- this.resolvePath(path$3),
568
+ this.resolvePath(path),
569
569
  flag(options?.recursive !== false),
570
570
  flag(options?.overwrite !== false)
571
571
  ];
572
- await this.run("write", args, path$3, toBytes(content));
572
+ await this.run("write", args, path, toBytes(content));
573
573
  }
574
- async appendFile(path$4, content) {
574
+ async appendFile(path, content) {
575
575
  this.assertWritable("appendFile");
576
- await this.run("append", [this.resolvePath(path$4), "1"], path$4, toBytes(content));
576
+ await this.run("append", [this.resolvePath(path), "1"], path, toBytes(content));
577
577
  }
578
- async deleteFile(path$5, options) {
578
+ async deleteFile(path, options) {
579
579
  this.assertWritable("deleteFile");
580
- await this.run("deleteFile", [this.resolvePath(path$5), flag(!!options?.force)], path$5);
580
+ await this.run("deleteFile", [this.resolvePath(path), flag(!!options?.force)], path);
581
581
  }
582
582
  async copyFile(src, dest, options) {
583
583
  this.assertWritable("copyFile");
@@ -587,23 +587,23 @@ var ModalFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
587
587
  this.assertWritable("moveFile");
588
588
  await this.transfer("mv", src, dest, options);
589
589
  }
590
- async mkdir(path$6, options) {
590
+ async mkdir(path, options) {
591
591
  this.assertWritable("mkdir");
592
- await this.run("mkdir", [this.resolvePath(path$6), flag(options?.recursive !== false)], path$6, void 0, true);
592
+ await this.run("mkdir", [this.resolvePath(path), flag(options?.recursive !== false)], path, void 0, true);
593
593
  }
594
- async rmdir(path$7, options) {
594
+ async rmdir(path, options) {
595
595
  this.assertWritable("rmdir");
596
- const resolved = this.resolvePath(path$7);
597
- if (resolved === this.basePath) throw new _mastra_core_workspace.PermissionError(path$7, "remove filesystem base path");
596
+ const resolved = this.resolvePath(path);
597
+ if (resolved === this.basePath) throw new _mastra_core_workspace.PermissionError(path, "remove filesystem base path");
598
598
  await this.run("rmdir", [
599
599
  resolved,
600
600
  flag(!!options?.recursive),
601
601
  flag(!!options?.force)
602
- ], path$7, void 0, true);
602
+ ], path, void 0, true);
603
603
  }
604
- async readdir(path$8, options) {
604
+ async readdir(path, options) {
605
605
  const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;
606
- const { stdout } = await this.run("readdir", [this.resolvePath(path$8), String(depth)], path$8, void 0, true);
606
+ const { stdout } = await this.run("readdir", [this.resolvePath(path), String(depth)], path, void 0, true);
607
607
  const fields = new TextDecoder().decode(stdout).split("\0");
608
608
  const entries = [];
609
609
  for (let i = 0; i + 4 < fields.length; i += 5) {
@@ -623,13 +623,13 @@ var ModalFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
623
623
  }
624
624
  return entries;
625
625
  }
626
- async exists(path$9) {
627
- const { exitCode } = await this.exec("exists", [this.resolvePath(path$9)]);
626
+ async exists(path) {
627
+ const { exitCode } = await this.exec("exists", [this.resolvePath(path)]);
628
628
  return exitCode === 0;
629
629
  }
630
- async stat(path$10) {
631
- const resolved = this.resolvePath(path$10);
632
- const { stdout } = await this.run("stat", [resolved], path$10);
630
+ async stat(path$2) {
631
+ const resolved = this.resolvePath(path$2);
632
+ const { stdout } = await this.run("stat", [resolved], path$2);
633
633
  const [kind = "", size = "0", birth = "0", mtime = "0"] = new TextDecoder().decode(stdout).trim().split("|");
634
634
  const type = kind === "directory" ? "directory" : "file";
635
635
  const modifiedAt = /* @__PURE__ */ new Date(Number(mtime) * 1e3);
@@ -657,21 +657,21 @@ var ModalFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
657
657
  await this.run("transfer", args, src);
658
658
  }
659
659
  /** Run a script and translate non-zero exit codes into filesystem errors. */
660
- async run(script, args, path$11, stdin, directoryOp = false) {
660
+ async run(script, args, path$3, stdin, directoryOp = false) {
661
661
  const result = await this.exec(script, args, stdin);
662
662
  switch (result.exitCode) {
663
663
  case 0: return result;
664
- case EXIT.NOT_FOUND: throw directoryOp ? new _mastra_core_workspace.DirectoryNotFoundError(path$11) : new _mastra_core_workspace.FileNotFoundError(path$11);
665
- case EXIT.NO_PARENT: throw new _mastra_core_workspace.DirectoryNotFoundError(path.posix.dirname(path$11));
666
- case EXIT.EXISTS: throw new _mastra_core_workspace.FileExistsError(path$11);
667
- case EXIT.IS_DIR: throw new _mastra_core_workspace.IsDirectoryError(path$11);
668
- case EXIT.NOT_DIR: throw new _mastra_core_workspace.NotDirectoryError(path$11);
669
- case EXIT.NOT_EMPTY: throw new _mastra_core_workspace.DirectoryNotEmptyError(path$11);
670
- case EXIT.OUTSIDE: throw new _mastra_core_workspace.PermissionError(path$11, "access outside filesystem base path");
664
+ case EXIT.NOT_FOUND: throw directoryOp ? new _mastra_core_workspace.DirectoryNotFoundError(path$3) : new _mastra_core_workspace.FileNotFoundError(path$3);
665
+ case EXIT.NO_PARENT: throw new _mastra_core_workspace.DirectoryNotFoundError(path.posix.dirname(path$3));
666
+ case EXIT.EXISTS: throw new _mastra_core_workspace.FileExistsError(path$3);
667
+ case EXIT.IS_DIR: throw new _mastra_core_workspace.IsDirectoryError(path$3);
668
+ case EXIT.NOT_DIR: throw new _mastra_core_workspace.NotDirectoryError(path$3);
669
+ case EXIT.NOT_EMPTY: throw new _mastra_core_workspace.DirectoryNotEmptyError(path$3);
670
+ case EXIT.OUTSIDE: throw new _mastra_core_workspace.PermissionError(path$3, "access outside filesystem base path");
671
671
  default: {
672
672
  const message = result.stderr.trim();
673
- if (/permission denied|read-only file system/i.test(message)) throw new _mastra_core_workspace.PermissionError(path$11, script);
674
- throw new _mastra_core_workspace.FilesystemError(`[ModalFilesystem] ${script} failed for ${path$11} (exit ${result.exitCode})${message ? `: ${message}` : ""}`, "EIO", path$11);
673
+ if (/permission denied|read-only file system/i.test(message)) throw new _mastra_core_workspace.PermissionError(path$3, script);
674
+ throw new _mastra_core_workspace.FilesystemError(`[ModalFilesystem] ${script} failed for ${path$3} (exit ${result.exitCode})${message ? `: ${message}` : ""}`, "EIO", path$3);
675
675
  }
676
676
  }
677
677
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["ProcessHandle","UnsupportedStdinCloseError","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","NotFoundError","ClientClosedError","ModalClient","posix","MastraFilesystem","path","PermissionError","FileNotFoundError","StaleFileError","WorkspaceReadOnlyError","DirectoryNotFoundError","FileExistsError","IsDirectoryError","NotDirectoryError","DirectoryNotEmptyError","FilesystemError"],"sources":["../src/sandbox/process-manager.ts","../src/sandbox/index.ts","../src/filesystem/index.ts"],"sourcesContent":["/**\n * Modal process manager. Each spawn() creates a ContainerProcess via exec().\n * kill() has no SDK equivalent — it cancels stream readers locally; the remote\n * process runs until the sandbox timeout.\n */\n\nimport { ProcessHandle, UnsupportedStdinCloseError, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { ContainerProcess } from 'modal';\nimport type { ModalSandbox } from './index';\n\n// =============================================================================\n// Modal Process Handle\n// =============================================================================\n\n/**\n * Wraps a Modal ContainerProcess to conform to Mastra's ProcessHandle.\n */\nclass ModalProcessHandle extends ProcessHandle {\n readonly pid: string;\n\n private readonly _proc: ContainerProcess<string>;\n private readonly _startTime: number;\n private readonly _timeout?: number;\n\n private _exitCode: number | undefined;\n private _waitPromise: Promise<CommandResult> | null = null;\n private _streamingPromise: Promise<void> | null = null;\n private _killed = false;\n private _stdoutReader: ReadableStreamDefaultReader<string> | null = null;\n private _stderrReader: ReadableStreamDefaultReader<string> | null = null;\n\n constructor(pid: string, proc: ContainerProcess<string>, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = pid;\n this._proc = proc;\n this._startTime = startTime;\n this._timeout = options?.timeout;\n }\n\n get exitCode(): number | undefined {\n return this._exitCode;\n }\n\n /** @internal Set by the process manager after streaming starts. */\n set streamingPromise(p: Promise<void>) {\n this._streamingPromise = p;\n\n // Resolve exit code when streaming ends so exitCode is available without calling wait()\n p.then(() => this._resolveExitCode()).catch(() => this._resolveExitCode());\n }\n\n /** @internal Set by the process manager so kill() can cancel the readers. */\n setReaders(\n stdoutReader: ReadableStreamDefaultReader<string>,\n stderrReader: ReadableStreamDefaultReader<string>,\n ): void {\n this._stdoutReader = stdoutReader;\n this._stderrReader = stderrReader;\n }\n\n /** Fetch the exit code from the Modal process. No-op if already set. */\n private async _resolveExitCode(): Promise<void> {\n if (this._exitCode !== undefined) return;\n try {\n this._exitCode = await this._proc.wait();\n } catch {\n if (this._exitCode === undefined) {\n this._exitCode = 1;\n }\n }\n }\n\n async wait(): Promise<CommandResult> {\n if (!this._waitPromise) {\n this._waitPromise = this._doWait();\n }\n return this._waitPromise;\n }\n\n private async _doWait(): Promise<CommandResult> {\n const streamDone = this._streamingPromise ?? Promise.resolve();\n\n if (this._timeout) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(`Command timed out after ${this._timeout}ms`)), this._timeout);\n });\n\n try {\n await Promise.race([streamDone, timeoutPromise]);\n } catch (error) {\n if (error instanceof Error && error.message.includes('timed out')) {\n await this.kill();\n this._exitCode = 124; // conventional timeout exit code\n return {\n success: false,\n exitCode: 124,\n stdout: this.stdout,\n stderr: this.stderr || error.message,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: true,\n };\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n } else {\n await streamDone.catch(() => {});\n }\n\n if (this._killed) {\n return {\n success: false,\n exitCode: this._exitCode ?? 137,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: false,\n };\n }\n\n await this._resolveExitCode();\n\n return {\n success: this._exitCode === 0,\n exitCode: this._exitCode ?? 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n async kill(): Promise<boolean> {\n if (this._exitCode !== undefined) return false;\n this._killed = true;\n this._exitCode = 137; // SIGKILL\n // The remote process may continue running; Modal JS SDK has no per-exec kill.\n try {\n await this._stdoutReader?.cancel();\n } catch {\n // Ignore cancellation errors\n }\n try {\n await this._stderrReader?.cancel();\n } catch {\n // Ignore cancellation errors\n }\n return true;\n }\n\n async sendStdin(_data: string): Promise<void> {\n throw new Error('Modal JS SDK does not expose stdin on exec() — sendStdin() is not supported');\n }\n\n async closeStdin(): Promise<void> {\n throw new UnsupportedStdinCloseError(\n 'Modal JS SDK does not expose stdin on exec() — closeStdin() is not supported',\n );\n }\n}\n\n// =============================================================================\n// Modal Process Manager\n// =============================================================================\n\n/**\n * Modal implementation of SandboxProcessManager.\n * Uses the Modal SDK's exec() API with one ContainerProcess per spawn.\n */\nexport class ModalProcessManager extends SandboxProcessManager<ModalSandbox> {\n private _spawnCounter = 0;\n\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n return this.sandbox.retryOnDead(async () => {\n const sb = this.sandbox.modal;\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 // exec() takes string[] — wrap in sh -c to support pipes, redirects, etc.\n const argv = ['sh', '-c', command];\n\n const proc = await sb.exec(argv, {\n env: Object.keys(env).length > 0 ? env : undefined,\n workdir: options.cwd ?? this.sandbox.workingDirectory,\n timeoutMs: options.timeout,\n });\n\n const pid = `modal-proc-${Date.now().toString(36)}-${++this._spawnCounter}`;\n const handle = new ModalProcessHandle(pid, proc, Date.now(), options);\n\n const stdoutReader = proc.stdout.getReader();\n const stderrReader = proc.stderr.getReader();\n handle.setReaders(stdoutReader, stderrReader);\n\n const streamingPromise = Promise.all([\n drainReader(stdoutReader, chunk => handle.emitStdout(chunk)),\n drainReader(stderrReader, chunk => handle.emitStderr(chunk)),\n ]).then(() => {});\n\n handle.streamingPromise = streamingPromise;\n\n this._tracked.set(pid, handle);\n return handle;\n });\n }\n\n async list(): Promise<ProcessInfo[]> {\n const result: ProcessInfo[] = [];\n for (const [pid, handle] of this._tracked) {\n result.push({\n pid,\n command: handle.command,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n });\n }\n return result;\n }\n}\n\n// =============================================================================\n// Stream Helpers\n// =============================================================================\n\n/** Reads chunks from a stream until done or cancelled. */\nasync function drainReader(reader: ReadableStreamDefaultReader<string>, emit: (chunk: string) => void): Promise<void> {\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n emit(value);\n }\n } catch {\n // cancelled or network error\n }\n}\n","/**\n * @see https://modal.com/docs/reference/modal.Sandbox\n */\n\nimport type { MastraSandboxOptions, ProviderStatus, SandboxCloneOptions, SandboxInfo } from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { ClientClosedError, ModalClient, NotFoundError } from 'modal';\nimport type { App, Image, Sandbox, SandboxReloadVolumesParams, Volume } from 'modal';\nimport { ModalProcessManager } from './process-manager';\n\nconst LOG_PREFIX = '[ModalSandbox]';\n\n// =============================================================================\n// Options\n// =============================================================================\n\ntype InstructionsOption = string | ((opts: { defaultInstructions: string }) => string);\n\n/**\n * Modal sandbox provider configuration.\n */\nexport interface ModalSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Stable name for this sandbox. Reusing the same id reconnects to a running sandbox. */\n id?: string;\n /**\n * Modal App name to associate sandboxes with.\n *\n * @default 'mastra'\n */\n appName?: string;\n /**\n * Docker image to use for the sandbox.\n *\n * @default 'ubuntu:22.04'\n */\n baseImage?: string;\n /**\n * Wall-clock max lifetime in milliseconds. The sandbox is terminated when this expires,\n * regardless of activity. Modal's maximum is 24 hours (86_400_000).\n *\n * @default 300_000 // 5 minutes\n */\n timeoutMs?: number;\n /** Environment variables baked into the sandbox at create time. */\n env?: Record<string, string>;\n /** Default working directory inside the sandbox.\n * @deprecated Use `workingDirectory` (the base sandbox option) instead.\n * When both are set, `workingDirectory` wins.\n */\n workdir?: string;\n /** Modal token ID. Falls back to MODAL_TOKEN_ID env var. */\n tokenId?: string;\n /** Modal token secret. Falls back to MODAL_TOKEN_SECRET env var. */\n tokenSecret?: string;\n /** Custom instructions for getInstructions(). String replaces the default; function receives it. */\n instructions?: InstructionsOption;\n /**\n * Modal Volumes to mount, keyed by absolute mount path inside the sandbox.\n *\n * The working directory must not be a mount path or sit inside one, otherwise\n * `reloadVolumes()` fails. Writes made by other sandboxes only become visible\n * in a long-lived sandbox after calling `reloadVolumes()`.\n *\n * @example\n * ```typescript\n * const volume = await modal.volumes.fromName('agent-files', { createIfMissing: true });\n * new ModalSandbox({ volumes: { '/mnt/agent': volume }, workingDirectory: '/workspace' });\n * ```\n */\n volumes?: Record<string, Volume>;\n}\n\n// =============================================================================\n// ModalSandbox\n// =============================================================================\n\n/**\n * Modal cloud sandbox provider for Mastra workspaces.\n *\n * @example\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { ModalSandbox } from '@mastra/modal';\n *\n * const sandbox = new ModalSandbox({\n * baseImage: 'ubuntu:22.04',\n * timeoutMs: 60_000,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCommand('echo hello');\n * ```\n */\nexport class ModalSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'ModalSandbox';\n readonly provider = 'modal';\n status: ProviderStatus = 'pending';\n\n declare readonly processes: ModalProcessManager;\n\n private _sb: Sandbox | null = null;\n private _imageSnapshot: Image | null = null; // for stop-and-resume\n private _client: ModalClient | null = null;\n private _createdAt: Date | null = null;\n private _isRetrying = false;\n\n private readonly appName: string;\n private readonly baseImage: string;\n private readonly timeoutMs: number;\n private readonly env: Record<string, string>;\n private readonly tokenId?: string;\n private readonly tokenSecret?: string;\n private readonly _instructionsOverride?: InstructionsOption;\n private readonly volumes?: Record<string, Volume>;\n private readonly _constructorOptions: ModalSandboxOptions;\n\n constructor(options: ModalSandboxOptions = {}) {\n super({\n ...options,\n name: 'ModalSandbox',\n processes: new ModalProcessManager(),\n });\n\n this.id = options.id ?? this._generateId();\n this.appName = options.appName ?? 'mastra';\n this.baseImage = options.baseImage ?? 'ubuntu:22.04';\n this.timeoutMs = options.timeoutMs ?? 300_000;\n this.env = options.env ?? {};\n if (options.workingDirectory === undefined && options.workdir !== undefined) {\n this.setWorkingDirectory(options.workdir);\n }\n this.tokenId = options.tokenId;\n this.tokenSecret = options.tokenSecret;\n this._instructionsOverride = options.instructions;\n this.volumes = options.volumes && Object.keys(options.volumes).length > 0 ? options.volumes : undefined;\n this._assertWorkdirOutsideVolumes();\n this._constructorOptions = { ...options };\n }\n\n /**\n * Construct a sibling `ModalSandbox` that inherits this sandbox's\n * configuration (credentials, app, base image, workdir, instructions) with\n * per-instance overrides.\n *\n * Performs no I/O — the sandbox clone provisions (or reconnects to a\n * running Modal sandbox with the same logical `id`) on its own `start()`.\n * Use it when one configured sandbox acts as the template for a fleet of\n * independent sandboxes (e.g. one per project).\n *\n * `options.idleTimeoutMinutes` maps to Modal's `timeoutMs` (wall-clock\n * lifetime); `options.sandboxId` is ignored because Modal reconnects by\n * logical `id`.\n */\n clone(options: SandboxCloneOptions = {}): ModalSandbox {\n const { id: _id, ...base } = this._constructorOptions;\n return new ModalSandbox({\n ...base,\n ...(options.id !== undefined && { id: options.id }),\n ...(options.env !== undefined && { env: options.env }),\n ...(options.workingDirectory !== undefined && { workingDirectory: options.workingDirectory }),\n ...(options.idleTimeoutMinutes !== undefined && { timeoutMs: options.idleTimeoutMinutes * 60_000 }),\n });\n }\n\n /**\n * Get the underlying Modal Sandbox instance for direct SDK access.\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started.\n */\n get modal(): Sandbox {\n if (!this._sb) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sb;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /** Reconnects to a running sandbox with this id if one exists, otherwise creates a new one. */\n async start(): Promise<void> {\n if (this._sb) {\n return;\n }\n\n const client = this._getClient();\n\n try {\n this._sb = await client.sandboxes.fromName(this.appName, this.id);\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to running sandbox: ${this.id}`);\n return;\n } catch (error) {\n if (!(error instanceof NotFoundError)) {\n throw error;\n }\n }\n\n const app: App = await client.apps.fromName(this.appName, { createIfMissing: true });\n\n if (this._imageSnapshot) {\n this.logger.debug(`${LOG_PREFIX} Rebooting from snapshot: ${this.id}`);\n this._sb = await client.sandboxes.create(app, this._imageSnapshot, {\n name: this.id,\n timeoutMs: this.timeoutMs,\n env: Object.keys(this.env).length > 0 ? this.env : undefined,\n workdir: this.workingDirectory,\n volumes: this.volumes,\n });\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Created new sandbox from snapshot: ${this._sb?.sandboxId}`);\n return;\n }\n\n const image: Image = client.images.fromRegistry(this.baseImage);\n this.logger.debug(`${LOG_PREFIX} Creating sandbox: ${this.id} (baseImage: ${this.baseImage})`);\n this._sb = await client.sandboxes.create(app, image, {\n name: this.id,\n timeoutMs: this.timeoutMs,\n env: Object.keys(this.env).length > 0 ? this.env : undefined,\n workdir: this.workingDirectory,\n volumes: this.volumes,\n });\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Created sandbox: ${this._sb.sandboxId}`);\n }\n\n /**\n * Snapshot the sandbox filesystem before terminating it.\n * Future starts will create net-new sandboxes from the snapshot.\n */\n async stop(): Promise<void> {\n if (!this._sb) return;\n\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.filter(p => p.running).map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n try {\n this._imageSnapshot = await this._sb.snapshotFilesystem();\n this.logger.debug(`${LOG_PREFIX} Snapshot created: ${this._imageSnapshot.imageId}`);\n } catch (error) {\n this.logger.debug(`${LOG_PREFIX} Snapshot failed, terminating without snapshot:`, error);\n }\n\n try {\n await this._sb.terminate({ wait: true });\n this.logger.debug(`${LOG_PREFIX} Sandbox terminated: ${this._sb.sandboxId}`);\n this._sb = null;\n } catch (error) {\n // Best-effort: sandbox may already be dead\n if (this.isSandboxDeadError(error)) {\n this._sb = null;\n } else {\n throw error;\n }\n }\n }\n\n /** Terminates the sandbox, ending its lifetime. Unlike stop(), no snapshot is preserved. */\n async destroy(): Promise<void> {\n if (this._sb) {\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.filter(p => p.running).map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n try {\n await this._sb.terminate();\n this.logger.debug(`${LOG_PREFIX} Sandbox terminated: ${this._sb.sandboxId}`);\n } catch {\n // Ignore errors during destroy\n }\n\n this._sb = null;\n }\n\n this._imageSnapshot = null;\n }\n\n /**\n * Reload all Volumes mounted in the sandbox so it sees writes committed by\n * other sandboxes or clients.\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started.\n */\n async reloadVolumes(params?: SandboxReloadVolumesParams): Promise<void> {\n await this.retryOnDead(() => this.modal.reloadVolumes(params));\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 appName: this.appName,\n image: this._imageSnapshot?.imageId ?? this.baseImage,\n timeoutMs: this.timeoutMs,\n },\n };\n }\n\n getInstructions(): string {\n const defaultInstructions = this._getDefaultInstructions();\n if (this._instructionsOverride === undefined) return defaultInstructions;\n if (typeof this._instructionsOverride === 'string') return this._instructionsOverride;\n return this._instructionsOverride({ defaultInstructions });\n }\n\n private _getDefaultInstructions(): string {\n return `Modal cloud sandbox running ${this.baseImage}. Use executeCommand() to run shell commands.`;\n }\n\n // ---------------------------------------------------------------------------\n // Dead-sandbox Retry\n // ---------------------------------------------------------------------------\n\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n if (error instanceof ClientClosedError) return true;\n if (error instanceof NotFoundError) return true;\n const errorStr = String(error);\n return (\n errorStr.includes('sandbox not found') ||\n errorStr.includes('has been terminated') ||\n errorStr.includes('already completed') ||\n errorStr.includes('was cancelled') ||\n // gRPC NOT_FOUND (code 5)\n /status[:\\s]+5\\b/.test(errorStr) ||\n errorStr.includes('NOT_FOUND')\n );\n }\n\n private handleSandboxDead(): void {\n this._sb = null;\n this.status = 'stopped';\n }\n\n /** @internal Retries fn() once after restarting if the sandbox is dead. */\n async retryOnDead<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (this.isSandboxDeadError(error) && !this._isRetrying) {\n this.handleSandboxDead();\n this._isRetrying = true;\n try {\n await this.ensureRunning();\n return await fn();\n } finally {\n this._isRetrying = false;\n }\n }\n throw error;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n private _assertWorkdirOutsideVolumes(): void {\n const workdir = this.workingDirectory;\n if (!this.volumes || !workdir) return;\n const normalize = (p: string) => {\n let end = p.length;\n while (end > 1 && p[end - 1] === '/') end--;\n return p.slice(0, end);\n };\n const dir = normalize(workdir);\n for (const mountPath of Object.keys(this.volumes)) {\n const mount = normalize(mountPath);\n if (dir === mount || dir.startsWith(`${mount}/`)) {\n throw new Error(\n `${LOG_PREFIX} workingDirectory \"${workdir}\" must be outside Volume mount \"${mountPath}\"; reloadVolumes() fails when the working directory is inside a mount.`,\n );\n }\n }\n }\n\n private _generateId(): string {\n return `modal-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n private _getClient(): ModalClient {\n if (!this._client) {\n this._client = new ModalClient({\n ...(this.tokenId && { tokenId: this.tokenId }),\n ...(this.tokenSecret && { tokenSecret: this.tokenSecret }),\n });\n }\n return this._client;\n }\n}\n","/**\n * Modal filesystem provider.\n *\n * A WorkspaceFilesystem backed by a running ModalSandbox. Every operation runs\n * a fixed POSIX shell script inside the sandbox with paths passed as positional\n * arguments (never interpolated), so it works for any path the sandbox can see,\n * including Modal Volume mounts.\n */\n\nimport { posix } from 'node:path';\n\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemIcon,\n FilesystemInfo,\n ListOptions,\n MastraFilesystemOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport {\n DirectoryNotEmptyError,\n DirectoryNotFoundError,\n FileExistsError,\n FileNotFoundError,\n FilesystemError,\n IsDirectoryError,\n MastraFilesystem,\n NotDirectoryError,\n PermissionError,\n StaleFileError,\n WorkspaceReadOnlyError,\n} from '@mastra/core/workspace';\n\nimport type { ModalSandbox } from '../sandbox';\n\nexport interface ModalFilesystemOptions extends MastraFilesystemOptions {\n /** Unique identifier for this filesystem instance */\n id?: string;\n /** Sandbox the filesystem operates through. The filesystem does not own its lifecycle. */\n sandbox: ModalSandbox;\n /**\n * Absolute directory inside the sandbox that workspace paths resolve against,\n * typically a Volume mount path (e.g. `/mnt/agent`). Paths cannot escape it.\n */\n basePath: string;\n /** Reject all write operations */\n readOnly?: boolean;\n /** Human-friendly display name for the UI */\n displayName?: string;\n /** Description shown in tooltips */\n description?: string;\n}\n\n/** Exit codes used by the in-sandbox scripts. */\nconst EXIT = { NOT_FOUND: 2, EXISTS: 3, IS_DIR: 4, NOT_DIR: 5, NOT_EMPTY: 6, NO_PARENT: 7, OUTSIDE: 8 } as const;\n\n/**\n * Runs before every script. Receives `basePath` and the number of leading path\n * arguments, then shifts them off. Each path is resolved through symlinks\n * (resolving the deepest existing ancestor for paths that don't exist yet) and\n * rejected when it lands outside `basePath`. Uses only POSIX sh + `readlink -f`,\n * which GNU coreutils and BusyBox both provide.\n */\nconst CONFINE = `b=$(readlink -f -- \"$1\") || exit ${EXIT.OUTSIDE}; n=$2; shift 2; canon() { p=$1; rest=; while [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; do rest=/$(basename -- \"$p\")$rest; p=$(dirname -- \"$p\"); done; r=$(readlink -f -- \"$p\") || return 1; printf '%s%s' \"$r\" \"$rest\"; }; i=0; for a; do [ \"$i\" -lt \"$n\" ] || break; r=$(canon \"$a\") || exit ${EXIT.OUTSIDE}; case \"$r\" in \"$b\"|\"$b\"/*) ;; *) exit ${EXIT.OUTSIDE};; esac; i=$((i+1)); done;`;\n\n// Scripts receive `$0` = script name and positional args; paths are always quoted.\nconst PARENT_CHECK = `d=$(dirname -- \"$1\"); if [ ! -d \"$d\" ]; then if [ \"$2\" = 1 ]; then mkdir -p -- \"$d\" || exit 1; else exit ${EXIT.NO_PARENT}; fi; fi; [ -d \"$1\" ] && exit ${EXIT.IS_DIR};`;\n\nconst SCRIPTS = {\n read: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; [ -d \"$1\" ] && exit ${EXIT.IS_DIR}; cat -- \"$1\"`,\n write: `${PARENT_CHECK} [ \"$3\" = 0 ] && [ -e \"$1\" ] && exit ${EXIT.EXISTS}; cat > \"$1\"`,\n append: `${PARENT_CHECK} cat >> \"$1\"`,\n deleteFile: `if [ ! -e \"$1\" ] && [ ! -L \"$1\" ]; then [ \"$2\" = 1 ] && exit 0; exit ${EXIT.NOT_FOUND}; fi; [ -d \"$1\" ] && exit ${EXIT.IS_DIR}; rm -f -- \"$1\"`,\n // $1 src, $2 dest, $3 recursive, $4 overwrite, $5 op (cp|mv)\n transfer: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; if [ -d \"$1\" ] && [ \"$5\" = cp ] && [ \"$3\" != 1 ]; then exit ${EXIT.IS_DIR}; fi; if [ -e \"$2\" ]; then [ \"$1\" -ef \"$2\" ] && exit ${EXIT.EXISTS}; [ \"$4\" = 0 ] && exit ${EXIT.EXISTS}; rm -rf -- \"$2\"; fi; mkdir -p -- \"$(dirname -- \"$2\")\" || exit 1; if [ \"$5\" = mv ]; then mv -- \"$1\" \"$2\"; else cp -R -- \"$1\" \"$2\"; fi`,\n mkdir: `if [ \"$2\" = 1 ]; then [ -e \"$1\" ] && [ ! -d \"$1\" ] && exit ${EXIT.EXISTS}; mkdir -p -- \"$1\"; else [ -e \"$1\" ] && exit ${EXIT.EXISTS}; [ -d \"$(dirname -- \"$1\")\" ] || exit ${EXIT.NO_PARENT}; mkdir -- \"$1\"; fi`,\n rmdir: `if [ ! -e \"$1\" ]; then [ \"$3\" = 1 ] && exit 0; exit ${EXIT.NOT_FOUND}; fi; [ -d \"$1\" ] || exit ${EXIT.NOT_DIR}; if [ \"$2\" = 1 ]; then rm -rf -- \"$1\"; else [ -z \"$(ls -A -- \"$1\")\" ] || exit ${EXIT.NOT_EMPTY}; rmdir -- \"$1\"; fi`,\n // Emits NUL-separated records: target type, own type, size, relative path, link target.\n readdir: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; [ -d \"$1\" ] || exit ${EXIT.NOT_DIR}; find \"$1\" -mindepth 1 -maxdepth \"$2\" -exec sh -c 'b=$1; shift; for p; do if [ -d \"$p\" ]; then t=d; else t=f; fi; o=$t; l=; if [ -L \"$p\" ]; then o=l; l=$(readlink -- \"$p\"); fi; s=0; if [ \"$o\" = f ]; then s=$(($(wc -c < \"$p\"))); fi; printf \"%s\\\\0%s\\\\0%s\\\\0%s\\\\0%s\\\\0\" \"$t\" \"$o\" \"$s\" \"\\${p#\"$b\"/}\" \"$l\"; done' sh \"$1\" {} +`,\n exists: `[ -e \"$1\" ]`,\n // Emits: type, size, birth time, modification time (epoch seconds).\n stat: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; stat -L -c '%F|%s|%W|%Y' -- \"$1\"`,\n} as const;\n\nconst DEFAULT_MAX_DEPTH = 100;\n\ninterface ExecResult {\n exitCode: number;\n stdout: Uint8Array;\n stderr: string;\n}\n\nfunction toBytes(content: FileContent): Uint8Array {\n return typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content);\n}\n\nfunction flag(value: boolean): string {\n return value ? '1' : '0';\n}\n\nfunction matchesExtension(name: string, extension: string | string[]): boolean {\n const ext = posix.extname(name);\n const extensions = Array.isArray(extension) ? extension : [extension];\n return extensions.some(e => e === ext || e === ext.slice(1));\n}\n\n/**\n * Workspace filesystem that reads and writes files inside a Modal Sandbox.\n *\n * Mount a Modal Volume on the sandbox and point `basePath` at the mount to give\n * agents persistent files that survive sandbox restarts.\n *\n * @example\n * ```typescript\n * import { Volume } from 'modal';\n * import { Workspace } from '@mastra/core/workspace';\n * import { ModalSandbox, ModalFilesystem } from '@mastra/modal';\n *\n * const volume = await modal.volumes.fromName('agent-files', { createIfMissing: true });\n * const sandbox = new ModalSandbox({ volumes: { '/mnt/agent': volume }, workingDirectory: '/workspace' });\n * const filesystem = new ModalFilesystem({ sandbox, basePath: '/mnt/agent' });\n *\n * const workspace = new Workspace({ sandbox, filesystem });\n * ```\n */\nexport class ModalFilesystem extends MastraFilesystem {\n readonly id: string;\n readonly name = 'ModalFilesystem';\n readonly provider = 'modal';\n readonly readOnly?: boolean;\n readonly displayName?: string;\n readonly description?: string;\n readonly icon: FilesystemIcon = 'folder';\n readonly basePath: string;\n\n status: ProviderStatus = 'pending';\n\n private readonly sandbox: ModalSandbox;\n /** Serializes stdin-streaming execs; concurrent stdin writes can wedge a Modal exec. */\n private _writeQueue: Promise<unknown> = Promise.resolve();\n\n constructor(options: ModalFilesystemOptions) {\n super({ ...options, name: 'ModalFilesystem' });\n if (!posix.isAbsolute(options.basePath)) {\n throw new Error(`[ModalFilesystem] basePath must be absolute, got \"${options.basePath}\"`);\n }\n this.id = options.id ?? `modal-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n this.sandbox = options.sandbox;\n this.basePath = posix.normalize(options.basePath).replace(/(.)\\/$/, '$1');\n this.readOnly = options.readOnly;\n this.displayName = options.displayName;\n this.description = options.description;\n }\n\n async init(): Promise<void> {\n await this.sandbox.ensureRunning();\n }\n\n getInfo(): FilesystemInfo<{ basePath: string }> {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n readOnly: this.readOnly,\n icon: this.icon,\n metadata: { basePath: this.basePath },\n };\n }\n\n getInstructions(): string {\n const access = this.readOnly ? 'Read-only' : 'Persistent';\n return `${access} files stored at ${this.basePath} inside the Modal sandbox.`;\n }\n\n /**\n * Resolve a workspace path to an absolute sandbox path under `basePath`.\n * Rejects paths that would escape the base directory.\n */\n resolvePath(path: string): string {\n const relative = posix.normalize(`./${path.replace(/^\\/+/, '')}`).replace(/\\/$/, '') || '.';\n if (relative === '..' || relative.startsWith('../')) {\n throw new PermissionError(path, 'access outside filesystem base path');\n }\n return relative === '.' ? this.basePath : posix.join(this.basePath, relative);\n }\n\n // ---------------------------------------------------------------------------\n // File operations\n // ---------------------------------------------------------------------------\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const { stdout } = await this.run('read', [this.resolvePath(path)], path);\n const buffer = Buffer.from(stdout);\n return options?.encoding ? buffer.toString(options.encoding) : buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n this.assertWritable('writeFile');\n if (options?.expectedMtime) {\n const current = await this.stat(path).catch(error => {\n if (error instanceof FileNotFoundError) return undefined;\n throw error;\n });\n if (current && current.modifiedAt.getTime() !== options.expectedMtime.getTime()) {\n throw new StaleFileError(path, options.expectedMtime, current.modifiedAt);\n }\n }\n const args = [this.resolvePath(path), flag(options?.recursive !== false), flag(options?.overwrite !== false)];\n await this.run('write', args, path, toBytes(content));\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n this.assertWritable('appendFile');\n await this.run('append', [this.resolvePath(path), '1'], path, toBytes(content));\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n this.assertWritable('deleteFile');\n await this.run('deleteFile', [this.resolvePath(path), flag(!!options?.force)], path);\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n this.assertWritable('copyFile');\n await this.transfer('cp', src, dest, options);\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n this.assertWritable('moveFile');\n await this.transfer('mv', src, dest, options);\n }\n\n // ---------------------------------------------------------------------------\n // Directory operations\n // ---------------------------------------------------------------------------\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n this.assertWritable('mkdir');\n await this.run('mkdir', [this.resolvePath(path), flag(options?.recursive !== false)], path, undefined, true);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n this.assertWritable('rmdir');\n const resolved = this.resolvePath(path);\n if (resolved === this.basePath) {\n throw new PermissionError(path, 'remove filesystem base path');\n }\n await this.run('rmdir', [resolved, flag(!!options?.recursive), flag(!!options?.force)], path, undefined, true);\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;\n const { stdout } = await this.run('readdir', [this.resolvePath(path), String(depth)], path, undefined, true);\n\n const fields = new TextDecoder().decode(stdout).split('\\0');\n const entries: FileEntry[] = [];\n for (let i = 0; i + 4 < fields.length; i += 5) {\n const [targetType, ownType, size, name, linkTarget] = fields.slice(i, i + 5) as [\n string,\n string,\n string,\n string,\n string,\n ];\n const type = targetType === 'd' ? 'directory' : 'file';\n const isSymlink = ownType === 'l';\n if (options?.extension && type === 'file' && !matchesExtension(name, options.extension)) continue;\n\n const entry: FileEntry = { name, type };\n if (isSymlink) {\n entry.isSymlink = true;\n entry.symlinkTarget = linkTarget;\n } else if (type === 'file') {\n entry.size = Number(size);\n }\n entries.push(entry);\n }\n return entries;\n }\n\n // ---------------------------------------------------------------------------\n // Path operations\n // ---------------------------------------------------------------------------\n\n async exists(path: string): Promise<boolean> {\n const { exitCode } = await this.exec('exists', [this.resolvePath(path)]);\n return exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const resolved = this.resolvePath(path);\n const { stdout } = await this.run('stat', [resolved], path);\n const [kind = '', size = '0', birth = '0', mtime = '0'] = new TextDecoder().decode(stdout).trim().split('|');\n const type = kind === 'directory' ? 'directory' : 'file';\n const modifiedAt = new Date(Number(mtime) * 1000);\n const birthSeconds = Number(birth);\n return {\n name: posix.basename(resolved),\n path: resolved,\n type,\n size: type === 'directory' ? 0 : Number(size),\n createdAt: birthSeconds > 0 ? new Date(birthSeconds * 1000) : modifiedAt,\n modifiedAt,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internals\n // ---------------------------------------------------------------------------\n\n private assertWritable(operation: string): void {\n if (this.readOnly) throw new WorkspaceReadOnlyError(operation);\n }\n\n private async transfer(op: 'cp' | 'mv', src: string, dest: string, options?: CopyOptions): Promise<void> {\n const args = [\n this.resolvePath(src),\n this.resolvePath(dest),\n flag(!!options?.recursive),\n flag(options?.overwrite !== false),\n op,\n ];\n await this.run('transfer', args, src);\n }\n\n /** Run a script and translate non-zero exit codes into filesystem errors. */\n private async run(\n script: keyof typeof SCRIPTS,\n args: string[],\n path: string,\n stdin?: Uint8Array,\n directoryOp = false,\n ): Promise<ExecResult> {\n const result = await this.exec(script, args, stdin);\n switch (result.exitCode) {\n case 0:\n return result;\n case EXIT.NOT_FOUND:\n throw directoryOp ? new DirectoryNotFoundError(path) : new FileNotFoundError(path);\n case EXIT.NO_PARENT:\n throw new DirectoryNotFoundError(posix.dirname(path));\n case EXIT.EXISTS:\n throw new FileExistsError(path);\n case EXIT.IS_DIR:\n throw new IsDirectoryError(path);\n case EXIT.NOT_DIR:\n throw new NotDirectoryError(path);\n case EXIT.NOT_EMPTY:\n throw new DirectoryNotEmptyError(path);\n case EXIT.OUTSIDE:\n throw new PermissionError(path, 'access outside filesystem base path');\n default: {\n const message = result.stderr.trim();\n if (/permission denied|read-only file system/i.test(message)) {\n throw new PermissionError(path, script);\n }\n throw new FilesystemError(\n `[ModalFilesystem] ${script} failed for ${path} (exit ${result.exitCode})${message ? `: ${message}` : ''}`,\n 'EIO',\n path,\n );\n }\n }\n }\n\n private async exec(script: keyof typeof SCRIPTS, args: string[], stdin?: Uint8Array): Promise<ExecResult> {\n await this.ensureReady();\n const execute = async (): Promise<ExecResult> => {\n const pathCount = script === 'transfer' ? '2' : '1';\n const command = ['sh', '-c', `${CONFINE} ${SCRIPTS[script]}`, script, this.basePath, pathCount, ...args];\n const proc = await this.sandbox.modal.exec(command, {\n mode: 'binary',\n });\n if (stdin) {\n await proc.stdin.writeBytes(stdin);\n }\n await proc.stdin.close();\n const [stdout, stderr, exitCode] = await Promise.all([\n proc.stdout.readBytes(),\n proc.stderr.readBytes(),\n proc.wait(),\n ]);\n return { exitCode, stdout, stderr: new TextDecoder().decode(stderr) };\n };\n // Append isn't idempotent: the bytes may already be applied when the process dies, so never replay it.\n const runOnce = () => (script === 'append' ? execute() : this.sandbox.retryOnDead(execute));\n\n if (!stdin) return runOnce();\n\n const next = this._writeQ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IACnD,KAAK,OAAO,UAAU;IACtB,KAAK,OAAO,UAAU;IACtB,KAAK,KAAK;GACZ,CAAC;GACD,OAAO;IAAE;IAAU;IAAQ,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,MAAM;GAAE;EACtE;EAEA,MAAM,gBAAiB,WAAW,WAAW,QAAQ,IAAI,KAAK,QAAQ,YAAY,OAAO;EAEzF,IAAI,CAAC,OAAO,OAAO,QAAQ;EAE3B,MAAM,OAAO,KAAK,YAAY,KAAK,SAAS,OAAO;EACnD,KAAK,cAAc,KAAK,YAAY,CAAC,CAAC;EACtC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["ProcessHandle","UnsupportedStdinCloseError","SandboxProcessManager","MastraSandbox","SandboxNotReadyError","NotFoundError","ClientClosedError","ModalClient","posix","MastraFilesystem","path","PermissionError","FileNotFoundError","StaleFileError","WorkspaceReadOnlyError","DirectoryNotFoundError","FileExistsError","IsDirectoryError","NotDirectoryError","DirectoryNotEmptyError","FilesystemError"],"sources":["../src/sandbox/process-manager.ts","../src/sandbox/index.ts","../src/filesystem/index.ts"],"sourcesContent":["/**\n * Modal process manager. Each spawn() creates a ContainerProcess via exec().\n * kill() has no SDK equivalent — it cancels stream readers locally; the remote\n * process runs until the sandbox timeout.\n */\n\nimport { ProcessHandle, UnsupportedStdinCloseError, SandboxProcessManager } from '@mastra/core/workspace';\nimport type { CommandResult, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';\nimport type { ContainerProcess } from 'modal';\nimport type { ModalSandbox } from './index';\n\n// =============================================================================\n// Modal Process Handle\n// =============================================================================\n\n/**\n * Wraps a Modal ContainerProcess to conform to Mastra's ProcessHandle.\n */\nclass ModalProcessHandle extends ProcessHandle {\n readonly pid: string;\n\n private readonly _proc: ContainerProcess<string>;\n private readonly _startTime: number;\n private readonly _timeout?: number;\n\n private _exitCode: number | undefined;\n private _waitPromise: Promise<CommandResult> | null = null;\n private _streamingPromise: Promise<void> | null = null;\n private _killed = false;\n private _stdoutReader: ReadableStreamDefaultReader<string> | null = null;\n private _stderrReader: ReadableStreamDefaultReader<string> | null = null;\n\n constructor(pid: string, proc: ContainerProcess<string>, startTime: number, options?: SpawnProcessOptions) {\n super(options);\n this.pid = pid;\n this._proc = proc;\n this._startTime = startTime;\n this._timeout = options?.timeout;\n }\n\n get exitCode(): number | undefined {\n return this._exitCode;\n }\n\n /** @internal Set by the process manager after streaming starts. */\n set streamingPromise(p: Promise<void>) {\n this._streamingPromise = p;\n\n // Resolve exit code when streaming ends so exitCode is available without calling wait()\n p.then(() => this._resolveExitCode()).catch(() => this._resolveExitCode());\n }\n\n /** @internal Set by the process manager so kill() can cancel the readers. */\n setReaders(\n stdoutReader: ReadableStreamDefaultReader<string>,\n stderrReader: ReadableStreamDefaultReader<string>,\n ): void {\n this._stdoutReader = stdoutReader;\n this._stderrReader = stderrReader;\n }\n\n /** Fetch the exit code from the Modal process. No-op if already set. */\n private async _resolveExitCode(): Promise<void> {\n if (this._exitCode !== undefined) return;\n try {\n this._exitCode = await this._proc.wait();\n } catch {\n if (this._exitCode === undefined) {\n this._exitCode = 1;\n }\n }\n }\n\n async wait(): Promise<CommandResult> {\n if (!this._waitPromise) {\n this._waitPromise = this._doWait();\n }\n return this._waitPromise;\n }\n\n private async _doWait(): Promise<CommandResult> {\n const streamDone = this._streamingPromise ?? Promise.resolve();\n\n if (this._timeout) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(`Command timed out after ${this._timeout}ms`)), this._timeout);\n });\n\n try {\n await Promise.race([streamDone, timeoutPromise]);\n } catch (error) {\n if (error instanceof Error && error.message.includes('timed out')) {\n await this.kill();\n this._exitCode = 124; // conventional timeout exit code\n return {\n success: false,\n exitCode: 124,\n stdout: this.stdout,\n stderr: this.stderr || error.message,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: true,\n };\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n } else {\n await streamDone.catch(() => {});\n }\n\n if (this._killed) {\n return {\n success: false,\n exitCode: this._exitCode ?? 137,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n killed: true,\n timedOut: false,\n };\n }\n\n await this._resolveExitCode();\n\n return {\n success: this._exitCode === 0,\n exitCode: this._exitCode ?? 1,\n stdout: this.stdout,\n stderr: this.stderr,\n executionTimeMs: Date.now() - this._startTime,\n };\n }\n\n async kill(): Promise<boolean> {\n if (this._exitCode !== undefined) return false;\n this._killed = true;\n this._exitCode = 137; // SIGKILL\n // The remote process may continue running; Modal JS SDK has no per-exec kill.\n try {\n await this._stdoutReader?.cancel();\n } catch {\n // Ignore cancellation errors\n }\n try {\n await this._stderrReader?.cancel();\n } catch {\n // Ignore cancellation errors\n }\n return true;\n }\n\n async sendStdin(_data: string): Promise<void> {\n throw new Error('Modal JS SDK does not expose stdin on exec() — sendStdin() is not supported');\n }\n\n async closeStdin(): Promise<void> {\n throw new UnsupportedStdinCloseError(\n 'Modal JS SDK does not expose stdin on exec() — closeStdin() is not supported',\n );\n }\n}\n\n// =============================================================================\n// Modal Process Manager\n// =============================================================================\n\n/**\n * Modal implementation of SandboxProcessManager.\n * Uses the Modal SDK's exec() API with one ContainerProcess per spawn.\n */\nexport class ModalProcessManager extends SandboxProcessManager<ModalSandbox> {\n private _spawnCounter = 0;\n\n async spawn(command: string, options: SpawnProcessOptions = {}): Promise<ProcessHandle> {\n return this.sandbox.retryOnDead(async () => {\n const sb = this.sandbox.modal;\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 // exec() takes string[] — wrap in sh -c to support pipes, redirects, etc.\n const argv = ['sh', '-c', command];\n\n const proc = await sb.exec(argv, {\n env: Object.keys(env).length > 0 ? env : undefined,\n workdir: options.cwd ?? this.sandbox.workingDirectory,\n timeoutMs: options.timeout,\n });\n\n const pid = `modal-proc-${Date.now().toString(36)}-${++this._spawnCounter}`;\n const handle = new ModalProcessHandle(pid, proc, Date.now(), options);\n\n const stdoutReader = proc.stdout.getReader();\n const stderrReader = proc.stderr.getReader();\n handle.setReaders(stdoutReader, stderrReader);\n\n const streamingPromise = Promise.all([\n drainReader(stdoutReader, chunk => handle.emitStdout(chunk)),\n drainReader(stderrReader, chunk => handle.emitStderr(chunk)),\n ]).then(() => {});\n\n handle.streamingPromise = streamingPromise;\n\n this._tracked.set(pid, handle);\n return handle;\n });\n }\n\n async list(): Promise<ProcessInfo[]> {\n const result: ProcessInfo[] = [];\n for (const [pid, handle] of this._tracked) {\n result.push({\n pid,\n command: handle.command,\n running: handle.exitCode === undefined,\n exitCode: handle.exitCode,\n });\n }\n return result;\n }\n}\n\n// =============================================================================\n// Stream Helpers\n// =============================================================================\n\n/** Reads chunks from a stream until done or cancelled. */\nasync function drainReader(reader: ReadableStreamDefaultReader<string>, emit: (chunk: string) => void): Promise<void> {\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n emit(value);\n }\n } catch {\n // cancelled or network error\n }\n}\n","/**\n * @see https://modal.com/docs/reference/modal.Sandbox\n */\n\nimport type { MastraSandboxOptions, ProviderStatus, SandboxCloneOptions, SandboxInfo } from '@mastra/core/workspace';\nimport { MastraSandbox, SandboxNotReadyError } from '@mastra/core/workspace';\nimport { ClientClosedError, ModalClient, NotFoundError } from 'modal';\nimport type { App, Image, Sandbox, SandboxReloadVolumesParams, Volume } from 'modal';\nimport { ModalProcessManager } from './process-manager';\n\nconst LOG_PREFIX = '[ModalSandbox]';\n\n// =============================================================================\n// Options\n// =============================================================================\n\ntype InstructionsOption = string | ((opts: { defaultInstructions: string }) => string);\n\n/**\n * Modal sandbox provider configuration.\n */\nexport interface ModalSandboxOptions extends Omit<MastraSandboxOptions, 'processes'> {\n /** Stable name for this sandbox. Reusing the same id reconnects to a running sandbox. */\n id?: string;\n /**\n * Modal App name to associate sandboxes with.\n *\n * @default 'mastra'\n */\n appName?: string;\n /**\n * Docker image to use for the sandbox.\n *\n * @default 'ubuntu:22.04'\n */\n baseImage?: string;\n /**\n * Wall-clock max lifetime in milliseconds. The sandbox is terminated when this expires,\n * regardless of activity. Modal's maximum is 24 hours (86_400_000).\n *\n * @default 300_000 // 5 minutes\n */\n timeoutMs?: number;\n /** Environment variables baked into the sandbox at create time. */\n env?: Record<string, string>;\n /** Default working directory inside the sandbox.\n * @deprecated Use `workingDirectory` (the base sandbox option) instead.\n * When both are set, `workingDirectory` wins.\n */\n workdir?: string;\n /** Modal token ID. Falls back to MODAL_TOKEN_ID env var. */\n tokenId?: string;\n /** Modal token secret. Falls back to MODAL_TOKEN_SECRET env var. */\n tokenSecret?: string;\n /** Custom instructions for getInstructions(). String replaces the default; function receives it. */\n instructions?: InstructionsOption;\n /**\n * Modal Volumes to mount, keyed by absolute mount path inside the sandbox.\n *\n * The working directory must not be a mount path or sit inside one, otherwise\n * `reloadVolumes()` fails. Writes made by other sandboxes only become visible\n * in a long-lived sandbox after calling `reloadVolumes()`.\n *\n * @example\n * ```typescript\n * const volume = await modal.volumes.fromName('agent-files', { createIfMissing: true });\n * new ModalSandbox({ volumes: { '/mnt/agent': volume }, workingDirectory: '/workspace' });\n * ```\n */\n volumes?: Record<string, Volume>;\n}\n\n// =============================================================================\n// ModalSandbox\n// =============================================================================\n\n/**\n * Modal cloud sandbox provider for Mastra workspaces.\n *\n * @example\n * ```typescript\n * import { Workspace } from '@mastra/core/workspace';\n * import { ModalSandbox } from '@mastra/modal';\n *\n * const sandbox = new ModalSandbox({\n * baseImage: 'ubuntu:22.04',\n * timeoutMs: 60_000,\n * });\n *\n * const workspace = new Workspace({ sandbox });\n * const result = await workspace.executeCommand('echo hello');\n * ```\n */\nexport class ModalSandbox extends MastraSandbox {\n readonly id: string;\n readonly name = 'ModalSandbox';\n readonly provider = 'modal';\n status: ProviderStatus = 'pending';\n\n declare readonly processes: ModalProcessManager;\n\n private _sb: Sandbox | null = null;\n private _imageSnapshot: Image | null = null; // for stop-and-resume\n private _client: ModalClient | null = null;\n private _createdAt: Date | null = null;\n private _isRetrying = false;\n\n private readonly appName: string;\n private readonly baseImage: string;\n private readonly timeoutMs: number;\n private readonly env: Record<string, string>;\n private readonly tokenId?: string;\n private readonly tokenSecret?: string;\n private readonly _instructionsOverride?: InstructionsOption;\n private readonly volumes?: Record<string, Volume>;\n private readonly _constructorOptions: ModalSandboxOptions;\n\n constructor(options: ModalSandboxOptions = {}) {\n super({\n ...options,\n name: 'ModalSandbox',\n processes: new ModalProcessManager(),\n });\n\n this.id = options.id ?? this._generateId();\n this.appName = options.appName ?? 'mastra';\n this.baseImage = options.baseImage ?? 'ubuntu:22.04';\n this.timeoutMs = options.timeoutMs ?? 300_000;\n this.env = options.env ?? {};\n if (options.workingDirectory === undefined && options.workdir !== undefined) {\n this.setWorkingDirectory(options.workdir);\n }\n this.tokenId = options.tokenId;\n this.tokenSecret = options.tokenSecret;\n this._instructionsOverride = options.instructions;\n this.volumes = options.volumes && Object.keys(options.volumes).length > 0 ? options.volumes : undefined;\n this._assertWorkdirOutsideVolumes();\n this._constructorOptions = { ...options };\n }\n\n /**\n * Construct a sibling `ModalSandbox` that inherits this sandbox's\n * configuration (credentials, app, base image, workdir, instructions) with\n * per-instance overrides.\n *\n * Performs no I/O — the sandbox clone provisions (or reconnects to a\n * running Modal sandbox with the same logical `id`) on its own `start()`.\n * Use it when one configured sandbox acts as the template for a fleet of\n * independent sandboxes (e.g. one per project).\n *\n * `options.idleTimeoutMinutes` maps to Modal's `timeoutMs` (wall-clock\n * lifetime); `options.sandboxId` is ignored because Modal reconnects by\n * logical `id`.\n */\n clone(options: SandboxCloneOptions = {}): ModalSandbox {\n const { id: _id, ...base } = this._constructorOptions;\n return new ModalSandbox({\n ...base,\n ...(options.id !== undefined && { id: options.id }),\n ...(options.env !== undefined && { env: options.env }),\n ...(options.workingDirectory !== undefined && { workingDirectory: options.workingDirectory }),\n ...(options.idleTimeoutMinutes !== undefined && { timeoutMs: options.idleTimeoutMinutes * 60_000 }),\n });\n }\n\n /**\n * Get the underlying Modal Sandbox instance for direct SDK access.\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started.\n */\n get modal(): Sandbox {\n if (!this._sb) {\n throw new SandboxNotReadyError(this.id);\n }\n return this._sb;\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /** Reconnects to a running sandbox with this id if one exists, otherwise creates a new one. */\n async start(): Promise<void> {\n if (this._sb) {\n return;\n }\n\n const client = this._getClient();\n\n try {\n this._sb = await client.sandboxes.fromName(this.appName, this.id);\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Reconnected to running sandbox: ${this.id}`);\n return;\n } catch (error) {\n if (!(error instanceof NotFoundError)) {\n throw error;\n }\n }\n\n const app: App = await client.apps.fromName(this.appName, { createIfMissing: true });\n\n if (this._imageSnapshot) {\n this.logger.debug(`${LOG_PREFIX} Rebooting from snapshot: ${this.id}`);\n this._sb = await client.sandboxes.create(app, this._imageSnapshot, {\n name: this.id,\n timeoutMs: this.timeoutMs,\n env: Object.keys(this.env).length > 0 ? this.env : undefined,\n workdir: this.workingDirectory,\n volumes: this.volumes,\n });\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Created new sandbox from snapshot: ${this._sb?.sandboxId}`);\n return;\n }\n\n const image: Image = client.images.fromRegistry(this.baseImage);\n this.logger.debug(`${LOG_PREFIX} Creating sandbox: ${this.id} (baseImage: ${this.baseImage})`);\n this._sb = await client.sandboxes.create(app, image, {\n name: this.id,\n timeoutMs: this.timeoutMs,\n env: Object.keys(this.env).length > 0 ? this.env : undefined,\n workdir: this.workingDirectory,\n volumes: this.volumes,\n });\n this._createdAt = new Date();\n this.logger.debug(`${LOG_PREFIX} Created sandbox: ${this._sb.sandboxId}`);\n }\n\n /**\n * Snapshot the sandbox filesystem before terminating it.\n * Future starts will create net-new sandboxes from the snapshot.\n */\n async stop(): Promise<void> {\n if (!this._sb) return;\n\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.filter(p => p.running).map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n try {\n this._imageSnapshot = await this._sb.snapshotFilesystem();\n this.logger.debug(`${LOG_PREFIX} Snapshot created: ${this._imageSnapshot.imageId}`);\n } catch (error) {\n this.logger.debug(`${LOG_PREFIX} Snapshot failed, terminating without snapshot:`, error);\n }\n\n try {\n await this._sb.terminate({ wait: true });\n this.logger.debug(`${LOG_PREFIX} Sandbox terminated: ${this._sb.sandboxId}`);\n this._sb = null;\n } catch (error) {\n // Best-effort: sandbox may already be dead\n if (this.isSandboxDeadError(error)) {\n this._sb = null;\n } else {\n throw error;\n }\n }\n }\n\n /** Terminates the sandbox, ending its lifetime. Unlike stop(), no snapshot is preserved. */\n async destroy(): Promise<void> {\n if (this._sb) {\n try {\n const procs = await this.processes.list();\n await Promise.all(procs.filter(p => p.running).map(p => this.processes.kill(p.pid)));\n } catch {\n // Best-effort: sandbox may already be dead\n }\n\n try {\n await this._sb.terminate();\n this.logger.debug(`${LOG_PREFIX} Sandbox terminated: ${this._sb.sandboxId}`);\n } catch {\n // Ignore errors during destroy\n }\n\n this._sb = null;\n }\n\n this._imageSnapshot = null;\n }\n\n /**\n * Reload all Volumes mounted in the sandbox so it sees writes committed by\n * other sandboxes or clients.\n *\n * @throws {SandboxNotReadyError} If the sandbox has not been started.\n */\n async reloadVolumes(params?: SandboxReloadVolumesParams): Promise<void> {\n await this.retryOnDead(() => this.modal.reloadVolumes(params));\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 appName: this.appName,\n image: this._imageSnapshot?.imageId ?? this.baseImage,\n timeoutMs: this.timeoutMs,\n },\n };\n }\n\n getInstructions(): string {\n const defaultInstructions = this._getDefaultInstructions();\n if (this._instructionsOverride === undefined) return defaultInstructions;\n if (typeof this._instructionsOverride === 'string') return this._instructionsOverride;\n return this._instructionsOverride({ defaultInstructions });\n }\n\n private _getDefaultInstructions(): string {\n return `Modal cloud sandbox running ${this.baseImage}. Use executeCommand() to run shell commands.`;\n }\n\n // ---------------------------------------------------------------------------\n // Dead-sandbox Retry\n // ---------------------------------------------------------------------------\n\n private isSandboxDeadError(error: unknown): boolean {\n if (!error) return false;\n if (error instanceof ClientClosedError) return true;\n if (error instanceof NotFoundError) return true;\n const errorStr = String(error);\n return (\n errorStr.includes('sandbox not found') ||\n errorStr.includes('has been terminated') ||\n errorStr.includes('already completed') ||\n errorStr.includes('was cancelled') ||\n // gRPC NOT_FOUND (code 5)\n /status[:\\s]+5\\b/.test(errorStr) ||\n errorStr.includes('NOT_FOUND')\n );\n }\n\n private handleSandboxDead(): void {\n this._sb = null;\n this.status = 'stopped';\n }\n\n /** @internal Retries fn() once after restarting if the sandbox is dead. */\n async retryOnDead<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (this.isSandboxDeadError(error) && !this._isRetrying) {\n this.handleSandboxDead();\n this._isRetrying = true;\n try {\n await this.ensureRunning();\n return await fn();\n } finally {\n this._isRetrying = false;\n }\n }\n throw error;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Internal Helpers\n // ---------------------------------------------------------------------------\n\n private _assertWorkdirOutsideVolumes(): void {\n const workdir = this.workingDirectory;\n if (!this.volumes || !workdir) return;\n const normalize = (p: string) => {\n let end = p.length;\n while (end > 1 && p[end - 1] === '/') end--;\n return p.slice(0, end);\n };\n const dir = normalize(workdir);\n for (const mountPath of Object.keys(this.volumes)) {\n const mount = normalize(mountPath);\n if (dir === mount || dir.startsWith(`${mount}/`)) {\n throw new Error(\n `${LOG_PREFIX} workingDirectory \"${workdir}\" must be outside Volume mount \"${mountPath}\"; reloadVolumes() fails when the working directory is inside a mount.`,\n );\n }\n }\n }\n\n private _generateId(): string {\n return `modal-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n }\n\n private _getClient(): ModalClient {\n if (!this._client) {\n this._client = new ModalClient({\n ...(this.tokenId && { tokenId: this.tokenId }),\n ...(this.tokenSecret && { tokenSecret: this.tokenSecret }),\n });\n }\n return this._client;\n }\n}\n","/**\n * Modal filesystem provider.\n *\n * A WorkspaceFilesystem backed by a running ModalSandbox. Every operation runs\n * a fixed POSIX shell script inside the sandbox with paths passed as positional\n * arguments (never interpolated), so it works for any path the sandbox can see,\n * including Modal Volume mounts.\n */\n\nimport { posix } from 'node:path';\n\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemIcon,\n FilesystemInfo,\n ListOptions,\n MastraFilesystemOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport {\n DirectoryNotEmptyError,\n DirectoryNotFoundError,\n FileExistsError,\n FileNotFoundError,\n FilesystemError,\n IsDirectoryError,\n MastraFilesystem,\n NotDirectoryError,\n PermissionError,\n StaleFileError,\n WorkspaceReadOnlyError,\n} from '@mastra/core/workspace';\n\nimport type { ModalSandbox } from '../sandbox';\n\nexport interface ModalFilesystemOptions extends MastraFilesystemOptions {\n /** Unique identifier for this filesystem instance */\n id?: string;\n /** Sandbox the filesystem operates through. The filesystem does not own its lifecycle. */\n sandbox: ModalSandbox;\n /**\n * Absolute directory inside the sandbox that workspace paths resolve against,\n * typically a Volume mount path (e.g. `/mnt/agent`). Paths cannot escape it.\n */\n basePath: string;\n /** Reject all write operations */\n readOnly?: boolean;\n /** Human-friendly display name for the UI */\n displayName?: string;\n /** Description shown in tooltips */\n description?: string;\n}\n\n/** Exit codes used by the in-sandbox scripts. */\nconst EXIT = { NOT_FOUND: 2, EXISTS: 3, IS_DIR: 4, NOT_DIR: 5, NOT_EMPTY: 6, NO_PARENT: 7, OUTSIDE: 8 } as const;\n\n/**\n * Runs before every script. Receives `basePath` and the number of leading path\n * arguments, then shifts them off. Each path is resolved through symlinks\n * (resolving the deepest existing ancestor for paths that don't exist yet) and\n * rejected when it lands outside `basePath`. Uses only POSIX sh + `readlink -f`,\n * which GNU coreutils and BusyBox both provide.\n */\nconst CONFINE = `b=$(readlink -f -- \"$1\") || exit ${EXIT.OUTSIDE}; n=$2; shift 2; canon() { p=$1; rest=; while [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; do rest=/$(basename -- \"$p\")$rest; p=$(dirname -- \"$p\"); done; r=$(readlink -f -- \"$p\") || return 1; printf '%s%s' \"$r\" \"$rest\"; }; i=0; for a; do [ \"$i\" -lt \"$n\" ] || break; r=$(canon \"$a\") || exit ${EXIT.OUTSIDE}; case \"$r\" in \"$b\"|\"$b\"/*) ;; *) exit ${EXIT.OUTSIDE};; esac; i=$((i+1)); done;`;\n\n// Scripts receive `$0` = script name and positional args; paths are always quoted.\nconst PARENT_CHECK = `d=$(dirname -- \"$1\"); if [ ! -d \"$d\" ]; then if [ \"$2\" = 1 ]; then mkdir -p -- \"$d\" || exit 1; else exit ${EXIT.NO_PARENT}; fi; fi; [ -d \"$1\" ] && exit ${EXIT.IS_DIR};`;\n\nconst SCRIPTS = {\n read: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; [ -d \"$1\" ] && exit ${EXIT.IS_DIR}; cat -- \"$1\"`,\n write: `${PARENT_CHECK} [ \"$3\" = 0 ] && [ -e \"$1\" ] && exit ${EXIT.EXISTS}; cat > \"$1\"`,\n append: `${PARENT_CHECK} cat >> \"$1\"`,\n deleteFile: `if [ ! -e \"$1\" ] && [ ! -L \"$1\" ]; then [ \"$2\" = 1 ] && exit 0; exit ${EXIT.NOT_FOUND}; fi; [ -d \"$1\" ] && exit ${EXIT.IS_DIR}; rm -f -- \"$1\"`,\n // $1 src, $2 dest, $3 recursive, $4 overwrite, $5 op (cp|mv)\n transfer: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; if [ -d \"$1\" ] && [ \"$5\" = cp ] && [ \"$3\" != 1 ]; then exit ${EXIT.IS_DIR}; fi; if [ -e \"$2\" ]; then [ \"$1\" -ef \"$2\" ] && exit ${EXIT.EXISTS}; [ \"$4\" = 0 ] && exit ${EXIT.EXISTS}; rm -rf -- \"$2\"; fi; mkdir -p -- \"$(dirname -- \"$2\")\" || exit 1; if [ \"$5\" = mv ]; then mv -- \"$1\" \"$2\"; else cp -R -- \"$1\" \"$2\"; fi`,\n mkdir: `if [ \"$2\" = 1 ]; then [ -e \"$1\" ] && [ ! -d \"$1\" ] && exit ${EXIT.EXISTS}; mkdir -p -- \"$1\"; else [ -e \"$1\" ] && exit ${EXIT.EXISTS}; [ -d \"$(dirname -- \"$1\")\" ] || exit ${EXIT.NO_PARENT}; mkdir -- \"$1\"; fi`,\n rmdir: `if [ ! -e \"$1\" ]; then [ \"$3\" = 1 ] && exit 0; exit ${EXIT.NOT_FOUND}; fi; [ -d \"$1\" ] || exit ${EXIT.NOT_DIR}; if [ \"$2\" = 1 ]; then rm -rf -- \"$1\"; else [ -z \"$(ls -A -- \"$1\")\" ] || exit ${EXIT.NOT_EMPTY}; rmdir -- \"$1\"; fi`,\n // Emits NUL-separated records: target type, own type, size, relative path, link target.\n readdir: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; [ -d \"$1\" ] || exit ${EXIT.NOT_DIR}; find \"$1\" -mindepth 1 -maxdepth \"$2\" -exec sh -c 'b=$1; shift; for p; do if [ -d \"$p\" ]; then t=d; else t=f; fi; o=$t; l=; if [ -L \"$p\" ]; then o=l; l=$(readlink -- \"$p\"); fi; s=0; if [ \"$o\" = f ]; then s=$(($(wc -c < \"$p\"))); fi; printf \"%s\\\\0%s\\\\0%s\\\\0%s\\\\0%s\\\\0\" \"$t\" \"$o\" \"$s\" \"\\${p#\"$b\"/}\" \"$l\"; done' sh \"$1\" {} +`,\n exists: `[ -e \"$1\" ]`,\n // Emits: type, size, birth time, modification time (epoch seconds).\n stat: `[ -e \"$1\" ] || exit ${EXIT.NOT_FOUND}; stat -L -c '%F|%s|%W|%Y' -- \"$1\"`,\n} as const;\n\nconst DEFAULT_MAX_DEPTH = 100;\n\ninterface ExecResult {\n exitCode: number;\n stdout: Uint8Array;\n stderr: string;\n}\n\nfunction toBytes(content: FileContent): Uint8Array {\n return typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content);\n}\n\nfunction flag(value: boolean): string {\n return value ? '1' : '0';\n}\n\nfunction matchesExtension(name: string, extension: string | string[]): boolean {\n const ext = posix.extname(name);\n const extensions = Array.isArray(extension) ? extension : [extension];\n return extensions.some(e => e === ext || e === ext.slice(1));\n}\n\n/**\n * Workspace filesystem that reads and writes files inside a Modal Sandbox.\n *\n * Mount a Modal Volume on the sandbox and point `basePath` at the mount to give\n * agents persistent files that survive sandbox restarts.\n *\n * @example\n * ```typescript\n * import { Volume } from 'modal';\n * import { Workspace } from '@mastra/core/workspace';\n * import { ModalSandbox, ModalFilesystem } from '@mastra/modal';\n *\n * const volume = await modal.volumes.fromName('agent-files', { createIfMissing: true });\n * const sandbox = new ModalSandbox({ volumes: { '/mnt/agent': volume }, workingDirectory: '/workspace' });\n * const filesystem = new ModalFilesystem({ sandbox, basePath: '/mnt/agent' });\n *\n * const workspace = new Workspace({ sandbox, filesystem });\n * ```\n */\nexport class ModalFilesystem extends MastraFilesystem {\n readonly id: string;\n readonly name = 'ModalFilesystem';\n readonly provider = 'modal';\n readonly readOnly?: boolean;\n readonly displayName?: string;\n readonly description?: string;\n readonly icon: FilesystemIcon = 'folder';\n readonly basePath: string;\n\n status: ProviderStatus = 'pending';\n\n private readonly sandbox: ModalSandbox;\n /** Serializes stdin-streaming execs; concurrent stdin writes can wedge a Modal exec. */\n private _writeQueue: Promise<unknown> = Promise.resolve();\n\n constructor(options: ModalFilesystemOptions) {\n super({ ...options, name: 'ModalFilesystem' });\n if (!posix.isAbsolute(options.basePath)) {\n throw new Error(`[ModalFilesystem] basePath must be absolute, got \"${options.basePath}\"`);\n }\n this.id = options.id ?? `modal-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n this.sandbox = options.sandbox;\n this.basePath = posix.normalize(options.basePath).replace(/(.)\\/$/, '$1');\n this.readOnly = options.readOnly;\n this.displayName = options.displayName;\n this.description = options.description;\n }\n\n async init(): Promise<void> {\n await this.sandbox.ensureRunning();\n }\n\n getInfo(): FilesystemInfo<{ basePath: string }> {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n readOnly: this.readOnly,\n icon: this.icon,\n metadata: { basePath: this.basePath },\n };\n }\n\n getInstructions(): string {\n const access = this.readOnly ? 'Read-only' : 'Persistent';\n return `${access} files stored at ${this.basePath} inside the Modal sandbox.`;\n }\n\n /**\n * Resolve a workspace path to an absolute sandbox path under `basePath`.\n * Rejects paths that would escape the base directory.\n */\n resolvePath(path: string): string {\n const relative = posix.normalize(`./${path.replace(/^\\/+/, '')}`).replace(/\\/$/, '') || '.';\n if (relative === '..' || relative.startsWith('../')) {\n throw new PermissionError(path, 'access outside filesystem base path');\n }\n return relative === '.' ? this.basePath : posix.join(this.basePath, relative);\n }\n\n // ---------------------------------------------------------------------------\n // File operations\n // ---------------------------------------------------------------------------\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const { stdout } = await this.run('read', [this.resolvePath(path)], path);\n const buffer = Buffer.from(stdout);\n return options?.encoding ? buffer.toString(options.encoding) : buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n this.assertWritable('writeFile');\n if (options?.expectedMtime) {\n const current = await this.stat(path).catch(error => {\n if (error instanceof FileNotFoundError) return undefined;\n throw error;\n });\n if (current && current.modifiedAt.getTime() !== options.expectedMtime.getTime()) {\n throw new StaleFileError(path, options.expectedMtime, current.modifiedAt);\n }\n }\n const args = [this.resolvePath(path), flag(options?.recursive !== false), flag(options?.overwrite !== false)];\n await this.run('write', args, path, toBytes(content));\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n this.assertWritable('appendFile');\n await this.run('append', [this.resolvePath(path), '1'], path, toBytes(content));\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n this.assertWritable('deleteFile');\n await this.run('deleteFile', [this.resolvePath(path), flag(!!options?.force)], path);\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n this.assertWritable('copyFile');\n await this.transfer('cp', src, dest, options);\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n this.assertWritable('moveFile');\n await this.transfer('mv', src, dest, options);\n }\n\n // ---------------------------------------------------------------------------\n // Directory operations\n // ---------------------------------------------------------------------------\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n this.assertWritable('mkdir');\n await this.run('mkdir', [this.resolvePath(path), flag(options?.recursive !== false)], path, undefined, true);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n this.assertWritable('rmdir');\n const resolved = this.resolvePath(path);\n if (resolved === this.basePath) {\n throw new PermissionError(path, 'remove filesystem base path');\n }\n await this.run('rmdir', [resolved, flag(!!options?.recursive), flag(!!options?.force)], path, undefined, true);\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;\n const { stdout } = await this.run('readdir', [this.resolvePath(path), String(depth)], path, undefined, true);\n\n const fields = new TextDecoder().decode(stdout).split('\\0');\n const entries: FileEntry[] = [];\n for (let i = 0; i + 4 < fields.length; i += 5) {\n const [targetType, ownType, size, name, linkTarget] = fields.slice(i, i + 5) as [\n string,\n string,\n string,\n string,\n string,\n ];\n const type = targetType === 'd' ? 'directory' : 'file';\n const isSymlink = ownType === 'l';\n if (options?.extension && type === 'file' && !matchesExtension(name, options.extension)) continue;\n\n const entry: FileEntry = { name, type };\n if (isSymlink) {\n entry.isSymlink = true;\n entry.symlinkTarget = linkTarget;\n } else if (type === 'file') {\n entry.size = Number(size);\n }\n entries.push(entry);\n }\n return entries;\n }\n\n // ---------------------------------------------------------------------------\n // Path operations\n // ---------------------------------------------------------------------------\n\n async exists(path: string): Promise<boolean> {\n const { exitCode } = await this.exec('exists', [this.resolvePath(path)]);\n return exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const resolved = this.resolvePath(path);\n const { stdout } = await this.run('stat', [resolved], path);\n const [kind = '', size = '0', birth = '0', mtime = '0'] = new TextDecoder().decode(stdout).trim().split('|');\n const type = kind === 'directory' ? 'directory' : 'file';\n const modifiedAt = new Date(Number(mtime) * 1000);\n const birthSeconds = Number(birth);\n return {\n name: posix.basename(resolved),\n path: resolved,\n type,\n size: type === 'directory' ? 0 : Number(size),\n createdAt: birthSeconds > 0 ? new Date(birthSeconds * 1000) : modifiedAt,\n modifiedAt,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internals\n // ---------------------------------------------------------------------------\n\n private assertWritable(operation: string): void {\n if (this.readOnly) throw new WorkspaceReadOnlyError(operation);\n }\n\n private async transfer(op: 'cp' | 'mv', src: string, dest: string, options?: CopyOptions): Promise<void> {\n const args = [\n this.resolvePath(src),\n this.resolvePath(dest),\n flag(!!options?.recursive),\n flag(options?.overwrite !== false),\n op,\n ];\n await this.run('transfer', args, src);\n }\n\n /** Run a script and translate non-zero exit codes into filesystem errors. */\n private async run(\n script: keyof typeof SCRIPTS,\n args: string[],\n path: string,\n stdin?: Uint8Array,\n directoryOp = false,\n ): Promise<ExecResult> {\n const result = await this.exec(script, args, stdin);\n switch (result.exitCode) {\n case 0:\n return result;\n case EXIT.NOT_FOUND:\n throw directoryOp ? new DirectoryNotFoundError(path) : new FileNotFoundError(path);\n case EXIT.NO_PARENT:\n throw new DirectoryNotFoundError(posix.dirname(path));\n case EXIT.EXISTS:\n throw new FileExistsError(path);\n case EXIT.IS_DIR:\n throw new IsDirectoryError(path);\n case EXIT.NOT_DIR:\n throw new NotDirectoryError(path);\n case EXIT.NOT_EMPTY:\n throw new DirectoryNotEmptyError(path);\n case EXIT.OUTSIDE:\n throw new PermissionError(path, 'access outside filesystem base path');\n default: {\n const message = result.stderr.trim();\n if (/permission denied|read-only file system/i.test(message)) {\n throw new PermissionError(path, script);\n }\n throw new FilesystemError(\n `[ModalFilesystem] ${script} failed for ${path} (exit ${result.exitCode})${message ? `: ${message}` : ''}`,\n 'EIO',\n path,\n );\n }\n }\n }\n\n private async exec(script: keyof typeof SCRIPTS, args: string[], stdin?: Uint8Array): Promise<ExecResult> {\n await this.ensureReady();\n const execute = async (): Promise<ExecResult> => {\n const pathCount = script === 'transfer' ? '2' : '1';\n const command = ['sh', '-c', `${CONFINE} ${SCRIPTS[script]}`, script, this.basePath, pathCount, ...args];\n const proc = await this.sandbox.modal.exec(command, {\n mode: 'binary',\n });\n if (stdin) {\n await proc.stdin.writeBytes(stdin);\n }\n await proc.stdin.close();\n const [stdout, stderr, exitCode] = await Promise.all([\n proc.stdout.readBytes(),\n proc.stderr.readBytes(),\n proc.wait(),\n ]);\n return { exitCode, stdout, stderr: new TextDecoder().decode(stderr) };\n };\n // Append isn't idempotent: the bytes may already be applied when the process dies, so never replay it.\n const runOnce = () => (script === 'append' ? execute() : this.sandbox.retryOnDead(execute));\n\n if (!stdin) return runOnce();\n\n const next = this._writeQueue.then(runOnce, runOnce);\n this._writeQueue = next.catch(() => {});\n return next;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAM,qBAAN,cAAiCA,uBAAAA,cAAc;CAC7C;CAEA;CACA;CACA;CAEA;CACA,eAAsD;CACtD,oBAAkD;CAClD,UAAkB;CAClB,gBAAoE;CACpE,gBAAoE;CAEpE,YAAY,KAAa,MAAgC,WAAmB,SAA+B;EACzG,MAAM,OAAO;EACb,KAAK,MAAM;EACX,KAAK,QAAQ;EACb,KAAK,aAAa;EAClB,KAAK,WAAW,SAAS;CAC3B;CAEA,IAAI,WAA+B;EACjC,OAAO,KAAK;CACd;;CAGA,IAAI,iBAAiB,GAAkB;EACrC,KAAK,oBAAoB;EAGzB,EAAE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.2",
4
4
  "description": "Modal cloud sandbox provider for Mastra workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -27,14 +27,13 @@
27
27
  "@vitest/coverage-v8": "4.1.11",
28
28
  "@vitest/ui": "4.1.11",
29
29
  "dotenv": "^17.4.2",
30
- "eslint": "^10.7.0",
31
30
  "tsdown": "0.22.9",
32
31
  "typescript": "^7.0.2",
33
32
  "vitest": "4.1.11",
34
- "@internal/lint": "0.0.144",
35
- "@mastra/core": "1.78.1-alpha.0",
36
- "@internal/workspace-test-utils": "0.0.88",
37
- "@internal/types-builder": "0.0.119"
33
+ "@internal/types-builder": "0.0.120",
34
+ "@internal/lint": "0.0.145",
35
+ "@internal/workspace-test-utils": "0.0.89",
36
+ "@mastra/core": "1.79.0"
38
37
  },
39
38
  "peerDependencies": {
40
39
  "@mastra/core": ">=1.12.0-0 <2.0.0-0"
@@ -62,7 +61,7 @@
62
61
  "test:watch": "vitest watch",
63
62
  "test": "vitest run ./src/**/*.integration.test.ts",
64
63
  "test:cloud": "pnpm test",
65
- "lint": "oxlint . && eslint .",
66
- "lint:fix": "oxlint --fix . && eslint --fix ."
64
+ "lint": "oxlint --type-aware .",
65
+ "lint:fix": "oxlint --type-aware --fix ."
67
66
  }
68
67
  }