( options: QuickJsExecutorOptions, code: string, toolInvoker: SandboxToolInvoker, runPromise: RunPromise, )
| 415 | }; |
| 416 | |
| 417 | const evaluateInQuickJs = async ( |
| 418 | options: QuickJsExecutorOptions, |
| 419 | code: string, |
| 420 | toolInvoker: SandboxToolInvoker, |
| 421 | runPromise: RunPromise, |
| 422 | ): Promise<ExecuteResult> => { |
| 423 | const timeoutMs = Math.max(100, options.timeoutMs ?? DEFAULT_TIMEOUT_MS); |
| 424 | const deadline = makeDeadlineTracker(timeoutMs); |
| 425 | const logs: string[] = []; |
| 426 | const pendingDeferreds = new Set<QuickJSDeferredPromise>(); |
| 427 | const QuickJS = await resolveQuickJS(); |
| 428 | const runtime = QuickJS.newRuntime(); |
| 429 | |
| 430 | try { |
| 431 | runtime.setMemoryLimit(options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES); |
| 432 | runtime.setMaxStackSize(options.maxStackSizeBytes ?? DEFAULT_MAX_STACK_SIZE_BYTES); |
| 433 | |
| 434 | runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline)); |
| 435 | |
| 436 | const context = runtime.newContext(); |
| 437 | try { |
| 438 | const logBridge = createLogBridge(context, logs); |
| 439 | context.setProp(context.global, "__executor_log", logBridge); |
| 440 | logBridge.dispose(); |
| 441 | |
| 442 | const toolBridge = createToolBridge( |
| 443 | context, |
| 444 | toolInvoker, |
| 445 | pendingDeferreds, |
| 446 | runPromise, |
| 447 | deadline, |
| 448 | ); |
| 449 | context.setProp(context.global, "__executor_invokeTool", toolBridge); |
| 450 | toolBridge.dispose(); |
| 451 | |
| 452 | const evaluated = context.evalCode(buildExecutionSource(code), EXECUTION_FILENAME); |
| 453 | if (evaluated.error) { |
| 454 | const error = context.dump(evaluated.error); |
| 455 | evaluated.error.dispose(); |
| 456 | return { |
| 457 | result: null, |
| 458 | error: normalizeExecutionError(error, deadline, timeoutMs), |
| 459 | logs, |
| 460 | } satisfies ExecuteResult; |
| 461 | } |
| 462 | |
| 463 | context.setProp(context.global, "__executor_result", evaluated.value); |
| 464 | evaluated.value.dispose(); |
| 465 | |
| 466 | const stateResult = context.evalCode( |
| 467 | "(function(p){ var s = { v: void 0, e: void 0, settled: false }; var formatError = function(e){ if (e && typeof e === 'object') { var message = typeof e.message === 'string' ? e.message : ''; var stack = typeof e.stack === 'string' ? e.stack : ''; if (message && stack) { return stack.indexOf(message) === -1 ? message + '\\n' + stack : stack; } if (message) return message; if (stack) return stack; } return String(e); }; p.then(function(v){ s.v = v; s.settled = true; }, function(e){ s.e = formatError(e); s.settled = true; }); return s; })(__executor_result)", |
| 468 | ); |
| 469 | if (stateResult.error) { |
| 470 | const error = context.dump(stateResult.error); |
| 471 | stateResult.error.dispose(); |
| 472 | return { |
| 473 | result: null, |
| 474 | error: normalizeExecutionError(error, deadline, timeoutMs), |
no test coverage detected