@mastra/platform-workspace 1.9.0 → 1.10.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let buffer = require("buffer");
25
24
  let path = require("path");
26
25
  path = __toESM(path, 1);
@@ -29,7 +28,7 @@ let crypto = require("crypto");
29
28
  let e2b = require("e2b");
30
29
  let child_process = require("child_process");
31
30
  let util = require("util");
32
- //#region src/client.ts
31
+ // src/client.ts
33
32
  const DEFAULT_PROXY_URL = "https://workspaces.mastra.ai";
34
33
  const REGIONAL_PROXY_URLS = {
35
34
  us: "https://workspaces.us.mastra.ai",
@@ -160,8 +159,7 @@ var PlatformClient = class {
160
159
  return response;
161
160
  }
162
161
  };
163
- //#endregion
164
- //#region src/filesystem.ts
162
+ // src/filesystem.ts
165
163
  function normalizePath(input) {
166
164
  if (!input || input === ".") return "/";
167
165
  let normalized = input.startsWith("/") ? input : `/${input}`;
@@ -420,8 +418,7 @@ var PlatformFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
420
418
  function matchesExtension$1(name, extension) {
421
419
  return (Array.isArray(extension) ? extension : [extension]).some((ext) => name.endsWith(ext));
422
420
  }
423
- //#endregion
424
- //#region src/template.ts
421
+ // src/template.ts
425
422
  const SERIALIZE_TEMPLATE = Symbol("serializeTemplate");
426
423
  const GET_TEMPLATE_BUILD_ENVS = Symbol("getTemplateBuildEnvs");
427
424
  const MAX_OPERATIONS = 256;
@@ -599,450 +596,62 @@ function cloneJson(value) {
599
596
  if (typeof value === "number" && !Number.isFinite(value)) throw new TypeError("Sandbox template values must contain only finite numbers");
600
597
  return value;
601
598
  }
602
- //#endregion
603
- //#region src/direct-exec.ts
599
+ // ../../packages/_internals/workspace/dist/index.js
600
+ /** Directory, relative to the template's build cwd, that holds every marker below. */
601
+ const SETUP_MARKER_DIR = ".mastra-sandbox";
604
602
  /**
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.
603
+ * Setup completion marker shared by repo templates and their consumers.
611
604
  *
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.
605
+ * A repo template writes this file beside the checkout as its last build
606
+ * step, so it exists only in images where every setup command succeeded. Its
607
+ * content is a digest of the setup commands the image ran, letting a sandbox
608
+ * booted from the image tell whether the setup it is about to run already
609
+ * happened. Relative to the template's build cwd, which is also the runtime
610
+ * working directory the repo was cloned into.
611
+ *
612
+ * This is the single-repository marker. Templates built from a repository
613
+ * list write one marker per repository instead ({@link repoSetupMarkerPath}).
616
614
  */
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;
615
+ const SETUP_MARKER_PATH = ".mastra-sandbox/setup";
621
616
  /**
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.
617
+ * Marker for the workspace-level setup of a multi-repository template: the
618
+ * commands that ran at the working directory after every repository was set
619
+ * up. Written even when there were no such commands, so a consumer can tell
620
+ * "ran nothing" from "never built".
627
621
  */
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
- };
622
+ const WORKSPACE_SETUP_MARKER_PATH = ".mastra-sandbox/workspace-setup";
634
623
  /**
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.
624
+ * One line per repository directory whose setup failed while the build was
625
+ * told to continue. Absent when nothing failed. Consumers check this before
626
+ * trusting a per-repository marker: that marker means every step ran, not
627
+ * that every step succeeded.
641
628
  */
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
- });
629
+ const SETUP_FAILED_MARKER_PATH = ".mastra-sandbox/setup-failed";
630
+ /** Per-repository marker of a multi-repository template, keyed by the clone directory name. */
631
+ function repoSetupMarkerPath(repoDir) {
632
+ return `${SETUP_MARKER_DIR}/repos/${repoDir}`;
755
633
  }
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
634
+ /** Blank entries never become build steps, so they never count toward the digest either. */
635
+ function normalizeSetupCommands(setupCommand) {
636
+ return (setupCommand === void 0 ? [] : Array.isArray(setupCommand) ? setupCommand : [setupCommand]).filter((command) => command.trim() !== "");
637
+ }
638
+ /** The marker content for a setup command list: `sha256:<hex>` over the commands joined by newlines. */
639
+ function setupMarkerContent(setupCommand) {
640
+ return `sha256:${(0, crypto.createHash)("sha256").update(normalizeSetupCommands(setupCommand).join("\n")).digest("hex")}`;
641
+ }
642
+ /** Shell step that writes the marker relative to the cwd. `content` is a digest, so it is shell-safe. */
643
+ function setupMarkerCommand(content, markerPath = SETUP_MARKER_PATH) {
644
+ return `mkdir -p "$(dirname "${markerPath}")" && printf '%s' '${content}' > "${markerPath}"`;
645
+ }
646
+ /** A clone directory name is one path segment of word characters, dots and dashes, so it never needs quoting. */
647
+ const REPO_DIR_PATTERN = /^[\w.-]+$/;
822
648
  /**
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
- //#region ../../packages/_internals/workspace/dist/index.js
991
- /** Directory, relative to the template's build cwd, that holds every marker below. */
992
- const SETUP_MARKER_DIR = ".mastra-sandbox";
993
- /**
994
- * Setup completion marker shared by repo templates and their consumers.
995
- *
996
- * A repo template writes this file beside the checkout as its last build
997
- * step, so it exists only in images where every setup command succeeded. Its
998
- * content is a digest of the setup commands the image ran, letting a sandbox
999
- * booted from the image tell whether the setup it is about to run already
1000
- * happened. Relative to the template's build cwd, which is also the runtime
1001
- * working directory the repo was cloned into.
1002
- *
1003
- * This is the single-repository marker. Templates built from a repository
1004
- * list write one marker per repository instead ({@link repoSetupMarkerPath}).
1005
- */
1006
- const SETUP_MARKER_PATH = ".mastra-sandbox/setup";
1007
- /**
1008
- * Marker for the workspace-level setup of a multi-repository template: the
1009
- * commands that ran at the working directory after every repository was set
1010
- * up. Written even when there were no such commands, so a consumer can tell
1011
- * "ran nothing" from "never built".
1012
- */
1013
- const WORKSPACE_SETUP_MARKER_PATH = ".mastra-sandbox/workspace-setup";
1014
- /**
1015
- * One line per repository directory whose setup failed while the build was
1016
- * told to continue. Absent when nothing failed. Consumers check this before
1017
- * trusting a per-repository marker: that marker means every step ran, not
1018
- * that every step succeeded.
1019
- */
1020
- const SETUP_FAILED_MARKER_PATH = ".mastra-sandbox/setup-failed";
1021
- /** Per-repository marker of a multi-repository template, keyed by the clone directory name. */
1022
- function repoSetupMarkerPath(repoDir) {
1023
- return `${SETUP_MARKER_DIR}/repos/${repoDir}`;
1024
- }
1025
- /** Blank entries never become build steps, so they never count toward the digest either. */
1026
- function normalizeSetupCommands(setupCommand) {
1027
- return (setupCommand === void 0 ? [] : Array.isArray(setupCommand) ? setupCommand : [setupCommand]).filter((command) => command.trim() !== "");
1028
- }
1029
- /** The marker content for a setup command list: `sha256:<hex>` over the commands joined by newlines. */
1030
- function setupMarkerContent(setupCommand) {
1031
- return `sha256:${(0, crypto.createHash)("sha256").update(normalizeSetupCommands(setupCommand).join("\n")).digest("hex")}`;
1032
- }
1033
- /** Shell step that writes the marker relative to the cwd. `content` is a digest, so it is shell-safe. */
1034
- function setupMarkerCommand(content, markerPath = SETUP_MARKER_PATH) {
1035
- return `mkdir -p "$(dirname "${markerPath}")" && printf '%s' '${content}' > "${markerPath}"`;
1036
- }
1037
- /** A clone directory name is one path segment of word characters, dots and dashes, so it never needs quoting. */
1038
- const REPO_DIR_PATTERN = /^[\w.-]+$/;
1039
- /**
1040
- * Shell step that runs one setup command inside a repository clone.
1041
- *
1042
- * Without the guard this is the plain `cd "<dir>" && <cmd>` step. With it,
1043
- * the `cd` sits inside the parenthesized group so that the failure branch
1044
- * runs back at the build cwd and the failure list lands at the workspace
1045
- * level, never inside the repository.
649
+ * Shell step that runs one setup command inside a repository clone.
650
+ *
651
+ * Without the guard this is the plain `cd "<dir>" && <cmd>` step. With it,
652
+ * the `cd` sits inside the parenthesized group so that the failure branch
653
+ * runs back at the build cwd and the failure list lands at the workspace
654
+ * level, never inside the repository.
1046
655
  */
