@mastra/modal 0.6.0-alpha.1 → 0.7.0-alpha.0

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.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Modal filesystem provider.
3
+ *
4
+ * A WorkspaceFilesystem backed by a running ModalSandbox. Every operation runs
5
+ * a fixed POSIX shell script inside the sandbox with paths passed as positional
6
+ * arguments (never interpolated), so it works for any path the sandbox can see,
7
+ * including Modal Volume mounts.
8
+ */
9
+ import type { CopyOptions, FileContent, FileEntry, FileStat, FilesystemIcon, FilesystemInfo, ListOptions, MastraFilesystemOptions, ProviderStatus, ReadOptions, RemoveOptions, WriteOptions } from '@mastra/core/workspace';
10
+ import { MastraFilesystem } from '@mastra/core/workspace';
11
+ import type { ModalSandbox } from '../sandbox/index.js';
12
+ export interface ModalFilesystemOptions extends MastraFilesystemOptions {
13
+ /** Unique identifier for this filesystem instance */
14
+ id?: string;
15
+ /** Sandbox the filesystem operates through. The filesystem does not own its lifecycle. */
16
+ sandbox: ModalSandbox;
17
+ /**
18
+ * Absolute directory inside the sandbox that workspace paths resolve against,
19
+ * typically a Volume mount path (e.g. `/mnt/agent`). Paths cannot escape it.
20
+ */
21
+ basePath: string;
22
+ /** Reject all write operations */
23
+ readOnly?: boolean;
24
+ /** Human-friendly display name for the UI */
25
+ displayName?: string;
26
+ /** Description shown in tooltips */
27
+ description?: string;
28
+ }
29
+ /**
30
+ * Workspace filesystem that reads and writes files inside a Modal Sandbox.
31
+ *
32
+ * Mount a Modal Volume on the sandbox and point `basePath` at the mount to give
33
+ * agents persistent files that survive sandbox restarts.
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * import { Volume } from 'modal';
38
+ * import { Workspace } from '@mastra/core/workspace';
39
+ * import { ModalSandbox, ModalFilesystem } from '@mastra/modal';
40
+ *
41
+ * const volume = await modal.volumes.fromName('agent-files', { createIfMissing: true });
42
+ * const sandbox = new ModalSandbox({ volumes: { '/mnt/agent': volume }, workingDirectory: '/workspace' });
43
+ * const filesystem = new ModalFilesystem({ sandbox, basePath: '/mnt/agent' });
44
+ *
45
+ * const workspace = new Workspace({ sandbox, filesystem });
46
+ * ```
47
+ */
48
+ export declare class ModalFilesystem extends MastraFilesystem {
49
+ readonly id: string;
50
+ readonly name = "ModalFilesystem";
51
+ readonly provider = "modal";
52
+ readonly readOnly?: boolean;
53
+ readonly displayName?: string;
54
+ readonly description?: string;
55
+ readonly icon: FilesystemIcon;
56
+ readonly basePath: string;
57
+ status: ProviderStatus;
58
+ private readonly sandbox;
59
+ /** Serializes stdin-streaming execs; concurrent stdin writes can wedge a Modal exec. */
60
+ private _writeQueue;
61
+ constructor(options: ModalFilesystemOptions);
62
+ init(): Promise<void>;
63
+ getInfo(): FilesystemInfo<{
64
+ basePath: string;
65
+ }>;
66
+ getInstructions(): string;
67
+ /**
68
+ * Resolve a workspace path to an absolute sandbox path under `basePath`.
69
+ * Rejects paths that would escape the base directory.
70
+ */
71
+ resolvePath(path: string): string;
72
+ readFile(path: string, options?: ReadOptions): Promise<string | Buffer>;
73
+ writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void>;
74
+ appendFile(path: string, content: FileContent): Promise<void>;
75
+ deleteFile(path: string, options?: RemoveOptions): Promise<void>;
76
+ copyFile(src: string, dest: string, options?: CopyOptions): Promise<void>;
77
+ moveFile(src: string, dest: string, options?: CopyOptions): Promise<void>;
78
+ mkdir(path: string, options?: {
79
+ recursive?: boolean;
80
+ }): Promise<void>;
81
+ rmdir(path: string, options?: RemoveOptions): Promise<void>;
82
+ readdir(path: string, options?: ListOptions): Promise<FileEntry[]>;
83
+ exists(path: string): Promise<boolean>;
84
+ stat(path: string): Promise<FileStat>;
85
+ private assertWritable;
86
+ private transfer;
87
+ /** Run a script and translate non-zero exit codes into filesystem errors. */
88
+ private run;
89
+ private exec;
90
+ }
91
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d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AAO,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CA4BvE;IAMK,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAG3C;IAEK,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAe1C;IAMD,OAAO,CAAC,cAAc;YAIR,QAAQ;IAWtB,6EAA6E;YAC/D,GAAG;YAuCH,IAAI;CA4BnB"}
package/dist/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _mastra_core_workspace = require("@mastra/core/workspace");
3
3
  let modal = require("modal");
