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

Function executeCode

scripts/sparc2/src/sandbox/codeInterpreter.ts:86–202  ·  view source on GitHub ↗
(
  code: string,
  options: {
    stream?: boolean;
    language?: "python" | "javascript" | "typescript";
    timeout?: number;
  } = {},
)

Source from the content-addressed store, hash-verified

84 * @returns The execution result
85 */
86export async function executeCode(
87 code: string,
88 options: {
89 stream?: boolean;
90 language?: "python" | "javascript" | "typescript";
91 timeout?: number;
92 } = {},
93): Promise<ExecutionResult> {
94 const sandbox = await createSandbox();
95
96 try {
97 // Prepare the code based on the language
98 let preparedCode = code;
99 const language = options.language || "python";
100
101 if (language === "typescript" && !code.includes("///@ts-nocheck")) {
102 // Add ts-nocheck to avoid TypeScript errors in the sandbox
103 preparedCode = "///@ts-nocheck\n" + code;
104 }
105
106 if (
107 language === "python" && !code.trim().startsWith("!pip") && !code.trim().startsWith("import")
108 ) {
109 // For Python, ensure basic imports are available
110 preparedCode = "import sys\nimport os\n" + preparedCode;
111 }
112
113 // Set up execution options
114 const execOptions: any = {
115 language,
116 };
117
118 if (options.stream) {
119 execOptions.onStdout = (data: any) => console.log("[stdout]", data);
120 execOptions.onStderr = (data: any) => console.error("[stderr]", data);
121 }
122
123 // Execute the code with timeout
124 let execution: any;
125 if (options.timeout) {
126 // Create a promise that rejects after the timeout
127 const timeoutPromise = new Promise<never>((_, reject) => {
128 setTimeout(
129 () => reject(new Error(`Execution timed out after ${options.timeout}ms`)),
130 options.timeout,
131 );
132 });
133
134 // Race the execution against the timeout
135 // @ts-ignore - Ignore TypeScript errors for API compatibility
136 execution = await Promise.race([
137 sandbox.runCode(preparedCode, execOptions),
138 timeoutPromise,
139 ]);
140 } else {
141 // @ts-ignore - Ignore TypeScript errors for API compatibility
142 execution = await sandbox.runCode(preparedCode, execOptions);
143 }

Callers 12

runSWEBenchFunction · 0.90
runHumanEvalFunction · 0.90
runRedCodeFunction · 0.90
fnFunction · 0.90
executeCommandFunction · 0.90
startMCPServerFunction · 0.90
startMCPServerStdioFunction · 0.90
handleExecuteFunction · 0.90
executeCodeMethod · 0.90
tools.tsFile · 0.90
runHumanEvalTaskFunction · 0.90
executeFileFunction · 0.70

Calls 2

logMessageFunction · 0.90
createSandboxFunction · 0.70

Tested by 1

fnFunction · 0.72