1047
656
  function guardedSetupCommand({ repoDir, command, continueOnFailure }) {
1048
657
  if (!REPO_DIR_PATTERN.test(repoDir)) throw new TypeError(`Repository directory "${repoDir}" must match ${REPO_DIR_PATTERN}.`);
@@ -1374,72 +983,655 @@ var FilesApiFilesystem = class extends _mastra_core_workspace.MastraFilesystem {
1374
983
  const abs = toAbsolute(path);
1375
984
  return this.runFiles("exists", async (files) => Boolean((await this.#info(files, abs))?.type));
1376
985
  }
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
- };
986
+ async stat(path$5) {
987
+ const abs = toAbsolute(path$5);
988
+ return this.runFiles("stat", async (files) => {
989
+ let info = await this.#info(files, abs);
990
+ if (info?.type && isSymlink(info)) info = await this.#info(files, path.posix.resolve(path.posix.dirname(abs), info.symlinkTarget));
991
+ if (!info?.type) throw new _mastra_core_workspace.FileNotFoundError(path$5);
992
+ const modifiedAt = info.modifiedTime ?? /* @__PURE__ */ new Date(0);
993
+ return {
994
+ name: path.posix.basename(abs),
995
+ path: abs,
996
+ type: info.type === "dir" ? "directory" : "file",
997
+ size: info.type === "dir" ? 0 : info.size,
998
+ createdAt: modifiedAt,
999
+ modifiedAt,
1000
+ ...info.type !== "dir" && { mimeType: (0, _mastra_core_workspace.getMimeType)(abs) }
1001
+ };
1002
+ });
1003
+ }
1004
+ /** `getInfo` without following the entry itself, or `undefined` when nothing is there. */
1005
+ async #info(files, abs) {
1006
+ try {
1007
+ return await files.getInfo(abs);
1008
+ } catch (error) {
1009
+ if (this.errorKind(error) === "not-found") return void 0;
1010
+ throw error;
1011
+ }
1012
+ }
1013
+ async #assertParentDirectory(files, abs, path$6) {
1014
+ const parent = await this.#info(files, path.posix.dirname(abs));
1015
+ if (!parent?.type) throw new _mastra_core_workspace.DirectoryNotFoundError(path.posix.dirname(path$6));
1016
+ if (parent.type !== "dir") throw new _mastra_core_workspace.NotDirectoryError(path.posix.dirname(path$6));
1017
+ }
1018
+ async #write(files, abs, path, data) {
1019
+ try {
1020
+ await files.write(abs, data);
1021
+ } catch (error) {
1022
+ if (this.errorKind(error) === "invalid-argument") throw new _mastra_core_workspace.IsDirectoryError(path);
1023
+ throw error;
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Upload the temp file `tmp`, then run the command that consumes it. The
1028
+ * script deletes it on every path it controls; if the upload or the command
1029
+ * fails part-way, delete it here so it doesn't linger in the user's tree.
1030
+ */
1031
+ async #publishTemp(tmp, operation, upload, script, subject, errors) {
1032
+ try {
1033
+ await this.runFiles(operation, upload);
1034
+ await this.#command(operation, script, subject, errors);
1035
+ } catch (error) {
1036
+ await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
1037
+ throw error;
1038
+ }
1039
+ }
1040
+ /** Run a file command and turn its known exit codes into typed errors. */
1041
+ async #command(operation, script, subject, errors) {
1042
+ const result = await this.runCommand(operation, script);
1043
+ if (result.exitCode === 0) return;
1044
+ for (const [outcome, code] of Object.entries(FILE_COMMAND_EXIT)) {
1045
+ const toError = errors[outcome];
1046
+ if (code === result.exitCode && toError) throw toError();
1047
+ }
1048
+ throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
1049
+ }
1050
+ };
1051
+ /**
1052
+ * Output callbacks for `run`/`connect` that hold output until the handle
1053
+ * exists. The SDK's handle reads events from construction, before `run()`
1054
+ * returns, so output that arrives with the start event reaches the
1055
+ * callbacks first.
1056
+ */
1057
+ function outputUntilHandled() {
1058
+ let handle;
1059
+ const early = [];
1060
+ return {
1061
+ onStdout: (data) => {
1062
+ if (handle) handle.emitStdout(data);
1063
+ else early.push({
1064
+ stream: "stdout",
1065
+ data
1066
+ });
1067
+ },
1068
+ onStderr: (data) => {
1069
+ if (handle) handle.emitStderr(data);
1070
+ else early.push({
1071
+ stream: "stderr",
1072
+ data
1073
+ });
1074
+ },
1075
+ handledBy(created) {
1076
+ for (const { stream, data } of early) if (stream === "stdout") created.emitStdout(data);
1077
+ else created.emitStderr(data);
1078
+ early.length = 0;
1079
+ handle = created;
1080
+ return created;
1081
+ }
1082
+ };
1083
+ }
1084
+ /** envd runs every command as `/bin/bash -l -c <command>`; show the command itself. */
1085
+ function commandOf(proc) {
1086
+ const [flag, c, command] = proc.args;
1087
+ if (proc.cmd === "/bin/bash" && flag === "-l" && c === "-c" && command !== void 0 && proc.args.length === 3) return command;
1088
+ return [proc.cmd, ...proc.args].join(" ");
1089
+ }
1090
+ /**
1091
+ * A process started or attached through a {@link CommandsApi}. `kill` and
1092
+ * `sendStdin` go back through the manager, so they use whatever commands
1093
+ * handle the provider currently supplies.
1094
+ */
1095
+ var CommandsApiProcessHandle = class extends _mastra_core_workspace.ProcessHandle {
1096
+ inner;
1097
+ manager;
1098
+ startTime;
1099
+ stdinMode;
1100
+ pid;
1101
+ /** The exit code `wait()` saw, for a handle that doesn't update its own. */
1102
+ waitedExitCode;
1103
+ constructor(inner, manager, startTime, stdinMode, options) {
1104
+ super(options);
1105
+ this.inner = inner;
1106
+ this.manager = manager;
1107
+ this.startTime = startTime;
1108
+ this.stdinMode = stdinMode;
1109
+ this.pid = String(inner.pid);
1110
+ }
1111
+ /** Read from the commands handle, so it reflects server-side state without `wait()`. */
1112
+ get exitCode() {
1113
+ return this.inner.exitCode ?? this.waitedExitCode;
1114
+ }
1115
+ /** Wait for the process to exit. Providers whose output stream can drop while the process runs override this. */
1116
+ waitForExit() {
1117
+ return this.inner.wait();
1118
+ }
1119
+ async wait() {
1120
+ try {
1121
+ const result = await this.waitForExit();
1122
+ this.waitedExitCode = result.exitCode;
1123
+ return {
1124
+ success: result.exitCode === 0,
1125
+ exitCode: result.exitCode,
1126
+ stdout: this.stdout,
1127
+ stderr: this.stderr,
1128
+ executionTimeMs: Date.now() - this.startTime
1129
+ };
1130
+ } catch (error) {
1131
+ const errorObj = error;
1132
+ const reportedExitCode = errorObj.result?.exitCode ?? errorObj.exitCode;
1133
+ if (reportedExitCode !== void 0) this.waitedExitCode = reportedExitCode;
1134
+ const exitCode = reportedExitCode ?? this.exitCode ?? 1;
1135
+ const attachedStdout = errorObj.result?.stdout || errorObj.stdout;
1136
+ const attachedStderr = errorObj.result?.stderr || errorObj.stderr;
1137
+ if (!this.stdout && !this.stdoutTruncated && attachedStdout) this.emitStdout(attachedStdout);
1138
+ if (!this.stderr && !this.stderrTruncated && attachedStderr) this.emitStderr(attachedStderr);
1139
+ const stdout = this.stdout;
1140
+ const stderr = this.stderr;
1141
+ const terminalError = errorObj.result?.error || errorObj.error || (error instanceof Error ? error.message : String(error));
1142
+ return {
1143
+ success: false,
1144
+ exitCode,
1145
+ stdout,
1146
+ stderr: [stderr, terminalError && !stderr.includes(terminalError) ? `Error: ${terminalError}` : ""].filter(Boolean).join("\n"),
1147
+ executionTimeMs: Date.now() - this.startTime
1148
+ };
1149
+ }
1150
+ }
1151
+ async kill() {
1152
+ if (this.exitCode !== void 0) return false;
1153
+ return this.manager.runCommands("kill", (commands) => commands.kill(this.inner.pid));
1154
+ }
1155
+ async sendStdin(data) {
1156
+ if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
1157
+ if (this.stdinMode === "ignore") throw new Error(`Process ${this.pid} was not started with stdin support`);
1158
+ await this.manager.runCommands("sendStdin", (commands) => commands.sendStdin(this.inner.pid, data));
1159
+ }
1160
+ async closeStdin() {
1161
+ throw new _mastra_core_workspace.UnsupportedStdinCloseError("The commands API does not expose a way to close stdin for a running command");
1162
+ }
1163
+ };
1164
+ /**
1165
+ * A process manager over E2B's envd commands API. Providers supply the
1166
+ * commands handle through {@link runCommands}; everything else is shared.
1167
+ */
1168
+ var CommandsApiProcessManager = class extends _mastra_core_workspace.SandboxProcessManager {
1169
+ defaultTimeout;
1170
+ constructor({ defaultTimeout, ...options } = {}) {
1171
+ super(options);
1172
+ this.defaultTimeout = defaultTimeout;
1173
+ }
1174
+ /** Wrap a started or attached command. Providers override this to supply their own handle. */
1175
+ createHandle(inner, stdinMode, options) {
1176
+ return new CommandsApiProcessHandle(inner, this, Date.now(), stdinMode, options);
1177
+ }
1178
+ /** Where a command runs when the caller gives no `cwd`. */
1179
+ defaultCwd() {
1180
+ return this.sandbox.workingDirectory;
1181
+ }
1182
+ async spawn(command, options = {}) {
1183
+ const envs = Object.fromEntries(Object.entries({ ...options.env }).filter((entry) => entry[1] !== void 0));
1184
+ return this.runCommands("spawn", async (commands) => {
1185
+ const output = outputUntilHandled();
1186
+ const inner = await commands.run(command, {
1187
+ background: true,
1188
+ stdin: options.stdinMode !== "ignore",
1189
+ cwd: options.cwd ?? this.defaultCwd(),
1190
+ envs,
1191
+ timeoutMs: options.timeout ?? this.defaultTimeout,
1192
+ onStdout: output.onStdout,
1193
+ onStderr: output.onStderr
1194
+ });
1195
+ const handle = output.handledBy(this.createHandle(inner, options.stdinMode, options));
1196
+ this._tracked.set(handle.pid, handle);
1197
+ return handle;
1198
+ });
1199
+ }
1200
+ /**
1201
+ * Running processes as the VM reports them, plus exited processes this
1202
+ * manager still holds, so a finished command stays visible until it is released.
1203
+ */
1204
+ async list() {
1205
+ const infos = (await this.runCommands("list", (commands) => commands.list())).map((proc) => ({
1206
+ pid: String(proc.pid),
1207
+ command: commandOf(proc),
1208
+ running: true
1209
+ }));
1210
+ const listed = new Set(infos.map((info) => info.pid));
1211
+ for (const [pid, handle] of this._tracked) {
1212
+ if (handle.exitCode === void 0 || listed.has(pid)) continue;
1213
+ infos.push({
1214
+ pid,
1215
+ command: handle.command,
1216
+ running: false,
1217
+ exitCode: handle.exitCode
1218
+ });
1219
+ }
1220
+ return infos;
1221
+ }
1222
+ /**
1223
+ * A tracked process, or one this manager didn't start, attached through
1224
+ * `connect`. Output from before attaching is not available.
1225
+ */
1226
+ async get(pid, _options) {
1227
+ const tracked = this._tracked.get(pid);
1228
+ if (tracked) return tracked;
1229
+ const numericPid = /^\d+$/.test(pid) ? Number(pid) : void 0;
1230
+ if (numericPid === void 0) return void 0;
1231
+ const output = outputUntilHandled();
1232
+ try {
1233
+ const inner = await this.runCommands("connect", (commands) => commands.connect(numericPid, {
1234
+ onStdout: output.onStdout,
1235
+ onStderr: output.onStderr,
1236
+ timeoutMs: 0
1237
+ }));
1238
+ const handle = output.handledBy(this.createHandle(inner, void 0));
1239
+ this._tracked.set(handle.pid, handle);
1240
+ return handle;
1241
+ } catch {
1242
+ return;
1243
+ }
1244
+ }
1245
+ };
1246
+ // src/direct-exec.ts
1247
+ /**
1248
+ * Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
1249
+ * a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
1250
+ * removes the platform data plane from the exec stdout/stderr path entirely
1251
+ * (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
1252
+ * cutting payload-scaled Cloud Run egress and RTT for commands like
1253
+ * `pnpm install` that stream tens of MB of output.
1254
+ *
1255
+ * The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
1256
+ * (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
1257
+ * SDK's version is pinned on both sides (platform + here); a version bump
1258
+ * signals the protocol may have drifted and this module must be revisited.
1259
+ */
1260
+ /** Byte-0 tag on binary WS frames for stdout output. */
1261
+ const STDOUT_FRAME = 1;
1262
+ /** Byte-0 tag on binary WS frames for stderr output. */
1263
+ const STDERR_FRAME = 3;
1264
+ /**
1265
+ * Upper bound on how long we'll wait for the WebSocket to open when the
1266
+ * caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
1267
+ * handshake leaving the promise unresolved forever. Not applied once the
1268
+ * socket has opened — a caller with no timeout has opted in to unbounded
1269
+ * command runtime, just not to unbounded connection setup.
1270
+ */
1271
+ const HANDSHAKE_DEADLINE_MS = 3e4;
1272
+ const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
1273
+ const WS = globalThis.WebSocket;
1274
+ if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
1275
+ return new WS(endpoint, subprotocols);
1276
+ };
1277
+ /**
1278
+ * Open the provider exec WebSocket using `lease`, run `command`, and resolve
1279
+ * with the accumulated stdout/stderr + exit code. See the module docstring
1280
+ * for the wire protocol reference.
1281
+ *
1282
+ * The client sends `stdin_close` immediately after `init_exec`, matching the
1283
+ * SDK's own one-shot exec behavior — we never stream stdin from the caller.
1284
+ */
1285
+ function execViaLease(lease, options) {
1286
+ const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
1287
+ const stdoutDecoder = new TextDecoder();
1288
+ const stderrDecoder = new TextDecoder();
1289
+ return new Promise((resolve) => {
1290
+ let stdout = "";
1291
+ let stderr = "";
1292
+ let exitCode = null;
1293
+ let timedOut = false;
1294
+ let settled = false;
1295
+ let opened = false;
1296
+ let closeCode;
1297
+ let closeReason;
1298
+ let timer;
1299
+ let handshakeTimer;
1300
+ const settle = () => {
1301
+ if (settled) return;
1302
+ settled = true;
1303
+ if (timer) clearTimeout(timer);
1304
+ if (handshakeTimer) clearTimeout(handshakeTimer);
1305
+ const stdoutTail = stdoutDecoder.decode();
1306
+ if (stdoutTail) {
1307
+ stdout += stdoutTail;
1308
+ options.onStdout?.(stdoutTail);
1309
+ }
1310
+ const stderrTail = stderrDecoder.decode();
1311
+ if (stderrTail) {
1312
+ stderr += stderrTail;
1313
+ options.onStderr?.(stderrTail);
1314
+ }
1315
+ try {
1316
+ socket.close(1e3, "");
1317
+ } catch {}
1318
+ resolve({
1319
+ exitCode,
1320
+ stdout,
1321
+ stderr,
1322
+ truncated: false,
1323
+ timedOut,
1324
+ ...closeCode !== void 0 && { closeCode },
1325
+ ...closeReason !== void 0 && { closeReason },
1326
+ opened
1327
+ });
1328
+ };
1329
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
1330
+ timedOut = true;
1331
+ if (exitCode === null) exitCode = 124;
1332
+ settle();
1333
+ }, options.timeoutMs);
1334
+ else handshakeTimer = setTimeout(() => {
1335
+ if (!opened) settle();
1336
+ }, HANDSHAKE_DEADLINE_MS);
1337
+ const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
1338
+ socket.binaryType = "arraybuffer";
1339
+ socket.onopen = () => {
1340
+ opened = true;
1341
+ if (handshakeTimer) {
1342
+ clearTimeout(handshakeTimer);
1343
+ handshakeTimer = void 0;
1344
+ }
1345
+ const data = { command: options.command };
1346
+ if (options.cwd) data.cwd = options.cwd;
1347
+ if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
1348
+ socket.send(JSON.stringify({
1349
+ type: "init_exec",
1350
+ data
1351
+ }));
1352
+ socket.send(JSON.stringify({ type: "stdin_close" }));
1353
+ };
1354
+ socket.onmessage = (event) => {
1355
+ const { data } = event;
1356
+ if (data instanceof ArrayBuffer) handleBinaryFrame(data);
1357
+ else if (typeof data === "string") handleTextFrame(data);
1358
+ };
1359
+ socket.onclose = (event) => {
1360
+ closeCode = event.code;
1361
+ closeReason = event.reason;
1362
+ if (!opened) {
1363
+ settle();
1364
+ return;
1365
+ }
1366
+ settle();
1367
+ };
1368
+ socket.onerror = () => {
1369
+ if (settled) return;
1370
+ if (!opened) settle();
1371
+ };
1372
+ function handleBinaryFrame(buffer) {
1373
+ const view = new Uint8Array(buffer);
1374
+ if (view.length <= 1) return;
1375
+ if (view[0] === STDOUT_FRAME) {
1376
+ const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
1377
+ stdout += chunk;
1378
+ options.onStdout?.(chunk);
1379
+ } else if (view[0] === STDERR_FRAME) {
1380
+ const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
1381
+ stderr += chunk;
1382
+ options.onStderr?.(chunk);
1383
+ }
1384
+ }
1385
+ function handleTextFrame(text) {
1386
+ let frame;
1387
+ try {
1388
+ frame = JSON.parse(text);
1389
+ } catch {
1390
+ return;
1391
+ }
1392
+ if (frame.type === "exit") {
1393
+ exitCode = frame.data?.exit_code ?? 0;
1394
+ settle();
1395
+ }
1396
+ }
1397
+ });
1398
+ }
1399
+ // src/e2b-exec.ts
1400
+ const E2B_ENVD_VERSION = "0.4.0";
1401
+ const execViaE2BLease = async (lease, options) => {
1402
+ const stdoutChunks = [];
1403
+ const stderrChunks = [];
1404
+ const onStdout = (data) => {
1405
+ stdoutChunks.push(data);
1406
+ options.onStdout?.(data);
1407
+ };
1408
+ const onStderr = (data) => {
1409
+ stderrChunks.push(data);
1410
+ options.onStderr?.(data);
1411
+ };
1412
+ try {
1413
+ const result = await new e2b.Sandbox({
1414
+ sandboxId: lease.sandboxId,
1415
+ envdVersion: E2B_ENVD_VERSION,
1416
+ envdAccessToken: lease.jwt,
1417
+ sandboxUrl: lease.wsEndpoint,
1418
+ validateApiKey: false
1419
+ }).commands.run(options.command, {
1420
+ cwd: options.cwd,
1421
+ envs: options.env,
1422
+ timeoutMs: options.timeoutMs,
1423
+ onStdout,
1424
+ onStderr
1425
+ });
1426
+ return {
1427
+ exitCode: result.exitCode,
1428
+ stdout: result.stdout,
1429
+ stderr: result.stderr,
1430
+ truncated: false,
1431
+ timedOut: false,
1432
+ opened: true
1433
+ };
1434
+ } catch (error) {
1435
+ if (error instanceof e2b.CommandExitError) return {
1436
+ exitCode: error.exitCode,
1437
+ stdout: error.stdout,
1438
+ stderr: error.stderr,
1439
+ truncated: false,
1440
+ timedOut: false,
1441
+ opened: true
1442
+ };
1443
+ return {
1444
+ exitCode: null,
1445
+ stdout: stdoutChunks.join(""),
1446
+ stderr: stderrChunks.join(""),
1447
+ truncated: false,
1448
+ timedOut: error instanceof e2b.TimeoutError,
1449
+ closeReason: error instanceof Error ? error.message : String(error),
1450
+ opened: true
1451
+ };
1452
+ }
1453
+ };
1454
+ /** The VM's envd API, authenticated by the exec lease. */
1455
+ const sandboxForLease = (lease) => new e2b.Sandbox({
1456
+ sandboxId: lease.sandboxId,
1457
+ envdVersion: E2B_ENVD_VERSION,
1458
+ envdAccessToken: lease.jwt,
1459
+ sandboxUrl: lease.wsEndpoint,
1460
+ validateApiKey: false
1461
+ });
1462
+ /** Opens E2B's files API directly against the VM, authenticated by the exec lease. */
1463
+ const e2bFilesForLease = (lease) => sandboxForLease(lease).files;
1464
+ /** Opens E2B's commands API directly against the VM, authenticated by the exec lease. */
1465
+ const commandsForLease = (lease) => sandboxForLease(lease).commands;
1466
+ // src/private-net-exec.ts
1467
+ /**
1468
+ * Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
1469
+ * HTTP response. This is an *application* error, not a transport error — the
1470
+ * sidecar is reachable and answered, it just refused the exec. Callers should
1471
+ * fall back to the lease path for this one call but MUST NOT invalidate the
1472
+ * cached `instanceUrl` (the address is still good).
1473
+ */
1474
+ var PrivateNetExecHttpError = class extends Error {
1475
+ status;
1476
+ body;
1477
+ constructor(status, body) {
1478
+ super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
1479
+ this.name = "PrivateNetExecHttpError";
1480
+ this.status = status;
1481
+ this.body = body;
1482
+ }
1483
+ };
1484
+ const DEFAULT_FETCH = (input, init) => {
1485
+ const f = globalThis.fetch;
1486
+ if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
1487
+ return f(input, init);
1488
+ };
1489
+ /**
1490
+ * Dial `${instanceUrl}/exec` and stream the response, resolving with the
1491
+ * accumulated stdout/stderr + exit code.
1492
+ *
1493
+ * Errors:
1494
+ * - Connection failure (DNS, refused, reset) → resolves with
1495
+ * `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
1496
+ * transport failures — the shape matches the lease-path result so the
1497
+ * caller can treat both transports uniformly.
1498
+ * - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
1499
+ * Application-level; caller decides whether to fall back.
1500
+ * - Stream ends without an `exit` frame → resolves with
1501
+ * `{opened:true, exitCode:null}`, matching the lease-path semantics for a
1502
+ * mid-stream drop.
1503
+ * - `timeoutMs` elapsed → aborts the request, resolves with
1504
+ * `{timedOut:true, exitCode:124}`.
1505
+ */
1506
+ async function execViaPrivateNetwork(instanceUrl, options) {
1507
+ const fetchImpl = options.fetch ?? DEFAULT_FETCH;
1508
+ const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
1509
+ const controller = new AbortController();
1510
+ let timedOut = false;
1511
+ let timeoutTimer;
1512
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
1513
+ timedOut = true;
1514
+ controller.abort();
1515
+ }, options.timeoutMs);
1516
+ const body = { command: options.command };
1517
+ if (options.cwd) body.cwd = options.cwd;
1518
+ if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
1519
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
1520
+ const headers = { "content-type": "application/json" };
1521
+ if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
1522
+ let response;
1523
+ try {
1524
+ response = await fetchImpl(url, {
1525
+ method: "POST",
1526
+ headers,
1527
+ body: JSON.stringify(body),
1528
+ signal: controller.signal
1392
1529
  });
1530
+ } catch (error) {
1531
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1532
+ if (timedOut) return {
1533
+ exitCode: 124,
1534
+ stdout: "",
1535
+ stderr: "",
1536
+ timedOut: true,
1537
+ opened: false
1538
+ };
1539
+ return {
1540
+ exitCode: null,
1541
+ stdout: "",
1542
+ stderr: "",
1543
+ timedOut: false,
1544
+ opened: false,
1545
+ transportErrorMessage: error instanceof Error ? error.message : String(error)
1546
+ };
1393
1547
  }
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));
1548
+ if (!response.ok) {
1549
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1550
+ const text = await response.text().catch(() => "");
1551
+ throw new PrivateNetExecHttpError(response.status, text);
1407
1552
  }
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
- }
1553
+ if (!response.body) {
1554
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1555
+ return {
1556
+ exitCode: null,
1557
+ stdout: "",
1558
+ stderr: "",
1559
+ timedOut: false,
1560
+ opened: true,
1561
+ status: response.status
1562
+ };
1415
1563
  }
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) {
1564
+ let stdout = "";
1565
+ let stderr = "";
1566
+ let exitCode = null;
1567
+ const decoder = new TextDecoder();
1568
+ let buffer = "";
1569
+ const handleLine = (line) => {
1570
+ if (!line) return;
1571
+ let frame;
1422
1572
  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;
1573
+ frame = JSON.parse(line);
1574
+ } catch {
1575
+ return;
1428
1576
  }
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();
1577
+ if (!frame || typeof frame !== "object") return;
1578
+ if (frame.type === "stdout" && typeof frame.data === "string") {
1579
+ stdout += frame.data;
1580
+ options.onStdout?.(frame.data);
1581
+ } else if (frame.type === "stderr" && typeof frame.data === "string") {
1582
+ stderr += frame.data;
1583
+ options.onStderr?.(frame.data);
1584
+ } else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
1585
+ };
1586
+ try {
1587
+ const reader = response.body.getReader();
1588
+ while (true) {
1589
+ const { value, done } = await reader.read();
1590
+ if (done) break;
1591
+ buffer += decoder.decode(value, { stream: true });
1592
+ let newlineIdx = buffer.indexOf("\n");
1593
+ while (newlineIdx !== -1) {
1594
+ const line = buffer.slice(0, newlineIdx).trim();
1595
+ buffer = buffer.slice(newlineIdx + 1);
1596
+ handleLine(line);
1597
+ newlineIdx = buffer.indexOf("\n");
1598
+ }
1437
1599
  }
1438
- throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
1600
+ buffer += decoder.decode();
1601
+ const trailing = buffer.trim();
1602
+ if (trailing) handleLine(trailing);
1603
+ } catch (error) {
1604
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1605
+ if (timedOut) return {
1606
+ exitCode: 124,
1607
+ stdout,
1608
+ stderr,
1609
+ timedOut: true,
1610
+ opened: true,
1611
+ status: response.status
1612
+ };
1613
+ return {
1614
+ exitCode,
1615
+ stdout,
1616
+ stderr,
1617
+ timedOut: false,
1618
+ opened: true,
1619
+ status: response.status,
1620
+ transportErrorMessage: error instanceof Error ? error.message : String(error)
1621
+ };
1622
+ } finally {
1623
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1439
1624
  }
