@mastra/platform-workspace 1.9.0 → 1.10.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.
package/dist/index.cjs CHANGED
@@ -600,393 +600,6 @@ function cloneJson(value) {
600
600
  return value;
601
601
  }
602
602
  //#endregion
603
- //#region src/direct-exec.ts
604
- /**
605
- * Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
606
- * a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
607
- * removes the platform data plane from the exec stdout/stderr path entirely
608
- * (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
609
- * cutting payload-scaled Cloud Run egress and RTT for commands like
610
- * `pnpm install` that stream tens of MB of output.
611
- *
612
- * The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
613
- * (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
614
- * SDK's version is pinned on both sides (platform + here); a version bump
615
- * signals the protocol may have drifted and this module must be revisited.
616
- */
617
- /** Byte-0 tag on binary WS frames for stdout output. */
618
- const STDOUT_FRAME = 1;
619
- /** Byte-0 tag on binary WS frames for stderr output. */
620
- const STDERR_FRAME = 3;
621
- /**
622
- * Upper bound on how long we'll wait for the WebSocket to open when the
623
- * caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
624
- * handshake leaving the promise unresolved forever. Not applied once the
625
- * socket has opened — a caller with no timeout has opted in to unbounded
626
- * command runtime, just not to unbounded connection setup.
627
- */
628
- const HANDSHAKE_DEADLINE_MS = 3e4;
629
- const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
630
- const WS = globalThis.WebSocket;
631
- if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
632
- return new WS(endpoint, subprotocols);
633
- };
634
- /**
635
- * Open the provider exec WebSocket using `lease`, run `command`, and resolve
636
- * with the accumulated stdout/stderr + exit code. See the module docstring
637
- * for the wire protocol reference.
638
- *
639
- * The client sends `stdin_close` immediately after `init_exec`, matching the
640
- * SDK's own one-shot exec behavior — we never stream stdin from the caller.
641
- */
642
- function execViaLease(lease, options) {
643
- const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
644
- const stdoutDecoder = new TextDecoder();
645
- const stderrDecoder = new TextDecoder();
646
- return new Promise((resolve) => {
647
- let stdout = "";
648
- let stderr = "";
649
- let exitCode = null;
650
- let timedOut = false;
651
- let settled = false;
652
- let opened = false;
653
- let closeCode;
654
- let closeReason;
655
- let timer;
656
- let handshakeTimer;
657
- const settle = () => {
658
- if (settled) return;
659
- settled = true;
660
- if (timer) clearTimeout(timer);
661
- if (handshakeTimer) clearTimeout(handshakeTimer);
662
- const stdoutTail = stdoutDecoder.decode();
663
- if (stdoutTail) {
664
- stdout += stdoutTail;
665
- options.onStdout?.(stdoutTail);
666
- }
667
- const stderrTail = stderrDecoder.decode();
668
- if (stderrTail) {
669
- stderr += stderrTail;
670
- options.onStderr?.(stderrTail);
671
- }
672
- try {
673
- socket.close(1e3, "");
674
- } catch {}
675
- resolve({
676
- exitCode,
677
- stdout,
678
- stderr,
679
- truncated: false,
680
- timedOut,
681
- ...closeCode !== void 0 && { closeCode },
682
- ...closeReason !== void 0 && { closeReason },
683
- opened
684
- });
685
- };
686
- if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
687
- timedOut = true;
688
- if (exitCode === null) exitCode = 124;
689
- settle();
690
- }, options.timeoutMs);
691
- else handshakeTimer = setTimeout(() => {
692
- if (!opened) settle();
693
- }, HANDSHAKE_DEADLINE_MS);
694
- const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
695
- socket.binaryType = "arraybuffer";
696
- socket.onopen = () => {
697
- opened = true;
698
- if (handshakeTimer) {
699
- clearTimeout(handshakeTimer);
700
- handshakeTimer = void 0;
701
- }
702
- const data = { command: options.command };
703
- if (options.cwd) data.cwd = options.cwd;
704
- if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
705
- socket.send(JSON.stringify({
706
- type: "init_exec",
707
- data
708
- }));
709
- socket.send(JSON.stringify({ type: "stdin_close" }));
710
- };
711
- socket.onmessage = (event) => {
712
- const { data } = event;
713
- if (data instanceof ArrayBuffer) handleBinaryFrame(data);
714
- else if (typeof data === "string") handleTextFrame(data);
715
- };
716
- socket.onclose = (event) => {
717
- closeCode = event.code;
718
- closeReason = event.reason;
719
- if (!opened) {
720
- settle();
721
- return;
722
- }
723
- settle();
724
- };
725
- socket.onerror = () => {
726
- if (settled) return;
727
- if (!opened) settle();
728
- };
729
- function handleBinaryFrame(buffer) {
730
- const view = new Uint8Array(buffer);
731
- if (view.length <= 1) return;
732
- if (view[0] === STDOUT_FRAME) {
733
- const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
734
- stdout += chunk;
735
- options.onStdout?.(chunk);
736
- } else if (view[0] === STDERR_FRAME) {
737
- const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
738
- stderr += chunk;
739
- options.onStderr?.(chunk);
740
- }
741
- }
742
- function handleTextFrame(text) {
743
- let frame;
744
- try {
745
- frame = JSON.parse(text);
746
- } catch {
747
- return;
748
- }
749
- if (frame.type === "exit") {
750
- exitCode = frame.data?.exit_code ?? 0;
751
- settle();
752
- }
753
- }
754
- });
755
- }
756
- //#endregion
757
- //#region src/e2b-exec.ts
758
- const E2B_ENVD_VERSION = "0.4.0";
759
- const execViaE2BLease = async (lease, options) => {
760
- const stdoutChunks = [];
761
- const stderrChunks = [];
762
- const onStdout = (data) => {
763
- stdoutChunks.push(data);
764
- options.onStdout?.(data);
765
- };
766
- const onStderr = (data) => {
767
- stderrChunks.push(data);
768
- options.onStderr?.(data);
769
- };
770
- try {
771
- const result = await new e2b.Sandbox({
772
- sandboxId: lease.sandboxId,
773
- envdVersion: E2B_ENVD_VERSION,
774
- envdAccessToken: lease.jwt,
775
- sandboxUrl: lease.wsEndpoint,
776
- validateApiKey: false
777
- }).commands.run(options.command, {
778
- cwd: options.cwd,
779
- envs: options.env,
780
- timeoutMs: options.timeoutMs,
781
- onStdout,
782
- onStderr
783
- });
784
- return {
785
- exitCode: result.exitCode,
786
- stdout: result.stdout,
787
- stderr: result.stderr,
788
- truncated: false,
789
- timedOut: false,
790
- opened: true
791
- };
792
- } catch (error) {
793
- if (error instanceof e2b.CommandExitError) return {
794
- exitCode: error.exitCode,
795
- stdout: error.stdout,
796
- stderr: error.stderr,
797
- truncated: false,
798
- timedOut: false,
799
- opened: true
800
- };
801
- return {
802
- exitCode: null,
803
- stdout: stdoutChunks.join(""),
804
- stderr: stderrChunks.join(""),
805
- truncated: false,
806
- timedOut: error instanceof e2b.TimeoutError,
807
- closeReason: error instanceof Error ? error.message : String(error),
808
- opened: true
809
- };
810
- }
811
- };
812
- /** Opens E2B's files API directly against the VM, authenticated by the exec lease. */
813
- const e2bFilesForLease = (lease) => new e2b.Sandbox({
814
- sandboxId: lease.sandboxId,
815
- envdVersion: E2B_ENVD_VERSION,
816
- envdAccessToken: lease.jwt,
817
- sandboxUrl: lease.wsEndpoint,
818
- validateApiKey: false
819
- }).files;
820
- //#endregion
821
- //#region src/private-net-exec.ts
822
- /**
823
- * Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
824
- * HTTP response. This is an *application* error, not a transport error — the
825
- * sidecar is reachable and answered, it just refused the exec. Callers should
826
- * fall back to the lease path for this one call but MUST NOT invalidate the
827
- * cached `instanceUrl` (the address is still good).
828
- */
829
- var PrivateNetExecHttpError = class extends Error {
830
- status;
831
- body;
832
- constructor(status, body) {
833
- super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
834
- this.name = "PrivateNetExecHttpError";
835
- this.status = status;
836
- this.body = body;
837
- }
838
- };
839
- const DEFAULT_FETCH = (input, init) => {
840
- const f = globalThis.fetch;
841
- if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
842
- return f(input, init);
843
- };
844
- /**
845
- * Dial `${instanceUrl}/exec` and stream the response, resolving with the
846
- * accumulated stdout/stderr + exit code.
847
- *
848
- * Errors:
849
- * - Connection failure (DNS, refused, reset) → resolves with
850
- * `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
851
- * transport failures — the shape matches the lease-path result so the
852
- * caller can treat both transports uniformly.
853
- * - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
854
- * Application-level; caller decides whether to fall back.
855
- * - Stream ends without an `exit` frame → resolves with
856
- * `{opened:true, exitCode:null}`, matching the lease-path semantics for a
857
- * mid-stream drop.
858
- * - `timeoutMs` elapsed → aborts the request, resolves with
859
- * `{timedOut:true, exitCode:124}`.
860
- */
861
- async function execViaPrivateNetwork(instanceUrl, options) {
862
- const fetchImpl = options.fetch ?? DEFAULT_FETCH;
863
- const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
864
- const controller = new AbortController();
865
- let timedOut = false;
866
- let timeoutTimer;
867
- if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
868
- timedOut = true;
869
- controller.abort();
870
- }, options.timeoutMs);
871
- const body = { command: options.command };
872
- if (options.cwd) body.cwd = options.cwd;
873
- if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
874
- if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
875
- const headers = { "content-type": "application/json" };
876
- if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
877
- let response;
878
- try {
879
- response = await fetchImpl(url, {
880
- method: "POST",
881
- headers,
882
- body: JSON.stringify(body),
883
- signal: controller.signal
884
- });
885
- } catch (error) {
886
- if (timeoutTimer) clearTimeout(timeoutTimer);
887
- if (timedOut) return {
888
- exitCode: 124,
889
- stdout: "",
890
- stderr: "",
891
- timedOut: true,
892
- opened: false
893
- };
894
- return {
895
- exitCode: null,
896
- stdout: "",
897
- stderr: "",
898
- timedOut: false,
899
- opened: false,
900
- transportErrorMessage: error instanceof Error ? error.message : String(error)
901
- };
902
- }
903
- if (!response.ok) {
904
- if (timeoutTimer) clearTimeout(timeoutTimer);
905
- const text = await response.text().catch(() => "");
906
- throw new PrivateNetExecHttpError(response.status, text);
907
- }
908
- if (!response.body) {
909
- if (timeoutTimer) clearTimeout(timeoutTimer);
910
- return {
911
- exitCode: null,
912
- stdout: "",
913
- stderr: "",
914
- timedOut: false,
915
- opened: true,
916
- status: response.status
917
- };
918
- }
919
- let stdout = "";
920
- let stderr = "";
921
- let exitCode = null;
922
- const decoder = new TextDecoder();
923
- let buffer = "";
924
- const handleLine = (line) => {
925
- if (!line) return;
926
- let frame;
927
- try {
928
- frame = JSON.parse(line);
929
- } catch {
930
- return;
931
- }
932
- if (!frame || typeof frame !== "object") return;
933
- if (frame.type === "stdout" && typeof frame.data === "string") {
934
- stdout += frame.data;
935
- options.onStdout?.(frame.data);
936
- } else if (frame.type === "stderr" && typeof frame.data === "string") {
937
- stderr += frame.data;
938
- options.onStderr?.(frame.data);
939
- } else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
940
- };
941
- try {
942
- const reader = response.body.getReader();
943
- while (true) {
944
- const { value, done } = await reader.read();
945
- if (done) break;
946
- buffer += decoder.decode(value, { stream: true });
947
- let newlineIdx = buffer.indexOf("\n");
948
- while (newlineIdx !== -1) {
949
- const line = buffer.slice(0, newlineIdx).trim();
950
- buffer = buffer.slice(newlineIdx + 1);
951
- handleLine(line);
952
- newlineIdx = buffer.indexOf("\n");
953
- }
954
- }
955
- buffer += decoder.decode();
956
- const trailing = buffer.trim();
957
- if (trailing) handleLine(trailing);
958
- } catch (error) {
959
- if (timeoutTimer) clearTimeout(timeoutTimer);
960
- if (timedOut) return {
961
- exitCode: 124,
962
- stdout,
963
- stderr,
964
- timedOut: true,
965
- opened: true,
966
- status: response.status
967
- };
968
- return {
969
- exitCode,
970
- stdout,
971
- stderr,
972
- timedOut: false,
973
- opened: true,
974
- status: response.status,
975
- transportErrorMessage: error instanceof Error ? error.message : String(error)
976
- };
977
- } finally {
978
- if (timeoutTimer) clearTimeout(timeoutTimer);
979
- }
980
- return {
981
- exitCode,
982
- stdout,
983
- stderr,
984
- timedOut: false,
985
- opened: true,
986
- status: response.status
987
- };
988
- }
989
- //#endregion
990
603
  //#region ../../packages/_internals/workspace/dist/index.js
