( options: QuickJsExecutorOptions, code: string, toolInvoker: SandboxToolInvoker, runPromise: RunPromise, )
| 435 | }; |
| 436 | |
| 437 | const evaluateInQuickJs = async ( |
| 438 | options: QuickJsExecutorOptions, |
| 439 | code: string, |
| 440 | toolInvoker: SandboxToolInvoker, |
| 441 | runPromise: RunPromise, |
| 442 | ): Promise<ExecuteResult> => { |
| 443 | const timeoutMs = Math.max(100, options.timeoutMs ?? DEFAULT_TIMEOUT_MS); |
| 444 | const deadline = makeDeadlineTracker(timeoutMs); |
| 445 | const logs: string[] = []; |
| 446 | const pendingDeferreds = new Set<QuickJSDeferredPromise>(); |
| 447 | const QuickJS = await resolveQuickJS(); |
| 448 | const runtime = QuickJS.newRuntime(); |
| 449 | |
| 450 | try { |
| 451 | runtime.setMemoryLimit(options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES); |
| 452 | runtime.setMaxStackSize(options.maxStackSizeBytes ?? DEFAULT_MAX_STACK_SIZE_BYTES); |
| 453 | |
| 454 | runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline)); |
| 455 | |
| 456 | const context = runtime.newContext(); |
| 457 | try { |
| 458 | const logBridge = createLogBridge(context, logs); |
| 459 | context.setProp(context.global, "__executor_log", logBridge); |
| 460 | logBridge.dispose(); |
| 461 | |
| 462 | const toolBridge = createToolBridge( |
| 463 | context, |
| 464 | toolInvoker, |
| 465 | pendingDeferreds, |
| 466 | runPromise, |
| 467 | deadline, |
| 468 | ); |
| 469 | context.setProp(context.global, "__executor_invokeTool", toolBridge); |
| 470 | toolBridge.dispose(); |
| 471 | |
| 472 | const evaluated = context.evalCode(buildExecutionSource(code), EXECUTION_FILENAME); |
| 473 | if (evaluated.error) { |
| 474 | const error = context.dump(evaluated.error); |
| 475 | evaluated.error.dispose(); |
| 476 | return { |
| 477 | result: null, |
| 478 | error: normalizeExecutionError(error, deadline, timeoutMs), |
| 479 | logs, |
| 480 | } satisfies ExecuteResult; |
| 481 | } |
| 482 | |
| 483 | context.setProp(context.global, "__executor_result", evaluated.value); |
| 484 | evaluated.value.dispose(); |
| 485 | |
| 486 | const stateResult = context.evalCode( |
| 487 | "(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)", |
| 488 | ); |
| 489 | if (stateResult.error) { |
| 490 | const error = context.dump(stateResult.error); |
| 491 | stateResult.error.dispose(); |
| 492 | return { |
| 493 | result: null, |
| 494 | error: normalizeExecutionError(error, deadline, timeoutMs), |
no test coverage detected