1440
- };
1441
- //#endregion
1442
- //#region src/sandbox-filesystem.ts
1625
+ return {
1626
+ exitCode,
1627
+ stdout,
1628
+ stderr,
1629
+ timedOut: false,
1630
+ opened: true,
1631
+ status: response.status
1632
+ };
1633
+ }
1634
+ // src/sandbox-filesystem.ts
1443
1635
  /**
1444
1636
  * envd's edge answers a paused or missing sandbox with a 404 or 502 that the
1445
1637
  * SDK reports as `FileNotFoundError` or `TimeoutError`. Same message pattern as
@@ -1479,8 +1671,7 @@ var PlatformSandboxFilesystem = class extends FilesApiFilesystem {
1479
1671
  if (error instanceof e2b.InvalidArgumentError) return "invalid-argument";
1480
1672
  }
1481
1673
  };
1482
- //#endregion
1483
- //#region src/sandbox.ts
1674
+ // src/sandbox.ts
1484
1675
  /**
1485
1676
  * How long before a lease's stated `expiresAt` we should treat it as
1486
1677
  * expired. Avoids a race where the JWT is valid at cache-hit time but the
@@ -1638,6 +1829,70 @@ var PlatformProcessManager = class extends _mastra_core_workspace.SandboxProcess
1638
1829
  }));
1639
1830
  }
1640
1831
  };
1832
+ /** Reaches the sandbox's commands handle without making it part of the class's public API. */
1833
+ const withCommands = Symbol("withCommands");
1834
+ /**
1835
+ * Background processes on an E2B-backed sandbox through envd's commands API,
1836
+ * reached with the same lease `executeCommand` uses. Output streams while the
1837
+ * process runs, `kill` stops it, and `list` reports what is running in the VM.
1838
+ */
1839
+ var PlatformCommandsProcessManager = class extends CommandsApiProcessManager {
1840
+ runCommands(operation, fn) {
1841
+ return this.sandbox[withCommands](operation, fn);
1842
+ }
1843
+ createHandle(inner, stdinMode, options) {
1844
+ return new PlatformProcessHandleOverLease(inner, this, Date.now(), stdinMode, options);
1845
+ }
1846
+ };
1847
+ /** envd ends the output stream when the lease it was opened with expires; the process keeps running. */
1848
+ function isLeaseStreamDrop(error) {
1849
+ return error instanceof e2b.TimeoutError && error.message.startsWith("[unavailable]");
1850
+ }
1851
+ /**
1852
+ * The process left the VM while no stream was attached, so envd can't say how
1853
+ * it ended. Carries an exit code so the handle reads as exited: it shows in
1854
+ * `list()` and is released like any other finished process.
1855
+ */
1856
+ var ProcessEndedUnseenError = class extends Error {
1857
+ exitCode = 1;
1858
+ constructor(cause) {
1859
+ super(`${cause instanceof Error ? cause.message : String(cause)} (the process ended before it could be reattached)`);
1860
+ }
1861
+ };
1862
+ /**
1863
+ * A process outlives the lease it was started with. When that lease expires
1864
+ * envd ends the output stream, so reattach on the current lease and keep
1865
+ * waiting. Output written between the drop and the reattach is not seen.
1866
+ */
1867
+ var PlatformProcessHandleOverLease = class extends CommandsApiProcessHandle {
1868
+ /** One reattach loop shared by every `wait()` caller. */
1869
+ exited;
1870
+ waitForExit() {
1871
+ return this.exited ??= this.waitAcrossLeases();
1872
+ }
1873
+ async waitAcrossLeases() {
1874
+ for (;;) try {
1875
+ return await this.inner.wait();
1876
+ } catch (error) {
1877
+ if (!isLeaseStreamDrop(error)) throw error;
1878
+ const pid = this.inner.pid;
1879
+ const reattached = await this.manager.runCommands("connect", async (commands) => {
1880
+ if (!(await commands.list()).some((proc) => proc.pid === pid)) return "ended";
1881
+ return commands.connect(pid, {
1882
+ onStdout: (data) => this.emitStdout(data),
1883
+ onStderr: (data) => this.emitStderr(data),
1884
+ timeoutMs: 0
1885
+ });
1886
+ }).catch(() => void 0);
1887
+ if (reattached === "ended") throw new ProcessEndedUnseenError(error);
1888
+ if (!reattached) {
1889
+ this.exited = void 0;
1890
+ throw error;
1891
+ }
1892
+ this.inner = reattached;
1893
+ }
1894
+ }
1895
+ };
1641
1896
  var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.MastraSandbox {
1642
1897
  id;
1643
1898
  name = "PlatformSandbox";
@@ -1685,6 +1940,8 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
1685
1940
  _e2bFilesFactory;
1686
1941
  /** Files handle for the current lease, rebuilt whenever the lease changes. */
1687
1942
  _e2bFiles = null;
1943
+ _e2bCommandsFactory;
1944
+ _e2bCommands = null;
1688
1945
  _filesystem;
1689
1946
  _privateNetFetch;
1690
1947
  /**
@@ -1753,10 +2010,11 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
1753
2010
  */
1754
2011
  _probeTarget = null;
1755
2012
  constructor(options = {}) {
2013
+ const e2bBacked = resolveSandboxProvider(options.sandboxProvider ?? process.env.SANDBOX_PROVIDER?.trim()) === "e2b";
1756
2014
  super({
1757
2015
  ...options,
1758
2016
  name: "PlatformSandbox",
1759
- processes: new PlatformProcessManager()
2017
+ processes: e2bBacked ? new PlatformCommandsProcessManager({ defaultTimeout: options.timeout ?? 0 }) : new PlatformProcessManager()
1760
2018
  });
1761
2019
  this._hasRecoveryKey = options.id !== void 0;
1762
2020
  this.id = options.id ?? this.generateId();
@@ -1776,6 +2034,7 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
1776
2034
  this._webSocketFactory = options.webSocketFactory;
1777
2035
  this._e2bExecRunner = options.e2bExecRunner ?? execViaE2BLease;
1778
2036
  this._e2bFilesFactory = options.e2bFilesFactory ?? e2bFilesForLease;
2037
+ this._e2bCommandsFactory = options.e2bCommandsFactory ?? commandsForLease;
1779
2038
  this._privateNetFetch = options.privateNetFetch;
1780
2039
  this._addressRegistry = options.addressRegistry;
1781
2040
  }
@@ -2569,8 +2828,55 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
2569
2828
  };