991
604
  /** Directory, relative to the template's build cwd, that holds every marker below. */
992
605
  const SETUP_MARKER_DIR = ".mastra-sandbox";
@@ -1097,347 +710,933 @@ function siblingTempPath(path$1) {
1097
710
  * create the link inside it and succeed, so that case is undone and reported
1098
711
  * as taken too.
1099
712
  */
1100
- function linkTempIntoPlace() {
713
+ function linkTempIntoPlace() {
714
+ return [
715
+ `ln "$tmp" "$dest" 2>/dev/null || { rm -f "$tmp"; ${present("dest")} && exit ${exists}; exit 1; }`,
716
+ `if [ -d "$dest" ]; then rm -f "$dest/$(basename "$tmp")" "$tmp"; exit ${exists}; fi`,
717
+ `rm -f "$tmp"`
718
+ ];
719
+ }
720
+ /**
721
+ * Copy `src` to `dest` inside the sandbox, creating `dest`'s parent.
722
+ *
723
+ * A file source copies its content (a symlinked source is followed). A
724
+ * directory source with `recursive` copies its contents into `dest`, keeping
725
+ * symlinks inside the tree as links. With `overwrite: false` the destination
726
+ * is claimed atomically: a directory with an exclusive `mkdir`, a file by
727
+ * copying to a temp name and hard-linking it into place (`link(2)` fails when
728
+ * the destination exists).
729
+ *
730
+ * Exits: `notFound` (no source), `isDirectory` (directory source without
731
+ * `recursive`), `destIsDirectory` (a file onto an existing directory or a link
732
+ * to one), `exists`.
733
+ */
734
+ function copyCommand(src, dest, options = {}) {
735
+ const noClobber = options.overwrite === false;
736
+ return [
737
+ `src=${shellQuote$3(src)}`,
738
+ `dest=${shellQuote$3(dest)}`,
739
+ `[ -e "$src" ] || exit ${notFound}`,
740
+ `mkdir -p "$(dirname "$dest")" || exit 1`,
741
+ `if [ -d "$src" ]; then`,
742
+ options.recursive ? ` :` : ` exit ${isDirectory}`,
743
+ noClobber ? ` mkdir "$dest" 2>/dev/null || exit ${exists}` : ` mkdir -p "$dest" || exit 1`,
744
+ ` cp -R -P "$src"/. "$dest"/ || exit 1`,
745
+ ` exit 0`,
746
+ `fi`,
747
+ noClobber ? `${present("dest")} && exit ${exists}` : `if [ -d "$dest" ]; then exit ${destIsDirectory}; fi`,
748
+ ...noClobber ? [
749
+ `tmp=${shellQuote$3(siblingTempPath(dest))}`,
750
+ `cp "$src" "$tmp" || { rm -f "$tmp"; exit 1; }`,
751
+ ...linkTempIntoPlace()
752
+ ] : [`cp "$src" "$dest" || exit 1`]
753
+ ].join("\n");
754
+ }
755
+ /**
756
+ * Move `src` to `dest` without replacing anything at `dest`, creating `dest`'s
757
+ * parent. A skipped `mv -n` is detected by the source surviving, whatever
758
+ * its exit code. If a directory appears at `dest` between the check and the
759
+ * move, `mv` moves `src` into it (BSD `mv` has no `-T`), and that is reported
760
+ * as success; the no-clobber rename itself is atomic.
761
+ *
762
+ * Exits: `notFound` (no source), `exists`.
763
+ */
764
+ function moveNoClobberCommand(src, dest) {
765
+ return [
766
+ `src=${shellQuote$3(src)}`,
767
+ `dest=${shellQuote$3(dest)}`,
768
+ `${present("src")} || exit ${notFound}`,
769
+ `${present("dest")} && exit ${exists}`,
770
+ `mkdir -p "$(dirname "$dest")" || exit 1`,
771
+ `mv -n "$src" "$dest" 2>/dev/null || { ${present("src")} && ${present("dest")} && exit ${exists}; exit 1; }`,
772
+ `${present("src")} && exit ${exists}`,
773
+ `exit 0`
774
+ ].join("\n");
775
+ }
776
+ /**
777
+ * Append the bytes already written to `tmp` onto `dest`, then delete `tmp`.
778
+ * The content travels as a file rather than a command argument, so it has no
779
+ * size limit. Creates `dest` (and its parent) when missing.
780
+ *
781
+ * Exits: `isDirectory` (dest is a directory).
782
+ */
783
+ function appendFromCommand(tmp, dest) {
1101
784
  return [
1102
- `ln "$tmp" "$dest" 2>/dev/null || { rm -f "$tmp"; ${present("dest")} && exit ${exists}; exit 1; }`,
1103
- `if [ -d "$dest" ]; then rm -f "$dest/$(basename "$tmp")" "$tmp"; exit ${exists}; fi`,
1104
- `rm -f "$tmp"`
1105
- ];
785
+ `tmp=${shellQuote$3(tmp)}`,
786
+ `dest=${shellQuote$3(dest)}`,
787
+ `if [ -d "$dest" ]; then rm -f "$tmp"; exit ${isDirectory}; fi`,
788
+ `mkdir -p "$(dirname "$dest")" && cat "$tmp" >> "$dest"`,
789
+ `status=$?`,
790
+ `rm -f "$tmp"`,
791
+ `exit $status`
792
+ ].join("\n");
1106
793
  }
1107
794
  /**
1108
- * Copy `src` to `dest` inside the sandbox, creating `dest`'s parent.
1109
- *
1110
- * A file source copies its content (a symlinked source is followed). A
1111
- * directory source with `recursive` copies its contents into `dest`, keeping
1112
- * symlinks inside the tree as links. With `overwrite: false` the destination
1113
- * is claimed atomically: a directory with an exclusive `mkdir`, a file by
1114
- * copying to a temp name and hard-linking it into place (`link(2)` fails when
1115
- * the destination exists).
795
+ * Publish the file already written to `tmp` at `dest` only if nothing is
796
+ * there, then delete `tmp`. `ln` (`link(2)`) is the atomic exclusivity check;
797
+ * `tmp` must be on the same filesystem, e.g. from {@link siblingTempPath}.
1116
798
  *
1117
- * Exits: `notFound` (no source), `isDirectory` (directory source without
1118
- * `recursive`), `destIsDirectory` (a file onto an existing directory or a link
1119
- * to one), `exists`.
799
+ * Exits: `exists`, `notDirectory` (dest's parent is not a directory).
1120
800
  */
1121
- function copyCommand(src, dest, options = {}) {
1122
- const noClobber = options.overwrite === false;
801
+ function linkNoClobberCommand(tmp, dest) {
1123
802
  return [
1124
- `src=${shellQuote$3(src)}`,
803
+ `tmp=${shellQuote$3(tmp)}`,
1125
804
  `dest=${shellQuote$3(dest)}`,
1126
- `[ -e "$src" ] || exit ${notFound}`,
1127
- `mkdir -p "$(dirname "$dest")" || exit 1`,
1128
- `if [ -d "$src" ]; then`,
1129
- options.recursive ? ` :` : ` exit ${isDirectory}`,
1130
- noClobber ? ` mkdir "$dest" 2>/dev/null || exit ${exists}` : ` mkdir -p "$dest" || exit 1`,
1131
- ` cp -R -P "$src"/. "$dest"/ || exit 1`,
1132
- ` exit 0`,
1133
- `fi`,
1134
- noClobber ? `${present("dest")} && exit ${exists}` : `if [ -d "$dest" ]; then exit ${destIsDirectory}; fi`,
1135
- ...noClobber ? [
1136
- `tmp=${shellQuote$3(siblingTempPath(dest))}`,
1137
- `cp "$src" "$tmp" || { rm -f "$tmp"; exit 1; }`,
1138
- ...linkTempIntoPlace()
1139
- ] : [`cp "$src" "$dest" || exit 1`]
805
+ `if [ ! -d "$(dirname "$dest")" ]; then rm -f "$tmp"; exit ${notDirectory}; fi`,
806
+ `if ${present("dest")}; then rm -f "$tmp"; exit ${exists}; fi`,
807
+ ...linkTempIntoPlace()
1140
808
  ].join("\n");
1141
809
  }
810
+ /** Default recursion depth for `readdir({ recursive: true })`, matching `LocalFilesystem`. */
811
+ const DEFAULT_MAX_DEPTH = 100;
812
+ const toAbsolute = (path$2) => path.posix.resolve("/", path$2);
813
+ /** The entry's own type: a symlink is a link even when it points at a directory. */
814
+ const isSymlink = (info) => info.symlinkTarget !== void 0;
815
+ function toWriteData(content) {
816
+ if (typeof content === "string") return content;
817
+ return content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);
818
+ }
819
+ function matchesExtension(name, extension) {
820
+ if (!extension) return true;
821
+ const ext = path.posix.extname(name);
822
+ return (Array.isArray(extension) ? extension : [extension]).some((e) => e === ext || e === ext.slice(1));
823
+ }
824
+ /**
825
+ * A sandbox's disk, read and written through E2B's envd files API, with the
826
+ * operations the files API can't do in one call (copy, append, no-clobber
827
+ * writes and moves) run as one shell command inside the VM so they are atomic
828
+ * and file bytes never round-trip through the host. Paths are absolute inside
829
+ * the sandbox; this class does not confine paths or symlinks to any root.
830
+ *
831
+ * Providers supply how to reach the files API and the shell, and how to read
832
+ * their SDK's errors.
833
+ *
834
+ * If a provider's `runCommand` re-runs a command whose first run already
835
+ * finished (e.g. a retry after a dropped connection), the second run sees the
836
+ * first's result: a no-clobber copy, write or move reports `FileExistsError`
837
+ * or `FileNotFoundError`, and an append fails, even though the work was done.
838
+ */
839
+ var FilesApiFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
840
+ async readFile(path, options) {
841
+ const abs = toAbsolute(path);
842
+ const bytes = await this.runFiles("readFile", async (files) => {
843
+ try {
844
+ return await files.read(abs, { format: "bytes" });
845
+ } catch (error) {
846
+ const kind = this.errorKind(error);
847
+ if (kind === "not-found") throw new _mastra_core_workspace.FileNotFoundError(path);
848
+ if (kind === "invalid-argument") throw new _mastra_core_workspace.IsDirectoryError(path);
849
+ throw error;
850
+ }
851
+ });
852
+ const buffer$1 = buffer.Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
853
+ return options?.encoding ? buffer$1.toString(options.encoding) : buffer$1;
854
+ }
855
+ async writeFile(path$3, content, options) {
856
+ const abs = toAbsolute(path$3);
857
+ if (options?.overwrite !== false) {
858
+ await this.runFiles("writeFile", async (files) => {
859
+ if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path$3);
860
+ await this.#write(files, abs, path$3, toWriteData(content));
861
+ });
862
+ return;
863
+ }
864
+ const tmp = siblingTempPath(abs);
865
+ const upload = async (files) => {
866
+ if (options.recursive === false) await this.#assertParentDirectory(files, abs, path$3);
867
+ await this.#write(files, tmp, path$3, toWriteData(content));
868
+ };
869
+ await this.#publishTemp(tmp, "writeFile", upload, linkNoClobberCommand(tmp, abs), path$3, {
870
+ exists: () => new _mastra_core_workspace.FileExistsError(path$3),
871
+ notDirectory: () => new _mastra_core_workspace.NotDirectoryError(path.posix.dirname(path$3))
872
+ });
873
+ }
874
+ async appendFile(path, content) {
875
+ const abs = toAbsolute(path);
876
+ const tmp = siblingTempPath(abs);
877
+ const upload = (files) => this.#write(files, tmp, path, toWriteData(content));
878
+ await this.#publishTemp(tmp, "appendFile", upload, appendFromCommand(tmp, abs), path, { isDirectory: () => new _mastra_core_workspace.IsDirectoryError(path) });
879
+ }
880
+ async deleteFile(path, options) {
881
+ const abs = toAbsolute(path);
882
+ await this.runFiles("deleteFile", async (files) => {
883
+ const info = await this.#info(files, abs);
884
+ if (!info) {
885
+ if (options?.force) return;
886
+ throw new _mastra_core_workspace.FileNotFoundError(path);
887
+ }
888
+ if (!isSymlink(info) && info.type === "dir") throw new _mastra_core_workspace.IsDirectoryError(path);
889
+ await files.remove(abs);
890
+ });
891
+ }
892
+ /**
893
+ * One `cp` inside the VM. A recursive copy keeps symlinks inside the tree as
894
+ * links; `overwrite: false` claims the destination atomically.
895
+ */
896
+ async copyFile(src, dest, options) {
897
+ const command = copyCommand(toAbsolute(src), toAbsolute(dest), {
898
+ recursive: options?.recursive,
899
+ overwrite: options?.overwrite
900
+ });
901
+ await this.#command("copyFile", command, `${src} -> ${dest}`, {
902
+ notFound: () => new _mastra_core_workspace.FileNotFoundError(src),
903
+ isDirectory: () => new _mastra_core_workspace.IsDirectoryError(src),
904
+ destIsDirectory: () => new _mastra_core_workspace.IsDirectoryError(dest),
905
+ exists: () => new _mastra_core_workspace.FileExistsError(dest)
906
+ });
907
+ }
908
+ async moveFile(src, dest, options) {
909
+ const srcAbs = toAbsolute(src);
910
+ const destAbs = toAbsolute(dest);
911
+ if (options?.overwrite === false) {
912
+ await this.#command("moveFile", moveNoClobberCommand(srcAbs, destAbs), `${src} -> ${dest}`, {
913
+ notFound: () => new _mastra_core_workspace.FileNotFoundError(src),
914
+ exists: () => new _mastra_core_workspace.FileExistsError(dest)
915
+ });
916
+ return;
917
+ }
918
+ await this.runFiles("moveFile", async (files) => {
919
+ try {
920
+ await files.rename(srcAbs, destAbs);
921
+ } catch (error) {
922
+ if (this.errorKind(error) === "not-found") throw new _mastra_core_workspace.FileNotFoundError(src);
923
+ throw error;
924
+ }
925
+ });
926
+ }
927
+ async mkdir(path, options) {
928
+ const abs = toAbsolute(path);
929
+ await this.runFiles("mkdir", async (files) => {
930
+ if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path);
931
+ try {
932
+ await files.makeDir(abs);
933
+ } catch (error) {
934
+ if (this.errorKind(error) === "invalid-argument") throw new _mastra_core_workspace.FileExistsError(path);
935
+ throw error;
936
+ }
937
+ });
938
+ }
939
+ async rmdir(path, options) {
940
+ const abs = toAbsolute(path);
941
+ await this.runFiles("rmdir", async (files) => {
942
+ const info = await this.#info(files, abs);
943
+ if (!info) {
944
+ if (options?.force) return;
945
+ throw new _mastra_core_workspace.DirectoryNotFoundError(path);
946
+ }
947
+ if (!options?.recursive) {
948
+ if (isSymlink(info) || info.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path);
949
+ if ((await files.list(abs)).length > 0) throw new _mastra_core_workspace.DirectoryNotEmptyError(path);
950
+ } else if (!isSymlink(info) && info.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path);
951
+ await files.remove(abs);
952
+ });
953
+ }
954
+ async readdir(path$4, options) {
955
+ const abs = toAbsolute(path$4);
956
+ const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;
957
+ const entries = await this.runFiles("readdir", async (files) => {
958
+ try {
959
+ return await files.list(abs, { depth });
960
+ } catch (error) {
961
+ const kind = this.errorKind(error);
962
+ if (kind === "not-found") throw new _mastra_core_workspace.DirectoryNotFoundError(path$4);
963
+ if (kind === "invalid-argument") throw new _mastra_core_workspace.NotDirectoryError(path$4);
964
+ throw error;
965
+ }
966
+ });
967
+ const result = [];
968
+ for (const entry of entries) {
969
+ if (!entry.type) continue;
970
+ const name = path.posix.relative(abs, entry.path);
971
+ const type = entry.type === "dir" ? "directory" : "file";
972
+ if (type === "file" && !matchesExtension(name, options?.extension)) continue;
973
+ const link = isSymlink(entry);
974
+ result.push({
975
+ name,
976
+ type,
977
+ ...type === "file" && !link && { size: entry.size },
978
+ ...link && {
979
+ isSymlink: true,
980
+ symlinkTarget: entry.symlinkTarget
981
+ }
982
+ });
983
+ }
984
+ return result;
985
+ }
986
+ async exists(path) {
987
+ const abs = toAbsolute(path);
988
+ return this.runFiles("exists", async (files) => Boolean((await this.#info(files, abs))?.type));
989
+ }
990
+ async stat(path$5) {
991
+ const abs = toAbsolute(path$5);
992
+ return this.runFiles("stat", async (files) => {
993
+ let info = await this.#info(files, abs);
994
+ if (info?.type && isSymlink(info)) info = await this.#info(files, path.posix.resolve(path.posix.dirname(abs), info.symlinkTarget));
995
+ if (!info?.type) throw new _mastra_core_workspace.FileNotFoundError(path$5);
996
+ const modifiedAt = info.modifiedTime ?? /* @__PURE__ */ new Date(0);
997
+ return {
998
+ name: path.posix.basename(abs),
999
+ path: abs,
1000
+ type: info.type === "dir" ? "directory" : "file",
1001
+ size: info.type === "dir" ? 0 : info.size,
1002
+ createdAt: modifiedAt,
1003
+ modifiedAt
1004
+ };
1005
+ });
1006
+ }
1007
+ /** `getInfo` without following the entry itself, or `undefined` when nothing is there. */
1008
+ async #info(files, abs) {
1009
+ try {
1010
+ return await files.getInfo(abs);
1011
+ } catch (error) {
1012
+ if (this.errorKind(error) === "not-found") return void 0;
1013
+ throw error;
1014
+ }
1015
+ }
1016
+ async #assertParentDirectory(files, abs, path$6) {
1017
+ const parent = await this.#info(files, path.posix.dirname(abs));
1018
+ if (!parent?.type) throw new _mastra_core_workspace.DirectoryNotFoundError(path.posix.dirname(path$6));
1019
+ if (parent.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path.posix.dirname(path$6));
1020
+ }
1021
+ async #write(files, abs, path, data) {
1022
+ try {
1023
+ await files.write(abs, data);
1024
+ } catch (error) {
1025
+ if (this.errorKind(error) === "invalid-argument") throw new _mastra_core_workspace.IsDirectoryError(path);
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Upload the temp file `tmp`, then run the command that consumes it. The
1031
+ * script deletes it on every path it controls; if the upload or the command
1032
+ * fails part-way, delete it here so it doesn't linger in the user's tree.
1033
+ */
1034
+ async #publishTemp(tmp, operation, upload, script, subject, errors) {
1035
+ try {
1036
+ await this.runFiles(operation, upload);
1037
+ await this.#command(operation, script, subject, errors);
1038
+ } catch (error) {
1039
+ await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
1040
+ throw error;
1041
+ }
1042
+ }
1043
+ /** Run a file command and turn its known exit codes into typed errors. */
1044
+ async #command(operation, script, subject, errors) {
1045
+ const result = await this.runCommand(operation, script);
1046
+ if (result.exitCode === 0) return;
1047
+ for (const [outcome, code] of Object.entries(FILE_COMMAND_EXIT)) {
1048
+ const toError = errors[outcome];
1049
+ if (code === result.exitCode && toError) throw toError();
1050
+ }
1051
+ throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
1052
+ }
1053
+ };
1142
1054
  /**
1143
- * Move `src` to `dest` without replacing anything at `dest`, creating `dest`'s
1144
- * parent. A skipped `mv -n` is detected by the source surviving, whatever
1145
- * its exit code. If a directory appears at `dest` between the check and the
1146
- * move, `mv` moves `src` into it (BSD `mv` has no `-T`), and that is reported
1147
- * as success; the no-clobber rename itself is atomic.
1148
- *
1149
- * Exits: `notFound` (no source), `exists`.
1055
+ * Output callbacks for `run`/`connect` that hold output until the handle
1056
+ * exists. The SDK's handle reads events from construction, before `run()`
1057
+ * returns, so output that arrives with the start event reaches the
1058
+ * callbacks first.
1150
1059
  */
