@mastra/platform-workspace 1.9.0 → 1.10.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_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 +1004 -690
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +885 -571
- 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 +5 -5
package/dist/index.js
CHANGED
|
@@ -576,393 +576,6 @@ function cloneJson(value) {
|
|
|
576
576
|
return value;
|
|
577
577
|
}
|
|
578
578
|
//#endregion
|
|
579
|
-
//#region src/direct-exec.ts
|
|
580
|
-
/**
|
|
581
|
-
* Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
|
|
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.
|
|
587
|
-
*
|
|
588
|
-
* The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
|
|
589
|
-
* (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
|
|
590
|
-
* SDK's version is pinned on both sides (platform + here); a version bump
|
|
591
|
-
* signals the protocol may have drifted and this module must be revisited.
|
|
592
|
-
*/
|
|
593
|
-
/** Byte-0 tag on binary WS frames for stdout output. */
|
|
594
|
-
const STDOUT_FRAME = 1;
|
|
595
|
-
/** Byte-0 tag on binary WS frames for stderr output. */
|
|
596
|
-
const STDERR_FRAME = 3;
|
|
597
|
-
/**
|
|
598
|
-
* Upper bound on how long we'll wait for the WebSocket to open when the
|
|
599
|
-
* caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
|
|
600
|
-
* handshake leaving the promise unresolved forever. Not applied once the
|
|
601
|
-
* socket has opened — a caller with no timeout has opted in to unbounded
|
|
602
|
-
* command runtime, just not to unbounded connection setup.
|
|
603
|
-
*/
|
|
604
|
-
const HANDSHAKE_DEADLINE_MS = 3e4;
|
|
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
|
-
};
|
|
610
|
-
/**
|
|
611
|
-
* Open the provider exec WebSocket using `lease`, run `command`, and resolve
|
|
612
|
-
* with the accumulated stdout/stderr + exit code. See the module docstring
|
|
613
|
-
* for the wire protocol reference.
|
|
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.
|
|
617
|
-
*/
|
|
618
|
-
function execViaLease(lease, options) {
|
|
619
|
-
const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
|
|
620
|
-
const stdoutDecoder = new TextDecoder();
|
|
621
|
-
const stderrDecoder = new TextDecoder();
|
|
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
|
-
});
|
|
731
|
-
}
|
|
732
|
-
//#endregion
|
|
733
|
-
//#region src/e2b-exec.ts
|
|
734
|
-
const E2B_ENVD_VERSION = "0.4.0";
|
|
735
|
-
const execViaE2BLease = async (lease, options) => {
|
|
736
|
-
const stdoutChunks = [];
|
|
737
|
-
const stderrChunks = [];
|
|
738
|
-
const onStdout = (data) => {
|
|
739
|
-
stdoutChunks.push(data);
|
|
740
|
-
options.onStdout?.(data);
|
|
741
|
-
};
|
|
742
|
-
const onStderr = (data) => {
|
|
743
|
-
stderrChunks.push(data);
|
|
744
|
-
options.onStderr?.(data);
|
|
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
|
|
798
|
-
/**
|
|
799
|
-
* Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
|
|
800
|
-
* HTTP response. This is an *application* error, not a transport error — the
|
|
801
|
-
* sidecar is reachable and answered, it just refused the exec. Callers should
|
|
802
|
-
* fall back to the lease path for this one call but MUST NOT invalidate the
|
|
803
|
-
* cached `instanceUrl` (the address is still good).
|
|
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
579
|
//#region ../../packages/_internals/workspace/dist/index.js
|
|
967
580
|
/** Directory, relative to the template's build cwd, that holds every marker below. */
|
|
968
581
|
const SETUP_MARKER_DIR = ".mastra-sandbox";
|
|
@@ -1202,218 +815,804 @@ function matchesExtension(name, extension) {
|
|
|
1202
815
|
var FilesApiFilesystem = class extends MastraFilesystem {
|
|
1203
816
|
async readFile(path, options) {
|
|
1204
817
|
const abs = toAbsolute(path);
|
|
1205
|
-
const bytes = await this.runFiles("readFile", async (files) => {
|
|
818
|
+
const bytes = await this.runFiles("readFile", async (files) => {
|
|
819
|
+
try {
|
|
820
|
+
return await files.read(abs, { format: "bytes" });
|
|
821
|
+
} catch (error) {
|
|
822
|
+
const kind = this.errorKind(error);
|
|
823
|
+
if (kind === "not-found") throw new FileNotFoundError(path);
|
|
824
|
+
if (kind === "invalid-argument") throw new IsDirectoryError(path);
|
|
825
|
+
throw error;
|
|
826
|
+
}
|
|
827
|
+
});
|
|
828
|
+
const buffer = Buffer$1.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
829
|
+
return options?.encoding ? buffer.toString(options.encoding) : buffer;
|
|
830
|
+
}
|
|
831
|
+
async writeFile(path, content, options) {
|
|
832
|
+
const abs = toAbsolute(path);
|
|
833
|
+
if (options?.overwrite !== false) {
|
|
834
|
+
await this.runFiles("writeFile", async (files) => {
|
|
835
|
+
if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path);
|
|
836
|
+
await this.#write(files, abs, path, toWriteData(content));
|
|
837
|
+
});
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
const tmp = siblingTempPath(abs);
|
|
841
|
+
const upload = async (files) => {
|
|
842
|
+
if (options.recursive === false) await this.#assertParentDirectory(files, abs, path);
|
|
843
|
+
await this.#write(files, tmp, path, toWriteData(content));
|
|
844
|
+
};
|
|
845
|
+
await this.#publishTemp(tmp, "writeFile", upload, linkNoClobberCommand(tmp, abs), path, {
|
|
846
|
+
exists: () => new FileExistsError(path),
|
|
847
|
+
notDirectory: () => new NotDirectoryError(posix.dirname(path))
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
async appendFile(path, content) {
|
|
851
|
+
const abs = toAbsolute(path);
|
|
852
|
+
const tmp = siblingTempPath(abs);
|
|
853
|
+
const upload = (files) => this.#write(files, tmp, path, toWriteData(content));
|
|
854
|
+
await this.#publishTemp(tmp, "appendFile", upload, appendFromCommand(tmp, abs), path, { isDirectory: () => new IsDirectoryError(path) });
|
|
855
|
+
}
|
|
856
|
+
async deleteFile(path, options) {
|
|
857
|
+
const abs = toAbsolute(path);
|
|
858
|
+
await this.runFiles("deleteFile", async (files) => {
|
|
859
|
+
const info = await this.#info(files, abs);
|
|
860
|
+
if (!info) {
|
|
861
|
+
if (options?.force) return;
|
|
862
|
+
throw new FileNotFoundError(path);
|
|
863
|
+
}
|
|
864
|
+
if (!isSymlink(info) && info.type === "dir") throw new IsDirectoryError(path);
|
|
865
|
+
await files.remove(abs);
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* One `cp` inside the VM. A recursive copy keeps symlinks inside the tree as
|
|
870
|
+
* links; `overwrite: false` claims the destination atomically.
|
|
871
|
+
*/
|
|
872
|
+
async copyFile(src, dest, options) {
|
|
873
|
+
const command = copyCommand(toAbsolute(src), toAbsolute(dest), {
|
|
874
|
+
recursive: options?.recursive,
|
|
875
|
+
overwrite: options?.overwrite
|
|
876
|
+
});
|
|
877
|
+
await this.#command("copyFile", command, `${src} -> ${dest}`, {
|
|
878
|
+
notFound: () => new FileNotFoundError(src),
|
|
879
|
+
isDirectory: () => new IsDirectoryError(src),
|
|
880
|
+
destIsDirectory: () => new IsDirectoryError(dest),
|
|
881
|
+
exists: () => new FileExistsError(dest)
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
async moveFile(src, dest, options) {
|
|
885
|
+
const srcAbs = toAbsolute(src);
|
|
886
|
+
const destAbs = toAbsolute(dest);
|
|
887
|
+
if (options?.overwrite === false) {
|
|
888
|
+
await this.#command("moveFile", moveNoClobberCommand(srcAbs, destAbs), `${src} -> ${dest}`, {
|
|
889
|
+
notFound: () => new FileNotFoundError(src),
|
|
890
|
+
exists: () => new FileExistsError(dest)
|
|
891
|
+
});
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
await this.runFiles("moveFile", async (files) => {
|
|
895
|
+
try {
|
|
896
|
+
await files.rename(srcAbs, destAbs);
|
|
897
|
+
} catch (error) {
|
|
898
|
+
if (this.errorKind(error) === "not-found") throw new FileNotFoundError(src);
|
|
899
|
+
throw error;
|
|
900
|
+
}
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
async mkdir(path, options) {
|
|
904
|
+
const abs = toAbsolute(path);
|
|
905
|
+
await this.runFiles("mkdir", async (files) => {
|
|
906
|
+
if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path);
|
|
1206
907
|
try {
|
|
1207
|
-
|
|
908
|
+
await files.makeDir(abs);
|
|
1208
909
|
} catch (error) {
|
|
1209
|
-
|
|
1210
|
-
if (kind === "not-found") throw new FileNotFoundError(path);
|
|
1211
|
-
if (kind === "invalid-argument") throw new IsDirectoryError(path);
|
|
910
|
+
if (this.errorKind(error) === "invalid-argument") throw new FileExistsError(path);
|
|
1212
911
|
throw error;
|
|
1213
912
|
}
|
|
1214
913
|
});
|
|
1215
|
-
const buffer = Buffer$1.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1216
|
-
return options?.encoding ? buffer.toString(options.encoding) : buffer;
|
|
1217
914
|
}
|
|
1218
|
-
async
|
|
915
|
+
async rmdir(path, options) {
|
|
1219
916
|
const abs = toAbsolute(path);
|
|
1220
|
-
|
|
1221
|
-
await this
|
|
1222
|
-
|
|
1223
|
-
|
|
917
|
+
await this.runFiles("rmdir", async (files) => {
|
|
918
|
+
const info = await this.#info(files, abs);
|
|
919
|
+
if (!info) {
|
|
920
|
+
if (options?.force) return;
|
|
921
|
+
throw new DirectoryNotFoundError(path);
|
|
922
|
+
}
|
|
923
|
+
if (!options?.recursive) {
|
|
924
|
+
if (isSymlink(info) || info.type !== "dir") throw new NotDirectoryError(path);
|
|
925
|
+
if ((await files.list(abs)).length > 0) throw new DirectoryNotEmptyError(path);
|
|
926
|
+
} else if (!isSymlink(info) && info.type !== "dir") throw new NotDirectoryError(path);
|
|
927
|
+
await files.remove(abs);
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
async readdir(path, options) {
|
|
931
|
+
const abs = toAbsolute(path);
|
|
932
|
+
const depth = options?.recursive ? (options.maxDepth ?? DEFAULT_MAX_DEPTH) + 1 : 1;
|
|
933
|
+
const entries = await this.runFiles("readdir", async (files) => {
|
|
934
|
+
try {
|
|
935
|
+
return await files.list(abs, { depth });
|
|
936
|
+
} catch (error) {
|
|
937
|
+
const kind = this.errorKind(error);
|
|
938
|
+
if (kind === "not-found") throw new DirectoryNotFoundError(path);
|
|
939
|
+
if (kind === "invalid-argument") throw new NotDirectoryError(path);
|
|
940
|
+
throw error;
|
|
941
|
+
}
|
|
942
|
+
});
|
|
943
|
+
const result = [];
|
|
944
|
+
for (const entry of entries) {
|
|
945
|
+
if (!entry.type) continue;
|
|
946
|
+
const name = posix.relative(abs, entry.path);
|
|
947
|
+
const type = entry.type === "dir" ? "directory" : "file";
|
|
948
|
+
if (type === "file" && !matchesExtension(name, options?.extension)) continue;
|
|
949
|
+
const link = isSymlink(entry);
|
|
950
|
+
result.push({
|
|
951
|
+
name,
|
|
952
|
+
type,
|
|
953
|
+
...type === "file" && !link && { size: entry.size },
|
|
954
|
+
...link && {
|
|
955
|
+
isSymlink: true,
|
|
956
|
+
symlinkTarget: entry.symlinkTarget
|
|
957
|
+
}
|
|
1224
958
|
});
|
|
1225
|
-
return;
|
|
1226
959
|
}
|
|
1227
|
-
|
|
1228
|
-
const upload = async (files) => {
|
|
1229
|
-
if (options.recursive === false) await this.#assertParentDirectory(files, abs, path);
|
|
1230
|
-
await this.#write(files, tmp, path, toWriteData(content));
|
|
1231
|
-
};
|
|
1232
|
-
await this.#publishTemp(tmp, "writeFile", upload, linkNoClobberCommand(tmp, abs), path, {
|
|
1233
|
-
exists: () => new FileExistsError(path),
|
|
1234
|
-
notDirectory: () => new NotDirectoryError(posix.dirname(path))
|
|
1235
|
-
});
|
|
960
|
+
return result;
|
|
1236
961
|
}
|
|
1237
|
-
async
|
|
962
|
+
async exists(path) {
|
|
1238
963
|
const abs = toAbsolute(path);
|
|
1239
|
-
|
|
1240
|
-
const upload = (files) => this.#write(files, tmp, path, toWriteData(content));
|
|
1241
|
-
await this.#publishTemp(tmp, "appendFile", upload, appendFromCommand(tmp, abs), path, { isDirectory: () => new IsDirectoryError(path) });
|
|
964
|
+
return this.runFiles("exists", async (files) => Boolean((await this.#info(files, abs))?.type));
|
|
1242
965
|
}
|
|
1243
|
-
async
|
|
966
|
+
async stat(path) {
|
|
1244
967
|
const abs = toAbsolute(path);
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
if (
|
|
1248
|
-
|
|
1249
|
-
|
|
968
|
+
return this.runFiles("stat", async (files) => {
|
|
969
|
+
let info = await this.#info(files, abs);
|
|
970
|
+
if (info?.type && isSymlink(info)) info = await this.#info(files, posix.resolve(posix.dirname(abs), info.symlinkTarget));
|
|
971
|
+
if (!info?.type) throw new FileNotFoundError(path);
|
|
972
|
+
const modifiedAt = info.modifiedTime ?? /* @__PURE__ */ new Date(0);
|
|
973
|
+
return {
|
|
974
|
+
name: posix.basename(abs),
|
|
975
|
+
path: abs,
|
|
976
|
+
type: info.type === "dir" ? "directory" : "file",
|
|
977
|
+
size: info.type === "dir" ? 0 : info.size,
|
|
978
|
+
createdAt: modifiedAt,
|
|
979
|
+
modifiedAt
|
|
980
|
+
};
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
/** `getInfo` without following the entry itself, or `undefined` when nothing is there. */
|
|
984
|
+
async #info(files, abs) {
|
|
985
|
+
try {
|
|
986
|
+
return await files.getInfo(abs);
|
|
987
|
+
} catch (error) {
|
|
988
|
+
if (this.errorKind(error) === "not-found") return void 0;
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
async #assertParentDirectory(files, abs, path) {
|
|
993
|
+
const parent = await this.#info(files, posix.dirname(abs));
|
|
994
|
+
if (!parent?.type) throw new DirectoryNotFoundError(posix.dirname(path));
|
|
995
|
+
if (parent.type !== "dir") throw new NotDirectoryError(posix.dirname(path));
|
|
996
|
+
}
|
|
997
|
+
async #write(files, abs, path, data) {
|
|
998
|
+
try {
|
|
999
|
+
await files.write(abs, data);
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
if (this.errorKind(error) === "invalid-argument") throw new IsDirectoryError(path);
|
|
1002
|
+
throw error;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Upload the temp file `tmp`, then run the command that consumes it. The
|
|
1007
|
+
* script deletes it on every path it controls; if the upload or the command
|
|
1008
|
+
* fails part-way, delete it here so it doesn't linger in the user's tree.
|
|
1009
|
+
*/
|
|
1010
|
+
async #publishTemp(tmp, operation, upload, script, subject, errors) {
|
|
1011
|
+
try {
|
|
1012
|
+
await this.runFiles(operation, upload);
|
|
1013
|
+
await this.#command(operation, script, subject, errors);
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
|
|
1016
|
+
throw error;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
/** Run a file command and turn its known exit codes into typed errors. */
|
|
1020
|
+
async #command(operation, script, subject, errors) {
|
|
1021
|
+
const result = await this.runCommand(operation, script);
|
|
1022
|
+
if (result.exitCode === 0) return;
|
|
1023
|
+
for (const [outcome, code] of Object.entries(FILE_COMMAND_EXIT)) {
|
|
1024
|
+
const toError = errors[outcome];
|
|
1025
|
+
if (code === result.exitCode && toError) throw toError();
|
|
1026
|
+
}
|
|
1027
|
+
throw new Error(`${operation} ${subject} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
/**
|
|
1031
|
+
* Output callbacks for `run`/`connect` that hold output until the handle
|
|
1032
|
+
* exists. The SDK's handle reads events from construction, before `run()`
|
|
1033
|
+
* returns, so output that arrives with the start event reaches the
|
|
1034
|
+
* callbacks first.
|
|
1035
|
+
*/
|
|
1036
|
+
function outputUntilHandled() {
|
|
1037
|
+
let handle;
|
|
1038
|
+
const early = [];
|
|
1039
|
+
return {
|
|
1040
|
+
onStdout: (data) => {
|
|
1041
|
+
if (handle) handle.emitStdout(data);
|
|
1042
|
+
else early.push({
|
|
1043
|
+
stream: "stdout",
|
|
1044
|
+
data
|
|
1045
|
+
});
|
|
1046
|
+
},
|
|
1047
|
+
onStderr: (data) => {
|
|
1048
|
+
if (handle) handle.emitStderr(data);
|
|
1049
|
+
else early.push({
|
|
1050
|
+
stream: "stderr",
|
|
1051
|
+
data
|
|
1052
|
+
});
|
|
1053
|
+
},
|
|
1054
|
+
handledBy(created) {
|
|
1055
|
+
for (const { stream, data } of early) if (stream === "stdout") created.emitStdout(data);
|
|
1056
|
+
else created.emitStderr(data);
|
|
1057
|
+
early.length = 0;
|
|
1058
|
+
handle = created;
|
|
1059
|
+
return created;
|
|
1060
|
+
}
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
/** envd runs every command as `/bin/bash -l -c <command>`; show the command itself. */
|
|
1064
|
+
function commandOf(proc) {
|
|
1065
|
+
const [flag, c, command] = proc.args;
|
|
1066
|
+
if (proc.cmd === "/bin/bash" && flag === "-l" && c === "-c" && command !== void 0 && proc.args.length === 3) return command;
|
|
1067
|
+
return [proc.cmd, ...proc.args].join(" ");
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* A process started or attached through a {@link CommandsApi}. `kill` and
|
|
1071
|
+
* `sendStdin` go back through the manager, so they use whatever commands
|
|
1072
|
+
* handle the provider currently supplies.
|
|
1073
|
+
*/
|
|
1074
|
+
var CommandsApiProcessHandle = class extends ProcessHandle {
|
|
1075
|
+
inner;
|
|
1076
|
+
manager;
|
|
1077
|
+
startTime;
|
|
1078
|
+
stdinMode;
|
|
1079
|
+
pid;
|
|
1080
|
+
/** The exit code `wait()` saw, for a handle that doesn't update its own. */
|
|
1081
|
+
waitedExitCode;
|
|
1082
|
+
constructor(inner, manager, startTime, stdinMode, options) {
|
|
1083
|
+
super(options);
|
|
1084
|
+
this.inner = inner;
|
|
1085
|
+
this.manager = manager;
|
|
1086
|
+
this.startTime = startTime;
|
|
1087
|
+
this.stdinMode = stdinMode;
|
|
1088
|
+
this.pid = String(inner.pid);
|
|
1089
|
+
}
|
|
1090
|
+
/** Read from the commands handle, so it reflects server-side state without `wait()`. */
|
|
1091
|
+
get exitCode() {
|
|
1092
|
+
return this.inner.exitCode ?? this.waitedExitCode;
|
|
1093
|
+
}
|
|
1094
|
+
/** Wait for the process to exit. Providers whose output stream can drop while the process runs override this. */
|
|
1095
|
+
waitForExit() {
|
|
1096
|
+
return this.inner.wait();
|
|
1097
|
+
}
|
|
1098
|
+
async wait() {
|
|
1099
|
+
try {
|
|
1100
|
+
const result = await this.waitForExit();
|
|
1101
|
+
this.waitedExitCode = result.exitCode;
|
|
1102
|
+
return {
|
|
1103
|
+
success: result.exitCode === 0,
|
|
1104
|
+
exitCode: result.exitCode,
|
|
1105
|
+
stdout: this.stdout,
|
|
1106
|
+
stderr: this.stderr,
|
|
1107
|
+
executionTimeMs: Date.now() - this.startTime
|
|
1108
|
+
};
|
|
1109
|
+
} catch (error) {
|
|
1110
|
+
const errorObj = error;
|
|
1111
|
+
const reportedExitCode = errorObj.result?.exitCode ?? errorObj.exitCode;
|
|
1112
|
+
if (reportedExitCode !== void 0) this.waitedExitCode = reportedExitCode;
|
|
1113
|
+
const exitCode = reportedExitCode ?? this.exitCode ?? 1;
|
|
1114
|
+
const attachedStdout = errorObj.result?.stdout || errorObj.stdout;
|
|
1115
|
+
const attachedStderr = errorObj.result?.stderr || errorObj.stderr;
|
|
1116
|
+
if (!this.stdout && !this.stdoutTruncated && attachedStdout) this.emitStdout(attachedStdout);
|
|
1117
|
+
if (!this.stderr && !this.stderrTruncated && attachedStderr) this.emitStderr(attachedStderr);
|
|
1118
|
+
const stdout = this.stdout;
|
|
1119
|
+
const stderr = this.stderr;
|
|
1120
|
+
const terminalError = errorObj.result?.error || errorObj.error || (error instanceof Error ? error.message : String(error));
|
|
1121
|
+
return {
|
|
1122
|
+
success: false,
|
|
1123
|
+
exitCode,
|
|
1124
|
+
stdout,
|
|
1125
|
+
stderr: [stderr, terminalError && !stderr.includes(terminalError) ? `Error: ${terminalError}` : ""].filter(Boolean).join("\n"),
|
|
1126
|
+
executionTimeMs: Date.now() - this.startTime
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
async kill() {
|
|
1131
|
+
if (this.exitCode !== void 0) return false;
|
|
1132
|
+
return this.manager.runCommands("kill", (commands) => commands.kill(this.inner.pid));
|
|
1133
|
+
}
|
|
1134
|
+
async sendStdin(data) {
|
|
1135
|
+
if (this.exitCode !== void 0) throw new Error(`Process ${this.pid} has already exited with code ${this.exitCode}`);
|
|
1136
|
+
if (this.stdinMode === "ignore") throw new Error(`Process ${this.pid} was not started with stdin support`);
|
|
1137
|
+
await this.manager.runCommands("sendStdin", (commands) => commands.sendStdin(this.inner.pid, data));
|
|
1138
|
+
}
|
|
1139
|
+
async closeStdin() {
|
|
1140
|
+
throw new UnsupportedStdinCloseError("The commands API does not expose a way to close stdin for a running command");
|
|
1141
|
+
}
|
|
1142
|
+
};
|
|
1143
|
+
/**
|
|
1144
|
+
* A process manager over E2B's envd commands API. Providers supply the
|
|
1145
|
+
* commands handle through {@link runCommands}; everything else is shared.
|
|
1146
|
+
*/
|
|
1147
|
+
var CommandsApiProcessManager = class extends SandboxProcessManager {
|
|
1148
|
+
defaultTimeout;
|
|
1149
|
+
constructor({ defaultTimeout, ...options } = {}) {
|
|
1150
|
+
super(options);
|
|
1151
|
+
this.defaultTimeout = defaultTimeout;
|
|
1152
|
+
}
|
|
1153
|
+
/** Wrap a started or attached command. Providers override this to supply their own handle. */
|
|
1154
|
+
createHandle(inner, stdinMode, options) {
|
|
1155
|
+
return new CommandsApiProcessHandle(inner, this, Date.now(), stdinMode, options);
|
|
1156
|
+
}
|
|
1157
|
+
/** Where a command runs when the caller gives no `cwd`. */
|
|
1158
|
+
defaultCwd() {
|
|
1159
|
+
return this.sandbox.workingDirectory;
|
|
1160
|
+
}
|
|
1161
|
+
async spawn(command, options = {}) {
|
|
1162
|
+
const envs = Object.fromEntries(Object.entries({ ...options.env }).filter((entry) => entry[1] !== void 0));
|
|
1163
|
+
return this.runCommands("spawn", async (commands) => {
|
|
1164
|
+
const output = outputUntilHandled();
|
|
1165
|
+
const inner = await commands.run(command, {
|
|
1166
|
+
background: true,
|
|
1167
|
+
stdin: options.stdinMode !== "ignore",
|
|
1168
|
+
cwd: options.cwd ?? this.defaultCwd(),
|
|
1169
|
+
envs,
|
|
1170
|
+
timeoutMs: options.timeout ?? this.defaultTimeout,
|
|
1171
|
+
onStdout: output.onStdout,
|
|
1172
|
+
onStderr: output.onStderr
|
|
1173
|
+
});
|
|
1174
|
+
const handle = output.handledBy(this.createHandle(inner, options.stdinMode, options));
|
|
1175
|
+
this._tracked.set(handle.pid, handle);
|
|
1176
|
+
return handle;
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Running processes as the VM reports them, plus exited processes this
|
|
1181
|
+
* manager still holds, so a finished command stays visible until it is released.
|
|
1182
|
+
*/
|
|
1183
|
+
async list() {
|
|
1184
|
+
const infos = (await this.runCommands("list", (commands) => commands.list())).map((proc) => ({
|
|
1185
|
+
pid: String(proc.pid),
|
|
1186
|
+
command: commandOf(proc),
|
|
1187
|
+
running: true
|
|
1188
|
+
}));
|
|
1189
|
+
const listed = new Set(infos.map((info) => info.pid));
|
|
1190
|
+
for (const [pid, handle] of this._tracked) {
|
|
1191
|
+
if (handle.exitCode === void 0 || listed.has(pid)) continue;
|
|
1192
|
+
infos.push({
|
|
1193
|
+
pid,
|
|
1194
|
+
command: handle.command,
|
|
1195
|
+
running: false,
|
|
1196
|
+
exitCode: handle.exitCode
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
return infos;
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* A tracked process, or one this manager didn't start, attached through
|
|
1203
|
+
* `connect`. Output from before attaching is not available.
|
|
1204
|
+
*/
|
|
1205
|
+
async get(pid, _options) {
|
|
1206
|
+
const tracked = this._tracked.get(pid);
|
|
1207
|
+
if (tracked) return tracked;
|
|
1208
|
+
const numericPid = /^\d+$/.test(pid) ? Number(pid) : void 0;
|
|
1209
|
+
if (numericPid === void 0) return void 0;
|
|
1210
|
+
const output = outputUntilHandled();
|
|
1211
|
+
try {
|
|
1212
|
+
const inner = await this.runCommands("connect", (commands) => commands.connect(numericPid, {
|
|
1213
|
+
onStdout: output.onStdout,
|
|
1214
|
+
onStderr: output.onStderr,
|
|
1215
|
+
timeoutMs: 0
|
|
1216
|
+
}));
|
|
1217
|
+
const handle = output.handledBy(this.createHandle(inner, void 0));
|
|
1218
|
+
this._tracked.set(handle.pid, handle);
|
|
1219
|
+
return handle;
|
|
1220
|
+
} catch {
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
//#endregion
|
|
1226
|
+
//#region src/direct-exec.ts
|
|
1227
|
+
/**
|
|
1228
|
+
* Direct exec client — opens Railway's tcp-proxy exec WebSocket directly using
|
|
1229
|
+
* a short-lived JWT minted by the workspace proxy's exec-lease endpoint. This
|
|
1230
|
+
* removes the platform data plane from the exec stdout/stderr path entirely
|
|
1231
|
+
* (see `docs/factory/direct-sandbox-connection.md` in the Platform repo),
|
|
1232
|
+
* cutting payload-scaled Cloud Run egress and RTT for commands like
|
|
1233
|
+
* `pnpm install` that stream tens of MB of output.
|
|
1234
|
+
*
|
|
1235
|
+
* The frame protocol below mirrors `connectExecWs()` in `railway@3.5.5`
|
|
1236
|
+
* (`workspaces/railway/node_modules/railway/dist/index.js`). The `railway`
|
|
1237
|
+
* SDK's version is pinned on both sides (platform + here); a version bump
|
|
1238
|
+
* signals the protocol may have drifted and this module must be revisited.
|
|
1239
|
+
*/
|
|
1240
|
+
/** Byte-0 tag on binary WS frames for stdout output. */
|
|
1241
|
+
const STDOUT_FRAME = 1;
|
|
1242
|
+
/** Byte-0 tag on binary WS frames for stderr output. */
|
|
1243
|
+
const STDERR_FRAME = 3;
|
|
1244
|
+
/**
|
|
1245
|
+
* Upper bound on how long we'll wait for the WebSocket to open when the
|
|
1246
|
+
* caller didn't supply a `timeoutMs`. Guards against a stalled TLS/WS
|
|
1247
|
+
* handshake leaving the promise unresolved forever. Not applied once the
|
|
1248
|
+
* socket has opened — a caller with no timeout has opted in to unbounded
|
|
1249
|
+
* command runtime, just not to unbounded connection setup.
|
|
1250
|
+
*/
|
|
1251
|
+
const HANDSHAKE_DEADLINE_MS = 3e4;
|
|
1252
|
+
const DEFAULT_WS_FACTORY = (endpoint, subprotocols) => {
|
|
1253
|
+
const WS = globalThis.WebSocket;
|
|
1254
|
+
if (!WS) throw new Error("Direct exec requires a WebSocket implementation. Node 22+ provides one globally; on older runtimes, pass webSocketFactory explicitly.");
|
|
1255
|
+
return new WS(endpoint, subprotocols);
|
|
1256
|
+
};
|
|
1257
|
+
/**
|
|
1258
|
+
* Open the provider exec WebSocket using `lease`, run `command`, and resolve
|
|
1259
|
+
* with the accumulated stdout/stderr + exit code. See the module docstring
|
|
1260
|
+
* for the wire protocol reference.
|
|
1261
|
+
*
|
|
1262
|
+
* The client sends `stdin_close` immediately after `init_exec`, matching the
|
|
1263
|
+
* SDK's own one-shot exec behavior — we never stream stdin from the caller.
|
|
1264
|
+
*/
|
|
1265
|
+
function execViaLease(lease, options) {
|
|
1266
|
+
const factory = options.webSocketFactory ?? DEFAULT_WS_FACTORY;
|
|
1267
|
+
const stdoutDecoder = new TextDecoder();
|
|
1268
|
+
const stderrDecoder = new TextDecoder();
|
|
1269
|
+
return new Promise((resolve) => {
|
|
1270
|
+
let stdout = "";
|
|
1271
|
+
let stderr = "";
|
|
1272
|
+
let exitCode = null;
|
|
1273
|
+
let timedOut = false;
|
|
1274
|
+
let settled = false;
|
|
1275
|
+
let opened = false;
|
|
1276
|
+
let closeCode;
|
|
1277
|
+
let closeReason;
|
|
1278
|
+
let timer;
|
|
1279
|
+
let handshakeTimer;
|
|
1280
|
+
const settle = () => {
|
|
1281
|
+
if (settled) return;
|
|
1282
|
+
settled = true;
|
|
1283
|
+
if (timer) clearTimeout(timer);
|
|
1284
|
+
if (handshakeTimer) clearTimeout(handshakeTimer);
|
|
1285
|
+
const stdoutTail = stdoutDecoder.decode();
|
|
1286
|
+
if (stdoutTail) {
|
|
1287
|
+
stdout += stdoutTail;
|
|
1288
|
+
options.onStdout?.(stdoutTail);
|
|
1250
1289
|
}
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
/**
|
|
1256
|
-
* One `cp` inside the VM. A recursive copy keeps symlinks inside the tree as
|
|
1257
|
-
* links; `overwrite: false` claims the destination atomically.
|
|
1258
|
-
*/
|
|
1259
|
-
async copyFile(src, dest, options) {
|
|
1260
|
-
const command = copyCommand(toAbsolute(src), toAbsolute(dest), {
|
|
1261
|
-
recursive: options?.recursive,
|
|
1262
|
-
overwrite: options?.overwrite
|
|
1263
|
-
});
|
|
1264
|
-
await this.#command("copyFile", command, `${src} -> ${dest}`, {
|
|
1265
|
-
notFound: () => new FileNotFoundError(src),
|
|
1266
|
-
isDirectory: () => new IsDirectoryError(src),
|
|
1267
|
-
destIsDirectory: () => new IsDirectoryError(dest),
|
|
1268
|
-
exists: () => new FileExistsError(dest)
|
|
1269
|
-
});
|
|
1270
|
-
}
|
|
1271
|
-
async moveFile(src, dest, options) {
|
|
1272
|
-
const srcAbs = toAbsolute(src);
|
|
1273
|
-
const destAbs = toAbsolute(dest);
|
|
1274
|
-
if (options?.overwrite === false) {
|
|
1275
|
-
await this.#command("moveFile", moveNoClobberCommand(srcAbs, destAbs), `${src} -> ${dest}`, {
|
|
1276
|
-
notFound: () => new FileNotFoundError(src),
|
|
1277
|
-
exists: () => new FileExistsError(dest)
|
|
1278
|
-
});
|
|
1279
|
-
return;
|
|
1280
|
-
}
|
|
1281
|
-
await this.runFiles("moveFile", async (files) => {
|
|
1282
|
-
try {
|
|
1283
|
-
await files.rename(srcAbs, destAbs);
|
|
1284
|
-
} catch (error) {
|
|
1285
|
-
if (this.errorKind(error) === "not-found") throw new FileNotFoundError(src);
|
|
1286
|
-
throw error;
|
|
1290
|
+
const stderrTail = stderrDecoder.decode();
|
|
1291
|
+
if (stderrTail) {
|
|
1292
|
+
stderr += stderrTail;
|
|
1293
|
+
options.onStderr?.(stderrTail);
|
|
1287
1294
|
}
|
|
1288
|
-
});
|
|
1289
|
-
}
|
|
1290
|
-
async mkdir(path, options) {
|
|
1291
|
-
const abs = toAbsolute(path);
|
|
1292
|
-
await this.runFiles("mkdir", async (files) => {
|
|
1293
|
-
if (options?.recursive === false) await this.#assertParentDirectory(files, abs, path);
|
|
1294
1295
|
try {
|
|
1295
|
-
|
|
1296
|
-
} catch
|
|
1297
|
-
|
|
1298
|
-
|
|
1296
|
+
socket.close(1e3, "");
|
|
1297
|
+
} catch {}
|
|
1298
|
+
resolve({
|
|
1299
|
+
exitCode,
|
|
1300
|
+
stdout,
|
|
1301
|
+
stderr,
|
|
1302
|
+
truncated: false,
|
|
1303
|
+
timedOut,
|
|
1304
|
+
...closeCode !== void 0 && { closeCode },
|
|
1305
|
+
...closeReason !== void 0 && { closeReason },
|
|
1306
|
+
opened
|
|
1307
|
+
});
|
|
1308
|
+
};
|
|
1309
|
+
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timer = setTimeout(() => {
|
|
1310
|
+
timedOut = true;
|
|
1311
|
+
if (exitCode === null) exitCode = 124;
|
|
1312
|
+
settle();
|
|
1313
|
+
}, options.timeoutMs);
|
|
1314
|
+
else handshakeTimer = setTimeout(() => {
|
|
1315
|
+
if (!opened) settle();
|
|
1316
|
+
}, HANDSHAKE_DEADLINE_MS);
|
|
1317
|
+
const socket = factory(lease.wsEndpoint, [lease.subprotocol, lease.jwt]);
|
|
1318
|
+
socket.binaryType = "arraybuffer";
|
|
1319
|
+
socket.onopen = () => {
|
|
1320
|
+
opened = true;
|
|
1321
|
+
if (handshakeTimer) {
|
|
1322
|
+
clearTimeout(handshakeTimer);
|
|
1323
|
+
handshakeTimer = void 0;
|
|
1299
1324
|
}
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1325
|
+
const data = { command: options.command };
|
|
1326
|
+
if (options.cwd) data.cwd = options.cwd;
|
|
1327
|
+
if (options.env && Object.keys(options.env).length > 0) data.env = options.env;
|
|
1328
|
+
socket.send(JSON.stringify({
|
|
1329
|
+
type: "init_exec",
|
|
1330
|
+
data
|
|
1331
|
+
}));
|
|
1332
|
+
socket.send(JSON.stringify({ type: "stdin_close" }));
|
|
1333
|
+
};
|
|
1334
|
+
socket.onmessage = (event) => {
|
|
1335
|
+
const { data } = event;
|
|
1336
|
+
if (data instanceof ArrayBuffer) handleBinaryFrame(data);
|
|
1337
|
+
else if (typeof data === "string") handleTextFrame(data);
|
|
1338
|
+
};
|
|
1339
|
+
socket.onclose = (event) => {
|
|
1340
|
+
closeCode = event.code;
|
|
1341
|
+
closeReason = event.reason;
|
|
1342
|
+
if (!opened) {
|
|
1343
|
+
settle();
|
|
1344
|
+
return;
|
|
1309
1345
|
}
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1346
|
+
settle();
|
|
1347
|
+
};
|
|
1348
|
+
socket.onerror = () => {
|
|
1349
|
+
if (settled) return;
|
|
1350
|
+
if (!opened) settle();
|
|
1351
|
+
};
|
|
1352
|
+
function handleBinaryFrame(buffer) {
|
|
1353
|
+
const view = new Uint8Array(buffer);
|
|
1354
|
+
if (view.length <= 1) return;
|
|
1355
|
+
if (view[0] === STDOUT_FRAME) {
|
|
1356
|
+
const chunk = stdoutDecoder.decode(view.subarray(1), { stream: true });
|
|
1357
|
+
stdout += chunk;
|
|
1358
|
+
options.onStdout?.(chunk);
|
|
1359
|
+
} else if (view[0] === STDERR_FRAME) {
|
|
1360
|
+
const chunk = stderrDecoder.decode(view.subarray(1), { stream: true });
|
|
1361
|
+
stderr += chunk;
|
|
1362
|
+
options.onStderr?.(chunk);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
function handleTextFrame(text) {
|
|
1366
|
+
let frame;
|
|
1321
1367
|
try {
|
|
1322
|
-
|
|
1323
|
-
} catch
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1368
|
+
frame = JSON.parse(text);
|
|
1369
|
+
} catch {
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
if (frame.type === "exit") {
|
|
1373
|
+
exitCode = frame.data?.exit_code ?? 0;
|
|
1374
|
+
settle();
|
|
1328
1375
|
}
|
|
1329
|
-
});
|
|
1330
|
-
const result = [];
|
|
1331
|
-
for (const entry of entries) {
|
|
1332
|
-
if (!entry.type) continue;
|
|
1333
|
-
const name = posix.relative(abs, entry.path);
|
|
1334
|
-
const type = entry.type === "dir" ? "directory" : "file";
|
|
1335
|
-
if (type === "file" && !matchesExtension(name, options?.extension)) continue;
|
|
1336
|
-
const link = isSymlink(entry);
|
|
1337
|
-
result.push({
|
|
1338
|
-
name,
|
|
1339
|
-
type,
|
|
1340
|
-
...type === "file" && !link && { size: entry.size },
|
|
1341
|
-
...link && {
|
|
1342
|
-
isSymlink: true,
|
|
1343
|
-
symlinkTarget: entry.symlinkTarget
|
|
1344
|
-
}
|
|
1345
|
-
});
|
|
1346
1376
|
}
|
|
1347
|
-
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
//#endregion
|
|
1380
|
+
//#region src/e2b-exec.ts
|
|
1381
|
+
const E2B_ENVD_VERSION = "0.4.0";
|
|
1382
|
+
const execViaE2BLease = async (lease, options) => {
|
|
1383
|
+
const stdoutChunks = [];
|
|
1384
|
+
const stderrChunks = [];
|
|
1385
|
+
const onStdout = (data) => {
|
|
1386
|
+
stdoutChunks.push(data);
|
|
1387
|
+
options.onStdout?.(data);
|
|
1388
|
+
};
|
|
1389
|
+
const onStderr = (data) => {
|
|
1390
|
+
stderrChunks.push(data);
|
|
1391
|
+
options.onStderr?.(data);
|
|
1392
|
+
};
|
|
1393
|
+
try {
|
|
1394
|
+
const result = await new Sandbox({
|
|
1395
|
+
sandboxId: lease.sandboxId,
|
|
1396
|
+
envdVersion: E2B_ENVD_VERSION,
|
|
1397
|
+
envdAccessToken: lease.jwt,
|
|
1398
|
+
sandboxUrl: lease.wsEndpoint,
|
|
1399
|
+
validateApiKey: false
|
|
1400
|
+
}).commands.run(options.command, {
|
|
1401
|
+
cwd: options.cwd,
|
|
1402
|
+
envs: options.env,
|
|
1403
|
+
timeoutMs: options.timeoutMs,
|
|
1404
|
+
onStdout,
|
|
1405
|
+
onStderr
|
|
1406
|
+
});
|
|
1407
|
+
return {
|
|
1408
|
+
exitCode: result.exitCode,
|
|
1409
|
+
stdout: result.stdout,
|
|
1410
|
+
stderr: result.stderr,
|
|
1411
|
+
truncated: false,
|
|
1412
|
+
timedOut: false,
|
|
1413
|
+
opened: true
|
|
1414
|
+
};
|
|
1415
|
+
} catch (error) {
|
|
1416
|
+
if (error instanceof CommandExitError) return {
|
|
1417
|
+
exitCode: error.exitCode,
|
|
1418
|
+
stdout: error.stdout,
|
|
1419
|
+
stderr: error.stderr,
|
|
1420
|
+
truncated: false,
|
|
1421
|
+
timedOut: false,
|
|
1422
|
+
opened: true
|
|
1423
|
+
};
|
|
1424
|
+
return {
|
|
1425
|
+
exitCode: null,
|
|
1426
|
+
stdout: stdoutChunks.join(""),
|
|
1427
|
+
stderr: stderrChunks.join(""),
|
|
1428
|
+
truncated: false,
|
|
1429
|
+
timedOut: error instanceof TimeoutError,
|
|
1430
|
+
closeReason: error instanceof Error ? error.message : String(error),
|
|
1431
|
+
opened: true
|
|
1432
|
+
};
|
|
1348
1433
|
}
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1434
|
+
};
|
|
1435
|
+
/** The VM's envd API, authenticated by the exec lease. */
|
|
1436
|
+
const sandboxForLease = (lease) => new Sandbox({
|
|
1437
|
+
sandboxId: lease.sandboxId,
|
|
1438
|
+
envdVersion: E2B_ENVD_VERSION,
|
|
1439
|
+
envdAccessToken: lease.jwt,
|
|
1440
|
+
sandboxUrl: lease.wsEndpoint,
|
|
1441
|
+
validateApiKey: false
|
|
1442
|
+
});
|
|
1443
|
+
/** Opens E2B's files API directly against the VM, authenticated by the exec lease. */
|
|
1444
|
+
const e2bFilesForLease = (lease) => sandboxForLease(lease).files;
|
|
1445
|
+
/** Opens E2B's commands API directly against the VM, authenticated by the exec lease. */
|
|
1446
|
+
const commandsForLease = (lease) => sandboxForLease(lease).commands;
|
|
1447
|
+
//#endregion
|
|
1448
|
+
//#region src/private-net-exec.ts
|
|
1449
|
+
/**
|
|
1450
|
+
* Thrown by {@link execViaPrivateNetwork} when the sidecar returns a non-2xx
|
|
1451
|
+
* HTTP response. This is an *application* error, not a transport error — the
|
|
1452
|
+
* sidecar is reachable and answered, it just refused the exec. Callers should
|
|
1453
|
+
* fall back to the lease path for this one call but MUST NOT invalidate the
|
|
1454
|
+
* cached `instanceUrl` (the address is still good).
|
|
1455
|
+
*/
|
|
1456
|
+
var PrivateNetExecHttpError = class extends Error {
|
|
1457
|
+
status;
|
|
1458
|
+
body;
|
|
1459
|
+
constructor(status, body) {
|
|
1460
|
+
super(`Sidecar /exec returned ${status}${body ? `: ${body.slice(0, 200)}` : ""}`);
|
|
1461
|
+
this.name = "PrivateNetExecHttpError";
|
|
1462
|
+
this.status = status;
|
|
1463
|
+
this.body = body;
|
|
1352
1464
|
}
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1465
|
+
};
|
|
1466
|
+
const DEFAULT_FETCH = (input, init) => {
|
|
1467
|
+
const f = globalThis.fetch;
|
|
1468
|
+
if (!f) throw new Error("Private-network exec requires a fetch implementation. Node 22+ provides one globally; on older runtimes, pass fetch explicitly.");
|
|
1469
|
+
return f(input, init);
|
|
1470
|
+
};
|
|
1471
|
+
/**
|
|
1472
|
+
* Dial `${instanceUrl}/exec` and stream the response, resolving with the
|
|
1473
|
+
* accumulated stdout/stderr + exit code.
|
|
1474
|
+
*
|
|
1475
|
+
* Errors:
|
|
1476
|
+
* - Connection failure (DNS, refused, reset) → resolves with
|
|
1477
|
+
* `{opened:false, exitCode:null, transportErrorMessage}`. Never throws for
|
|
1478
|
+
* transport failures — the shape matches the lease-path result so the
|
|
1479
|
+
* caller can treat both transports uniformly.
|
|
1480
|
+
* - Non-2xx HTTP response from the sidecar → throws {@link PrivateNetExecHttpError}.
|
|
1481
|
+
* Application-level; caller decides whether to fall back.
|
|
1482
|
+
* - Stream ends without an `exit` frame → resolves with
|
|
1483
|
+
* `{opened:true, exitCode:null}`, matching the lease-path semantics for a
|
|
1484
|
+
* mid-stream drop.
|
|
1485
|
+
* - `timeoutMs` elapsed → aborts the request, resolves with
|
|
1486
|
+
* `{timedOut:true, exitCode:124}`.
|
|
1487
|
+
*/
|
|
1488
|
+
async function execViaPrivateNetwork(instanceUrl, options) {
|
|
1489
|
+
const fetchImpl = options.fetch ?? DEFAULT_FETCH;
|
|
1490
|
+
const url = `${instanceUrl.replace(/\/$/, "")}/exec`;
|
|
1491
|
+
const controller = new AbortController();
|
|
1492
|
+
let timedOut = false;
|
|
1493
|
+
let timeoutTimer;
|
|
1494
|
+
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) timeoutTimer = setTimeout(() => {
|
|
1495
|
+
timedOut = true;
|
|
1496
|
+
controller.abort();
|
|
1497
|
+
}, options.timeoutMs);
|
|
1498
|
+
const body = { command: options.command };
|
|
1499
|
+
if (options.cwd) body.cwd = options.cwd;
|
|
1500
|
+
if (options.env && Object.keys(options.env).length > 0) body.env = options.env;
|
|
1501
|
+
if (options.timeoutMs !== void 0 && options.timeoutMs > 0) body.timeoutMs = options.timeoutMs;
|
|
1502
|
+
const headers = { "content-type": "application/json" };
|
|
1503
|
+
if (options.bearerToken) headers.authorization = `Bearer ${options.bearerToken}`;
|
|
1504
|
+
let response;
|
|
1505
|
+
try {
|
|
1506
|
+
response = await fetchImpl(url, {
|
|
1507
|
+
method: "POST",
|
|
1508
|
+
headers,
|
|
1509
|
+
body: JSON.stringify(body),
|
|
1510
|
+
signal: controller.signal
|
|
1368
1511
|
});
|
|
1512
|
+
} catch (error) {
|
|
1513
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1514
|
+
if (timedOut) return {
|
|
1515
|
+
exitCode: 124,
|
|
1516
|
+
stdout: "",
|
|
1517
|
+
stderr: "",
|
|
1518
|
+
timedOut: true,
|
|
1519
|
+
opened: false
|
|
1520
|
+
};
|
|
1521
|
+
return {
|
|
1522
|
+
exitCode: null,
|
|
1523
|
+
stdout: "",
|
|
1524
|
+
stderr: "",
|
|
1525
|
+
timedOut: false,
|
|
1526
|
+
opened: false,
|
|
1527
|
+
transportErrorMessage: error instanceof Error ? error.message : String(error)
|
|
1528
|
+
};
|
|
1369
1529
|
}
|
|
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));
|
|
1530
|
+
if (!response.ok) {
|
|
1531
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1532
|
+
const text = await response.text().catch(() => "");
|
|
1533
|
+
throw new PrivateNetExecHttpError(response.status, text);
|
|
1383
1534
|
}
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1535
|
+
if (!response.body) {
|
|
1536
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1537
|
+
return {
|
|
1538
|
+
exitCode: null,
|
|
1539
|
+
stdout: "",
|
|
1540
|
+
stderr: "",
|
|
1541
|
+
timedOut: false,
|
|
1542
|
+
opened: true,
|
|
1543
|
+
status: response.status
|
|
1544
|
+
};
|
|
1391
1545
|
}
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1546
|
+
let stdout = "";
|
|
1547
|
+
let stderr = "";
|
|
1548
|
+
let exitCode = null;
|
|
1549
|
+
const decoder = new TextDecoder();
|
|
1550
|
+
let buffer = "";
|
|
1551
|
+
const handleLine = (line) => {
|
|
1552
|
+
if (!line) return;
|
|
1553
|
+
let frame;
|
|
1398
1554
|
try {
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
await this.runFiles(operation, (files) => files.remove(tmp)).catch(() => {});
|
|
1403
|
-
throw error;
|
|
1555
|
+
frame = JSON.parse(line);
|
|
1556
|
+
} catch {
|
|
1557
|
+
return;
|
|
1404
1558
|
}
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
if (
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1559
|
+
if (!frame || typeof frame !== "object") return;
|
|
1560
|
+
if (frame.type === "stdout" && typeof frame.data === "string") {
|
|
1561
|
+
stdout += frame.data;
|
|
1562
|
+
options.onStdout?.(frame.data);
|
|
1563
|
+
} else if (frame.type === "stderr" && typeof frame.data === "string") {
|
|
1564
|
+
stderr += frame.data;
|
|
1565
|
+
options.onStderr?.(frame.data);
|
|
1566
|
+
} else if (frame.type === "exit" && typeof frame.code === "number") exitCode = frame.code;
|
|
1567
|
+
};
|
|
1568
|
+
try {
|
|
1569
|
+
const reader = response.body.getReader();
|
|
1570
|
+
while (true) {
|
|
1571
|
+
const { value, done } = await reader.read();
|
|
1572
|
+
if (done) break;
|
|
1573
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1574
|
+
let newlineIdx = buffer.indexOf("\n");
|
|
1575
|
+
while (newlineIdx !== -1) {
|
|
1576
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
1577
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
1578
|
+
handleLine(line);
|
|
1579
|
+
newlineIdx = buffer.indexOf("\n");
|
|
1580
|
+
}
|
|
1413
1581
|
}
|
|
1414
|
-
|
|
1582
|
+
buffer += decoder.decode();
|
|
1583
|
+
const trailing = buffer.trim();
|
|
1584
|
+
if (trailing) handleLine(trailing);
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1587
|
+
if (timedOut) return {
|
|
1588
|
+
exitCode: 124,
|
|
1589
|
+
stdout,
|
|
1590
|
+
stderr,
|
|
1591
|
+
timedOut: true,
|
|
1592
|
+
opened: true,
|
|
1593
|
+
status: response.status
|
|
1594
|
+
};
|
|
1595
|
+
return {
|
|
1596
|
+
exitCode,
|
|
1597
|
+
stdout,
|
|
1598
|
+
stderr,
|
|
1599
|
+
timedOut: false,
|
|
1600
|
+
opened: true,
|
|
1601
|
+
status: response.status,
|
|
1602
|
+
transportErrorMessage: error instanceof Error ? error.message : String(error)
|
|
1603
|
+
};
|
|
1604
|
+
} finally {
|
|
1605
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
1415
1606
|
}
|
|
1416
|
-
|
|
1607
|
+
return {
|
|
1608
|
+
exitCode,
|
|
1609
|
+
stdout,
|
|
1610
|
+
stderr,
|
|
1611
|
+
timedOut: false,
|
|
1612
|
+
opened: true,
|
|
1613
|
+
status: response.status
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1417
1616
|
//#endregion
|
|
1418
1617
|
//#region src/sandbox-filesystem.ts
|
|
1419
1618
|
/**
|
|
@@ -1614,6 +1813,70 @@ var PlatformProcessManager = class extends SandboxProcessManager {
|
|
|
1614
1813
|
}));
|
|
1615
1814
|
}
|
|
1616
1815
|
};
|
|
1816
|
+
/** Reaches the sandbox's commands handle without making it part of the class's public API. */
|
|
1817
|
+
const withCommands = Symbol("withCommands");
|
|
1818
|
+
/**
|
|
1819
|
+
* Background processes on an E2B-backed sandbox through envd's commands API,
|
|
1820
|
+
* reached with the same lease `executeCommand` uses. Output streams while the
|
|
1821
|
+
* process runs, `kill` stops it, and `list` reports what is running in the VM.
|
|
1822
|
+
*/
|
|
1823
|
+
var PlatformCommandsProcessManager = class extends CommandsApiProcessManager {
|
|
1824
|
+
runCommands(operation, fn) {
|
|
1825
|
+
return this.sandbox[withCommands](operation, fn);
|
|
1826
|
+
}
|
|
1827
|
+
createHandle(inner, stdinMode, options) {
|
|
1828
|
+
return new PlatformProcessHandleOverLease(inner, this, Date.now(), stdinMode, options);
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
/** envd ends the output stream when the lease it was opened with expires; the process keeps running. */
|
|
1832
|
+
function isLeaseStreamDrop(error) {
|
|
1833
|
+
return error instanceof TimeoutError && error.message.startsWith("[unavailable]");
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* The process left the VM while no stream was attached, so envd can't say how
|
|
1837
|
+
* it ended. Carries an exit code so the handle reads as exited: it shows in
|
|
1838
|
+
* `list()` and is released like any other finished process.
|
|
1839
|
+
*/
|
|
1840
|
+
var ProcessEndedUnseenError = class extends Error {
|
|
1841
|
+
exitCode = 1;
|
|
1842
|
+
constructor(cause) {
|
|
1843
|
+
super(`${cause instanceof Error ? cause.message : String(cause)} (the process ended before it could be reattached)`);
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
/**
|
|
1847
|
+
* A process outlives the lease it was started with. When that lease expires
|
|
1848
|
+
* envd ends the output stream, so reattach on the current lease and keep
|
|
1849
|
+
* waiting. Output written between the drop and the reattach is not seen.
|
|
1850
|
+
*/
|
|
1851
|
+
var PlatformProcessHandleOverLease = class extends CommandsApiProcessHandle {
|
|
1852
|
+
/** One reattach loop shared by every `wait()` caller. */
|
|
1853
|
+
exited;
|
|
1854
|
+
waitForExit() {
|
|
1855
|
+
return this.exited ??= this.waitAcrossLeases();
|
|
1856
|
+
}
|
|
1857
|
+
async waitAcrossLeases() {
|
|
1858
|
+
for (;;) try {
|
|
1859
|
+
return await this.inner.wait();
|
|
1860
|
+
} catch (error) {
|
|
1861
|
+
if (!isLeaseStreamDrop(error)) throw error;
|
|
1862
|
+
const pid = this.inner.pid;
|
|
1863
|
+
const reattached = await this.manager.runCommands("connect", async (commands) => {
|
|
1864
|
+
if (!(await commands.list()).some((proc) => proc.pid === pid)) return "ended";
|
|
1865
|
+
return commands.connect(pid, {
|
|
1866
|
+
onStdout: (data) => this.emitStdout(data),
|
|
1867
|
+
onStderr: (data) => this.emitStderr(data),
|
|
1868
|
+
timeoutMs: 0
|
|
1869
|
+
});
|
|
1870
|
+
}).catch(() => void 0);
|
|
1871
|
+
if (reattached === "ended") throw new ProcessEndedUnseenError(error);
|
|
1872
|
+
if (!reattached) {
|
|
1873
|
+
this.exited = void 0;
|
|
1874
|
+
throw error;
|
|
1875
|
+
}
|
|
1876
|
+
this.inner = reattached;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
};
|
|
1617
1880
|
var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
1618
1881
|
id;
|
|
1619
1882
|
name = "PlatformSandbox";
|
|
@@ -1661,6 +1924,8 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
1661
1924
|
_e2bFilesFactory;
|
|
1662
1925
|
/** Files handle for the current lease, rebuilt whenever the lease changes. */
|
|
1663
1926
|
_e2bFiles = null;
|
|
1927
|
+
_e2bCommandsFactory;
|
|
1928
|
+
_e2bCommands = null;
|
|
1664
1929
|
_filesystem;
|
|
1665
1930
|
_privateNetFetch;
|
|
1666
1931
|
/**
|
|
@@ -1729,10 +1994,11 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
1729
1994
|
*/
|
|
1730
1995
|
_probeTarget = null;
|
|
1731
1996
|
constructor(options = {}) {
|
|
1997
|
+
const e2bBacked = resolveSandboxProvider(options.sandboxProvider ?? process.env.SANDBOX_PROVIDER?.trim()) === "e2b";
|
|
1732
1998
|
super({
|
|
1733
1999
|
...options,
|
|
1734
2000
|
name: "PlatformSandbox",
|
|
1735
|
-
processes: new PlatformProcessManager()
|
|
2001
|
+
processes: e2bBacked ? new PlatformCommandsProcessManager({ defaultTimeout: options.timeout ?? 0 }) : new PlatformProcessManager()
|
|
1736
2002
|
});
|
|
1737
2003
|
this._hasRecoveryKey = options.id !== void 0;
|
|
1738
2004
|
this.id = options.id ?? this.generateId();
|
|
@@ -1752,6 +2018,7 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
1752
2018
|
this._webSocketFactory = options.webSocketFactory;
|
|
1753
2019
|
this._e2bExecRunner = options.e2bExecRunner ?? execViaE2BLease;
|
|
1754
2020
|
this._e2bFilesFactory = options.e2bFilesFactory ?? e2bFilesForLease;
|
|
2021
|
+
this._e2bCommandsFactory = options.e2bCommandsFactory ?? commandsForLease;
|
|
1755
2022
|
this._privateNetFetch = options.privateNetFetch;
|
|
1756
2023
|
this._addressRegistry = options.addressRegistry;
|
|
1757
2024
|
}
|
|
@@ -2545,8 +2812,55 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
2545
2812
|
};
|
|
2546
2813
|
return this._e2bFiles;
|
|
2547
2814
|
}
|
|
2815
|
+
/**
|
|
2816
|
+
* Run `fn` against envd's commands API with the current lease, the way
|
|
2817
|
+
* {@link _withE2BFiles} runs files calls: one retry, only after an
|
|
2818
|
+
* `AuthenticationError` proves the call never ran, so a spawn or kill is
|
|
2819
|
+
* never replayed. Each call fetches the lease again, so a process started
|
|
2820
|
+
* under one lease is stopped with whichever lease is current.
|
|
2821
|
+
*/
|
|
2822
|
+
async [withCommands](operation, fn) {
|
|
2823
|
+
await this.ensureRunning();
|
|
2824
|
+
if (!this._sandboxId) throw new SandboxNotReadyError(this.id);
|
|
2825
|
+
let current = await this._commandsHandle(operation, 1);
|
|
2826
|
+
const call = async (invoke) => {
|
|
2827
|
+
try {
|
|
2828
|
+
return await invoke(current.commands);
|
|
2829
|
+
} catch (error) {
|
|
2830
|
+
if (error instanceof AuthenticationError) {
|
|
2831
|
+
if (this._lease === current.lease) this._lease = null;
|
|
2832
|
+
current = await this._commandsHandle(operation, 2);
|
|
2833
|
+
try {
|
|
2834
|
+
return await invoke(current.commands);
|
|
2835
|
+
} catch (retryError) {
|
|
2836
|
+
if (isBrokenSandboxError(retryError) && this._lease === current.lease) this._lease = null;
|
|
2837
|
+
throw retryError;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
if (isBrokenSandboxError(error) && this._lease === current.lease) this._lease = null;
|
|
2841
|
+
throw error;
|
|
2842
|
+
}
|
|
2843
|
+
};
|
|
2844
|
+
return fn({
|
|
2845
|
+
run: (command, opts) => call((commands) => commands.run(command, opts)),
|
|
2846
|
+
connect: (pid, opts) => call((commands) => commands.connect(pid, opts)),
|
|
2847
|
+
list: () => call((commands) => commands.list()),
|
|
2848
|
+
kill: (pid) => call((commands) => commands.kill(pid)),
|
|
2849
|
+
sendStdin: (pid, data) => call((commands) => commands.sendStdin(pid, data))
|
|
2850
|
+
});
|
|
2851
|
+
}
|
|
2852
|
+
/** The commands handle for the current lease, rebuilt only when the lease changes. */
|
|
2853
|
+
async _commandsHandle(operation, attempts) {
|
|
2854
|
+
const lease = await this._fileLease(`processes.${operation}`, attempts, "");
|
|
2855
|
+
if (lease.provider !== "e2b") throw new Error(`PlatformSandbox.processes requires an E2B-backed sandbox; this sandbox's provider is "${lease.provider}"`);
|
|
2856
|
+
if (this._e2bCommands?.lease !== lease) this._e2bCommands = {
|
|
2857
|
+
lease,
|
|
2858
|
+
commands: this._e2bCommandsFactory(lease)
|
|
2859
|
+
};
|
|
2860
|
+
return this._e2bCommands;
|
|
2861
|
+
}
|
|
2548
2862
|
/** `_ensureLease`, with a 410 handled the same way `_runDirectExec` handles it. */
|
|
2549
|
-
async _fileLease(operation, attempts) {
|
|
2863
|
+
async _fileLease(operation, attempts, prefix = "filesystem.") {
|
|
2550
2864
|
try {
|
|
2551
2865
|
return await this._ensureLease();
|
|
2552
2866
|
} catch (error) {
|
|
@@ -2557,7 +2871,7 @@ var PlatformSandbox = class PlatformSandbox extends MastraSandbox {
|
|
|
2557
2871
|
this.status = "stopped";
|
|
2558
2872
|
throw new SandboxDestroyedError(`Sandbox ${priorSandboxId ?? "(unknown)"} was destroyed; /exec-lease returned 410`, {
|
|
2559
2873
|
...priorSandboxId && { sandboxId: priorSandboxId },
|
|
2560
|
-
command:
|
|
2874
|
+
command: `${prefix}${operation}`,
|
|
2561
2875
|
attempts
|
|
2562
2876
|
});
|
|
2563
2877
|
}
|