2570
2829
  return this._e2bFiles;
2571
2830
  }
2831
+ /**
2832
+ * Run `fn` against envd's commands API with the current lease, the way
2833
+ * {@link _withE2BFiles} runs files calls: one retry, only after an
2834
+ * `AuthenticationError` proves the call never ran, so a spawn or kill is
2835
+ * never replayed. Each call fetches the lease again, so a process started
2836
+ * under one lease is stopped with whichever lease is current.
2837
+ */
2838
+ async [withCommands](operation, fn) {
2839
+ await this.ensureRunning();
2840
+ if (!this._sandboxId) throw new _mastra_core_workspace.SandboxNotReadyError(this.id);
2841
+ let current = await this._commandsHandle(operation, 1);
2842
+ const call = async (invoke) => {
2843
+ try {
2844
+ return await invoke(current.commands);
2845
+ } catch (error) {
2846
+ if (error instanceof e2b.AuthenticationError) {
2847
+ if (this._lease === current.lease) this._lease = null;
2848
+ current = await this._commandsHandle(operation, 2);
2849
+ try {
2850
+ return await invoke(current.commands);
2851
+ } catch (retryError) {
2852
+ if (isBrokenSandboxError(retryError) && this._lease === current.lease) this._lease = null;
2853
+ throw retryError;
2854
+ }
2855
+ }
2856
+ if (isBrokenSandboxError(error) && this._lease === current.lease) this._lease = null;
2857
+ throw error;
2858
+ }
2859
+ };
2860
+ return fn({
2861
+ run: (command, opts) => call((commands) => commands.run(command, opts)),
2862
+ connect: (pid, opts) => call((commands) => commands.connect(pid, opts)),
2863
+ list: () => call((commands) => commands.list()),
2864
+ kill: (pid) => call((commands) => commands.kill(pid)),
2865
+ sendStdin: (pid, data) => call((commands) => commands.sendStdin(pid, data))
2866
+ });
2867
+ }
2868
+ /** The commands handle for the current lease, rebuilt only when the lease changes. */
2869
+ async _commandsHandle(operation, attempts) {
2870
+ const lease = await this._fileLease(`processes.${operation}`, attempts, "");
2871
+ if (lease.provider !== "e2b") throw new Error(`PlatformSandbox.processes requires an E2B-backed sandbox; this sandbox's provider is "${lease.provider}"`);
2872
+ if (this._e2bCommands?.lease !== lease) this._e2bCommands = {
2873
+ lease,
2874
+ commands: this._e2bCommandsFactory(lease)
2875
+ };
2876
+ return this._e2bCommands;
2877
+ }
2572
2878
  /** `_ensureLease`, with a 410 handled the same way `_runDirectExec` handles it. */
2573
- async _fileLease(operation, attempts) {
2879
+ async _fileLease(operation, attempts, prefix = "filesystem.") {
2574
2880
  try {
2575
2881
  return await this._ensureLease();
2576
2882
  } catch (error) {
@@ -2581,7 +2887,7 @@ var PlatformSandbox = class PlatformSandbox extends _mastra_core_workspace.Mastr
2581
2887
  this.status = "stopped";
2582
2888
  throw new SandboxDestroyedError(`Sandbox ${priorSandboxId ?? "(unknown)"} was destroyed; /exec-lease returned 410`, {
2583
2889
  ...priorSandboxId && { sandboxId: priorSandboxId },
2584
- command: `filesystem.${operation}`,
2890
+ command: `${prefix}${operation}`,
2585
2891
  attempts
2586
2892
  });
2587
2893
  }
@@ -2639,8 +2945,7 @@ function templateHash(definition) {
2639
2945
  const { family: _family, ...content } = definition;
2640
2946
  return (0, crypto.createHash)("sha256").update(JSON.stringify(content)).digest("hex").slice(0, 16);
2641
2947
  }
2642
- //#endregion
2643
- //#region src/repo-template.ts
2948
+ // src/repo-template.ts
2644
2949
  const execFileAsync = (0, util.promisify)(child_process.execFile);
2645
2950
  const SHA_PATTERN = /^[0-9a-f]{7,40}$/i;
2646
2951
  const BUILD_TOKEN_ENV = "MASTRA_REPOSITORY_ACCESS_TOKEN";
@@ -2929,8 +3234,7 @@ async function resolveDefaultBranchHead(cloneUrl, token, execute = execFileAsync
2929
3234
  throw new Error(`git ls-remote failed: ${detail}`);
2930
3235
  }
2931
3236
  }
2932
- //#endregion
2933
- //#region src/provider.ts
3237
+ // src/provider.ts
2934
3238
  const platformSandboxProvider = {
2935
3239
  id: "platform",
2936
3240
  name: "Mastra Platform Sandbox",
@@ -3015,8 +3319,7 @@ const platformFilesystemProvider = {
3015
3319
  },
3016
3320
  createFilesystem: (config) => new PlatformFilesystem(config)
3017
3321
  };
3018
- //#endregion
3019
- //#region src/factory-sandbox.ts
3322
+ // src/factory-sandbox.ts
3020
3323
  /** Applied when neither the environment setting nor a host default is set. */
3021
3324
  const DEFAULT_SETTINGS = {
3022
3325
  cpuCount: 2,
@@ -3186,8 +3489,7 @@ function toBuild(result) {
3186
3489
  ...result.error ? { error: result.error } : {}
3187
3490
  };
3188
3491
  }
3189
- //#endregion
3190
- //#region src/address-registry.ts
3492
+ // src/address-registry.ts
3191
3493
  /**
3192
3494
  * Concrete in-process {@link SandboxAddressRegistry}. Backed by a `Map`; no
3193
3495
  * eviction policy, no TTL — entries live until an observed transport failure
@@ -3219,7 +3521,6 @@ var InProcessSandboxAddressRegistry = class {
3219
3521
  return this.#map.size;
3220
3522
  }
3221
3523
  };
3222
- //#endregion
3223
3524
  exports.InProcessSandboxAddressRegistry = InProcessSandboxAddressRegistry;
3224
3525
  exports.PlatformApiError = PlatformApiError;
3225
3526
  exports.PlatformClient = PlatformClient;