1151
- function moveNoClobberCommand(src, dest) {
1152
- return [
1153
- `src=${shellQuote$3(src)}`,
1154
- `dest=${shellQuote$3(dest)}`,
1155
- `${present("src")} || exit ${notFound}`,
1156
- `${present("dest")} && exit ${exists}`,
1157
- `mkdir -p "$(dirname "$dest")" || exit 1`,
1158
- `mv -n "$src" "$dest" 2>/dev/null || { ${present("src")} && ${present("dest")} && exit ${exists}; exit 1; }`,
1159
- `${present("src")} && exit ${exists}`,
1160
- `exit 0`
1161
- ].join("\n");
1060
+ function outputUntilHandled() {
1061
+ let handle;
1062
+ const early = [];
1063
+ return {
1064
+ onStdout: (data) => {
1065
+ if (handle) handle.emitStdout(data);
1066
+ else early.push({
1067
+ stream: "stdout",
1068
+ data
1069
+ });
1070
+ },
1071
+ onStderr: (data) => {
1072
+ if (handle) handle.emitStderr(data);
1073
+ else early.push({
1074
+ stream: "stderr",
1075
+ data
1076
+ });
1077
+ },
1078
+ handledBy(created) {
1079
+ for (const { stream, data } of early) if (stream === "stdout") created.emitStdout(data);
1080
+ else created.emitStderr(data);
1081
+ early.length = 0;
1082
+ handle = created;
1083
+ return created;
1084
+ }
1085
+ };
1162
1086
  }
1163
- /**
1164
- * Append the bytes already written to `tmp` onto `dest`, then delete `tmp`.
1165
- * The content travels as a file rather than a command argument, so it has no
1166
- * size limit. Creates `dest` (and its parent) when missing.
1167
- *
1168
- * Exits: `isDirectory` (dest is a directory).
1169
- */
1170
- function appendFromCommand(tmp, dest) {
1171
- return [
1172
- `tmp=${shellQuote$3(tmp)}`,
1173
- `dest=${shellQuote$3(dest)}`,
1174
- `if [ -d "$dest" ]; then rm -f "$tmp"; exit ${isDirectory}; fi`,
1175
- `mkdir -p "$(dirname "$dest")" && cat "$tmp" >> "$dest"`,
1176
- `status=$?`,
1177
- `rm -f "$tmp"`,
1178
- `exit $status`
1179
- ].join("\n");
1087
+ /** envd runs every command as `/bin/bash -l -c <command>`; show the command itself. */
1088
+ function commandOf(proc) {
1089
+ const [flag, c, command] = proc.args;
1090
+ if (proc.cmd === "/bin/bash" && flag === "-l" && c === "-c" && command !== void 0 && proc.args.length === 3) return command;
1091
+ return [proc.cmd, ...proc.args].join(" ");
1180
1092
  }
1181
1093
  /**
1182
- * Publish the file already written to `tmp` at `dest` only if nothing is
1183
- * there, then delete `tmp`. `ln` (`link(2)`) is the atomic exclusivity check;
1184
- * `tmp` must be on the same filesystem, e.g. from {@link siblingTempPath}.
1185
- *
1186
- * Exits: `exists`, `notDirectory` (dest's parent is not a directory).
1094
+ * A process started or attached through a {@link CommandsApi}. `kill` and
1095
+ * `sendStdin` go back through the manager, so they use whatever commands
1096
+ * handle the provider currently supplies.
1187
1097
  */
1188
- function linkNoClobberCommand(tmp, dest) {
1189
- return [
1190
- `tmp=${shellQuote$3(tmp)}`,
1191
- `dest=${shellQuote$3(dest)}`,
1192
- `if [ ! -d "$(dirname "$dest")" ]; then rm -f "$tmp"; exit ${notDirectory}; fi`,
1193
- `if ${present("dest")}; then rm -f "$tmp"; exit ${exists}; fi`,
1194
- ...linkTempIntoPlace()
1195
- ].join("\n");
1196
- }
1197
- /** Default recursion depth for `readdir({ recursive: true })`, matching `LocalFilesystem`. */
1198
- const DEFAULT_MAX_DEPTH = 100;
1199
- const toAbsolute = (path$2) => path.posix.resolve("/", path$2);
1200
- /** The entry's own type: a symlink is a link even when it points at a directory. */
1201
- const isSymlink = (info) => info.symlinkTarget !== void 0;
1202
- function toWriteData(content) {
1203
- if (typeof content === "string") return content;
1204
- return content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);
1205
- }
1206
- function matchesExtension(name, extension) {
1207
- if (!extension) return true;
1208
- const ext = path.posix.extname(name);
1209
- return (Array.isArray(extension) ? extension : [extension]).some((e) => e === ext || e === ext.slice(1));
1210
- }
1098
+ var CommandsApiProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
1099
+ inner;
1100
+ manager;
1101
+ startTime;
1102
+ stdinMode;
1103
+ pid;
1104
+ /** The exit code `wait()` saw, for a handle that doesn't update its own. */
1105
+ waitedExitCode;
1106
+ constructor(inner, manager, startTime, stdinMode, options) {
1107
+ super(options);
1108
+ this.inner = inner;
1109
+ this.manager = manager;
1110
+ this.startTime = startTime;
1111
+ this.stdinMode = stdinMode;
1112
+ this.pid = String(inner.pid);
1113
+ }
1114
+ /** Read from the commands handle, so it reflects server-side state without `wait()`. */
1115
+ get exitCode() {
1116
+ return this.inner.exitCode ?? this.waitedExitCode;
1117
+ }
1118
+ /** Wait for the process to exit. Providers whose output stream can drop while the process runs override this. */
1119
+ waitForExit() {
1120
+ return this.inner.wait();
1121
+ }
1122
+ async wait() {
1123
+ try {
1124
+ const result = await this.waitForExit();
1125
+ this.waitedExitCode = result.exitCode;
1126
+ return {
1127
+ success: result.exitCode === 0,
1128
+ exitCode: result.exitCode,
1129
+ stdout: this.stdout,
1130
+ stderr: this.stderr,
1131
+ executionTimeMs: Date.now() - this.startTime
1132
+ };
1133
+ } catch (error) {
1134
+ const errorObj = error;
1135
+ const reportedExitCode = errorObj.result?.exitCode ?? errorObj.exitCode;
1136
+ if (reportedExitCode !== void 0) this.waitedExitCode = reportedExitCode;
1137
+ const exitCode = reportedExitCode ?? this.exitCode ?? 1;
1138
+ const attachedStdout = errorObj.result?.stdout || errorObj.stdout;
1139
+ const attachedStderr = errorObj.result?.stderr || errorObj.stderr;
1140
+ if (!this.stdout && !this.stdoutTruncated && attachedStdout) this.emitStdout(attachedStdout);
1141
+ if (!this.stderr && !this.stderrTruncated && attachedStderr) this.emitStderr(attachedStderr);
1142
+ const stdout = this.stdout;
1143
+ const stderr = this.stderr;
1144
+ const terminalError = errorObj.result?.error || errorObj.error || (error instanceof Error ? error.message : String(error));
1145
+ return {
1146
+ success: false,
1147
+ exitCode,
1148
+ stdout,
1149
+ stderr: [stderr, terminalError && !stderr.includes(terminalError) ? `Error: ${terminalError}` : ""].filter(Boolean).join("\n"),
1150
+ executionTimeMs: Date.now() - this.startTime
1151
+ };
1152
+ }
1153
+ }
1154
+ async kill() {
1155
+ if (this.exitCode !== void 0) return false;
1156
+ return this.manager.runCommands("kill", (commands) => commands.kill(this.inner.pid));
1157
+ }
1158
+ async sendStdin(data) {
1159
+ if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
1160
+ if (this.stdinMode === "ignore") throw new Error(`Process ${this.pid} was not started with stdin support`);
1161
+ await this.manager.runCommands("sendStdin", (commands) => commands.sendStdin(this.inner.pid, data));
1162
+ }
1163
+ async closeStdin() {
1164
+ throw new _mastra_core_workspace.UnsupportedStdinCloseError("The commands API does not expose a way to close stdin for a running command");
1165
+ }
1166
+ };
1211
1167
  /**
1212
- * A sandbox's disk, read and written through E2B's envd files API, with the
1213
- * operations the files API can't do in one call (copy, append, no-clobber
1214
- * writes and moves) run as one shell command inside the VM so they are atomic
1215
- * and file bytes never round-trip through the host. Paths are absolute inside
1216
- * the sandbox; this class does not confine paths or symlinks to any root.
1217
- *
1218
- * Providers supply how to reach the files API and the shell, and how to read
1219
- * their SDK's errors.
1220
- *
1221
- * If a provider's `runCommand` re-runs a command whose first run already
1222
- * finished (e.g. a retry after a dropped connection), the second run sees the
1223
- * first's result: a no-clobber copy, write or move reports `FileExistsError`
1224
- * or `FileNotFoundError`, and an append fails, even though the work was done.
1168
+ * A process manager over E2B's envd commands API. Providers supply the
1169
+ * commands handle through {@link runCommands}; everything else is shared.
1225
1170
  */
