(req: E2BExecutionRequest)
| 191 | } |
| 192 | |
| 193 | export async function executeInE2B(req: E2BExecutionRequest): Promise<E2BExecutionResult> { |
| 194 | const { code, language, timeoutMs } = req |
| 195 | |
| 196 | const sandbox = await createE2BSandbox(req.sandboxKind ?? 'code') |
| 197 | const sandboxId = sandbox.sandboxId |
| 198 | |
| 199 | const stdoutChunks = [] |
| 200 | |
| 201 | try { |
| 202 | // Inside the try so a failed mount still kills the sandbox via the finally below. |
| 203 | await writeSandboxInputs(sandbox, req.sandboxFiles, { sandboxId }) |
| 204 | |
| 205 | const execution = await sandbox.runCode(code, { |
| 206 | language: language === CodeLanguage.Python ? 'python' : 'javascript', |
| 207 | timeoutMs, |
| 208 | }) |
| 209 | |
| 210 | if (execution.error) { |
| 211 | const errorMessage = `${execution.error.name}: ${execution.error.value}` |
| 212 | logger.error(`E2B execution error`, { |
| 213 | sandboxId, |
| 214 | error: execution.error, |
| 215 | errorMessage, |
| 216 | }) |
| 217 | |
| 218 | const errorOutput = execution.error.traceback || errorMessage |
| 219 | return { |
| 220 | result: null, |
| 221 | stdout: errorOutput, |
| 222 | error: errorMessage, |
| 223 | sandboxId, |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | if (execution.text) { |
| 228 | stdoutChunks.push(execution.text) |
| 229 | } |
| 230 | if (execution.logs?.stdout) { |
| 231 | stdoutChunks.push(...execution.logs.stdout) |
| 232 | } |
| 233 | if (execution.logs?.stderr) { |
| 234 | stdoutChunks.push(...execution.logs.stderr) |
| 235 | } |
| 236 | |
| 237 | const stdout = stdoutChunks.join('\n') |
| 238 | |
| 239 | let result: unknown = null |
| 240 | const prefix = '__SIM_RESULT__=' |
| 241 | const lines = stdout.split('\n') |
| 242 | const marker = lines.find((l) => l.startsWith(prefix)) |
| 243 | let cleanedStdout = stdout |
| 244 | if (marker) { |
| 245 | const jsonPart = marker.slice(prefix.length) |
| 246 | try { |
| 247 | result = JSON.parse(jsonPart) |
| 248 | } catch { |
| 249 | result = jsonPart |
| 250 | } |
no test coverage detected