@mastra/e2b 0.15.0-alpha.1 → 0.15.1-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,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",
@@ -528,6 +528,201 @@ 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
+ /**
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
+ };
531
726
  //#endregion
532
727
  //#region src/sandbox/filesystem.ts
533
728
  /**
@@ -1004,134 +1199,17 @@ Error details: ${verifyResult.stderr || verifyResult.stdout || installResult?.st
1004
1199
  /**
1005
1200
  * E2B Process Manager
1006
1201
  *
1007
- * Implements SandboxProcessManager for E2B cloud sandboxes.
1008
- * Wraps the E2B SDK's commands API (background mode, sendStdin, kill, list).
1202
+ * Implements SandboxProcessManager for E2B cloud sandboxes over the E2B SDK's
1203
+ * commands API. The process handling itself is shared with other envd-backed
1204
+ * providers in `@internal/workspace`.
1009
1205
  */
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;
1206
+ var E2BProcessManager = class extends CommandsApiProcessManager {
1079
1207
  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
- });
1101
- }
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
- }));
1208
+ super({ defaultTimeout: opts.defaultTimeout });
1112
1209
  }
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
- }
1210
+ runCommands(operation, fn) {
1211
+ if (operation === "spawn") return this.sandbox.retryOnDead(() => fn(this.sandbox.e2b.commands));
1212
+ return fn(this.sandbox.e2b.commands);
1135
1213
  }
1136
1214
  };
1137
1215
  //#endregion