4
+ let path = require("path");
4
5
  //#region src/sandbox/process-manager.ts
5
6
  /**
6
7
  * Modal process manager. Each spawn() creates a ContainerProcess via exec().
@@ -208,6 +209,7 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
208
209
  tokenId;
209
210
  tokenSecret;
210
211
  _instructionsOverride;
212
+ volumes;
211
213
  _constructorOptions;
212
214
  constructor(options = {}) {
213
215
  super({
@@ -224,6 +226,8 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
224
226
  this.tokenId = options.tokenId;
225
227
  this.tokenSecret = options.tokenSecret;
226
228
  this._instructionsOverride = options.instructions;
229
+ this.volumes = options.volumes && Object.keys(options.volumes).length > 0 ? options.volumes : void 0;
230
+ this._assertWorkdirOutsideVolumes();
227
231
  this._constructorOptions = { ...options };
228
232
  }
229
233
  /**
@@ -277,7 +281,8 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
277
281
  name: this.id,
278
282
  timeoutMs: this.timeoutMs,
279
283
  env: Object.keys(this.env).length > 0 ? this.env : void 0,
280
- workdir: this.workingDirectory
284
+ workdir: this.workingDirectory,
285
+ volumes: this.volumes
281
286
  });
282
287
  this._createdAt = /* @__PURE__ */ new Date();
283
288
  this.logger.debug(`${LOG_PREFIX} Created new sandbox from snapshot: ${this._sb?.sandboxId}`);
@@ -289,7 +294,8 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
289
294
  name: this.id,
290
295
  timeoutMs: this.timeoutMs,
291
296
  env: Object.keys(this.env).length > 0 ? this.env : void 0,
292
- workdir: this.workingDirectory
297
+ workdir: this.workingDirectory,
298
+ volumes: this.volumes
293
299
  });
294
300
  this._createdAt = /* @__PURE__ */ new Date();
295
301
  this.logger.debug(`${LOG_PREFIX} Created sandbox: ${this._sb.sandboxId}`);
@@ -334,6 +340,15 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
334
340
  }
335
341
  this._imageSnapshot = null;
336
342
  }
343
+ /**
344
+ * Reload all Volumes mounted in the sandbox so it sees writes committed by
345
+ * other sandboxes or clients.
346
+ *
347
+ * @throws {SandboxNotReadyError} If the sandbox has not been started.
348
+ */
349
+ async reloadVolumes(params) {
350
+ await this.retryOnDead(() => this.modal.reloadVolumes(params));
351
+ }
337
352
  async getInfo() {
338
353
  return {
339
354
  id: this.id,
@@ -386,6 +401,20 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
386
401
  throw error;
387
402
  }
388
403
  }
404
+ _assertWorkdirOutsideVolumes() {
405
+ const workdir = this.workingDirectory;
406
+ if (!this.volumes || !workdir) return;
407
+ const normalize = (p) => {
408
+ let end = p.length;
409
+ while (end > 1 && p[end - 1] === "/") end--;
410
+ return p.slice(0, end);
411
+ };
412
+ const dir = normalize(workdir);
413
+ for (const mountPath of Object.keys(this.volumes)) {
414
+ const mount = normalize(mountPath);
415
+ if (dir === mount || dir.startsWith(`${mount}/`)) throw new Error(`${LOG_PREFIX} workingDirectory "${workdir}" must be outside Volume mount "${mountPath}"; reloadVolumes() fails when the working directory is inside a mount.`);
416
+ }
417
+ }
389
418
  _generateId() {
390
419
  return `modal-sandbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
391
420
  }
@@ -398,6 +427,289 @@ var ModalSandbox = class ModalSandbox extends _mastra_core_workspace.MastraSandb
398
427
  }
399
428
  };
400
429
  //#endregion
430
+ //#region src/filesystem/index.ts
431
+ /**
432
+ * Modal filesystem provider.
433
+ *
434
+ * A WorkspaceFilesystem backed by a running ModalSandbox. Every operation runs
435
+ * a fixed POSIX shell script inside the sandbox with paths passed as positional
436
+ * arguments (never interpolated), so it works for any path the sandbox can see,
437
+ * including Modal Volume mounts.
438
+ */
439
+ /** Exit codes used by the in-sandbox scripts. */
440
+ const EXIT = {
441
+ NOT_FOUND: 2,
442
+ EXISTS: 3,
443
+ IS_DIR: 4,
444
+ NOT_DIR: 5,
445
+ NOT_EMPTY: 6,
446
+ NO_PARENT: 7,
447
+ OUTSIDE: 8
448
+ };
449
+ /**
450
+ * Runs before every script. Receives `basePath` and the number of leading path
451
+ * arguments, then shifts them off. Each path is resolved through symlinks
452
+ * (resolving the deepest existing ancestor for paths that don't exist yet) and
453
+ * rejected when it lands outside `basePath`. Uses only POSIX sh + `readlink -f`,
454
+ * which GNU coreutils and BusyBox both provide.
455
+ */
456
+ const 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;`;
457
+ const 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};`;
458
+ const SCRIPTS = {
459
+ read: `[ -e "$1" ] || exit ${EXIT.NOT_FOUND}; [ -d "$1" ] && exit ${EXIT.IS_DIR}; cat -- "$1"`,
460
+ write: `${PARENT_CHECK} [ "$3" = 0 ] && [ -e "$1" ] && exit ${EXIT.EXISTS}; cat > "$1"`,
461
+ append: `${PARENT_CHECK} cat >> "$1"`,
462
+ 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"`,
463
+ transfer: `[ -e "$1" ] || exit ${EXIT.NOT_FOUND}; if [ -d "$1" ] && [ "$5" = cp ] && [ "$3" != 1 ]; then exit ${EXIT.IS_DIR}; fi; if [ -e "$2" ]; then [ "$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`,
464
+ 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`,
465
+ 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`,
466
+ 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" {} +`,
467
+ exists: `[ -e "$1" ]`,
468
+ stat: `[ -e "$1" ] || exit ${EXIT.NOT_FOUND}; stat -L -c '%F|%s|%W|%Y' -- "$1"`
469
+ };
470
+ const DEFAULT_MAX_DEPTH = 100;
471
+ function toBytes(content) {
472
+ return typeof content === "string" ? new TextEncoder().encode(content) : new Uint8Array(content);
473
+ }
474
+ function flag(value) {
475
+ return value ? "1" : "0";
476
+ }
477
+ function matchesExtension(name, extension) {
478
+ const ext = path.posix.extname(name);
479
+ return (Array.isArray(extension) ? extension : [extension]).some((e) => e === ext || e === ext.slice(1));
480
+ }
481
+ /**
482
+ * Workspace filesystem that reads and writes files inside a Modal Sandbox.
483
+ *
484
+ * Mount a Modal Volume on the sandbox and point `basePath` at the mount to give
485
+ * agents persistent files that survive sandbox restarts.
486
+ *
487
+ * @example
488
+ * ```typescript
489
+ * import { Volume } from 'modal';
490
+ * import { Workspace } from '@mastra/core/workspace';
491
+ * import { ModalSandbox, ModalFilesystem } from '@mastra/modal';
492
+ *
493
+ * const volume = await modal.volumes.fromName('agent-files', { createIfMissing: true });
494
+ * const sandbox = new ModalSandbox({ volumes: { '/mnt/agent': volume }, workingDirectory: '/workspace' });
495
+ * const filesystem = new ModalFilesystem({ sandbox, basePath: '/mnt/agent' });
496
+ *
497
+ * const workspace = new Workspace({ sandbox, filesystem });
498
+ * ```
499
+ */
500
+ var ModalFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
501
+ id;
502
+ name = "ModalFilesystem";
503
+ provider = "modal";
504
+ readOnly;
505
+ displayName;
506
+ description;
507
+ icon = "folder";
508
+ basePath;
509
+ status = "pending";
510
+ sandbox;
511
+ /** Serializes stdin-streaming execs; concurrent stdin writes can wedge a Modal exec. */
512
+ _writeQueue = Promise.resolve();
513
+ constructor(options) {
514
+ super({
515
+ ...options,
516
+ name: "ModalFilesystem"
517
+ });
518
+ if (!path.posix.isAbsolute(options.basePath)) throw new Error(`[ModalFilesystem] basePath must be absolute, got "${options.basePath}"`);
519
+ this.id = options.id ?? `modal-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
520
+ this.sandbox = options.sandbox;
521
+ this.basePath = path.posix.normalize(options.basePath).replace(/(.)\/$/, "$1");
522
+ this.readOnly = options.readOnly;
523
+ this.displayName = options.displayName;
524
+ this.description = options.description;
525
+ }
526
+ async init() {
527
+ await this.sandbox.ensureRunning();
528
+ }
529
+ getInfo() {
530
+ return {
531
+ id: this.id,
532
+ name: this.name,
533
+ provider: this.provider,
534
+ status: this.status,
535
+ readOnly: this.readOnly,
536
+ icon: this.icon,
537
+ metadata: { basePath: this.basePath }
538
+ };
539
+ }
540
+ getInstructions() {
541
+ return `${this.readOnly ? "Read-only" : "Persistent"} files stored at ${this.basePath} inside the Modal sandbox.`;
542
+ }
543
+ /**
544
+ * Resolve a workspace path to an absolute sandbox path under `basePath`.
545
+ * Rejects paths that would escape the base directory.
546
+ */
547
+ resolvePath(path$1) {
548
+ const relative = path.posix.normalize(`./${path$1.replace(/^\/+/, "")}`).replace(/\/$/, "") || ".";
549
+ if (relative === ".." || relative.startsWith("../")) throw new _mastra_core_workspace.PermissionError(path$1, "access outside filesystem base path");
550
+ return relative === "." ? this.basePath : path.posix.join(this.basePath, relative);
551
+ }
552
+ async readFile(path$2, options) {
553
+ const { stdout } = await this.run("read", [this.resolvePath(path$2)], path$2);
554
+ const buffer = Buffer.from(stdout);
555
+ return options?.encoding ? buffer.toString(options.encoding) : buffer;
556
+ }
557
+ async writeFile(path$3, content, options) {
558
+ this.assertWritable("writeFile");
559
+ if (options?.expectedMtime) {
560
+ const current = await this.stat(path$3).catch((error) => {
561
+ if (error instanceof _mastra_core_workspace.FileNotFoundError) return void 0;
562
+ throw error;
563
+ });
564
+ if (current && current.modifiedAt.getTime() !== options.expectedMtime.getTime()) throw new _mastra_core_workspace.StaleFileError(path$3, options.expectedMtime, current.modifiedAt);
565
+ }
566
+ const args = [
567
+ this.resolvePath(path$3),
568
+ flag(options?.recursive !== false),
569
+ flag(options?.overwrite !== false)
570
+ ];
571
+ await this.run("write", args, path$3, toBytes(content));
572
+ }
573
+ async appendFile(path$4, content) {
574
+ this.assertWritable("appendFile");
575
+ await this.run("append", [this.resolvePath(path$4), "1"], path$4, toBytes(content));
576
+ }
577
+ async deleteFile(path$5, options) {
578
+ this.assertWritable("deleteFile");
579
+ await this.run("deleteFile", [this.resolvePath(path$5), flag(!!options?.force)], path$5);
580
+ }
581
+ async copyFile(src, dest, options) {
582
+ this.assertWritable("copyFile");
583
+ await this.transfer("cp", src, dest, options);
584
+ }
585
+ async moveFile(src, dest, options) {
586
+ this.assertWritable("moveFile");
587
+ await this.transfer("mv", src, dest, options);
588
+ }
589
+ async mkdir(path$6, options) {
590
+ this.assertWritable("mkdir");
591
+ await this.run("mkdir", [this.resolvePath(path$6), flag(options?.recursive !== false)], path$6, void 0, true);
592
+ }
593
+ async rmdir(path$7, options) {
594
+ this.assertWritable("rmdir");
595
+ const resolved = this.resolvePath(path$7);
596
+ if (resolved === this.basePath) throw new _mastra_core_workspace.PermissionError(path$7, "remove filesystem base path");
597
+ await this.run("rmdir", [
598
+ resolved,
599
+ flag(!!options?.recursive),
600
+ flag(!!options?.force)
601
+ ], path$7, void 0, true);
602
+ }
603
+ async readdir(path$8, options) {
604
+ const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;
605
+ const { stdout } = await this.run("readdir", [this.resolvePath(path$8), String(depth)], path$8, void 0, true);
606
+ const fields = new TextDecoder().decode(stdout).split("\0");
607
+ const entries = [];
608
+ for (let i = 0; i + 4 < fields.length; i += 5) {
609
+ const [targetType, ownType, size, name, linkTarget] = fields.slice(i, i + 5);
610
+ const type = targetType === "d" ? "directory" : "file";
611
+ const isSymlink = ownType === "l";
612
+ if (options?.extension && type === "file" && !matchesExtension(name, options.extension)) continue;
613
+ const entry = {
614
+ name,
615
+ type
616
+ };
617
+ if (isSymlink) {
618
+ entry.isSymlink = true;
619
+ entry.symlinkTarget = linkTarget;
620
+ } else if (type === "file") entry.size = Number(size);
621
+ entries.push(entry);
622
+ }
623
+ return entries;
624
+ }
625
+ async exists(path$9) {
626
+ const { exitCode } = await this.exec("exists", [this.resolvePath(path$9)]);
627
+ return exitCode === 0;
628
+ }
629
+ async stat(path$10) {
630
+ const resolved = this.resolvePath(path$10);
631
+ const { stdout } = await this.run("stat", [resolved], path$10);
632
+ const [kind = "", size = "0", birth = "0", mtime = "0"] = new TextDecoder().decode(stdout).trim().split("|");
633
+ const type = kind === "directory" ? "directory" : "file";
634
+ const modifiedAt = /* @__PURE__ */ new Date(Number(mtime) * 1e3);
635
+ const birthSeconds = Number(birth);
636
+ return {
637
+ name: path.posix.basename(resolved),
638
+ path: resolved,
639
+ type,
640
+ size: type === "directory" ? 0 : Number(size),
641
+ createdAt: birthSeconds > 0 ? /* @__PURE__ */ new Date(birthSeconds * 1e3) : modifiedAt,
642
+ modifiedAt
643
+ };
644
+ }
645
+ assertWritable(operation) {
646
+ if (this.readOnly) throw new _mastra_core_workspace.WorkspaceReadOnlyError(operation);
647
+ }
648
+ async transfer(op, src, dest, options) {
649
+ const args = [
650
+ this.resolvePath(src),
651
+ this.resolvePath(dest),
652
+ flag(!!options?.recursive),
653
+ flag(options?.overwrite !== false),
654
+ op
655
+ ];
656
+ await this.run("transfer", args, src);
657
+ }
658
+ /** Run a script and translate non-zero exit codes into filesystem errors. */
659
+ async run(script, args, path$11, stdin, directoryOp = false) {
660
+ const result = await this.exec(script, args, stdin);
661
+ switch (result.exitCode) {
662
+ case 0: return result;
663
+ case EXIT.NOT_FOUND: throw directoryOp ? new _mastra_core_workspace.DirectoryNotFoundError(path$11) : new _mastra_core_workspace.FileNotFoundError(path$11);
664
+ case EXIT.NO_PARENT: throw new _mastra_core_workspace.DirectoryNotFoundError(path.posix.dirname(path$11));
665
+ case EXIT.EXISTS: throw new _mastra_core_workspace.FileExistsError(path$11);
666
+ case EXIT.IS_DIR: throw new _mastra_core_workspace.IsDirectoryError(path$11);
667
+ case EXIT.NOT_DIR: throw new _mastra_core_workspace.NotDirectoryError(path$11);
668
+ case EXIT.NOT_EMPTY: throw new _mastra_core_workspace.DirectoryNotEmptyError(path$11);
669
+ case EXIT.OUTSIDE: throw new _mastra_core_workspace.PermissionError(path$11, "access outside filesystem base path");
670
+ default: {
671
+ const message = result.stderr.trim();
672
+ if (/permission denied|read-only file system/i.test(message)) throw new _mastra_core_workspace.PermissionError(path$11, script);
673
+ throw new _mastra_core_workspace.FilesystemError(`[ModalFilesystem] ${script} failed for ${path$11} (exit ${result.exitCode})${message ? `: ${message}` : ""}`, "EIO", path$11);
674
+ }
675
+ }
676
+ }
677
+ async exec(script, args, stdin) {
678
+ await this.ensureReady();
679
+ const execute = async () => {
680
+ const pathCount = script === "transfer" ? "2" : "1";
681
+ const command = [
682
+ "sh",
683
+ "-c",
684
+ `${CONFINE} ${SCRIPTS[script]}`,
685
+ script,
686
+ this.basePath,
687
+ pathCount,
688
+ ...args
689
+ ];
690
+ const proc = await this.sandbox.modal.exec(command, { mode: "binary" });
691
+ if (stdin) await proc.stdin.writeBytes(stdin);
692
+ await proc.stdin.close();
693
+ const [stdout, stderr, exitCode] = await Promise.all([
694
+ proc.stdout.readBytes(),
695
+ proc.stderr.readBytes(),
696
+ proc.wait()
697
+ ]);
698
+ return {
699
+ exitCode,
700
+ stdout,
701
+ stderr: new TextDecoder().decode(stderr)
702
+ };
703
+ };
704
+ const runOnce = () => script === "append" ? execute() : this.sandbox.retryOnDead(execute);
705
+ if (!stdin) return runOnce();
706
+ const next = this._writeQueue.then(runOnce, runOnce);
707
+ this._writeQueue = next.catch(() => {});
708
+ return next;
709
+ }
710
+ };
711
+ //#endregion
712
+ exports.ModalFilesystem = ModalFilesystem;
401
713
  exports.ModalProcessManager = ModalProcessManager;
402
714
  exports.ModalSandbox = ModalSandbox;
403
715