@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/_types/@internal_workspace/dist/commands-api-process-manager.d.ts +99 -0
- package/dist/_types/@internal_workspace/dist/index.d.ts +1 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/e2b-exec.d.ts +4 -0
- package/dist/e2b-exec.d.ts.map +1 -1
- package/dist/index.cjs +815 -514
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +815 -513
- package/dist/index.js.map +1 -1
- package/dist/sandbox.d.ts +21 -16
- package/dist/sandbox.d.ts.map +1 -1
- package/package.json +11 -11
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Buffer as Buffer$1 } from "buffer";
|
|
2
2
|
import nodePath, { posix } from "path";
|
|
3
|
-
import { DirectoryNotEmptyError, DirectoryNotFoundError, FactorySandbox, FileExistsError, FileNotFoundError, IsDirectoryError, MastraFilesystem, MastraSandbox, NotDirectoryError, ProcessHandle, SandboxError, SandboxNotReadyError, SandboxProcessManager, UnsupportedStdinCloseError, WorkspaceReadOnlyError } from "@mastra/core/workspace";
|
|
3
|
+
import { DirectoryNotEmptyError, DirectoryNotFoundError, FactorySandbox, FileExistsError, FileNotFoundError, IsDirectoryError, MastraFilesystem, MastraSandbox, NotDirectoryError, ProcessHandle, SandboxError, SandboxNotReadyError, SandboxProcessManager, UnsupportedStdinCloseError, WorkspaceReadOnlyError, getMimeType } from "@mastra/core/workspace";
|
|
4
4
|
import { createHash } from "crypto";
|
|
5
5
|
import { AuthenticationError, CommandExitError, InvalidArgumentError, NotFoundError, Sandbox, SandboxError as SandboxError$1, SandboxNotFoundError, TimeoutError } from "e2b";
|
|
6
6
|
import { execFile } from "child_process";
|
|
7
7
|
import { promisify } from "util";
|
|
8
|
-
|
|
8
|
+
// src/client.ts
|
|
9
9
|
const DEFAULT_PROXY_URL = "https://workspaces.mastra.ai";
|
|
10
10
|
const REGIONAL_PROXY_URLS = {
|
|
11
11
|
us: "https://workspaces.us.mastra.ai",
|
|
@@ -136,8 +136,7 @@ var PlatformClient = class {
|
|
|
136
136
|
return response;
|
|
137
137
|
}
|
|
138
138
|
};
|
|
139
|
-
|
|
140
|
-
//#region src/filesystem.ts
|
|
139
|
+
// src/filesystem.ts
|
|
141
140
|
function normalizePath(input) {
|
|
142
141
|
if (!input || input === ".") return "/";
|
|
143
142
|
let normalized = input.startsWith("/") ? input : `/${input}`;
|
|
@@ -396,8 +395,7 @@ var PlatformFilesystem = class extends MastraFilesystem {
|
|
|
396
395
|
function matchesExtension$1(name, extension) {
|
|
397
396
|
return (Array.isArray(extension) ? extension : [extension]).some((ext) => name.endsWith(ext));
|
|
398
397
|
}
|
|
399
|
-
|
|
400
|
-
//#region src/template.ts
|
|
398
|
+
// src/template.ts
|
|
401
399
|
const SERIALIZE_TEMPLATE = Symbol("serializeTemplate");
|
|
402
400
|
const GET_TEMPLATE_BUILD_ENVS = Symbol("getTemplateBuildEnvs");
|
|
403
401
|
const MAX_OPERATIONS = 256;
|
|
@@ -575,450 +573,62 @@ function cloneJson(value) {
|
|
|
575
573
|
if (typeof value === "number" && !Number.isFinite(value)) throw new TypeError("Sandbox template values must contain only finite numbers");
|
|
576
574
|
return value;
|
|
577
575
|
}
|
|
578
|
-
|
|
579
|
-
|
|
576
|
+
// ../../packages/_internals/workspace/dist/index.js
|
|
577
|
+
/** Directory, relative to the template's build cwd, that holds every marker below. */
|
|
578
|
+
const SETUP_MARKER_DIR = ".mastra-sandbox";
|
|
580
579
|
/**
|
|
581
|
-
*
|
|
582
|
-
* a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
|
|
583
|
-
* removes the platform data plane from the exec stdout/stderr path entirely
|
|
584
|
-
* (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
|
|
585
|
-
* cutting payload-scaled Cloud Run egress and RTT for commands like
|
|
586
|
-
* `pnpm install` that stream tens of MB of output.
|
|
580
|
+
* Setup completion marker shared by repo templates and their consumers.
|
|
587
581
|
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
*
|
|
591
|
-
*
|
|
582
|
+
* A repo template writes this file beside the checkout as its last build
|
|
583
|
+
* step, so it exists only in images where every setup command succeeded. Its
|
|
584
|
+
* content is a digest of the setup commands the image ran, letting a sandbox
|
|
585
|
+
* booted from the image tell whether the setup it is about to run already
|
|
586
|
+
* happened. Relative to the template's build cwd, which is also the runtime
|
|
587
|
+
* working directory the repo was cloned into.
|
|
588
|
+
*
|
|
589
|
+
* This is the single-repository marker. Templates built from a repository
|
|
590
|
+
* list write one marker per repository instead ({@link repoSetupMarkerPath}).
|
|
592
591
|
*/
|
|
593
|
-
|
|
594
|
-
const STDOUT_FRAME = 1;
|
|
595
|
-
/** Byte-0 tag on binary WS frames for stderr output. */
|
|
596
|
-
const STDERR_FRAME = 3;
|
|
592
|
+
const SETUP_MARKER_PATH = ".mastra-sandbox/setup";
|
|
597
593
|
/**
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
* command runtime, just not to unbounded connection setup.
|
|
594
|
+
* Marker for the workspace-level setup of a multi-repository template: the
|
|
595
|
+
* commands that ran at the working directory after every repository was set
|
|
596
|
+
* up. Written even when there were no such commands, so a consumer can tell
|
|
597
|
+
* "ran nothing" from "never built".
|
|
603
598
|
*/
|
|
604
|
-
const
|
|
605
|
-
const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
|
|
606
|
-
const WS = globalThis.WebSocket;
|
|
607
|
-
if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
|
|
608
|
-
return new WS(endpoint, subprotocols);
|
|
609
|
-
};
|
|
599
|
+
const WORKSPACE_SETUP_MARKER_PATH = ".mastra-sandbox/workspace-setup";
|
|
610
600
|
/**
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
* The client sends `stdin_close` immediately after `init_exec`, matching the
|
|
616
|
-
* SDK's own one-shot exec behavior — we never stream stdin from the caller.
|
|
601
|
+
* One line per repository directory whose setup failed while the build was
|
|
602
|
+
* told to continue. Absent when nothing failed. Consumers check this before
|
|
603
|
+
* trusting a per-repository marker: that marker means every step ran, not
|
|
604
|
+
* that every step succeeded.
|
|
617
605
|
*/
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
return new Promise((resolve) => {
|
|
623
|
-
let stdout = "";
|
|
624
|
-
let stderr = "";
|
|
625
|
-
let exitCode = null;
|
|
626
|
-
let timedOut = false;
|
|
627
|
-
let settled = false;
|
|
628
|
-
let opened = false;
|
|
629
|
-
let closeCode;
|
|
630
|
-
let closeReason;
|
|
631
|
-
let timer;
|
|
632
|
-
let handshakeTimer;
|
|
633
|
-
const settle = () => {
|
|
634
|
-
if (settled) return;
|
|
635
|
-
settled = true;
|
|
636
|
-
if (timer) clearTimeout(timer);
|
|
637
|
-
if (handshakeTimer) clearTimeout(handshakeTimer);
|
|
638
|
-
const stdoutTail = stdoutDecoder.decode();
|
|
639
|
-
if (stdoutTail) {
|
|
640
|
-
stdout += stdoutTail;
|
|
641
|
-
options.onStdout?.(stdoutTail);
|
|
642
|
-
}
|
|
643
|
-
const stderrTail = stderrDecoder.decode();
|
|
644
|
-
if (stderrTail) {
|
|
645
|
-
stderr += stderrTail;
|
|
646
|
-
options.onStderr?.(stderrTail);
|
|
647
|
-
}
|
|
648
|
-
try {
|
|
649
|
-
socket.close(1e3, "");
|
|
650
|
-
} catch {}
|
|
651
|
-
resolve({
|
|
652
|
-
exitCode,
|
|
653
|
-
stdout,
|
|
654
|
-
stderr,
|
|
655
|
-
truncated: false,
|
|
656
|
-
timedOut,
|
|
657
|
-
...closeCode !== void 0 && { closeCode },
|
|
658
|
-
...closeReason !== void 0 && { closeReason },
|
|
659
|
-
opened
|
|
660
|
-
});
|
|
661
|
-
};
|
|
662
|
-
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
|
|
663
|
-
timedOut = true;
|
|
664
|
-
if (exitCode === null) exitCode = 124;
|
|
665
|
-
settle();
|
|
666
|
-
}, options.timeoutMs);
|
|
667
|
-
else handshakeTimer = setTimeout(() => {
|
|
668
|
-
if (!opened) settle();
|
|
669
|
-
}, HANDSHAKE_DEADLINE_MS);
|
|
670
|
-
const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
|
|
671
|
-
socket.binaryType = "arraybuffer";
|
|
672
|
-
socket.onopen = () => {
|
|
673
|
-
opened = true;
|
|
674
|
-
if (handshakeTimer) {
|
|
675
|
-
clearTimeout(handshakeTimer);
|
|
676
|
-
handshakeTimer = void 0;
|
|
677
|
-
}
|
|
678
|
-
const data = { command: options.command };
|
|
679
|
-
if (options.cwd) data.cwd = options.cwd;
|
|
680
|
-
if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
|
|
681
|
-
socket.send(JSON.stringify({
|
|
682
|
-
type: "init_exec",
|
|
683
|
-
data
|
|
684
|
-
}));
|
|
685
|
-
socket.send(JSON.stringify({ type: "stdin_close" }));
|
|
686
|
-
};
|
|
687
|
-
socket.onmessage = (event) => {
|
|
688
|
-
const { data } = event;
|
|
689
|
-
if (data instanceof ArrayBuffer) handleBinaryFrame(data);
|
|
690
|
-
else if (typeof data === "string") handleTextFrame(data);
|
|
691
|
-
};
|
|
692
|
-
socket.onclose = (event) => {
|
|
693
|
-
closeCode = event.code;
|
|
694
|
-
closeReason = event.reason;
|
|
695
|
-
if (!opened) {
|
|
696
|
-
settle();
|
|
697
|
-
return;
|
|
698
|
-
}
|
|
699
|
-
settle();
|
|
700
|
-
};
|
|
701
|
-
socket.onerror = () => {
|
|
702
|
-
if (settled) return;
|
|
703
|
-
if (!opened) settle();
|
|
704
|
-
};
|
|
705
|
-
function handleBinaryFrame(buffer) {
|
|
706
|
-
const view = new Uint8Array(buffer);
|
|
707
|
-
if (view.length <= 1) return;
|
|
708
|
-
if (view[0] === STDOUT_FRAME) {
|
|
709
|
-
const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
|
|
710
|
-
stdout += chunk;
|
|
711
|
-
options.onStdout?.(chunk);
|
|
712
|
-
} else if (view[0] === STDERR_FRAME) {
|
|
713
|
-
const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
|
|
714
|
-
stderr += chunk;
|
|
715
|
-
options.onStderr?.(chunk);
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
function handleTextFrame(text) {
|
|
719
|
-
let frame;
|
|
720
|
-
try {
|
|
721
|
-
frame = JSON.parse(text);
|
|
722
|
-
} catch {
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
if (frame.type === "exit") {
|
|
726
|
-
exitCode = frame.data?.exit_code ?? 0;
|
|
727
|
-
settle();
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
});
|
|
606
|
+
const SETUP_FAILED_MARKER_PATH = ".mastra-sandbox/setup-failed";
|
|
607
|
+
/** Per-repository marker of a multi-repository template, keyed by the clone directory name. */
|
|
608
|
+
function repoSetupMarkerPath(repoDir) {
|
|
609
|
+
return `${SETUP_MARKER_DIR}/repos/${repoDir}`;
|
|
731
610
|
}
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
try {
|
|
747
|
-
const result = await new Sandbox({
|
|
748
|
-
sandboxId: lease.sandboxId,
|
|
749
|
-
envdVersion: E2B_ENVD_VERSION,
|
|
750
|
-
envdAccessToken: lease.jwt,
|
|
751
|
-
sandboxUrl: lease.wsEndpoint,
|
|
752
|
-
validateApiKey: false
|
|
753
|
-
}).commands.run(options.command, {
|
|
754
|
-
cwd: options.cwd,
|
|
755
|
-
envs: options.env,
|
|
756
|
-
timeoutMs: options.timeoutMs,
|
|
757
|
-
onStdout,
|
|
758
|
-
onStderr
|
|
759
|
-
});
|
|
760
|
-
return {
|
|
761
|
-
exitCode: result.exitCode,
|
|
762
|
-
stdout: result.stdout,
|
|
763
|
-
stderr: result.stderr,
|
|
764
|
-
truncated: false,
|
|
765
|
-
timedOut: false,
|
|
766
|
-
opened: true
|
|
767
|
-
};
|
|
768
|
-
} catch (error) {
|
|
769
|
-
if (error instanceof CommandExitError) return {
|
|
770
|
-
exitCode: error.exitCode,
|
|
771
|
-
stdout: error.stdout,
|
|
772
|
-
stderr: error.stderr,
|
|
773
|
-
truncated: false,
|
|
774
|
-
timedOut: false,
|
|
775
|
-
opened: true
|
|
776
|
-
};
|
|
777
|
-
return {
|
|
778
|
-
exitCode: null,
|
|
779
|
-
stdout: stdoutChunks.join(""),
|
|
780
|
-
stderr: stderrChunks.join(""),
|
|
781
|
-
truncated: false,
|
|
782
|
-
timedOut: error instanceof TimeoutError,
|
|
783
|
-
closeReason: error instanceof Error ? error.message : String(error),
|
|
784
|
-
opened: true
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
};
|
|
788
|
-
/** Opens E2B's files API directly against the VM, authenticated by the exec lease. */
|
|
789
|
-
const e2bFilesForLease = (lease) => new Sandbox({
|
|
790
|
-
sandboxId: lease.sandboxId,
|
|
791
|
-
envdVersion: E2B_ENVD_VERSION,
|
|
792
|
-
envdAccessToken: lease.jwt,
|
|
793
|
-
sandboxUrl: lease.wsEndpoint,
|
|
794
|
-
validateApiKey: false
|
|
795
|
-
}).files;
|
|
796
|
-
//#endregion
|
|
797
|
-
//#region src/private-net-exec.ts
|
|
611
|
+
/** Blank entries never become build steps, so they never count toward the digest either. */
|
|
612
|
+
function normalizeSetupCommands(setupCommand) {
|
|
613
|
+
return (setupCommand === void 0 ? [] : Array.isArray(setupCommand) ? setupCommand : [setupCommand]).filter((command) => command.trim() !== "");
|
|
614
|
+
}
|
|
615
|
+
/** The marker content for a setup command list: `sha256:<hex>` over the commands joined by newlines. */
|
|
616
|
+
function setupMarkerContent(setupCommand) {
|
|
617
|
+
return `sha256:${createHash("sha256").update(normalizeSetupCommands(setupCommand).join("\n")).digest("hex")}`;
|
|
618
|
+
}
|
|
619
|
+
/** Shell step that writes the marker relative to the cwd. `content` is a digest, so it is shell-safe. */
|
|
620
|
+
function setupMarkerCommand(content, markerPath = SETUP_MARKER_PATH) {
|
|
621
|
+
return `mkdir -p "$(dirname "${markerPath}")" && printf '%s' '${content}' > "${markerPath}"`;
|
|
622
|
+
}
|
|
623
|
+
/** A clone directory name is one path segment of word characters, dots and dashes, so it never needs quoting. */
|
|
624
|
+
const REPO_DIR_PATTERN = /^[\w.-]+$/;
|
|
798
625
|
/**
|
|
799
|
-
*
|
|
800
|
-
*
|
|
801
|
-
*
|
|
802
|
-
*
|
|
803
|
-
*
|
|
804
|
-
|
|
805
|
-
var PrivateNetExecHttpError = class extends Error {
|
|
806
|
-
status;
|
|
807
|
-
body;
|
|
808
|
-
constructor(status, body) {
|
|
809
|
-
super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
|
|
810
|
-
this.name = "PrivateNetExecHttpError";
|
|
811
|
-
this.status = status;
|
|
812
|
-
this.body = body;
|
|
813
|
-
}
|
|
814
|
-
};
|
|
815
|
-
const DEFAULT_FETCH = (input, init) => {
|
|
816
|
-
const f = globalThis.fetch;
|
|
817
|
-
if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
|
|
818
|
-
return f(input, init);
|
|
819
|
-
};
|
|
820
|
-
/**
|
|
821
|
-
* Dial `${instanceUrl}/exec` and stream the response, resolving with the
|
|
822
|
-
* accumulated stdout/stderr + exit code.
|
|
823
|
-
*
|
|
824
|
-
* Errors:
|
|
825
|
-
* - Connection failure (DNS, refused, reset) → resolves with
|
|
826
|
-
* `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
|
|
827
|
-
* transport failures — the shape matches the lease-path result so the
|
|
828
|
-
* caller can treat both transports uniformly.
|
|
829
|
-
* - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
|
|
830
|
-
* Application-level; caller decides whether to fall back.
|
|
831
|
-
* - Stream ends without an `exit` frame → resolves with
|
|
832
|
-
* `{opened:true, exitCode:null}`, matching the lease-path semantics for a
|
|
833
|
-
* mid-stream drop.
|
|
834
|
-
* - `timeoutMs` elapsed → aborts the request, resolves with
|
|
835
|
-
* `{timedOut:true, exitCode:124}`.
|
|
836
|
-
*/
|
|
837
|
-
async function execViaPrivateNetwork(instanceUrl, options) {
|
|
838
|
-
const fetchImpl = options.fetch ?? DEFAULT_FETCH;
|
|
839
|
-
const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
|
|
840
|
-
const controller = new AbortController();
|
|
841
|
-
let timedOut = false;
|
|
842
|
-
let timeoutTimer;
|
|
843
|
-
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
|
|
844
|
-
timedOut = true;
|
|
845
|
-
controller.abort();
|
|
846
|
-
}, options.timeoutMs);
|
|
847
|
-
const body = { command: options.command };
|
|
848
|
-
if (options.cwd) body.cwd = options.cwd;
|
|
849
|
-
if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
|
|
850
|
-
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
|
|
851
|
-
const headers = { "content-type": "application/json" };
|
|
852
|
-
if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
|
|
853
|
-
let response;
|
|
854
|
-
try {
|
|
855
|
-
response = await fetchImpl(url, {
|
|
856
|
-
method: "POST",
|
|
857
|
-
headers,
|
|
858
|
-
body: JSON.stringify(body),
|
|
859
|
-
signal: controller.signal
|
|
860
|
-
});
|
|
861
|
-
} catch (error) {
|
|
862
|
-
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
863
|
-
if (timedOut) return {
|
|
864
|
-
exitCode: 124,
|
|
865
|
-
stdout: "",
|
|
866
|
-
stderr: "",
|
|
867
|
-
timedOut: true,
|
|
868
|
-
opened: false
|
|
869
|
-
};
|
|
870
|
-
return {
|
|
871
|
-
exitCode: null,
|
|
872
|
-
stdout: "",
|
|
873
|
-
stderr: "",
|
|
874
|
-
timedOut: false,
|
|
875
|
-
opened: false,
|
|
876
|
-
transportErrorMessage: error instanceof Error ? error.message : String(error)
|
|
877
|
-
};
|
|
878
|
-
}
|
|
879
|
-
if (!response.ok) {
|
|
880
|
-
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
881
|
-
const text = await response.text().catch(() => "");
|
|
882
|
-
throw new PrivateNetExecHttpError(response.status, text);
|
|
883
|
-
}
|
|
884
|
-
if (!response.body) {
|
|
885
|
-
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
886
|
-
return {
|
|
887
|
-
exitCode: null,
|
|
888
|
-
stdout: "",
|
|
889
|
-
stderr: "",
|
|
890
|
-
timedOut: false,
|
|
891
|
-
opened: true,
|
|
892
|
-
status: response.status
|
|
893
|
-
};
|
|
894
|
-
}
|
|
895
|
-
let stdout = "";
|
|
896
|
-
let stderr = "";
|
|
897
|
-
let exitCode = null;
|
|
898
|
-
const decoder = new TextDecoder();
|
|
899
|
-
let buffer = "";
|
|
900
|
-
const handleLine = (line) => {
|
|
901
|
-
if (!line) return;
|
|
902
|
-
let frame;
|
|
903
|
-
try {
|
|
904
|
-
frame = JSON.parse(line);
|
|
905
|
-
} catch {
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
if (!frame || typeof frame !== "object") return;
|
|
909
|
-
if (frame.type === "stdout" && typeof frame.data === "string") {
|
|
910
|
-
stdout += frame.data;
|
|
911
|
-
options.onStdout?.(frame.data);
|
|
912
|
-
} else if (frame.type === "stderr" && typeof frame.data === "string") {
|
|
913
|
-
stderr += frame.data;
|
|
914
|
-
options.onStderr?.(frame.data);
|
|
915
|
-
} else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
|
|
916
|
-
};
|
|
917
|
-
try {
|
|
918
|
-
const reader = response.body.getReader();
|
|
919
|
-
while (true) {
|
|
920
|
-
const { value, done } = await reader.read();
|
|
921
|
-
if (done) break;
|
|
922
|
-
buffer += decoder.decode(value, { stream: true });
|
|
923
|
-
let newlineIdx = buffer.indexOf("\n");
|
|
924
|
-
while (newlineIdx !== -1) {
|
|
925
|
-
const line = buffer.slice(0, newlineIdx).trim();
|
|
926
|
-
buffer = buffer.slice(newlineIdx + 1);
|
|
927
|
-
handleLine(line);
|
|
928
|
-
newlineIdx = buffer.indexOf("\n");
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
buffer += decoder.decode();
|
|
932
|
-
const trailing = buffer.trim();
|
|
933
|
-
if (trailing) handleLine(trailing);
|
|
934
|
-
} catch (error) {
|
|
935
|
-
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
936
|
-
if (timedOut) return {
|
|
937
|
-
exitCode: 124,
|
|
938
|
-
stdout,
|
|
939
|
-
stderr,
|
|
940
|
-
timedOut: true,
|
|
941
|
-
opened: true,
|
|
942
|
-
status: response.status
|
|
943
|
-
};
|
|
944
|
-
return {
|
|
945
|
-
exitCode,
|
|
946
|
-
stdout,
|
|
947
|
-
stderr,
|
|
948
|
-
timedOut: false,
|
|
949
|
-
opened: true,
|
|
950
|
-
status: response.status,
|
|
951
|
-
transportErrorMessage: error instanceof Error ? error.message : String(error)
|
|
952
|
-
};
|
|
953
|
-
} finally {
|
|
954
|
-
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
955
|
-
}
|
|
956
|
-
return {
|
|
957
|
-
exitCode,
|
|
958
|
-
stdout,
|
|
959
|
-
stderr,
|
|
960
|
-
timedOut: false,
|
|
961
|
-
opened: true,
|
|
962
|
-
status: response.status
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
//#endregion
|
|
966
|
-
//#region ../../packages/_internals/workspace/dist/index.js
|
|
967
|
-
/** Directory, relative to the template's build cwd, that holds every marker below. */
|
|
968
|
-
const SETUP_MARKER_DIR = ".mastra-sandbox";
|
|
969
|
-
/**
|
|
970
|
-
* Setup completion marker shared by repo templates and their consumers.
|
|
971
|
-
*
|
|
972
|
-
* A repo template writes this file beside the checkout as its last build
|
|
973
|
-
* step, so it exists only in images where every setup command succeeded. Its
|
|
974
|
-
* content is a digest of the setup commands the image ran, letting a sandbox
|
|
975
|
-
* booted from the image tell whether the setup it is about to run already
|
|
976
|
-
* happened. Relative to the template's build cwd, which is also the runtime
|
|
977
|
-
* working directory the repo was cloned into.
|
|
978
|
-
*
|
|
979
|
-
* This is the single-repository marker. Templates built from a repository
|
|
980
|
-
* list write one marker per repository instead ({@link repoSetupMarkerPath}).
|
|
981
|
-
*/
|
|
982
|
-
const SETUP_MARKER_PATH = ".mastra-sandbox/setup";
|
|
983
|
-
/**
|
|
984
|
-
* Marker for the workspace-level setup of a multi-repository template: the
|
|
985
|
-
* commands that ran at the working directory after every repository was set
|
|
986
|
-
* up. Written even when there were no such commands, so a consumer can tell
|
|
987
|
-
* "ran nothing" from "never built".
|
|
988
|
-
*/
|
|
989
|
-
const WORKSPACE_SETUP_MARKER_PATH = ".mastra-sandbox/workspace-setup";
|
|
990
|
-
/**
|
|
991
|
-
* One line per repository directory whose setup failed while the build was
|
|
992
|
-
* told to continue. Absent when nothing failed. Consumers check this before
|
|
993
|
-
* trusting a per-repository marker: that marker means every step ran, not
|
|
994
|
-
* that every step succeeded.
|
|
995
|
-
*/
|
|
996
|
-
const SETUP_FAILED_MARKER_PATH = ".mastra-sandbox/setup-failed";
|
|
997
|
-
/** Per-repository marker of a multi-repository template, keyed by the clone directory name. */
|
|
998
|
-
function repoSetupMarkerPath(repoDir) {
|
|
999
|
-
return `${SETUP_MARKER_DIR}/repos/${repoDir}`;
|
|
1000
|
-
}
|
|
1001
|
-
/** Blank entries never become build steps, so they never count toward the digest either. */
|
|
1002
|
-
function normalizeSetupCommands(setupCommand) {
|
|
1003
|
-
return (setupCommand === void 0 ? [] : Array.isArray(setupCommand) ? setupCommand : [setupCommand]).filter((command) => command.trim() !== "");
|
|
1004
|
-
}
|
|
1005
|
-
/** The marker content for a setup command list: `sha256:<hex>` over the commands joined by newlines. */
|
|
1006
|
-
function setupMarkerContent(setupCommand) {
|
|
1007
|
-
return `sha256:${createHash("sha256").update(normalizeSetupCommands(setupCommand).join("\n")).digest("hex")}`;
|
|
1008
|
-
}
|
|
1009
|
-
/** Shell step that writes the marker relative to the cwd. `content` is a digest, so it is shell-safe. */
|
|
1010
|
-
function setupMarkerCommand(content, markerPath = SETUP_MARKER_PATH) {
|
|
1011
|
-
return `mkdir -p "$(dirname "${markerPath}")" && printf '%s' '${content}' > "${markerPath}"`;
|
|
1012
|
-
}
|
|
1013
|
-
/** A clone directory name is one path segment of word characters, dots and dashes, so it never needs quoting. */
|
|
1014
|
-
const REPO_DIR_PATTERN = /^[\w.-]+$/;
|
|
1015
|
-
/**
|
|
1016
|
-
* Shell step that runs one setup command inside a repository clone.
|
|
1017
|
-
*
|
|
1018
|
-
* Without the guard this is the plain `cd "<dir>" && <cmd>` step. With it,
|
|
1019
|
-
* the `cd` sits inside the parenthesized group so that the failure branch
|
|
1020
|
-
* runs back at the build cwd and the failure list lands at the workspace
|
|
1021
|
-
* level, never inside the repository.
|
|
626
|
+
* Shell step that runs one setup command inside a repository clone.
|
|
627
|
+
*
|
|
628
|
+
* Without the guard this is the plain `cd "<dir>" && <cmd>` step. With it,
|
|
629
|
+
* the `cd` sits inside the parenthesized group so that the failure branch
|
|
630
|
+
* runs back at the build cwd and the failure list lands at the workspace
|
|
631
|
+
* level, never inside the repository.
|
|
1022
632
|
*/
|
|
1023
633
|
function guardedSetupCommand({ repoDir, command, continueOnFailure }) {
|
|
1024
634
|
if (!REPO_DIR_PATTERN.test(repoDir)) throw new TypeError(`Repository directory "${repoDir}" must match ${REPO_DIR_PATTERN}.`);
|
|
@@ -1350,72 +960,655 @@ var FilesApiFilesystem = class extends MastraFilesystem {
|
|
|
1350
960
|
const abs = toAbsolute(path);
|
|
1351
961
|
return this.runFiles("exists", async (files) => Boolean((await this.#info(files, abs))?.type));
|
|
1352
962
|
}
|
|
1353
|
-
async stat(path) {
|
|
1354
|
-
const abs = toAbsolute(path);
|
|
1355
|
-
return this.runFiles("stat", async (files) => {
|
|
1356
|
-
let info = await this.#info(files, abs);
|
|
1357
|
-
if (info?.type && isSymlink(info)) info = await this.#info(files, posix.resolve(posix.dirname(abs), info.symlinkTarget));
|
|
1358
|
-
if (!info?.type) throw new FileNotFoundError(path);
|
|
1359
|
-
const modifiedAt = info.modifiedTime ?? /* @__PURE__ */ new Date(0);
|
|
1360
|
-
return {
|
|
1361
|
-
name: posix.basename(abs),
|
|
1362
|
-
path: abs,
|
|
1363
|
-
type: info.type === "dir" ? "directory" : "file",
|
|
1364
|
-
size: info.type === "dir" ? 0 : info.size,
|
|
1365
|
-
createdAt: modifiedAt,
|
|
1366
|
-
modifiedAt
|
|
1367
|
-
|
|
963
|
+
async stat(path) {
|
|
964
|
+
const abs = toAbsolute(path);
|
|
965
|
+
return this.runFiles("stat", async (files) => {
|
|
966
|
+
let info = await this.#info(files, abs);
|
|
967
|
+
if (info?.type && isSymlink(info)) info = await this.#info(files, posix.resolve(posix.dirname(abs), info.symlinkTarget));
|
|
968
|
+
if (!info?.type) throw new FileNotFoundError(path);
|
|
969
|
+
const modifiedAt = info.modifiedTime ?? /* @__PURE__ */ new Date(0);
|
|
970
|
+
return {
|
|
971
|
+
name: posix.basename(abs),
|
|
972
|
+
path: abs,
|
|
973
|
+
type: info.type === "dir" ? "directory" : "file",
|
|
974
|
+
size: info.type === "dir" ? 0 : info.size,
|
|
975
|
+
createdAt: modifiedAt,
|
|
976
|
+
modifiedAt,
|
|
977
|
+
...info.type !== "dir" && { mimeType: getMimeType(abs) }
|
|
978
|
+
};
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
/** `getInfo` without following the entry itself, or `undefined` when nothing is there. */
|
|
982
|
+
async #info(files, abs) {
|
|
983
|
+
try {
|
|
984
|
+
return await files.getInfo(abs);
|
|
985
|
+
} catch (error) {
|
|
986
|
+
if (this.errorKind(error) === "not-found") return void 0;
|
|
987
|
+
throw error;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
async #assertParentDirectory(files, abs, path) {
|
|
991
|
+
const parent = await this.#info(files, posix.dirname(abs));
|
|
992
|
+
if (!parent?.type) throw new DirectoryNotFoundError(posix.dirname(path));
|
|
993
|
+
if (parent.type !== "dir") throw new NotDirectoryError(posix.dirname(path));
|
|
994
|
+
}
|
|
995
|
+
async #write(files, abs, path, data) {
|
|
996
|
+
try {
|
|
997
|
+
await files.write(abs, data);
|
|
998
|
+
} catch (error) {
|
|
999
|
+
if (this.errorKind(error) === "invalid-argument") throw new IsDirectoryError(path);
|
|
1000
|
+
throw error;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Upload the temp file `tmp`, then run the command that consumes it. The
|
|
1005
|
+
* script deletes it on every path it controls; if the upload or the command
|
|
1006
|
+
* fails part-way, delete it here so it doesn't linger in the user's tree.
|
|
1007
|
+
*/
|
|
1008
|
+
async #publishTemp(tmp, operation, upload, script, subject, errors) {
|
|
1009
|
+
try {
|
|
1010
|
+
await this.runFiles(operation, upload);
|
|
1011
|
+
await this.#command(operation, script, subject, errors);
|
|
1012
|
+
} catch (error) {
|
|
1013
|
+
await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
|
|
1014
|
+
throw error;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
/** Run a file command and turn its known exit codes into typed errors. */
|
|
1018
|
+
async #command(operation, script, subject, errors) {
|
|
1019
|
+
const result = await this.runCommand(operation, script);
|
|
1020
|
+
if (result.exitCode === 0) return;
|
|
1021
|
+
for (const [outcome, code] of Object.entries(FILE_COMMAND_EXIT)) {
|
|
1022
|
+
const toError = errors[outcome];
|
|
1023
|
+
if (code === result.exitCode && toError) throw toError();
|
|
1024
|
+
}
|
|
1025
|
+
throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
1026
|
+
}
|
|
1027
|
+
};
|
|
1028
|
+
/**
|
|
1029
|
+
* Output callbacks for `run`/`connect` that hold output until the handle
|
|
1030
|
+
* exists. The SDK's handle reads events from construction, before `run()`
|
|
1031
|
+
* returns, so output that arrives with the start event reaches the
|
|
1032
|
+
* callbacks first.
|
|
1033
|
+
*/
|
|
1034
|
+
function outputUntilHandled() {
|
|
1035
|
+
let handle;
|
|
1036
|
+
const early = [];
|
|
1037
|
+
return {
|
|
1038
|
+
onStdout: (data) => {
|
|
1039
|
+
if (handle) handle.emitStdout(data);
|
|
1040
|
+
else early.push({
|
|
1041
|
+
stream: "stdout",
|
|
1042
|
+
data
|
|
1043
|
+
});
|
|
1044
|
+
},
|
|
1045
|
+
onStderr: (data) => {
|
|
1046
|
+
if (handle) handle.emitStderr(data);
|
|
1047
|
+
else early.push({
|
|
1048
|
+
stream: "stderr",
|
|
1049
|
+
data
|
|
1050
|
+
});
|
|
1051
|
+
},
|
|
1052
|
+
handledBy(created) {
|
|
1053
|
+
for (const { stream, data } of early) if (stream === "stdout") created.emitStdout(data);
|
|
1054
|
+
else created.emitStderr(data);
|
|
1055
|
+
early.length = 0;
|
|
1056
|
+
handle = created;
|
|
1057
|
+
return created;
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
/** envd runs every command as `/bin/bash -l -c <command>`; show the command itself. */
|
|
1062
|
+
function commandOf(proc) {
|
|
1063
|
+
const [flag, c, command] = proc.args;
|
|
1064
|
+
if (proc.cmd === "/bin/bash" && flag === "-l" && c === "-c" && command !== void 0 && proc.args.length === 3) return command;
|
|
1065
|
+
return [proc.cmd, ...proc.args].join(" ");
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* A process started or attached through a {@link CommandsApi}. `kill` and
|
|
1069
|
+
* `sendStdin` go back through the manager, so they use whatever commands
|
|
1070
|
+
* handle the provider currently supplies.
|
|
1071
|
+
*/
|
|
1072
|
+
var CommandsApiProcessHandle = class extends ProcessHandle {
|
|
1073
|
+
inner;
|
|
1074
|
+
manager;
|
|
1075
|
+
startTime;
|
|
1076
|
+
stdinMode;
|
|
1077
|
+
pid;
|
|
1078
|
+
/** The exit code `wait()` saw, for a handle that doesn't update its own. */
|
|
1079
|
+
waitedExitCode;
|
|
1080
|
+
constructor(inner, manager, startTime, stdinMode, options) {
|
|
1081
|
+
super(options);
|
|
1082
|
+
this.inner = inner;
|
|
1083
|
+
this.manager = manager;
|
|
1084
|
+
this.startTime = startTime;
|
|
1085
|
+
this.stdinMode = stdinMode;
|
|
1086
|
+
this.pid = String(inner.pid);
|
|
1087
|
+
}
|
|
1088
|
+
/** Read from the commands handle, so it reflects server-side state without `wait()`. */
|
|
1089
|
+
get exitCode() {
|
|
1090
|
+
return this.inner.exitCode ?? this.waitedExitCode;
|
|
1091
|
+
}
|
|
1092
|
+
/** Wait for the process to exit. Providers whose output stream can drop while the process runs override this. */
|
|
1093
|
+
waitForExit() {
|
|
1094
|
+
return this.inner.wait();
|
|
1095
|
+
}
|
|
1096
|
+
async wait() {
|
|
1097
|
+
try {
|
|
1098
|
+
const result = await this.waitForExit();
|
|
1099
|
+
this.waitedExitCode = result.exitCode;
|
|
1100
|
+
return {
|
|
1101
|
+
success: result.exitCode === 0,
|
|
1102
|
+
exitCode: result.exitCode,
|
|
1103
|
+
stdout: this.stdout,
|
|
1104
|
+
stderr: this.stderr,
|
|
1105
|
+
executionTimeMs: Date.now() - this.startTime
|
|
1106
|
+
};
|
|
1107
|
+
} catch (error) {
|
|
1108
|
+
const errorObj = error;
|
|
1109
|
+
const reportedExitCode = errorObj.result?.exitCode ?? errorObj.exitCode;
|
|
1110
|
+
if (reportedExitCode !== void 0) this.waitedExitCode = reportedExitCode;
|
|
1111
|
+
const exitCode = reportedExitCode ?? this.exitCode ?? 1;
|
|
1112
|
+
const attachedStdout = errorObj.result?.stdout || errorObj.stdout;
|
|
1113
|
+
const attachedStderr = errorObj.result?.stderr || errorObj.stderr;
|
|
1114
|
+
if (!this.stdout && !this.stdoutTruncated && attachedStdout) this.emitStdout(attachedStdout);
|
|
1115
|
+
if (!this.stderr && !this.stderrTruncated && attachedStderr) this.emitStderr(attachedStderr);
|
|
1116
|
+
const stdout = this.stdout;
|
|
1117
|
+
const stderr = this.stderr;
|
|
1118
|
+
const terminalError = errorObj.result?.error || errorObj.error || (error instanceof Error ? error.message : String(error));
|
|
1119
|
+
return {
|
|
1120
|
+
success: false,
|
|
1121
|
+
exitCode,
|
|
1122
|
+
stdout,
|
|
1123
|
+
stderr: [stderr, terminalError && !stderr.includes(terminalError) ? `Error: ${terminalError}` : ""].filter(Boolean).join("\n"),
|
|
1124
|
+
executionTimeMs: Date.now() - this.startTime
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
async kill() {
|
|
1129
|
+
if (this.exitCode !== void 0) return false;
|
|
1130
|
+
return this.manager.runCommands("kill", (commands) => commands.kill(this.inner.pid));
|
|
1131
|
+
}
|
|
1132
|
+
async sendStdin(data) {
|
|
1133
|
+
if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
|
|
1134
|
+
if (this.stdinMode === "ignore") throw new Error(`Process ${this.pid} was not started with stdin support`);
|
|
1135
|
+
await this.manager.runCommands("sendStdin", (commands) => commands.sendStdin(this.inner.pid, data));
|
|
1136
|
+
}
|
|
1137
|
+
async closeStdin() {
|
|
1138
|
+
throw new UnsupportedStdinCloseError("The commands API does not expose a way to close stdin for a running command");
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
/**
|
|
1142
|
+
* A process manager over E2B's envd commands API. Providers supply the
|
|
1143
|
+
* commands handle through {@link runCommands}; everything else is shared.
|
|
1144
|
+
*/
|
|
1145
|
+
var CommandsApiProcessManager = class extends SandboxProcessManager {
|
|
1146
|
+
defaultTimeout;
|
|
1147
|
+
constructor({ defaultTimeout, ...options } = {}) {
|
|
1148
|
+
super(options);
|
|
1149
|
+
this.defaultTimeout = defaultTimeout;
|
|
1150
|
+
}
|
|
1151
|
+
/** Wrap a started or attached command. Providers override this to supply their own handle. */
|
|
1152
|
+
createHandle(inner, stdinMode, options) {
|
|
1153
|
+
return new CommandsApiProcessHandle(inner, this, Date.now(), stdinMode, options);
|
|
1154
|
+
}
|
|
1155
|
+
/** Where a command runs when the caller gives no `cwd`. */
|
|
1156
|
+
defaultCwd() {
|
|
1157
|
+
return this.sandbox.workingDirectory;
|
|
1158
|
+
}
|
|
1159
|
+
async spawn(command, options = {}) {
|
|
1160
|
+
const envs = Object.fromEntries(Object.entries({ ...options.env }).filter((entry) => entry[1] !== void 0));
|
|
1161
|
+
return this.runCommands("spawn", async (commands) => {
|
|
1162
|
+
const output = outputUntilHandled();
|
|
1163
|
+
const inner = await commands.run(command, {
|
|
1164
|
+
background: true,
|
|
1165
|
+
stdin: options.stdinMode !== "ignore",
|
|
1166
|
+
cwd: options.cwd ?? this.defaultCwd(),
|
|
1167
|
+
envs,
|
|
1168
|
+
timeoutMs: options.timeout ?? this.defaultTimeout,
|
|
1169
|
+
onStdout: output.onStdout,
|
|
1170
|
+
onStderr: output.onStderr
|
|
1171
|
+
});
|
|
1172
|
+
const handle = output.handledBy(this.createHandle(inner, options.stdinMode, options));
|
|
1173
|
+
this._tracked.set(handle.pid, handle);
|
|
1174
|
+
return handle;
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Running processes as the VM reports them, plus exited processes this
|
|
1179
|
+
* manager still holds, so a finished command stays visible until it is released.
|
|
1180
|
+
*/
|
|
1181
|
+
async list() {
|
|
1182
|
+
const infos = (await this.runCommands("list", (commands) => commands.list())).map((proc) => ({
|
|
1183
|
+
pid: String(proc.pid),
|
|
1184
|
+
command: commandOf(proc),
|
|
1185
|
+
running: true
|
|
1186
|
+
}));
|
|
1187
|
+
const listed = new Set(infos.map((info) => info.pid));
|
|
1188
|
+
for (const [pid, handle] of this._tracked) {
|
|
1189
|
+
if (handle.exitCode === void 0 || listed.has(pid)) continue;
|
|
1190
|
+
infos.push({
|
|
1191
|
+
pid,
|
|
1192
|
+
command: handle.command,
|
|
1193
|
+
running: false,
|
|
1194
|
+
exitCode: handle.exitCode
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
return infos;
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* A tracked process, or one this manager didn't start, attached through
|
|
1201
|
+
* `connect`. Output from before attaching is not available.
|
|
1202
|
+
*/
|
|
1203
|
+
async get(pid, _options) {
|
|
1204
|
+
const tracked = this._tracked.get(pid);
|
|
1205
|
+
if (tracked) return tracked;
|
|
1206
|
+
const numericPid = /^\d+$/.test(pid) ? Number(pid) : void 0;
|
|
1207
|
+
if (numericPid === void 0) return void 0;
|
|
1208
|
+
const output = outputUntilHandled();
|
|
1209
|
+
try {
|
|
1210
|
+
const inner = await this.runCommands("connect", (commands) => commands.connect(numericPid, {
|
|
1211
|
+
onStdout: output.onStdout,
|
|
1212
|
+
onStderr: output.onStderr,
|
|
1213
|
+
timeoutMs: 0
|
|
1214
|
+
}));
|
|
1215
|
+
const handle = output.handledBy(this.createHandle(inner, void 0));
|
|
1216
|
+
this._tracked.set(handle.pid, handle);
|
|
1217
|
+
return handle;
|
|
1218
|
+
} catch {
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
// src/direct-exec.ts
|
|
1224
|
+
/**
|
|
1225
|
+
* Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
|
|
1226
|
+
* a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
|
|
1227
|
+
* removes the platform data plane from the exec stdout/stderr path entirely
|
|
1228
|
+
* (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
|
|
1229
|
+
* cutting payload-scaled Cloud Run egress and RTT for commands like
|
|
1230
|
+
* `pnpm install` that stream tens of MB of output.
|
|
1231
|
+
*
|
|
1232
|
+
* The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
|
|
1233
|
+
* (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
|
|
1234
|
+
* SDK's version is pinned on both sides (platform + here); a version bump
|
|
1235
|
+
* signals the protocol may have drifted and this module must be revisited.
|
|
1236
|
+
*/
|
|
1237
|
+
/** Byte-0 tag on binary WS frames for stdout output. */
|
|
1238
|
+
const STDOUT_FRAME = 1;
|
|
1239
|
+
/** Byte-0 tag on binary WS frames for stderr output. */
|
|
1240
|
+
const STDERR_FRAME = 3;
|
|
1241
|
+
/**
|
|
1242
|
+
* Upper bound on how long we'll wait for the WebSocket to open when the
|
|
1243
|
+
* caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
|
|
1244
|
+
* handshake leaving the promise unresolved forever. Not applied once the
|
|
1245
|
+
* socket has opened — a caller with no timeout has opted in to unbounded
|
|
1246
|
+
* command runtime, just not to unbounded connection setup.
|
|
1247
|
+
*/
|
|
1248
|
+
const HANDSHAKE_DEADLINE_MS = 3e4;
|
|
1249
|
+
const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
|
|
1250
|
+
const WS = globalThis.WebSocket;
|
|
1251
|
+
if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
|
|
1252
|
+
return new WS(endpoint, subprotocols);
|
|
1253
|
+
};
|
|
1254
|
+
/**
|
|
1255
|
+
* Open the provider exec WebSocket using `lease`, run `command`, and resolve
|
|
1256
|
+
* with the accumulated stdout/stderr + exit code. See the module docstring
|
|
1257
|
+
* for the wire protocol reference.
|
|
1258
|
+
*
|
|
1259
|
+
* The client sends `stdin_close` immediately after `init_exec`, matching the
|
|
1260
|
+
* SDK's own one-shot exec behavior — we never stream stdin from the caller.
|
|
1261
|
+
*/
|
|
1262
|
+
function execViaLease(lease, options) {
|
|
1263
|
+
const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
|
|
1264
|
+
const stdoutDecoder = new TextDecoder();
|
|
1265
|
+
const stderrDecoder = new TextDecoder();
|
|
1266
|
+
return new Promise((resolve) => {
|
|
1267
|
+
let stdout = "";
|
|
1268
|
+
let stderr = "";
|
|
1269
|
+
let exitCode = null;
|
|
1270
|
+
let timedOut = false;
|
|
1271
|
+
let settled = false;
|
|
1272
|
+
let opened = false;
|
|
1273
|
+
let closeCode;
|
|
1274
|
+
let closeReason;
|
|
1275
|
+
let timer;
|
|
1276
|
+
let handshakeTimer;
|
|
1277
|
+
const settle = () => {
|
|
1278
|
+
if (settled) return;
|
|
1279
|
+
settled = true;
|
|
1280
|
+
if (timer) clearTimeout(timer);
|
|
1281
|
+
if (handshakeTimer) clearTimeout(handshakeTimer);
|
|
1282
|
+
const stdoutTail = stdoutDecoder.decode();
|
|
1283
|
+
if (stdoutTail) {
|
|
1284
|
+
stdout += stdoutTail;
|
|
1285
|
+
options.onStdout?.(stdoutTail);
|
|
1286
|
+
}
|
|
1287
|
+
const stderrTail = stderrDecoder.decode();
|
|
1288
|
+
if (stderrTail) {
|
|
1289
|
+
stderr += stderrTail;
|
|
1290
|
+
options.onStderr?.(stderrTail);
|
|
1291
|
+
}
|
|
1292
|
+
try {
|
|
1293
|
+
socket.close(1e3, "");
|
|
1294
|
+
} catch {}
|
|
1295
|
+
resolve({
|
|
1296
|
+
exitCode,
|
|
1297
|
+
stdout,
|
|
1298
|
+
stderr,
|
|
1299
|
+
truncated: false,
|
|
1300
|
+
timedOut,
|
|
1301
|
+
...closeCode !== void 0 && { closeCode },
|
|
1302
|
+
...closeReason !== void 0 && { closeReason },
|
|
1303
|
+
opened
|
|
1304
|
+
});
|
|
1305
|
+
};
|
|
1306
|
+
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
|
|
1307
|
+
timedOut = true;
|
|
1308
|
+
if (exitCode === null) exitCode = 124;
|
|
1309
|
+
settle();
|
|
1310
|
+
}, options.timeoutMs);
|
|
1311
|
+
else handshakeTimer = setTimeout(() => {
|
|
1312
|
+
if (!opened) settle();
|
|
1313
|
+
}, HANDSHAKE_DEADLINE_MS);
|
|
1314
|
+
const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
|
|
1315
|
+
socket.binaryType = "arraybuffer";
|
|
1316
|
+
socket.onopen = () => {
|
|
1317
|
+
opened = true;
|
|
1318
|
+
if (handshakeTimer) {
|
|
1319
|
+
clearTimeout(handshakeTimer);
|
|
1320
|
+
handshakeTimer = void 0;
|
|
1321
|
+
}
|
|
1322
|
+
const data = { command: options.command };
|
|
1323
|
+
if (options.cwd) data.cwd = options.cwd;
|
|
1324
|
+
if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
|
|
1325
|
+
socket.send(JSON.stringify({
|
|
1326
|
+
type: "init_exec",
|
|
1327
|
+
data
|
|
1328
|
+
}));
|
|
1329
|
+
socket.send(JSON.stringify({ type: "stdin_close" }));
|
|
1330
|
+
};
|
|
1331
|
+
socket.onmessage = (event) => {
|
|
1332
|
+
const { data } = event;
|
|
1333
|
+
if (data instanceof ArrayBuffer) handleBinaryFrame(data);
|
|
1334
|
+
else if (typeof data === "string") handleTextFrame(data);
|
|
1335
|
+
};
|
|
1336
|
+
socket.onclose = (event) => {
|
|
1337
|
+
closeCode = event.code;
|
|
1338
|
+
closeReason = event.reason;
|
|
1339
|
+
if (!opened) {
|
|
1340
|
+
settle();
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
settle();
|
|
1344
|
+
};
|
|
1345
|
+
socket.onerror = () => {
|
|
1346
|
+
if (settled) return;
|
|
1347
|
+
if (!opened) settle();
|
|
1348
|
+
};
|
|
1349
|
+
function handleBinaryFrame(buffer) {
|
|
1350
|
+
const view = new Uint8Array(buffer);
|
|
1351
|
+
if (view.length <= 1) return;
|
|
1352
|
+
if (view[0] === STDOUT_FRAME) {
|
|
1353
|
+
const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
|
|
1354
|
+
stdout += chunk;
|
|
1355
|
+
options.onStdout?.(chunk);
|
|
1356
|
+
} else if (view[0] === STDERR_FRAME) {
|
|
1357
|
+
const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
|
|
1358
|
+
stderr += chunk;
|
|
1359
|
+
options.onStderr?.(chunk);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
function handleTextFrame(text) {
|
|
1363
|
+
let frame;
|
|
1364
|
+
try {
|
|
1365
|
+
frame = JSON.parse(text);
|
|
1366
|
+
} catch {
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
if (frame.type === "exit") {
|
|
1370
|
+
exitCode = frame.data?.exit_code ?? 0;
|
|
1371
|
+
settle();
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
// src/e2b-exec.ts
|
|
1377
|
+
const E2B_ENVD_VERSION = "0.4.0";
|
|
1378
|
+
const execViaE2BLease = async (lease, options) => {
|
|
1379
|
+
const stdoutChunks = [];
|
|
1380
|
+
const stderrChunks = [];
|
|
1381
|
+
const onStdout = (data) => {
|
|
1382
|
+
stdoutChunks.push(data);
|
|
1383
|
+
options.onStdout?.(data);
|
|
1384
|
+
};
|
|
1385
|
+
const onStderr = (data) => {
|
|
1386
|
+
stderrChunks.push(data);
|
|
1387
|
+
options.onStderr?.(data);
|
|
1388
|
+
};
|
|
1389
|
+
try {
|
|
1390
|
+
const result = await new Sandbox({
|
|
1391
|
+
sandboxId: lease.sandboxId,
|
|
1392
|
+
envdVersion: E2B_ENVD_VERSION,
|
|
1393
|
+
envdAccessToken: lease.jwt,
|
|
1394
|
+
sandboxUrl: lease.wsEndpoint,
|
|
1395
|
+
validateApiKey: false
|
|
1396
|
+
}).commands.run(options.command, {
|
|
1397
|
+
cwd: options.cwd,
|
|
1398
|
+
envs: options.env,
|
|
1399
|
+
timeoutMs: options.timeoutMs,
|
|
1400
|
+
onStdout,
|
|
1401
|
+
onStderr
|
|
1402
|
+
});
|
|
1403
|
+
return {
|
|
1404
|
+
exitCode: result.exitCode,
|
|
1405
|
+
stdout: result.stdout,
|
|
1406
|
+
stderr: result.stderr,
|
|
1407
|
+
truncated: false,
|
|
1408
|
+
timedOut: false,
|
|
1409
|
+
opened: true
|
|
1410
|
+
};
|
|
1411
|
+
} catch (error) {
|
|
1412
|
+
if (error instanceof CommandExitError) return {
|
|
1413
|
+
exitCode: error.exitCode,
|
|
1414
|
+
stdout: error.stdout,
|
|
1415
|
+
stderr: error.stderr,
|
|
1416
|
+
truncated: false,
|
|
1417
|
+
timedOut: false,
|
|
1418
|
+
opened: true
|
|
1419
|
+
};
|
|
1420
|
+
return {
|
|
1421
|
+
exitCode: null,
|
|
1422
|
+
stdout: stdoutChunks.join(""),
|
|
1423
|
+
stderr: stderrChunks.join(""),
|
|
1424
|
+
truncated: false,
|
|
1425
|
+
timedOut: error instanceof TimeoutError,
|
|
1426
|
+
closeReason: error instanceof Error ? error.message : String(error),
|
|
1427
|
+
opened: true
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
};
|
|
1431
|
+
/** The VM's envd API, authenticated by the exec lease. */
|
|
1432
|
+
const sandboxForLease = (lease) => new Sandbox({
|
|
1433
|
+
sandboxId: lease.sandboxId,
|
|
1434
|
+
envdVersion: E2B_ENVD_VERSION,
|
|
1435
|
+
envdAccessToken: lease.jwt,
|
|
1436
|
+
sandboxUrl: lease.wsEndpoint,
|
|
1437
|
+
validateApiKey: false
|
|
1438
|
+
});
|
|
1439
|
+
/** Opens E2B's files API directly against the VM, authenticated by the exec lease. */
|
|
1440
|
+
const e2bFilesForLease = (lease) => sandboxForLease(lease).files;
|
|
1441
|
+
/** Opens E2B's commands API directly against the VM, authenticated by the exec lease. */
|
|
1442
|
+
const commandsForLease = (lease) => sandboxForLease(lease).commands;
|
|
1443
|
+
// src/private-net-exec.ts
|
|
1444
|
+
/**
|
|
1445
|
+
* Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
|
|
1446
|
+
* HTTP response. This is an *application* error, not a transport error — the
|
|
1447
|
+
* sidecar is reachable and answered, it just refused the exec. Callers should
|
|
1448
|
+
* fall back to the lease path for this one call but MUST NOT invalidate the
|
|
1449
|
+
* cached `instanceUrl` (the address is still good).
|
|
1450
|
+
*/
|
|
1451
|
+
var PrivateNetExecHttpError = class extends Error {
|
|
1452
|
+
status;
|
|
1453
|
+
body;
|
|
1454
|
+
constructor(status, body) {
|
|
1455
|
+
super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
|
|
1456
|
+
this.name = "PrivateNetExecHttpError";
|
|
1457
|
+
this.status = status;
|
|
1458
|
+
this.body = body;
|
|
1459
|
+
}
|
|
1460
|
+
};
|
|
1461
|
+
const DEFAULT_FETCH = (input, init) => {
|
|
1462
|
+
const f = globalThis.fetch;
|
|
1463
|
+
if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
|
|
1464
|
+
return f(input, init);
|
|
1465
|
+
};
|
|
1466
|
+
/**
|
|
1467
|
+
* Dial `${instanceUrl}/exec` and stream the response, resolving with the
|
|
1468
|
+
* accumulated stdout/stderr + exit code.
|
|
1469
|
+
*
|
|
1470
|
+
* Errors:
|
|
1471
|
+
* - Connection failure (DNS, refused, reset) → resolves with
|
|
1472
|
+
* `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
|
|
1473
|
+
* transport failures — the shape matches the lease-path result so the
|
|
1474
|
+
* caller can treat both transports uniformly.
|
|
1475
|
+
* - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
|
|
1476
|
+
* Application-level; caller decides whether to fall back.
|
|
1477
|
+
* - Stream ends without an `exit` frame → resolves with
|
|
1478
|
+
* `{opened:true, exitCode:null}`, matching the lease-path semantics for a
|
|
1479
|
+
* mid-stream drop.
|
|
1480
|
+
* - `timeoutMs` elapsed → aborts the request, resolves with
|
|
1481
|
+
* `{timedOut:true, exitCode:124}`.
|
|
1482
|
+
*/
|
|
1483
|
+
async function execViaPrivateNetwork(instanceUrl, options) {
|
|
1484
|
+
const fetchImpl = options.fetch ?? DEFAULT_FETCH;
|
|
1485
|
+
const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
|
|
1486
|
+
const controller = new AbortController();
|
|
1487
|
+
let timedOut = false;
|
|
1488
|
+
let timeoutTimer;
|
|
1489
|
+
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
|
|
1490
|
+
timedOut = true;
|
|
1491
|
+
controller.abort();
|
|
1492
|
+
}, options.timeoutMs);
|
|
1493
|
+
const body = { command: options.command };
|
|
1494
|
+
if (options.cwd) body.cwd = options.cwd;
|
|
1495
|
+
if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
|
|
1496
|
+
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
|
|
1497
|
+
const headers = { "content-type": "application/json" };
|
|
1498
|
+
if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
|
|
1499
|
+
let response;
|
|
1500
|
+
try {
|
|
1501
|
+
response = await fetchImpl(url, {
|
|
1502
|
+
method: "POST",
|
|
1503
|
+
headers,
|
|
1504
|
+
body: JSON.stringify(body),
|
|
1505
|
+
signal: controller.signal
|
|
1368
1506
|
});
|
|
1507
|
+
} catch (error) {
|
|
1508
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1509
|
+
if (timedOut) return {
|
|
1510
|
+
exitCode: 124,
|
|
1511
|
+
stdout: "",
|
|
1512
|
+
stderr: "",
|
|
1513
|
+
timedOut: true,
|
|
1514
|
+
opened: false
|
|
1515
|
+
};
|
|
1516
|
+
return {
|
|
1517
|
+
exitCode: null,
|
|
1518
|
+
stdout: "",
|
|
1519
|
+
stderr: "",
|
|
1520
|
+
timedOut: false,
|
|
1521
|
+
opened: false,
|
|
1522
|
+
transportErrorMessage: error instanceof Error ? error.message : String(error)
|
|
1523
|
+
};
|
|
1369
1524
|
}
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
} catch (error) {
|
|
1375
|
-
if (this.errorKind(error) === "not-found") return void 0;
|
|
1376
|
-
throw error;
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
async #assertParentDirectory(files, abs, path) {
|
|
1380
|
-
const parent = await this.#info(files, posix.dirname(abs));
|
|
1381
|
-
if (!parent?.type) throw new DirectoryNotFoundError(posix.dirname(path));
|
|
1382
|
-
if (parent.type !== "dir") throw new NotDirectoryError(posix.dirname(path));
|
|
1525
|
+
if (!response.ok) {
|
|
1526
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1527
|
+
const text = await response.text().catch(() => "");
|
|
1528
|
+
throw new PrivateNetExecHttpError(response.status, text);
|
|
1383
1529
|
}
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1530
|
+
if (!response.body) {
|
|
1531
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1532
|
+
return {
|
|
1533
|
+
exitCode: null,
|
|
1534
|
+
stdout: "",
|
|
1535
|
+
stderr: "",
|
|
1536
|
+
timedOut: false,
|
|
1537
|
+
opened: true,
|
|
1538
|
+
status: response.status
|
|
1539
|
+
};
|
|
1391
1540
|
}
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1541
|
+
let stdout = "";
|
|
1542
|
+
let stderr = "";
|
|
1543
|
+
let exitCode = null;
|
|
1544
|
+
const decoder = new TextDecoder();
|
|
1545
|
+
let buffer = "";
|
|
1546
|
+
const handleLine = (line) => {
|
|
1547
|
+
if (!line) return;
|
|
1548
|
+
let frame;
|
|
1398
1549
|
try {
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
|
|
1403
|
-
throw error;
|
|
1550
|
+
frame = JSON.parse(line);
|
|
1551
|
+
} catch {
|
|
1552
|
+
return;
|
|
1404
1553
|
}
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
if (
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1554
|
+
if (!frame || typeof frame !== "object") return;
|
|
1555
|
+
if (frame.type === "stdout" && typeof frame.data === "string") {
|
|
1556
|
+
stdout += frame.data;
|
|
1557
|
+
options.onStdout?.(frame.data);
|
|
1558
|
+
} else if (frame.type === "stderr" && typeof frame.data === "string") {
|
|
1559
|
+
stderr += frame.data;
|
|
1560
|
+
options.onStderr?.(frame.data);
|
|
1561
|
+
} else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
|
|
1562
|
+
};
|
|
1563
|
+
try {
|
|
1564
|
+
const reader = response.body.getReader();
|
|
1565
|
+
while (true) {
|
|
1566
|
+
const { value, done } = await reader.read();
|
|
1567
|
+
if (done) break;
|
|
1568
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1569
|
+
let newlineIdx = buffer.indexOf("\n");
|
|
1570
|
+
while (newlineIdx !== -1) {
|
|
1571
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
1572
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
1573
|
+
handleLine(line);
|
|
1574
|
+
newlineIdx = buffer.indexOf("\n");
|
|
1575
|
+
}
|
|
1413
1576
|
}
|
|
1414
|
-
|
|
1577
|
+
buffer += decoder.decode();
|
|
1578
|
+
const trailing = buffer.trim();
|
|
1579
|
+
if (trailing) handleLine(trailing);
|
|
1580
|
+
} catch (error) {
|
|
1581
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1582
|
+
if (timedOut) return {
|
|
1583
|
+
exitCode: 124,
|
|
1584
|
+
stdout,
|
|
1585
|
+
stderr,
|
|
1586
|
+
timedOut: true,
|
|
1587
|
+
opened: true,
|
|
1588
|
+
status: response.status
|
|
1589
|
+
};
|
|
1590
|
+
return {
|
|
1591
|
+
exitCode,
|
|
1592
|
+
stdout,
|
|
1593
|
+
stderr,
|
|
1594
|
+
timedOut: false,
|
|
1595
|
+
opened: true,
|
|
1596
|
+
status: response.status,
|
|
1597
|
+
transportErrorMessage: error instanceof Error ? error.message : String(error)
|
|
1598
|
+
};
|
|
1599
|
+
} finally {
|
|
1600
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1415
1601
|
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1602
|
+
return {
|
|
1603
|
+
exitCode,
|
|
1604
|
+
stdout,
|
|
1605
|
+
stderr,
|
|
1606
|
+
timedOut: false,
|
|
1607
|
+
opened: true,
|
|
1608
|
+
status: response.status
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
// src/sandbox-filesystem.ts
|
|
1419
1612
|
/**
|
|
1420
1613
|
* envd's edge answers a paused or missing sandbox with a 404 or 502 that the
|
|
1421
1614
|
* SDK reports as `FileNotFoundError` or `TimeoutError`. Same message pattern as
|
|
@@ -1455,8 +1648,7 @@ var PlatformSandboxFilesystem = class extends FilesApiFilesystem {
|
|
|
1455
1648
|
if (error instanceof InvalidArgumentError) return "invalid-argument";
|
|
1456
1649
|
}
|
|
1457
1650
|
};
|
|
1458
|
-
|
|
1459
|
-
//#region src/sandbox.ts
|
|
1651
|
+
// src/sandbox.ts
|
|
1460
1652
|
/**
|
|
1461
1653
|
* How long before a lease's stated `expiresAt` we should treat it as
|
|
1462
1654
|
* expired. Avoids a race where the JWT is valid at cache-hit time but the
|
|
@@ -1614,6 +1806,70 @@ var PlatformProcessManager = class extends SandboxProcessManager {
|
|
|
1614
1806
|
}));
|
|
1615
1807
|
}
|
|
1616
1808
|
};
|
|
1809
|
+
/** Reaches the sandbox's commands handle without making it part of the class's public API. */
|
|
1810
|
+
const withCommands = Symbol("withCommands");
|
|
1811
|
+
/**
|
|
1812
|
+
* Background processes on an E2B-backed sandbox through envd's commands API,
|
|
1813
|
+
* reached with the same lease `executeCommand` uses. Output streams while the
|
|
1814
|
+
* process runs, `kill` stops it, and `list` reports what is running in the VM.
|
|
1815
|
+
*/
|
|
1816
|
+
var PlatformCommandsProcessManager = class extends CommandsApiProcessManager {
|
|
1817
|
+
runCommands(operation, fn) {
|
|
1818
|
+
return this.sandbox[withCommands](operation, fn);
|
|
1819
|
+
}
|
|
1820
|
+
createHandle(inner, stdinMode, options) {
|
|
1821
|
+
return new PlatformProcessHandleOverLease(inner, this, Date.now(), stdinMode, options);
|
|
1822
|
+
}
|
|
1823
|
+
};
|
|
1824
|
+
/** envd ends the output stream when the lease it was opened with expires; the process keeps running. */
|
|
1825
|
+
function isLeaseStreamDrop(error) {
|
|
1826
|
+
return error instanceof TimeoutError && error.message.startsWith("[unavailable]");
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1829
|
+
* The process left the VM while no stream was attached, so envd can't say how
|
|
1830
|
+
* it ended. Carries an exit code so the handle reads as exited: it shows in
|
|
1831
|
+
* `list()` and is released like any other finished process.
|
|
1832
|
+
*/
|
|
1833
|
+
var ProcessEndedUnseenError = class extends Error {
|
|
1834
|
+
exitCode = 1;
|
|
1835
|
+
constructor(cause) {
|
|
1836
|
+
super(`${cause instanceof Error ? cause.message : String(cause)} (the process ended before it could be reattached)`);
|
|
1837
|
+
}
|
|
1838
|
+
};
|
|
1839
|
+
/**
|
|
1840
|
+
* A process outlives the lease it was started with. When that lease expires
|
|
1841
|
+
* envd ends the output stream, so reattach on the current lease and keep
|
|
1842
|
+
* waiting. Output written between the drop and the reattach is not seen.
|
|
1843
|
+
*/
|
|
1844
|
+
var PlatformProcessHandleOverLease = class extends CommandsApiProcessHandle {
|
|
1845
|
+
/** One reattach loop shared by every `wait()` caller. */
|
|
1846
|
+
exited;
|
|
1847
|
+
waitForExit() {
|
|
1848
|
+
return this.exited ??= this.waitAcrossLeases();
|
|
1849
|
+
}
|
|
1850
|
+
async waitAcrossLeases() {
|
|
1851
|
+
for (;;) try {
|
|
1852
|
+
return await this.inner.wait();
|
|
1853
|
+
} catch (error) {
|
|
1854
|
+
if (!isLeaseStreamDrop(error)) throw error;
|
|
1855
|
+
const pid = this.inner.pid;
|
|
1856
|
+
const reattached = await this.manager.runCommands("connect", async (commands) => {
|
|
1857
|
+
if (!(await commands.list()).some((proc) => proc.pid === pid)) return "ended";
|
|
1858
|
+
return commands.connect(pid, {
|
|
1859
|
+
onStdout: (data) => this.emitStdout(data),
|
|
1860
|
+
onStderr: (data) => this.emitStderr(data),
|
|
1861
|
+
timeoutMs: 0
|
|
1862
|
+
});
|
|
1863
|
+
}).catch(() => void 0);
|
|
1864
|
+
if (reattached === "ended") throw new ProcessEndedUnseenError(error);
|
|
1865
|
+
if (!reattached) {
|
|
1866
|
+
this.exited = void 0;
|
|
1867
|
+
throw error;
|
|
1868
|
+
}
|
|
1869
|
+
this.inner = reattached;
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
};
|
|
1617
1873
|
var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
1618
1874
|
id;
|
|
1619
1875
|
name = "PlatformSandbox";
|
|
@@ -1661,6 +1917,8 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
1661
1917
|
_e2bFilesFactory;
|
|
1662
1918
|
/** Files handle for the current lease, rebuilt whenever the lease changes. */
|
|
1663
1919
|
_e2bFiles = null;
|
|
1920
|
+
_e2bCommandsFactory;
|
|
1921
|
+
_e2bCommands = null;
|
|
1664
1922
|
_filesystem;
|
|
1665
1923
|
_privateNetFetch;
|
|
1666
1924
|
/**
|
|
@@ -1729,10 +1987,11 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
1729
1987
|
*/
|
|
1730
1988
|
_probeTarget = null;
|
|
1731
1989
|
constructor(options = {}) {
|
|
1990
|
+
const e2bBacked = resolveSandboxProvider(options.sandboxProvider ?? process.env.SANDBOX_PROVIDER?.trim()) === "e2b";
|
|
1732
1991
|
super({
|
|
1733
1992
|
...options,
|
|
1734
1993
|
name: "PlatformSandbox",
|
|
1735
|
-
processes: new PlatformProcessManager()
|
|
1994
|
+
processes: e2bBacked ? new PlatformCommandsProcessManager({ defaultTimeout: options.timeout ?? 0 }) : new PlatformProcessManager()
|
|
1736
1995
|
});
|
|
1737
1996
|
this._hasRecoveryKey = options.id !== void 0;
|
|
1738
1997
|
this.id = options.id ?? this.generateId();
|
|
@@ -1752,6 +2011,7 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
1752
2011
|
this._webSocketFactory = options.webSocketFactory;
|
|
1753
2012
|
this._e2bExecRunner = options.e2bExecRunner ?? execViaE2BLease;
|
|
1754
2013
|
this._e2bFilesFactory = options.e2bFilesFactory ?? e2bFilesForLease;
|
|
2014
|
+
this._e2bCommandsFactory = options.e2bCommandsFactory ?? commandsForLease;
|
|
1755
2015
|
this._privateNetFetch = options.privateNetFetch;
|
|
1756
2016
|
this._addressRegistry = options.addressRegistry;
|
|
1757
2017
|
}
|
|
@@ -2545,8 +2805,55 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
2545
2805
|
};
|
|
2546
2806
|
return this._e2bFiles;
|
|
2547
2807
|
}
|
|
2808
|
+
/**
|
|
2809
|
+
* Run `fn` against envd's commands API with the current lease, the way
|
|
2810
|
+
* {@link _withE2BFiles} runs files calls: one retry, only after an
|
|
2811
|
+
* `AuthenticationError` proves the call never ran, so a spawn or kill is
|
|
2812
|
+
* never replayed. Each call fetches the lease again, so a process started
|
|
2813
|
+
* under one lease is stopped with whichever lease is current.
|
|
2814
|
+
*/
|
|
2815
|
+
async [withCommands](operation, fn) {
|
|
2816
|
+
await this.ensureRunning();
|
|
2817
|
+
if (!this._sandboxId) throw new SandboxNotReadyError(this.id);
|
|
2818
|
+
let current = await this._commandsHandle(operation, 1);
|
|
2819
|
+
const call = async (invoke) => {
|
|
2820
|
+
try {
|
|
2821
|
+
return await invoke(current.commands);
|
|
2822
|
+
} catch (error) {
|
|
2823
|
+
if (error instanceof AuthenticationError) {
|
|
2824
|
+
if (this._lease === current.lease) this._lease = null;
|
|
2825
|
+
current = await this._commandsHandle(operation, 2);
|
|
2826
|
+
try {
|
|
2827
|
+
return await invoke(current.commands);
|
|
2828
|
+
} catch (retryError) {
|
|
2829
|
+
if (isBrokenSandboxError(retryError) && this._lease === current.lease) this._lease = null;
|
|
2830
|
+
throw retryError;
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
if (isBrokenSandboxError(error) && this._lease === current.lease) this._lease = null;
|
|
2834
|
+
throw error;
|
|
2835
|
+
}
|
|
2836
|
+
};
|
|
2837
|
+
return fn({
|
|
2838
|
+
run: (command, opts) => call((commands) => commands.run(command, opts)),
|
|
2839
|
+
connect: (pid, opts) => call((commands) => commands.connect(pid, opts)),
|
|
2840
|
+
list: () => call((commands) => commands.list()),
|
|
2841
|
+
kill: (pid) => call((commands) => commands.kill(pid)),
|
|
2842
|
+
sendStdin: (pid, data) => call((commands) => commands.sendStdin(pid, data))
|
|
2843
|
+
});
|
|
2844
|
+
}
|
|
2845
|
+
/** The commands handle for the current lease, rebuilt only when the lease changes. */
|
|
2846
|
+
async _commandsHandle(operation, attempts) {
|
|
2847
|
+
const lease = await this._fileLease(`processes.${operation}`, attempts, "");
|
|
2848
|
+
if (lease.provider !== "e2b") throw new Error(`PlatformSandbox.processes requires an E2B-backed sandbox; this sandbox's provider is "${lease.provider}"`);
|
|
2849
|
+
if (this._e2bCommands?.lease !== lease) this._e2bCommands = {
|
|
2850
|
+
lease,
|
|
2851
|
+
commands: this._e2bCommandsFactory(lease)
|
|
2852
|
+
};
|
|
2853
|
+
return this._e2bCommands;
|
|
2854
|
+
}
|
|
2548
2855
|
/** `_ensureLease`, with a 410 handled the same way `_runDirectExec` handles it. */
|
|
2549
|
-
async _fileLease(operation, attempts) {
|
|
2856
|
+
async _fileLease(operation, attempts, prefix = "filesystem.") {
|
|
2550
2857
|
try {
|
|
2551
2858
|
return await this._ensureLease();
|
|
2552
2859
|
} catch (error) {
|
|
@@ -2557,7 +2864,7 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
2557
2864
|
this.status = "stopped";
|
|
2558
2865
|
throw new SandboxDestroyedError(`Sandbox ${priorSandboxId ?? "(unknown)"} was destroyed; /exec-lease returned 410`, {
|
|
2559
2866
|
...priorSandboxId && { sandboxId: priorSandboxId },
|
|
2560
|
-
command:
|
|
2867
|
+
command: `${prefix}${operation}`,
|
|
2561
2868
|
attempts
|
|
2562
2869
|
});
|
|
2563
2870
|
}
|
|
@@ -2615,8 +2922,7 @@ function templateHash(definition) {
|
|
|
2615
2922
|
const { family: _family, ...content } = definition;
|
|
2616
2923
|
return createHash("sha256").update(JSON.stringify(content)).digest("hex").slice(0, 16);
|
|
2617
2924
|
}
|
|
2618
|
-
|
|
2619
|
-
//#region src/repo-template.ts
|
|
2925
|
+
// src/repo-template.ts
|
|
2620
2926
|
const execFileAsync = promisify(execFile);
|
|
2621
2927
|
const SHA_PATTERN = /^[0-9a-f]{7,40}$/i;
|
|
2622
2928
|
const BUILD_TOKEN_ENV = "MASTRA_REPOSITORY_ACCESS_TOKEN";
|
|
@@ -2905,8 +3211,7 @@ async function resolveDefaultBranchHead(cloneUrl, token, execute = execFileAsync
|
|
|
2905
3211
|
throw new Error(`git ls-remote failed: ${detail}`);
|
|
2906
3212
|
}
|
|
2907
3213
|
}
|
|
2908
|
-
|
|
2909
|
-
//#region src/provider.ts
|
|
3214
|
+
// src/provider.ts
|
|
2910
3215
|
const platformSandboxProvider = {
|
|
2911
3216
|
id: "platform",
|
|
2912
3217
|
name: "Mastra Platform Sandbox",
|
|
@@ -2991,8 +3296,7 @@ const platformFilesystemProvider = {
|
|
|
2991
3296
|
},
|
|
2992
3297
|
createFilesystem: (config) => new PlatformFilesystem(config)
|
|
2993
3298
|
};
|
|
2994
|
-
|
|
2995
|
-
//#region src/factory-sandbox.ts
|
|
3299
|
+
// src/factory-sandbox.ts
|
|
2996
3300
|
/** Applied when neither the environment setting nor a host default is set. */
|
|
2997
3301
|
const DEFAULT_SETTINGS = {
|
|
2998
3302
|
cpuCount: 2,
|
|
@@ -3162,8 +3466,7 @@ function toBuild(result) {
|
|
|
3162
3466
|
...result.error ? { error: result.error } : {}
|
|
3163
3467
|
};
|
|
3164
3468
|
}
|
|
3165
|
-
|
|
3166
|
-
//#region src/address-registry.ts
|
|
3469
|
+
// src/address-registry.ts
|
|
3167
3470
|
/**
|
|
3168
3471
|
* Concrete in-process {@link SandboxAddressRegistry}. Backed by a `Map`; no
|
|
3169
3472
|
* eviction policy, no TTL — entries live until an observed transport failure
|
|
@@ -3195,7 +3498,6 @@ var InProcessSandboxAddressRegistry = class {
|
|
|
3195
3498
|
return this.#map.size;
|
|
3196
3499
|
}
|
|
3197
3500
|
};
|
|
3198
|
-
//#endregion
|
|
3199
3501
|
export { InProcessSandboxAddressRegistry, PlatformApiError, PlatformClient, PlatformFactorySandbox, PlatformFilesystem, PlatformSandbox, PlatformSandboxFilesystem, PrivateNetExecHttpError, SandboxDestroyedError, SandboxExecTransportError, Template, createRepoTemplate, execViaPrivateNetwork, platformFilesystemProvider, platformSandboxProvider };
|
|
3200
3502
|
|
|
3201
3503
|
//# sourceMappingURL=index.js.map
|