1226
- var FilesApiFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
1227
- async readFile(path, options) {
1228
- const abs = toAbsolute(path);
1229
- const bytes = await this.runFiles("readFile", async (files) => {
1230
- try {
1231
- return await files.read(abs, { format: "bytes" });
1232
- } catch (error) {
1233
- const kind = this.errorKind(error);
1234
- if (kind === "not-found") throw new _mastra_core_workspace.FileNotFoundError(path);
1235
- if (kind === "invalid-argument") throw new _mastra_core_workspace.IsDirectoryError(path);
1236
- throw error;
1237
- }
1171
+ var CommandsApiProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
1172
+ defaultTimeout;
1173
+ constructor({ defaultTimeout, ...options } = {}) {
1174
+ super(options);
1175
+ this.defaultTimeout = defaultTimeout;
1176
+ }
1177
+ /** Wrap a started or attached command. Providers override this to supply their own handle. */
1178
+ createHandle(inner, stdinMode, options) {
1179
+ return new CommandsApiProcessHandle(inner, this, Date.now(), stdinMode, options);
1180
+ }
1181
+ /** Where a command runs when the caller gives no `cwd`. */
1182
+ defaultCwd() {
1183
+ return this.sandbox.workingDirectory;
1184
+ }
1185
+ async spawn(command, options = {}) {
1186
+ const envs = Object.fromEntries(Object.entries({ ...options.env }).filter((entry) => entry[1] !== void 0));
1187
+ return this.runCommands("spawn", async (commands) => {
1188
+ const output = outputUntilHandled();
1189
+ const inner = await commands.run(command, {
1190
+ background: true,
1191
+ stdin: options.stdinMode !== "ignore",
1192
+ cwd: options.cwd ?? this.defaultCwd(),
1193
+ envs,
1194
+ timeoutMs: options.timeout ?? this.defaultTimeout,
1195
+ onStdout: output.onStdout,
1196
+ onStderr: output.onStderr
1197
+ });
1198
+ const handle = output.handledBy(this.createHandle(inner, options.stdinMode, options));
1199
+ this._tracked.set(handle.pid, handle);
1200
+ return handle;
1238
1201
  });
1239
- const buffer$1 = buffer.Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1240
- return options?.encoding ? buffer$1.toString(options.encoding) : buffer$1;
1241
1202
  }
1242
- async writeFile(path$3, content, options) {
1243
- const abs = toAbsolute(path$3);
1244
- if (options?.overwrite !== false) {
1245
- await this.runFiles("writeFile", async (files) => {
1246
- if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path$3);
1247
- await this.#write(files, abs, path$3, toWriteData(content));
1203
+ /**
1204
+ * Running processes as the VM reports them, plus exited processes this
1205
+ * manager still holds, so a finished command stays visible until it is released.
1206
+ */
1207
+ async list() {
1208
+ const infos = (await this.runCommands("list", (commands) => commands.list())).map((proc) => ({
1209
+ pid: String(proc.pid),
1210
+ command: commandOf(proc),
1211
+ running: true
1212
+ }));
1213
+ const listed = new Set(infos.map((info) => info.pid));
1214
+ for (const [pid, handle] of this._tracked) {
1215
+ if (handle.exitCode === void 0 || listed.has(pid)) continue;
1216
+ infos.push({
1217
+ pid,
1218
+ command: handle.command,
1219
+ running: false,
1220
+ exitCode: handle.exitCode
1248
1221
  });
1249
- return;
1250
1222
  }
1251
- const tmp = siblingTempPath(abs);
1252
- const upload = async (files) => {
1253
- if (options.recursive === false) await this.#assertParentDirectory(files, abs, path$3);
1254
- await this.#write(files, tmp, path$3, toWriteData(content));
1255
- };
1256
- await this.#publishTemp(tmp, "writeFile", upload, linkNoClobberCommand(tmp, abs), path$3, {
1257
- exists: () => new _mastra_core_workspace.FileExistsError(path$3),
1258
- notDirectory: () => new _mastra_core_workspace.NotDirectoryError(path.posix.dirname(path$3))
1259
- });
1223
+ return infos;
1260
1224
  }
1261
- async appendFile(path, content) {
1262
- const abs = toAbsolute(path);
1263
- const tmp = siblingTempPath(abs);
1264
- const upload = (files) => this.#write(files, tmp, path, toWriteData(content));
1265
- await this.#publishTemp(tmp, "appendFile", upload, appendFromCommand(tmp, abs), path, { isDirectory: () => new _mastra_core_workspace.IsDirectoryError(path) });
1225
+ /**
1226
+ * A tracked process, or one this manager didn't start, attached through
1227
+ * `connect`. Output from before attaching is not available.
1228
+ */
1229
+ async get(pid, _options) {
1230
+ const tracked = this._tracked.get(pid);
1231
+ if (tracked) return tracked;
1232
+ const numericPid = /^\d+$/.test(pid) ? Number(pid) : void 0;
1233
+ if (numericPid === void 0) return void 0;
1234
+ const output = outputUntilHandled();
1235
+ try {
1236
+ const inner = await this.runCommands("connect", (commands) => commands.connect(numericPid, {
1237
+ onStdout: output.onStdout,
1238
+ onStderr: output.onStderr,
1239
+ timeoutMs: 0
1240
+ }));
1241
+ const handle = output.handledBy(this.createHandle(inner, void 0));
1242
+ this._tracked.set(handle.pid, handle);
1243
+ return handle;
1244
+ } catch {
1245
+ return;
1246
+ }
1266
1247
  }
1267
- async deleteFile(path, options) {
1268
- const abs = toAbsolute(path);
1269
- await this.runFiles("deleteFile", async (files) => {
1270
- const info = await this.#info(files, abs);
1271
- if (!info) {
1272
- if (options?.force) return;
1273
- throw new _mastra_core_workspace.FileNotFoundError(path);
1248
+ };
1249
+ //#endregion
1250
+ //#region src/direct-exec.ts
1251
+ /**
1252
+ * Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
1253
+ * a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
1254
+ * removes the platform data plane from the exec stdout/stderr path entirely
1255
+ * (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
1256
+ * cutting payload-scaled Cloud Run egress and RTT for commands like
1257
+ * `pnpm install` that stream tens of MB of output.
1258
+ *
1259
+ * The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
1260
+ * (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
1261
+ * SDK's version is pinned on both sides (platform + here); a version bump
1262
+ * signals the protocol may have drifted and this module must be revisited.
1263
+ */
1264
+ /** Byte-0 tag on binary WS frames for stdout output. */
1265
+ const STDOUT_FRAME = 1;
1266
+ /** Byte-0 tag on binary WS frames for stderr output. */
1267
+ const STDERR_FRAME = 3;
1268
+ /**
1269
+ * Upper bound on how long we'll wait for the WebSocket to open when the
1270
+ * caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
1271
+ * handshake leaving the promise unresolved forever. Not applied once the
1272
+ * socket has opened — a caller with no timeout has opted in to unbounded
1273
+ * command runtime, just not to unbounded connection setup.
1274
+ */
1275
+ const HANDSHAKE_DEADLINE_MS = 3e4;
1276
+ const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
1277
+ const WS = globalThis.WebSocket;
1278
+ if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
1279
+ return new WS(endpoint, subprotocols);
1280
+ };
1281
+ /**
1282
+ * Open the provider exec WebSocket using `lease`, run `command`, and resolve
1283
+ * with the accumulated stdout/stderr + exit code. See the module docstring
1284
+ * for the wire protocol reference.
1285
+ *
1286
+ * The client sends `stdin_close` immediately after `init_exec`, matching the
1287
+ * SDK's own one-shot exec behavior — we never stream stdin from the caller.
1288
+ */
1289
+ function execViaLease(lease, options) {
1290
+ const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
1291
+ const stdoutDecoder = new TextDecoder();
1292
+ const stderrDecoder = new TextDecoder();
1293
+ return new Promise((resolve) => {
1294
+ let stdout = "";
1295
+ let stderr = "";
1296
+ let exitCode = null;
1297
+ let timedOut = false;
1298
+ let settled = false;
1299
+ let opened = false;
1300
+ let closeCode;
1301
+ let closeReason;
1302
+ let timer;
1303
+ let handshakeTimer;
1304
+ const settle = () => {
1305
+ if (settled) return;
1306
+ settled = true;
1307
+ if (timer) clearTimeout(timer);
1308
+ if (handshakeTimer) clearTimeout(handshakeTimer);
1309
+ const stdoutTail = stdoutDecoder.decode();
1310
+ if (stdoutTail) {
1311
+ stdout += stdoutTail;
1312
+ options.onStdout?.(stdoutTail);
1274
1313
  }
1275
- if (!isSymlink(info) && info.type === "dir") throw new _mastra_core_workspace.IsDirectoryError(path);
1276
- await files.remove(abs);
1277
- });
1278
- }
1279
- /**
1280
- * One `cp` inside the VM. A recursive copy keeps symlinks inside the tree as
1281
- * links; `overwrite: false` claims the destination atomically.
1282
- */
1283
- async copyFile(src, dest, options) {
1284
- const command = copyCommand(toAbsolute(src), toAbsolute(dest), {
1285
- recursive: options?.recursive,
1286
- overwrite: options?.overwrite
1287
- });
1288
- await this.#command("copyFile", command, `${src} -> ${dest}`, {
1289
- notFound: () => new _mastra_core_workspace.FileNotFoundError(src),
1290
- isDirectory: () => new _mastra_core_workspace.IsDirectoryError(src),
1291
- destIsDirectory: () => new _mastra_core_workspace.IsDirectoryError(dest),
1292
- exists: () => new _mastra_core_workspace.FileExistsError(dest)
1293
- });
1294
- }
1295
- async moveFile(src, dest, options) {
1296
- const srcAbs = toAbsolute(src);
1297
- const destAbs = toAbsolute(dest);
1298
- if (options?.overwrite === false) {
1299
- await this.#command("moveFile", moveNoClobberCommand(srcAbs, destAbs), `${src} -> ${dest}`, {
1300
- notFound: () => new _mastra_core_workspace.FileNotFoundError(src),
1301
- exists: () => new _mastra_core_workspace.FileExistsError(dest)
1302
- });
1303
- return;
1304
- }
1305
- await this.runFiles("moveFile", async (files) => {
1306
- try {
1307
- await files.rename(srcAbs, destAbs);
1308
- } catch (error) {
1309
- if (this.errorKind(error) === "not-found") throw new _mastra_core_workspace.FileNotFoundError(src);
1310
- throw error;
1314
+ const stderrTail = stderrDecoder.decode();
1315
+ if (stderrTail) {
1316
+ stderr += stderrTail;
1317
+ options.onStderr?.(stderrTail);
1311
1318
  }
1312
- });
1313
- }
1314
- async mkdir(path, options) {
1315
- const abs = toAbsolute(path);
1316
- await this.runFiles("mkdir", async (files) => {
1317
- if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path);
1318
1319
  try {
1319
- await files.makeDir(abs);
1320
- } catch (error) {
1321
- if (this.errorKind(error) === "invalid-argument") throw new _mastra_core_workspace.FileExistsError(path);
1322
- throw error;
1320
+ socket.close(1e3, "");
1321
+ } catch {}
1322
+ resolve({
1323
+ exitCode,
1324
+ stdout,
1325
+ stderr,
1326
+ truncated: false,
1327
+ timedOut,
1328
+ ...closeCode !== void 0 && { closeCode },
1329
+ ...closeReason !== void 0 && { closeReason },
1330
+ opened
1331
+ });
1332
+ };
1333
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
1334
+ timedOut = true;
1335
+ if (exitCode === null) exitCode = 124;
1336
+ settle();
1337
+ }, options.timeoutMs);
1338
+ else handshakeTimer = setTimeout(() => {
1339
+ if (!opened) settle();
1340
+ }, HANDSHAKE_DEADLINE_MS);
1341
+ const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
1342
+ socket.binaryType = "arraybuffer";
1343
+ socket.onopen = () => {
1344
+ opened = true;
1345
+ if (handshakeTimer) {
1346
+ clearTimeout(handshakeTimer);
1347
+ handshakeTimer = void 0;
1323
1348
  }
1324
- });
1325
- }
1326
- async rmdir(path, options) {
1327
- const abs = toAbsolute(path);
1328
- await this.runFiles("rmdir", async (files) => {
1329
- const info = await this.#info(files, abs);
1330
- if (!info) {
1331
- if (options?.force) return;
1332
- throw new _mastra_core_workspace.DirectoryNotFoundError(path);
1349
+ const data = { command: options.command };
1350
+ if (options.cwd) data.cwd = options.cwd;
1351
+ if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
1352
+ socket.send(JSON.stringify({
1353
+ type: "init_exec",
1354
+ data
1355
+ }));
1356
+ socket.send(JSON.stringify({ type: "stdin_close" }));
1357
+ };
1358
+ socket.onmessage = (event) => {
1359
+ const { data } = event;
1360
+ if (data instanceof ArrayBuffer) handleBinaryFrame(data);
1361
+ else if (typeof data === "string") handleTextFrame(data);
1362
+ };
1363
+ socket.onclose = (event) => {
1364
+ closeCode = event.code;
1365
+ closeReason = event.reason;
1366
+ if (!opened) {
1367
+ settle();
1368
+ return;
1333
1369
  }
1334
- if (!options?.recursive) {
1335
- if (isSymlink(info) || info.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path);
1336
- if ((await files.list(abs)).length > 0) throw new _mastra_core_workspace.DirectoryNotEmptyError(path);
1337
- } else if (!isSymlink(info) && info.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path);
1338
- await files.remove(abs);
1339
- });
1340
- }
1341
- async readdir(path$4, options) {
1342
- const abs = toAbsolute(path$4);
1343
- const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;
1344
- const entries = await this.runFiles("readdir", async (files) => {
1370
+ settle();
1371
+ };
1372
+ socket.onerror = () => {
1373
+ if (settled) return;
1374
+ if (!opened) settle();
1375
+ };
1376
+ function handleBinaryFrame(buffer) {
1377
+ const view = new Uint8Array(buffer);
1378
+ if (view.length <= 1) return;
1379
+ if (view[0] === STDOUT_FRAME) {
1380
+ const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
1381
+ stdout += chunk;
1382
+ options.onStdout?.(chunk);
1383
+ } else if (view[0] === STDERR_FRAME) {
1384
+ const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
1385
+ stderr += chunk;
1386
+ options.onStderr?.(chunk);
1387
+ }
1388
+ }
1389
+ function handleTextFrame(text) {
1390
+ let frame;
1345
1391
  try {
1346
- return await files.list(abs, { depth });
1347
- } catch (error) {
1348
- const kind = this.errorKind(error);
1349
- if (kind === "not-found") throw new _mastra_core_workspace.DirectoryNotFoundError(path$4);
1350
- if (kind === "invalid-argument") throw new _mastra_core_workspace.NotDirectoryError(path$4);
1351
- throw error;
1392
+ frame = JSON.parse(text);
1393
+ } catch {
1394
+ return;
1395
+ }
1396
+ if (frame.type === "exit") {
1397
+ exitCode = frame.data?.exit_code ?? 0;
1398
+ settle();
1352
1399
  }
1353
- });
1354
- const result = [];
1355
- for (const entry of entries) {
1356
- if (!entry.type) continue;
1357
- const name = path.posix.relative(abs, entry.path);
1358
- const type = entry.type === "dir" ? "directory" : "file";
1359
- if (type === "file" && !matchesExtension(name, options?.extension)) continue;
1360
- const link = isSymlink(entry);
1361
- result.push({
1362
- name,
1363
- type,
1364
- ...type === "file" && !link && { size: entry.size },
1365
- ...link && {
1366
- isSymlink: true,
1367
- symlinkTarget: entry.symlinkTarget
1368
- }
1369
- });
1370
1400
  }
1371
- return result;
1401
+ });
1402
+ }
1403
+ //#endregion
1404
+ //#region src/e2b-exec.ts
1405
+ const E2B_ENVD_VERSION = "0.4.0";
1406
+ const execViaE2BLease = async (lease, options) => {
1407
+ const stdoutChunks = [];
1408
+ const stderrChunks = [];
1409
+ const onStdout = (data) => {
1410
+ stdoutChunks.push(data);
1411
+ options.onStdout?.(data);
1412
+ };
1413
+ const onStderr = (data) => {
1414
+ stderrChunks.push(data);
1415
+ options.onStderr?.(data);
1416
+ };
1417
+ try {
1418
+ const result = await new e2b.Sandbox({
1419
+ sandboxId: lease.sandboxId,
1420
+ envdVersion: E2B_ENVD_VERSION,
1421
+ envdAccessToken: lease.jwt,
1422
+ sandboxUrl: lease.wsEndpoint,
1423
+ validateApiKey: false
1424
+ }).commands.run(options.command, {
1425
+ cwd: options.cwd,
1426
+ envs: options.env,
1427
+ timeoutMs: options.timeoutMs,
1428
+ onStdout,
1429
+ onStderr
1430
+ });
1431
+ return {
1432
+ exitCode: result.exitCode,
1433
+ stdout: result.stdout,
1434
+ stderr: result.stderr,
1435
+ truncated: false,
1436
+ timedOut: false,
1437
+ opened: true
1438
+ };
1439
+ } catch (error) {
1440
+ if (error instanceof e2b.CommandExitError) return {
1441
+ exitCode: error.exitCode,
1442
+ stdout: error.stdout,
1443
+ stderr: error.stderr,
1444
+ truncated: false,
1445
+ timedOut: false,
1446
+ opened: true
1447
+ };
1448
+ return {
1449
+ exitCode: null,
1450
+ stdout: stdoutChunks.join(""),
1451
+ stderr: stderrChunks.join(""),
1452
+ truncated: false,
1453
+ timedOut: error instanceof e2b.TimeoutError,
1454
+ closeReason: error instanceof Error ? error.message : String(error),
1455
+ opened: true
1456
+ };
1372
1457
  }
1373
- async exists(path) {
1374
- const abs = toAbsolute(path);
1375
- return this.runFiles("exists", async (files) => Boolean((await this.#info(files, abs))?.type));
1458
+ };
1459
+ /** The VM's envd API, authenticated by the exec lease. */
1460
+ const sandboxForLease = (lease) => new e2b.Sandbox({
1461
+ sandboxId: lease.sandboxId,
1462
+ envdVersion: E2B_ENVD_VERSION,
1463
+ envdAccessToken: lease.jwt,
1464
+ sandboxUrl: lease.wsEndpoint,
1465
+ validateApiKey: false
1466
+ });
1467
+ /** Opens E2B's files API directly against the VM, authenticated by the exec lease. */
1468
+ const e2bFilesForLease = (lease) => sandboxForLease(lease).files;
1469
+ /** Opens E2B's commands API directly against the VM, authenticated by the exec lease. */
1470
+ const commandsForLease = (lease) => sandboxForLease(lease).commands;
1471
+ //#endregion
1472
+ //#region src/private-net-exec.ts
1473
+ /**
1474
+ * Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
1475
+ * HTTP response. This is an *application* error, not a transport error — the
1476
+ * sidecar is reachable and answered, it just refused the exec. Callers should
1477
+ * fall back to the lease path for this one call but MUST NOT invalidate the
1478
+ * cached `instanceUrl` (the address is still good).
1479
+ */
1480
+ var PrivateNetExecHttpError = class extends Error {
1481
+ status;
1482
+ body;
1483
+ constructor(status, body) {
1484
+ super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
1485
+ this.name = "PrivateNetExecHttpError";
1486
+ this.status = status;
1487
+ this.body = body;
1376
1488
  }
1377
- async stat(path$5) {
1378
- const abs = toAbsolute(path$5);
1379
- return this.runFiles("stat", async (files) => {
1380
- let info = await this.#info(files, abs);
1381
- if (info?.type && isSymlink(info)) info = await this.#info(files, path.posix.resolve(path.posix.dirname(abs), info.symlinkTarget));
1382
- if (!info?.type) throw new _mastra_core_workspace.FileNotFoundError(path$5);
1383
- const modifiedAt = info.modifiedTime ?? /* @__PURE__ */ new Date(0);
1384
- return {
1385
- name: path.posix.basename(abs),
1386
- path: abs,
1387
- type: info.type === "dir" ? "directory" : "file",
1388
- size: info.type === "dir" ? 0 : info.size,
1389
- createdAt: modifiedAt,
1390
- modifiedAt
1391
- };
1489
+ };
1490
+ const DEFAULT_FETCH = (input, init) => {
1491
+ const f = globalThis.fetch;
1492
+ if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
1493
+ return f(input, init);
1494
+ };
1495
+ /**
1496
+ * Dial `${instanceUrl}/exec` and stream the response, resolving with the
1497
+ * accumulated stdout/stderr + exit code.
1498
+ *
1499
+ * Errors:
1500
+ * - Connection failure (DNS, refused, reset) → resolves with
1501
+ * `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
1502
+ * transport failures — the shape matches the lease-path result so the
1503
+ * caller can treat both transports uniformly.
1504
+ * - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
1505
+ * Application-level; caller decides whether to fall back.
1506
+ * - Stream ends without an `exit` frame → resolves with
1507
+ * `{opened:true, exitCode:null}`, matching the lease-path semantics for a
1508
+ * mid-stream drop.
1509
+ * - `timeoutMs` elapsed → aborts the request, resolves with
1510
+ * `{timedOut:true, exitCode:124}`.
1511
+ */
1512
+ async function execViaPrivateNetwork(instanceUrl, options) {
1513
+ const fetchImpl = options.fetch ?? DEFAULT_FETCH;
1514
+ const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
1515
+ const controller = new AbortController();
1516
+ let timedOut = false;
1517
+ let timeoutTimer;
1518
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
1519
+ timedOut = true;
1520
+ controller.abort();
1521
+ }, options.timeoutMs);
1522
+ const body = { command: options.command };
1523
+ if (options.cwd) body.cwd = options.cwd;
1524
+ if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
1525
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
1526
+ const headers = { "content-type": "application/json" };
1527
+ if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
1528
+ let response;
1529
+ try {
1530
+ response = await fetchImpl(url, {
1531
+ method: "POST",
1532
+ headers,
1533
+ body: JSON.stringify(body),
1534
+ signal: controller.signal
1392
1535
  });
1536
+ } catch (error) {
1537
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1538
+ if (timedOut) return {
1539
+ exitCode: 124,
1540
+ stdout: "",
1541
+ stderr: "",
1542
+ timedOut: true,
1543
+ opened: false
1544
+ };
1545
+ return {
1546
+ exitCode: null,
1547
+ stdout: "",
1548
+ stderr: "",
1549
+ timedOut: false,
1550
+ opened: false,
1551
+ transportErrorMessage: error instanceof Error ? error.message : String(error)
1552
+ };
1393
1553
  }
1394
- /** `getInfo` without following the entry itself, or `undefined` when nothing is there. */
1395
- async #info(files, abs) {
1396
- try {
1397
- return await files.getInfo(abs);
1398
- } catch (error) {
1399
- if (this.errorKind(error) === "not-found") return void 0;
1400
- throw error;
1401
- }
1402
- }
1403
- async #assertParentDirectory(files, abs, path$6) {
1404
- const parent = await this.#info(files, path.posix.dirname(abs));
1405
- if (!parent?.type) throw new _mastra_core_workspace.DirectoryNotFoundError(path.posix.dirname(path$6));
1406
- if (parent.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path.posix.dirname(path$6));
1554
+ if (!response.ok) {
1555
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1556
+ const text = await response.text().catch(() => "");
1557
+ throw new PrivateNetExecHttpError(response.status, text);
1407
1558
  }
1408
- async #write(files, abs, path, data) {
1409
- try {
1410
- await files.write(abs, data);
1411
- } catch (error) {
1412
- if (this.errorKind(error) === "invalid-argument") throw new _mastra_core_workspace.IsDirectoryError(path);
1413
- throw error;
1414
- }
1559
+ if (!response.body) {
1560
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1561
+ return {
1562
+ exitCode: null,
1563
+ stdout: "",
1564
+ stderr: "",
1565
+ timedOut: false,
1566
+ opened: true,
1567
+ status: response.status
1568
+ };
1415
1569
  }
1416
- /**
1417
- * Upload the temp file `tmp`, then run the command that consumes it. The
1418
- * script deletes it on every path it controls; if the upload or the command
1419
- * fails part-way, delete it here so it doesn't linger in the user's tree.
1420
- */
1421
- async #publishTemp(tmp, operation, upload, script, subject, errors) {
1570
+ let stdout = "";
1571
+ let stderr = "";
1572
+ let exitCode = null;
1573
+ const decoder = new TextDecoder();
1574
+ let buffer = "";
1575
+ const handleLine = (line) => {
1576
+ if (!line) return;
1577
+ let frame;
1422
1578
  try {
1423
- await this.runFiles(operation, upload);
1424
- await this.#command(operation, script, subject, errors);
1425
- } catch (error) {
1426
- await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
1427
- throw error;
1579
+ frame = JSON.parse(line);
1580
+ } catch {
1581
+ return;
1428
1582
  }
1429
- }
1430
- /** Run a file command and turn its known exit codes into typed errors. */
1431
- async #command(operation, script, subject, errors) {
1432
- const result = await this.runCommand(operation, script);
1433
- if (result.exitCode === 0) return;
1434
- for (const [outcome, code] of Object.entries(FILE_COMMAND_EXIT)) {
1435
- const toError = errors[outcome];
1436
- if (code === result.exitCode && toError) throw toError();
1583
+ if (!frame || typeof frame !== "object") return;
1584
+ if (frame.type === "stdout" && typeof frame.data === "string") {
1585
+ stdout += frame.data;
1586
+ options.onStdout?.(frame.data);
1587
+ } else if (frame.type === "stderr" && typeof frame.data === "string") {
1588
+ stderr += frame.data;
1589
+ options.onStderr?.(frame.data);
1590
+ } else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
1591
+ };
1592
+ try {
1593
+ const reader = response.body.getReader();
1594
+ while (true) {
1595
+ const { value, done } = await reader.read();
1596
+ if (done) break;
1597
+ buffer += decoder.decode(value, { stream: true });
1598
+ let newlineIdx = buffer.indexOf("\n");
1599
+ while (newlineIdx !== -1) {
1600
+ const line = buffer.slice(0, newlineIdx).trim();
1601
+ buffer = buffer.slice(newlineIdx + 1);
1602
+ handleLine(line);
1603
+ newlineIdx = buffer.indexOf("\n");
1604
+ }
1437
1605
  }
1438
- throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
1606
+ buffer += decoder.decode();
1607
+ const trailing = buffer.trim();
1608
+ if (trailing) handleLine(trailing);
1609
+ } catch (error) {
1610
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1611
+ if (timedOut) return {
1612
+ exitCode: 124,
1613
+ stdout,
1614
+ stderr,
1615
+ timedOut: true,
1616
+ opened: true,
1617
+ status: response.status
1618
+ };
1619
+ return {
1620
+ exitCode,
1621
+ stdout,
1622
+ stderr,
1623
+ timedOut: false,
1624
+ opened: true,
1625
+ status: response.status,
1626
+ transportErrorMessage: error instanceof Error ? error.message : String(error)
1627
+ };
1628
+ } finally {
1629
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1439
1630
  }
1440
- };
1631
+ return {
1632
+ exitCode,
1633
+ stdout,
1634
+ stderr,
1635
+ timedOut: false,
1636
+ opened: true,
1637
+ status: response.status
1638
+ };
1639
+ }
1441
1640
  //#endregion
1442
1641
  //#region src/sandbox-filesystem.ts
1443
1642
  /**
@@ -1638,6 +1837,70 @@ var PlatformProcessManager = class extends _mastra_core_workspace.SandboxProcess
1638
1837
  }));
1639
1838
  }
1640
1839
  };
1840
+ /** Reaches the sandbox's commands handle without making it part of the class's public API. */
1841
+ const withCommands = Symbol("withCommands");
1842
+ /**
1843
+ * Background processes on an E2B-backed sandbox through envd's commands API,
1844
+ * reached with the same lease `executeCommand` uses. Output streams while the
1845
+ * process runs, `kill` stops it, and `list` reports what is running in the VM.
1846
+ */
1847
+ var PlatformCommandsProcessManager = class extends CommandsApiProcessManager {
1848
+ runCommands(operation, fn) {
1849
+ return this.sandbox[withCommands](operation, fn);
1850
+ }
1851
+ createHandle(inner, stdinMode, options) {
1852
+ return new PlatformProcessHandleOverLease(inner, this, Date.now(), stdinMode, options);
1853
+ }
1854
+ };
1855
+ /** envd ends the output stream when the lease it was opened with expires; the process keeps running. */
1856
+ function isLeaseStreamDrop(error) {
1857
+ return error instanceof e2b.TimeoutError && error.message.startsWith("[unavailable]");
1858
+ }
1859
+ /**
1860
+ * The process left the VM while no stream was attached, so envd can't say how
1861
+ * it ended. Carries an exit code so the handle reads as exited: it shows in
1862
+ * `list()` and is released like any other finished process.
1863
+ */
1864
+ var ProcessEndedUnseenError = class extends Error {
1865
+ exitCode = 1;
1866
+ constructor(cause) {
1867
+ super(`${cause instanceof Error ? cause.message : String(cause)} (the process ended before it could be reattached)`);
1868
+ }
1869
+ };
1870
+ /**
1871
+ * A process outlives the lease it was started with. When that lease expires
1872
+ * envd ends the output stream, so reattach on the current lease and keep
1873
+ * waiting. Output written between the drop and the reattach is not seen.
1874
+ */
1875
+ var PlatformProcessHandleOverLease = class extends CommandsApiProcessHandle {
1876
+ /** One reattach loop shared by every `wait()` caller. */
1877
+ exited;
1878
+ waitForExit() {
1879
+ return this.exited ??= this.waitAcrossLeases();
1880
+ }
1881
+ async waitAcrossLeases() {
1882
+ for (;;) try {
1883
+ return await this.inner.wait();
1884
+ } catch (error) {
1885
+ if (!isLeaseStreamDrop(error)) throw error;
1886
+ const pid = this.inner.pid;
1887
+ const reattached = await this.manager.runCommands("connect", async (commands) => {
1888
+ if (!(await commands.list()).some((proc) => proc.pid === pid)) return "ended";
1889
+ return commands.connect(pid, {
1890
+ onStdout: (data) => this.emitStdout(data),
1891
+ onStderr: (data) => this.emitStderr(data),
1892
+ timeoutMs: 0
1893
+ });
1894
+ }).catch(() => void 0);
1895
+ if (reattached === "ended") throw new ProcessEndedUnseenError(error);
1896
+ if (!reattached) {
1897
+ this.exited = void 0;
1898
+ throw error;
1899
+ }
1900
+ this.inner = reattached;
1901
+ }
1902
+ }
1903
+ };
1641
1904
  var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.MastraSandbox {
1642
1905
  id;
1643
1906
  name = "PlatformSandbox";
@@ -1685,6 +1948,8 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
1685
1948
  _e2bFilesFactory;
1686
1949
  /** Files handle for the current lease, rebuilt whenever the lease changes. */
1687
1950
  _e2bFiles = null;
1951
+ _e2bCommandsFactory;
1952
+ _e2bCommands = null;
1688
1953
  _filesystem;
1689
1954
  _privateNetFetch;
1690
1955
  /**
@@ -1753,10 +2018,11 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
1753
2018
  */
1754
2019
  _probeTarget = null;
1755
2020
  constructor(options = {}) {
2021
+ const e2bBacked = resolveSandboxProvider(options.sandboxProvider ?? process.env.SANDBOX_PROVIDER?.trim()) === "e2b";
1756
2022
  super({
1757
2023
  ...options,
1758
2024
  name: "PlatformSandbox",
1759
- processes: new PlatformProcessManager()
2025
+ processes: e2bBacked ? new PlatformCommandsProcessManager({ defaultTimeout: options.timeout ?? 0 }) : new PlatformProcessManager()
1760
2026
  });
1761
2027
  this._hasRecoveryKey = options.id !== void 0;
1762
2028
  this.id = options.id ?? this.generateId();
@@ -1776,6 +2042,7 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
1776
2042
  this._webSocketFactory = options.webSocketFactory;
1777
2043
  this._e2bExecRunner = options.e2bExecRunner ?? execViaE2BLease;
1778
2044
  this._e2bFilesFactory = options.e2bFilesFactory ?? e2bFilesForLease;
2045
+ this._e2bCommandsFactory = options.e2bCommandsFactory ?? commandsForLease;
1779
2046
  this._privateNetFetch = options.privateNetFetch;
1780
2047
  this._addressRegistry = options.addressRegistry;
1781
2048
  }
@@ -2569,8 +2836,55 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
2569
2836
  };
2570
2837
  return this._e2bFiles;
2571
2838
  }
2839
+ /**
2840
+ * Run `fn` against envd's commands API with the current lease, the way
2841
+ * {@link _withE2BFiles} runs files calls: one retry, only after an
2842
+ * `AuthenticationError` proves the call never ran, so a spawn or kill is
2843
+ * never replayed. Each call fetches the lease again, so a process started
2844
+ * under one lease is stopped with whichever lease is current.
2845
+ */
2846
+ async [withCommands](operation, fn) {
2847
+ await this.ensureRunning();
2848
+ if (!this._sandboxId) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
2849
+ let current = await this._commandsHandle(operation, 1);
2850
+ const call = async (invoke) => {
2851
+ try {
2852
+ return await invoke(current.commands);
2853
+ } catch (error) {
2854
+ if (error instanceof e2b.AuthenticationError) {
2855
+ if (this._lease === current.lease) this._lease = null;
2856
+ current = await this._commandsHandle(operation, 2);
2857
+ try {
2858
+ return await invoke(current.commands);
2859
+ } catch (retryError) {
2860
+ if (isBrokenSandboxError(retryError) && this._lease === current.lease) this._lease = null;
2861
+ throw retryError;
2862
+ }
2863
+ }
2864
+ if (isBrokenSandboxError(error) && this._lease === current.lease) this._lease = null;
2865
+ throw error;
2866
+ }
2867
+ };
2868
+ return fn({
2869
+ run: (command, opts) => call((commands) => commands.run(command, opts)),
2870
+ connect: (pid, opts) => call((commands) => commands.connect(pid, opts)),
2871
+ list: () => call((commands) => commands.list()),
2872
+ kill: (pid) => call((commands) => commands.kill(pid)),
2873
+ sendStdin: (pid, data) => call((commands) => commands.sendStdin(pid, data))
2874
+ });
2875
+ }
2876
+ /** The commands handle for the current lease, rebuilt only when the lease changes. */
2877
+ async _commandsHandle(operation, attempts) {
2878
+ const lease = await this._fileLease(`processes.${operation}`, attempts, "");
2879
+ if (lease.provider !== "e2b") throw new Error(`PlatformSandbox.processes requires an E2B-backed sandbox; this sandbox's provider is "${lease.provider}"`);
2880
+ if (this._e2bCommands?.lease !== lease) this._e2bCommands = {
2881
+ lease,
2882
+ commands: this._e2bCommandsFactory(lease)
2883
+ };
2884
+ return this._e2bCommands;
2885
+ }
2572
2886
  /** `_ensureLease`, with a 410 handled the same way `_runDirectExec` handles it. */
2573
- async _fileLease(operation, attempts) {
2887
+ async _fileLease(operation, attempts, prefix = "filesystem.") {
2574
2888
  try {
2575
2889
  return await this._ensureLease();
2576
2890
  } catch (error) {
@@ -2581,7 +2895,7 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
2581
2895
  this.status = "stopped";
2582
2896
  throw new SandboxDestroyedError(`Sandbox ${priorSandboxId ?? "(unknown)"} was destroyed; /exec-lease returned 410`, {
2583
2897
  ...priorSandboxId && { sandboxId: priorSandboxId },
2584
- command: `filesystem.${operation}`,
2898
+ command: `${prefix}${operation}`,
2585
2899
  attempts
2586
2900
  });
2587
2901
  }