MCPcopy Create free account
hub / github.com/agenticsorg/edge-agents / executeCode

Function executeCode

scripts/sparc2/scripts/e2b-code-interpreter.ts:69–164  ·  view source on GitHub ↗
(
  code: string,
  options: {
    stream?: boolean;
    language?: "python" | "javascript" | "typescript";
    timeout?: number;
  } = {}
)

Source from the content-addressed store, hash-verified

67 * @returns The execution result
68 */
69export async function executeCode(
70 code: string,
71 options: {
72 stream?: boolean;
73 language?: "python" | "javascript" | "typescript";
74 timeout?: number;
75 } = {}
76): Promise<ExecutionResult> {
77 const sandbox = await createSandbox();
78
79 try {
80 // Prepare the code based on the language
81 let preparedCode = code;
82 if (options.language === "typescript" && !code.includes("///@ts-nocheck")) {
83 // Add ts-nocheck to avoid TypeScript errors in the sandbox
84 preparedCode = "///@ts-nocheck\n" + code;
85 }
86
87 if (options.language === "python" && !code.trim().startsWith("!pip") && !code.trim().startsWith("import")) {
88 // For Python, ensure basic imports are available
89 preparedCode = "import sys\nimport os\n" + preparedCode;
90 }
91
92 // Set up execution options
93 const execOptions: any = {};
94 if (options.stream) {
95 execOptions.onStdout = (msg: string) => console.log("[stdout]", msg);
96 execOptions.onStderr = (msg: string) => console.error("[stderr]", msg);
97 }
98
99 // Execute the code with timeout
100 let execution: any;
101 if (options.timeout) {
102 const timeoutPromise = new Promise<never>((_, reject) => {
103 setTimeout(() => reject(new Error(`Execution timed out after ${options.timeout}ms`)), options.timeout);
104 });
105
106 execution = await Promise.race([
107 sandbox.notebook.execCell(preparedCode, execOptions),
108 timeoutPromise
109 ]);
110 } else {
111 execution = await sandbox.notebook.execCell(preparedCode, execOptions);
112 }
113
114 // Format the result to match our ExecutionResult interface
115 const result: ExecutionResult = {
116 text: execution.text || "",
117 results: execution.results || [],
118 error: execution.error ? {
119 type: "error",
120 value: typeof execution.error === 'string' ? execution.error :
121 JSON.stringify(execution.error)
122 } : null,
123 logs: {
124 stdout: Array.isArray(execution.logs?.stdout) ? execution.logs.stdout :
125 (execution.logs?.stdout ? [execution.logs.stdout] : []),
126 stderr: Array.isArray(execution.logs?.stderr) ? execution.logs.stderr :

Callers 3

mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.70

Calls 2

logMessageFunction · 0.90
createSandboxFunction · 0.70

Tested by

no test coverage detected