fixed tool execute subprocess

This commit is contained in:
ValueOn AG 2026-04-01 22:16:08 +02:00
parent 0a5fa20cb8
commit 563018b5e1

View file

@ -3,7 +3,6 @@
"""Sandboxed code execution for the AI agent executeCode tool.""" """Sandboxed code execution for the AI agent executeCode tool."""
import logging import logging
import signal
import sys import sys
import io import io
import traceback import traceback
@ -72,15 +71,12 @@ async def executePython(code: str) -> Dict[str, Any]:
sys.stdout = capturedOutput sys.stdout = capturedOutput
sys.stderr = capturedOutput sys.stderr = capturedOutput
if sys.platform != "win32": # Do not use signal.SIGALRM here: _run executes inside a thread-pool worker
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError("Execution timed out"))) # (asyncio.run_in_executor). signal.signal only works on the main thread.
signal.alarm(_MAX_EXECUTION_TIME_S) # Wall-clock limit is enforced by asyncio.wait_for around run_in_executor.
exec(compile(code, "<sandbox>", "exec"), restrictedGlobals) exec(compile(code, "<sandbox>", "exec"), restrictedGlobals)
if sys.platform != "win32":
signal.alarm(0)
output = capturedOutput.getvalue() output = capturedOutput.getvalue()
if len(output) > _MAX_OUTPUT_CHARS: if len(output) > _MAX_OUTPUT_CHARS:
output = output[:_MAX_OUTPUT_CHARS] + f"\n... (truncated at {_MAX_OUTPUT_CHARS} chars)" output = output[:_MAX_OUTPUT_CHARS] + f"\n... (truncated at {_MAX_OUTPUT_CHARS} chars)"
@ -94,14 +90,12 @@ async def executePython(code: str) -> Dict[str, Any]:
finally: finally:
sys.stdout = oldStdout sys.stdout = oldStdout
sys.stderr = oldStderr sys.stderr = oldStderr
if sys.platform != "win32":
signal.alarm(0)
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
try: try:
result = await asyncio.wait_for( result = await asyncio.wait_for(
loop.run_in_executor(None, _run), loop.run_in_executor(None, _run),
timeout=_MAX_EXECUTION_TIME_S + 5, timeout=float(_MAX_EXECUTION_TIME_S) + 5.0,
) )
return result return result
except asyncio.TimeoutError: except asyncio.TimeoutError: