@mastra/e2b 0.15.0 → 0.15.1-alpha.1

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,99 @@
1
+ import { ProcessHandle, SandboxProcessManager } from '@mastra/core/workspace';
2
+ import type { CommandResult, MastraSandbox, ProcessInfo, SpawnProcessOptions } from '@mastra/core/workspace';
3
+ /** A command as E2B's envd commands API reports it (`CommandHandle`), reduced to what is used here. */
4
+ export interface CommandsApiHandle {
5
+ readonly pid: number;
6
+ /** `undefined` while the command runs. */
7
+ readonly exitCode?: number;
8
+ /** Resolves on exit 0; rejects with a `CommandExitError`-shaped error otherwise. */
9
+ wait(): Promise<{
10
+ exitCode: number;
11
+ }>;
12
+ }
13
+ export interface CommandsApiStreamOptions {
14
+ onStdout?: (data: string) => void;
15
+ onStderr?: (data: string) => void;
16
+ timeoutMs?: number;
17
+ }
18
+ /** The envd commands calls the process manager makes (E2B's `sandbox.commands`). */
19
+ export interface CommandsApi {
20
+ run(command: string, opts: CommandsApiStreamOptions & {
21
+ background: true;
22
+ stdin?: boolean;
23
+ cwd?: string;
24
+ envs?: Record<string, string>;
25
+ }): Promise<CommandsApiHandle>;
26
+ connect(pid: number, opts?: CommandsApiStreamOptions): Promise<CommandsApiHandle>;
27
+ /** Running commands only. */
28
+ list(): Promise<Array<{
29
+ pid: number;
30
+ cmd: string;
31
+ args: string[];
32
+ }>>;
33
+ kill(pid: number): Promise<boolean>;
34
+ sendStdin(pid: number, data: string): Promise<void>;
35
+ }
36
+ /**
37
+ * Attaching sets no deadline of its own: without one the SDK cuts the stream
38
+ * after 60s, and the process's own timeout was set when it was spawned.
39
+ */
40
+ export declare const ATTACH_TIMEOUT_MS = 0;
41
+ export type CommandsApiOperation = 'spawn' | 'list' | 'connect' | 'kill' | 'sendStdin';
42
+ /**
43
+ * A process started or attached through a {@link CommandsApi}. `kill` and
44
+ * `sendStdin` go back through the manager, so they use whatever commands
45
+ * handle the provider currently supplies.
46
+ */
47
+ export declare class CommandsApiProcessHandle extends ProcessHandle {
48
+ protected inner: CommandsApiHandle;
49
+ protected readonly manager: CommandsApiProcessManager<any>;
50
+ private readonly startTime;
51
+ private readonly stdinMode;
52
+ readonly pid: string;
53
+ /** The exit code `wait()` saw, for a handle that doesn't update its own. */
54
+ private waitedExitCode?;
55
+ constructor(inner: CommandsApiHandle, manager: CommandsApiProcessManager<any>, startTime: number, stdinMode: SpawnProcessOptions['stdinMode'], options?: SpawnProcessOptions);
56
+ /** Read from the commands handle, so it reflects server-side state without `wait()`. */
57
+ get exitCode(): number | undefined;
58
+ /** Wait for the process to exit. Providers whose output stream can drop while the process runs override this. */
59
+ protected waitForExit(): Promise<{
60
+ exitCode: number;
61
+ }>;
62
+ wait(): Promise<CommandResult>;
63
+ kill(): Promise<boolean>;
64
+ sendStdin(data: string): Promise<void>;
65
+ closeStdin(): Promise<void>;
66
+ }
67
+ export interface CommandsApiProcessManagerOptions {
68
+ env?: Record<string, string | undefined>;
69
+ /** Default timeout in milliseconds for commands that don't specify one. */
70
+ defaultTimeout?: number;
71
+ }
72
+ /**
73
+ * A process manager over E2B's envd commands API. Providers supply the
74
+ * commands handle through {@link runCommands}; everything else is shared.
75
+ */
76
+ export declare abstract class CommandsApiProcessManager<TSandbox extends MastraSandbox = MastraSandbox> extends SandboxProcessManager<TSandbox> {
77
+ protected readonly defaultTimeout?: number;
78
+ constructor({ defaultTimeout, ...options }?: CommandsApiProcessManagerOptions);
79
+ /** Run `fn` against the provider's current commands handle. */
80
+ abstract runCommands<T>(operation: CommandsApiOperation, fn: (commands: CommandsApi) => Promise<T>): Promise<T>;
81
+ /** Wrap a started or attached command. Providers override this to supply their own handle. */
82
+ protected createHandle(inner: CommandsApiHandle, stdinMode: SpawnProcessOptions['stdinMode'], options?: SpawnProcessOptions): CommandsApiProcessHandle;
83
+ /** Where a command runs when the caller gives no `cwd`. */
84
+ protected defaultCwd(): string | undefined;
85
+ spawn(command: string, options?: SpawnProcessOptions): Promise<ProcessHandle>;
86
+ /**
87
+ * Running processes as the VM reports them, plus exited processes this
88
+ * manager still holds, so a finished command stays visible until it is released.
89
+ */
90
+ list(): Promise<ProcessInfo[]>;
91
+ /**
92
+ * A tracked process, or one this manager didn't start, attached through
93
+ * `connect`. Output from before attaching is not available.
94
+ */
95
+ get(pid: string, _options?: {
96
+ release?: boolean;
97
+ }): Promise<ProcessHandle | undefined>;
98
+ }
99
+ //# sourceMappingURL=commands-api-process-manager.d.ts.map
@@ -2,4 +2,5 @@ export { SETUP_MARKER_DIR, SETUP_MARKER_PATH, WORKSPACE_SETUP_MARKER_PATH, SETUP
2
2
  export { repoCloneCommand, type RepoCloneCommandOptions } from './repo-clone.js';
3
3
  export { FILE_COMMAND_EXIT, shellQuote, siblingTempPath, copyCommand, moveNoClobberCommand, appendFromCommand, linkNoClobberCommand, type CopyCommandOptions, } from './file-commands.js';
4
4
  export { FilesApiFilesystem, type FilesApi, type FilesApiEntry, type FilesApiErrorKind, type FilesCommandResult, } from './files-api-filesystem.js';
5
+ export { ATTACH_TIMEOUT_MS, CommandsApiProcessManager, CommandsApiProcessHandle, type CommandsApi, type CommandsApiHandle, type CommandsApiOperation, type CommandsApiProcessManagerOptions, type CommandsApiStreamOptions, } from './commands-api-process-manager.js';
5
6
  //# sourceMappingURL=index.d.ts.map
package/dist/index.cjs CHANGED
@@ -14,7 +14,7 @@ let esbuild = require("esbuild");
14
14
  * contents can never drift under a stable identity hash; bump deliberately
15
15
  * (each bump builds new templates).
16
16
  */
17
- const DEFAULT_NODE_VERSION = "24.20.0";
17
+ const DEFAULT_NODE_VERSION = "24.22.1";
18
18
  const NODE_VERSION_PATTERN = /^\d+\.\d+\.\d+$/;
19
19
  function isNamedTemplateSpec(spec) {
20
20
  return typeof spec === "object" && spec !== null && "ref" in spec && "template" in spec;
@@ -56,7 +56,7 @@ function createDefaultMountableTemplate(options) {
56
56
  const aptPackages = ["s3fs", "fuse"];
57
57
  const cpuCount = options?.cpuCount ?? 2;
58
58
  const memoryMB = options?.memoryMB ?? 1024;
59
- const nodeVersion = options?.nodeVersion ?? "24.20.0";
59
+ const nodeVersion = options?.nodeVersion ?? "24.22.1";
60
60
  if (!NODE_VERSION_PATTERN.test(nodeVersion)) throw new Error(`Invalid nodeVersion "${nodeVersion}": expected an exact version like "24.20.0"`);
61
61
  const config = {
62
62
  version: "v4",
@@ -76,8 +76,7 @@ function createDefaultMountableTemplate(options) {
76
76
  }
77
77
  };
78
78
  }
79
- //#endregion
80
- //#region ../../packages/_internals/workspace/dist/index.js
79
+ // ../../packages/_internals/workspace/dist/index.js
81
80
  /** Directory, relative to the template's build cwd, that holds every marker below. */
82
81
  const SETUP_MARKER_DIR = ".mastra-sandbox";
83
82
  /**
@@ -477,7 +476,8 @@ var FilesApiFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
477
476
  type: info.type === "dir" ? "directory" : "file",
478
477
  size: info.type === "dir" ? 0 : info.size,
479
478
  createdAt: modifiedAt,
480
- modifiedAt
479
+ modifiedAt,
480
+ ...info.type !== "dir" && { mimeType: (0, _mastra_core_workspace.getMimeType)(abs) }
481
481
  };
482
482
  });
483
483
  }
@@ -528,8 +528,202 @@ var FilesApiFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
528
528
  throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
529
529
  }
530
530
  };
531
- //#endregion
532
- //#region src/sandbox/filesystem.ts
531
+ /**
532
+ * Output callbacks for `run`/`connect` that hold output until the handle
533
+ * exists. The SDK's handle reads events from construction, before `run()`
534
+ * returns, so output that arrives with the start event reaches the
535
+ * callbacks first.
536
+ */
537
+ function outputUntilHandled() {
538
+ let handle;
539
+ const early = [];
540
+ return {
541
+ onStdout: (data) => {
542
+ if (handle) handle.emitStdout(data);
543
+ else early.push({
544
+ stream: "stdout",
545
+ data
546
+ });
547
+ },
548
+ onStderr: (data) => {
549
+ if (handle) handle.emitStderr(data);
550
+ else early.push({
551
+ stream: "stderr",
552
+ data
553
+ });
554
+ },
555
+ handledBy(created) {
556
+ for (const { stream, data } of early) if (stream === "stdout") created.emitStdout(data);
557
+ else created.emitStderr(data);
558
+ early.length = 0;
559
+ handle = created;
560
+ return created;
561
+ }
562
+ };
563
+ }
564
+ /** envd runs every command as `/bin/bash -l -c <command>`; show the command itself. */
565
+ function commandOf(proc) {
566
+ const [flag, c, command] = proc.args;
567
+ if (proc.cmd === "/bin/bash" && flag === "-l" && c === "-c" && command !== void 0 && proc.args.length === 3) return command;
568
+ return [proc.cmd, ...proc.args].join(" ");
569
+ }
570
+ /**
571
+ * A process started or attached through a {@link CommandsApi}. `kill` and
572
+ * `sendStdin` go back through the manager, so they use whatever commands
573
+ * handle the provider currently supplies.
574
+ */
575
+ var CommandsApiProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
576
+ inner;
577
+ manager;
578
+ startTime;
579
+ stdinMode;
580
+ pid;
581
+ /** The exit code `wait()` saw, for a handle that doesn't update its own. */
582
+ waitedExitCode;
583
+ constructor(inner, manager, startTime, stdinMode, options) {
584
+ super(options);
585
+ this.inner = inner;
586
+ this.manager = manager;
587
+ this.startTime = startTime;
588
+ this.stdinMode = stdinMode;
589
+ this.pid = String(inner.pid);
590
+ }
591
+ /** Read from the commands handle, so it reflects server-side state without `wait()`. */
592
+ get exitCode() {
593
+ return this.inner.exitCode ?? this.waitedExitCode;
594
+ }
595
+ /** Wait for the process to exit. Providers whose output stream can drop while the process runs override this. */
596
+ waitForExit() {
597
+ return this.inner.wait();
598
+ }
599
+ async wait() {
600
+ try {
601
+ const result = await this.waitForExit();
602
+ this.waitedExitCode = result.exitCode;
603
+ return {
604
+ success: result.exitCode === 0,
605
+ exitCode: result.exitCode,
606
+ stdout: this.stdout,
607
+ stderr: this.stderr,
608
+ executionTimeMs: Date.now() - this.startTime
609
+ };
610
+ } catch (error) {
611
+ const errorObj = error;
612
+ const reportedExitCode = errorObj.result?.exitCode ?? errorObj.exitCode;
613
+ if (reportedExitCode !== void 0) this.waitedExitCode = reportedExitCode;
614
+ const exitCode = reportedExitCode ?? this.exitCode ?? 1;
615
+ const attachedStdout = errorObj.result?.stdout || errorObj.stdout;
616
+ const attachedStderr = errorObj.result?.stderr || errorObj.stderr;
617
+ if (!this.stdout && !this.stdoutTruncated && attachedStdout) this.emitStdout(attachedStdout);
618
+ if (!this.stderr && !this.stderrTruncated && attachedStderr) this.emitStderr(attachedStderr);
619
+ const stdout = this.stdout;
620
+ const stderr = this.stderr;
621
+ const terminalError = errorObj.result?.error || errorObj.error || (error instanceof Error ? error.message : String(error));
622
+ return {
623
+ success: false,
624
+ exitCode,
625
+ stdout,
626
+ stderr: [stderr, terminalError && !stderr.includes(terminalError) ? `Error: ${terminalError}` : ""].filter(Boolean).join("\n"),
627
+ executionTimeMs: Date.now() - this.startTime
628
+ };
629
+ }
630
+ }
631
+ async kill() {
632
+ if (this.exitCode !== void 0) return false;
633
+ return this.manager.runCommands("kill", (commands) => commands.kill(this.inner.pid));
634
+ }
635
+ async sendStdin(data) {
636
+ if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
637
+ if (this.stdinMode === "ignore") throw new Error(`Process ${this.pid} was not started with stdin support`);
638
+ await this.manager.runCommands("sendStdin", (commands) => commands.sendStdin(this.inner.pid, data));
639
+ }
640
+ async closeStdin() {
641
+ throw new _mastra_core_workspace.UnsupportedStdinCloseError("The commands API does not expose a way to close stdin for a running command");
642
+ }
643
+ };
644
+ /**
645
+ * A process manager over E2B's envd commands API. Providers supply the
646
+ * commands handle through {@link runCommands}; everything else is shared.
647
+ */
648
+ var CommandsApiProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
649
+ defaultTimeout;
650
+ constructor({ defaultTimeout, ...options } = {}) {
651
+ super(options);
652
+ this.defaultTimeout = defaultTimeout;
653
+ }
654
+ /** Wrap a started or attached command. Providers override this to supply their own handle. */
655
+ createHandle(inner, stdinMode, options) {
656
+ return new CommandsApiProcessHandle(inner, this, Date.now(), stdinMode, options);
657
+ }
658
+ /** Where a command runs when the caller gives no `cwd`. */
659
+ defaultCwd() {
660
+ return this.sandbox.workingDirectory;
661
+ }
662
+ async spawn(command, options = {}) {
663
+ const envs = Object.fromEntries(Object.entries({ ...options.env }).filter((entry) => entry[1] !== void 0));
664
+ return this.runCommands("spawn", async (commands) => {
665
+ const output = outputUntilHandled();
666
+ const inner = await commands.run(command, {
667
+ background: true,
668
+ stdin: options.stdinMode !== "ignore",
669
+ cwd: options.cwd ?? this.defaultCwd(),
670
+ envs,
671
+ timeoutMs: options.timeout ?? this.defaultTimeout,
672
+ onStdout: output.onStdout,
673
+ onStderr: output.onStderr
674
+ });
675
+ const handle = output.handledBy(this.createHandle(inner, options.stdinMode, options));
676
+ this._tracked.set(handle.pid, handle);
677
+ return handle;
678
+ });
679
+ }
680
+ /**
681
+ * Running processes as the VM reports them, plus exited processes this
682
+ * manager still holds, so a finished command stays visible until it is released.
683
+ */
684
+ async list() {
685
+ const infos = (await this.runCommands("list", (commands) => commands.list())).map((proc) => ({
686
+ pid: String(proc.pid),
687
+ command: commandOf(proc),
688
+ running: true
689
+ }));
690
+ const listed = new Set(infos.map((info) => info.pid));
691
+ for (const [pid, handle] of this._tracked) {
692
+ if (handle.exitCode === void 0 || listed.has(pid)) continue;
693
+ infos.push({
694
+ pid,
695
+ command: handle.command,
696
+ running: false,
697
+ exitCode: handle.exitCode
698
+ });
699
+ }
700
+ return infos;
701
+ }
702
+ /**
703
+ * A tracked process, or one this manager didn't start, attached through
704
+ * `connect`. Output from before attaching is not available.
705
+ */
706
+ async get(pid, _options) {
707
+ const tracked = this._tracked.get(pid);
708
+ if (tracked) return tracked;
709
+ const numericPid = /^\d+$/.test(pid) ? Number(pid) : void 0;
710
+ if (numericPid === void 0) return void 0;
711
+ const output = outputUntilHandled();
712
+ try {
713
+ const inner = await this.runCommands("connect", (commands) => commands.connect(numericPid, {
714
+ onStdout: output.onStdout,
715
+ onStderr: output.onStderr,
716
+ timeoutMs: 0
717
+ }));
718
+ const handle = output.handledBy(this.createHandle(inner, void 0));
719
+ this._tracked.set(handle.pid, handle);
720
+ return handle;
721
+ } catch {
722
+ return;
723
+ }
724
+ }
725
+ };
726
+ // src/sandbox/filesystem.ts
533
727
  /**
534
728
  * envd's edge answers a paused or missing sandbox with a 404 that the SDK
535
729
  * reports as `FileNotFoundError`. Same pattern as `E2BSandbox`'s dead-sandbox
@@ -584,8 +778,7 @@ var E2BSandboxFilesystem = class extends FilesApiFilesystem {
584
778
  if (error instanceof e2b.InvalidArgumentError) return "invalid-argument";
585
779
  }
586
780
  };
587
- //#endregion
588
- //#region src/sandbox/mounts/types.ts
781
+ // src/sandbox/mounts/types.ts
589
782
  const LOG_PREFIX = "[@mastra/e2b]";
590
783
  const SAFE_S3_BUCKET_NAME = /^[a-z0-9][a-z0-9.\-]{1,61}[a-z0-9]$/;
591
784
  const SAFE_GCS_BUCKET_NAME = /^[a-z0-9][a-z0-9._-]{1,61}[a-z0-9]$/;
@@ -629,8 +822,7 @@ function validatePrefix(prefix) {
629
822
  if (/[\x00-\x1f\x7f]/.test(normalized)) throw new Error(`Invalid mount prefix: "${prefix}". Control characters are not allowed.`);
630
823
  return normalized;
631
824
  }
632
- //#endregion
633
- //#region src/utils/shell-quote.ts
825
+ // src/utils/shell-quote.ts
634
826
  /**
635
827
  * Shell-quote a single argument for safe use in a command string.
636
828
  *
@@ -641,8 +833,7 @@ function shellQuote(arg) {
641
833
  if (/^[a-zA-Z0-9._\-/@:=]+$/.test(arg)) return arg;
642
834
  return "'" + arg.replace(/'/g, "'\\''") + "'";
643
835
  }
644
- //#endregion
645
- //#region src/sandbox/mounts/s3.ts
836
+ // src/sandbox/mounts/s3.ts
646
837
  /**
647
838
  * Mount an S3 bucket using s3fs-fuse.
648
839
  */
@@ -749,8 +940,7 @@ Error details: ${installResult.stderr || installResult.stdout}`);
749
940
  }
750
941
  if ((await sandbox.commands.run(`mountpoint -q ${shellQuote(mountPath)}`)).exitCode !== 0) throw new Error(`s3fs returned exit 0 but ${mountPath} is not a mountpoint. The s3fs daemon likely failed during FUSE init (common causes: region mismatch, invalid credentials, or an S3-compatible endpoint that rejects the signature). Re-run inside the sandbox with '-f -o dbglevel=info' to see the underlying error.`);
751
942
  }
752
- //#endregion
753
- //#region src/sandbox/mounts/gcs.ts
943
+ // src/sandbox/mounts/gcs.ts
754
944
  /**
755
945
  * Mount a GCS bucket using gcsfuse.
756
946
  *
@@ -801,8 +991,7 @@ async function mountGCS(mountPath, config, ctx) {
801
991
  throw new Error(`Failed to mount GCS bucket: ${stderr || stdout || error}`);
802
992
  }
803
993
  }
804
- //#endregion
805
- //#region src/sandbox/mounts/azure.ts
994
+ // src/sandbox/mounts/azure.ts
806
995
  const SAFE_CONTAINER_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;
807
996
  const BLOBFUSE2_GITHUB_DEB = "https://github.com/Azure/azure-storage-fuse/releases/download/blobfuse2-2.5.1/blobfuse2-2.5.1-Ubuntu-22.04.x86_64.deb";
808
997
  function validateContainerName(name) {
@@ -999,143 +1188,24 @@ Error details: ${verifyResult.stderr || verifyResult.stdout || installResult?.st
999
1188
  throw new Error(`Failed to mount Azure Blob container: ${stderr || stdout || error}`);
1000
1189
  }
1001
1190
  }
1002
- //#endregion
1003
- //#region src/sandbox/process-manager.ts
1191
+ // src/sandbox/process-manager.ts
1004
1192
  /**
1005
1193
  * E2B Process Manager
1006
1194
  *
1007
- * Implements SandboxProcessManager for E2B cloud sandboxes.
1008
- * Wraps the E2B SDK's commands API (background mode, sendStdin, kill, list).
1195
+ * Implements SandboxProcessManager for E2B cloud sandboxes over the E2B SDK's
1196
+ * commands API. The process handling itself is shared with other envd-backed
1197
+ * providers in `@internal/workspace`.
1009
1198
  */
1010
- /**
1011
- * Wraps an E2B CommandHandle to conform to Mastra's ProcessHandle.
1012
- * Not exported — internal to this module.
1013
- *
1014
- * Listener dispatch is handled by the base class. The manager's spawn()/get()
1015
- * methods wire E2B's constructor-time callbacks to handle.emitStdout/emitStderr.
1016
- */
1017
- var E2BProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
1018
- pid;
1019
- _e2bHandle;
1020
- _sandbox;
1021
- _startTime;
1022
- _stdinMode;
1023
- constructor(e2bHandle, sandbox, startTime, options) {
1024
- super(options);
1025
- this.pid = String(e2bHandle.pid);
1026
- this._e2bHandle = e2bHandle;
1027
- this._sandbox = sandbox;
1028
- this._startTime = startTime;
1029
- this._stdinMode = options?.stdinMode;
1030
- }
1031
- /** Delegates to E2B's handle so exitCode reflects server-side state without needing wait(). */
1032
- get exitCode() {
1033
- return this._e2bHandle.exitCode;
1034
- }
1035
- async wait() {
1036
- try {
1037
- const result = await this._e2bHandle.wait();
1038
- return {
1039
- success: result.exitCode === 0,
1040
- exitCode: result.exitCode,
1041
- stdout: this.stdout,
1042
- stderr: this.stderr,
1043
- executionTimeMs: Date.now() - this._startTime
1044
- };
1045
- } catch (error) {
1046
- const errorObj = error;
1047
- const exitCode = errorObj.result?.exitCode ?? errorObj.exitCode ?? this.exitCode ?? 1;
1048
- const attachedStdout = errorObj.result?.stdout || errorObj.stdout;
1049
- const attachedStderr = errorObj.result?.stderr || errorObj.stderr;
1050
- if (!this.stdout && !this.stdoutTruncated && attachedStdout) this.emitStdout(attachedStdout);
1051
- if (!this.stderr && !this.stderrTruncated && attachedStderr) this.emitStderr(attachedStderr);
1052
- const stdout = this.stdout;
1053
- const stderr = this.stderr;
1054
- const terminalError = errorObj.result?.error || errorObj.error || (error instanceof Error ? error.message : String(error));
1055
- return {
1056
- success: false,
1057
- exitCode,
1058
- stdout,
1059
- stderr: [stderr, terminalError && !stderr.includes(terminalError) ? `Error: ${terminalError}` : ""].filter(Boolean).join("\n"),
1060
- executionTimeMs: Date.now() - this._startTime
1061
- };
1062
- }
1063
- }
1064
- async kill() {
1065
- if (this.exitCode !== void 0) return false;
1066
- return this._e2bHandle.kill();
1067
- }
1068
- async sendStdin(data) {
1069
- if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
1070
- if (this._stdinMode === "ignore") throw new Error(`Process ${this.pid} was not started with stdin support`);
1071
- await this._sandbox.commands.sendStdin(this._e2bHandle.pid, data);
1072
- }
1073
- async closeStdin() {
1074
- throw new _mastra_core_workspace.UnsupportedStdinCloseError("E2B SDK does not expose a way to close stdin for a running command");
1075
- }
1076
- };
1077
- var E2BProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
1078
- _defaultTimeout;
1199
+ var E2BProcessManager = class extends CommandsApiProcessManager {
1079
1200
  constructor(opts = {}) {
1080
- super();
1081
- this._defaultTimeout = opts.defaultTimeout;
1082
- }
1083
- async spawn(command, options = {}) {
1084
- return this.sandbox.retryOnDead(async () => {
1085
- const e2b = this.sandbox.e2b;
1086
- const mergedEnv = { ...options.env };
1087
- const envs = Object.fromEntries(Object.entries(mergedEnv).filter((entry) => entry[1] !== void 0));
1088
- let handle;
1089
- handle = new E2BProcessHandle(await e2b.commands.run(command, {
1090
- background: true,
1091
- stdin: options.stdinMode !== "ignore",
1092
- cwd: options.cwd ?? this.sandbox.workingDirectory,
1093
- envs,
1094
- timeoutMs: options.timeout ?? this._defaultTimeout,
1095
- onStdout: (data) => handle.emitStdout(data),
1096
- onStderr: (data) => handle.emitStderr(data)
1097
- }), e2b, Date.now(), options);
1098
- this._tracked.set(handle.pid, handle);
1099
- return handle;
1100
- });
1201
+ super({ defaultTimeout: opts.defaultTimeout });
1101
1202
  }
1102
- /**
1103
- * List processes by querying E2B's commands API.
1104
- * E2B manages all state server-side — no local tracking needed.
1105
- */
1106
- async list() {
1107
- return (await this.sandbox.e2b.commands.list()).map((proc) => ({
1108
- pid: String(proc.pid),
1109
- command: [proc.cmd, ...proc.args].join(" "),
1110
- running: true
1111
- }));
1112
- }
1113
- /**
1114
- * Get a handle to a process by PID.
1115
- * Checks base class tracking first, then falls back to commands.connect()
1116
- * for processes spawned externally or before reconnection.
1117
- */
1118
- async get(pid) {
1119
- const tracked = this._tracked.get(pid);
1120
- if (tracked) return tracked;
1121
- const numericPid = /^\d+$/.test(pid) ? Number(pid) : void 0;
1122
- if (numericPid === void 0) return void 0;
1123
- const e2b = this.sandbox.e2b;
1124
- let handle;
1125
- try {
1126
- handle = new E2BProcessHandle(await e2b.commands.connect(numericPid, {
1127
- onStdout: (data) => handle.emitStdout(data),
1128
- onStderr: (data) => handle.emitStderr(data)
1129
- }), e2b, Date.now());
1130
- this._tracked.set(handle.pid, handle);
1131
- return handle;
1132
- } catch {
1133
- return;
1134
- }
1203
+ runCommands(operation, fn) {
1204
+ if (operation === "spawn") return this.sandbox.retryOnDead(() => fn(this.sandbox.e2b.commands));
1205
+ return fn(this.sandbox.e2b.commands);
1135
1206
  }
1136
1207
  };
1137
- //#endregion
1138
- //#region src/sandbox/index.ts
1208
+ // src/sandbox/index.ts
1139
1209
  /** Allowlist pattern for mount paths — absolute path with safe characters only. */
1140
1210
  const SAFE_MOUNT_PATH = /^\/[a-zA-Z0-9_.\-/]+$/;
1141
1211
  function validateMountPath(mountPath) {
@@ -2127,8 +2197,7 @@ var E2BSandbox = class E2BSandbox extends _mastra_core_workspace.MastraSandbox {
2127
2197
  }
2128
2198
  }
2129
2199
  };
2130
- //#endregion
2131
- //#region src/utils/repo-template.ts
2200
+ // src/utils/repo-template.ts
2132
2201
  /**
2133
2202
  * Sha-tagged repo templates.
2134
2203
  *
@@ -2541,8 +2610,7 @@ function assertWorkingDirectory(dir) {
2541
2610
  if (!(/^\/[A-Za-z0-9._/-]*$/.test(dir) && !dir.split("/").includes(".."))) throw new Error(`Repo template workingDirectory must be an absolute path of plain path characters (got ${JSON.stringify(dir)}); ~ and $HOME are not expanded.`);
2542
2611
  return dir;
2543
2612
  }
2544
- //#endregion
2545
- //#region src/provider.ts
2613
+ // src/provider.ts
2546
2614
  const e2bSandboxProvider = {
2547
2615
  id: "e2b",
2548
2616
  name: "E2B Sandbox",
@@ -2589,8 +2657,7 @@ const e2bSandboxProvider = {
2589
2657
  },
2590
2658
  createSandbox: (config) => new E2BSandbox(config)
2591
2659
  };
2592
- //#endregion
2593
- //#region src/factory-sandbox.ts
2660
+ // src/factory-sandbox.ts
2594
2661
  /** Applied when neither the environment setting nor a host default is set. */
2595
2662
  const DEFAULT_SETTINGS = {
2596
2663
  cpuCount: 2,
@@ -2825,8 +2892,7 @@ function mapStatus(status) {
2825
2892
  default: return "unknown";
2826
2893
  }
2827
2894
  }
2828
- //#endregion
2829
- //#region src/code-mode/transport.ts
2895
+ // src/code-mode/transport.ts
2830
2896
  /**
2831
2897
  * Code Mode — E2B transport
2832
2898
  *
@@ -2966,9 +3032,7 @@ var E2BCodeModeTransport = class {
2966
3032
  };
2967
3033
  resolveDone();
2968
3034
  return;
2969
- case "rpc":
2970
- serveRpc(frame.id, frame.tool, frame.args).catch(() => {});
2971
- return;
3035
+ case "rpc": serveRpc(frame.id, frame.tool, frame.args).catch(() => {});
2972
3036
  }
2973
3037
  };
2974
3038
  handle = await sandbox.processes.spawn(`node ${runnerPath}`, {
@@ -3030,7 +3094,6 @@ var E2BCodeModeTransport = class {
3030
3094
  }
3031
3095
  }
3032
3096
  };
3033
- //#endregion
3034
3097
  exports.DEFAULT_NODE_VERSION = DEFAULT_NODE_VERSION;
3035
3098
  exports.E2BCodeModeTransport = E2BCodeModeTransport;
3036
3099
  exports.E2BFactorySandbox = E2BFactorySandbox;