diff --git a/tests/tools/test_code_kernel.py b/tests/tools/test_code_kernel.py index 19f3179044..d7df35720b 100644 --- a/tests/tools/test_code_kernel.py +++ b/tests/tools/test_code_kernel.py @@ -34,13 +34,7 @@ def _force_local_terminal(monkeypatch): monkeypatch.setenv("TERMINAL_ENV", "local") -from tools.code_execution_tool import ( - DEFAULT_KERNEL_MODE, - KERNEL_MODES, - _get_kernel_mode, - build_execute_code_schema, - execute_code, -) +from tools.code_execution_tool import build_execute_code_schema, execute_code from tools.code_kernel import _KERNELS, shutdown_all_kernels @@ -64,24 +58,6 @@ def _run(code, **kwargs): return json.loads(execute_code(code, task_id="kernel-test", **kwargs)) -class TestKernelModeResolution(unittest.TestCase): - """kernel_mode is retired: session kernels are always on for local runs. - - _get_kernel_mode() survives only as a compat shim; a leftover - kernel_mode key in user config (any value) must be ignored.""" - - def test_session_is_always_on(self): - self.assertEqual(DEFAULT_KERNEL_MODE, "session") - with patch("tools.code_execution_tool._load_config", return_value={}): - self.assertEqual(_get_kernel_mode(), "session") - - def test_leftover_config_key_is_ignored(self): - for stale in ("per-call", "forever", "", None): - with patch("tools.code_execution_tool._load_config", - return_value={"kernel_mode": stale}): - self.assertEqual(_get_kernel_mode(), "session") - - class TestSessionStatePersistence(unittest.TestCase): def test_state_persists_across_cells(self): with _kernel_config(): diff --git a/tools/code_execution_env.py b/tools/code_execution_env.py index e70eb874e3..00d40de390 100644 --- a/tools/code_execution_env.py +++ b/tools/code_execution_env.py @@ -36,39 +36,18 @@ _SECRET_SUBSTRINGS = ("KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL", # along or a child that imports Hermes code loses the Kanban mutation guard # while still inheriting HERMES_HOME. _HERMES_CHILD_ALLOWED = frozenset({ - "HERMES_HOME", - "HERMES_PROFILE", - "HERMES_CONFIG", - "HERMES_ENV", - "HERMES_DELEGATED_CHILD_CONTEXT", + "HERMES_HOME", "HERMES_PROFILE", "HERMES_CONFIG", "HERMES_ENV", "HERMES_DELEGATED_CHILD_CONTEXT", }) # Windows-only: without these the CRT itself fails — socket.socket() raises # WinError 10106 (Winsock can't find mswsock.dll) and subprocess can't resolve # cmd.exe. Well-known OS paths, not secrets; the substring block still runs. _WINDOWS_ESSENTIAL_ENV_VARS = frozenset({ - "SYSTEMROOT", - "SYSTEMDRIVE", - "WINDIR", - "COMSPEC", - "PATHEXT", - "OS", - "PROCESSOR_ARCHITECTURE", - "NUMBER_OF_PROCESSORS", - "PUBLIC", - "ALLUSERSPROFILE", - "PROGRAMDATA", - "PROGRAMFILES", - "PROGRAMFILES(X86)", - "PROGRAMW6432", - "APPDATA", - "LOCALAPPDATA", - "USERPROFILE", - "USERDOMAIN", - "USERNAME", - "HOMEDRIVE", - "HOMEPATH", - "COMPUTERNAME", + "SYSTEMROOT", "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT", "OS", + "PROCESSOR_ARCHITECTURE", "NUMBER_OF_PROCESSORS", "PUBLIC", "ALLUSERSPROFILE", + "PROGRAMDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", + "APPDATA", "LOCALAPPDATA", "USERPROFILE", "USERDOMAIN", "USERNAME", + "HOMEDRIVE", "HOMEPATH", "COMPUTERNAME", }) @@ -117,8 +96,7 @@ def _scrub_child_env(source_env, is_passthrough=None, is_windows=None): "sandbox child env (%s). This is intentional hardening (#27303); if " "a sandbox script legitimately needs one, declare it via " "env_passthrough in the skill/config so it passes by explicit opt-in.", - len(_dropped_hermes), - ", ".join(sorted(_dropped_hermes)), + len(_dropped_hermes), ", ".join(sorted(_dropped_hermes)), ) # delegate_task children are marked by a ContextVar, not os.environ, and the @@ -126,10 +104,7 @@ def _scrub_child_env(source_env, is_passthrough=None, is_windows=None): # dispatcher-owned Kanban vars AFTER the scrub so an explicit passthrough # cannot re-grant a delegated child the parent's board mutation capability. try: - from agent.delegation_context import ( - is_delegated_child_process_context, - scrub_kanban_env, - ) + from agent.delegation_context import is_delegated_child_process_context, scrub_kanban_env if is_delegated_child_process_context(): scrubbed = scrub_kanban_env(scrubbed) @@ -168,20 +143,16 @@ def _build_child_env(*, rpc_endpoint: str, rpc_token: str, tmpdir: str, # they never shadow the child's sys.path. from tools.environments.local import _strip_hermes_owned_pythonpath _strip_hermes_owned_pythonpath(child_env) - _hermes_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) _existing_pp = child_env.get("PYTHONPATH", "") _pp_parts = [tmpdir] if _uses_hermes_python_environment(child_python): - _pp_parts.append(_hermes_root) + _pp_parts.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) elif child_python not in _external_env_logged: # Import behavior changes silently otherwise — surface it once per # interpreter path so "import hermes_constants fails" is diagnosable. _external_env_logged.add(child_python) - logger.info( - "execute_code: child interpreter %s is outside the Hermes " - "environment; hermes root omitted from PYTHONPATH", - child_python, - ) + logger.info("execute_code: child interpreter %s is outside the Hermes " + "environment; hermes root omitted from PYTHONPATH", child_python) if _existing_pp: _pp_parts.append(_existing_pp) child_env["PYTHONPATH"] = os.pathsep.join(_pp_parts) @@ -212,13 +183,9 @@ def _probe_python(python_path: str, code: str, *, text: bool = False): from agent.delegation_context import delegated_child_subprocess_env return subprocess.run( - [python_path, "-c", code], - timeout=5, - capture_output=True, - text=text, + [python_path, "-c", code], timeout=5, capture_output=True, text=text, creationflags=subprocess.CREATE_NO_WINDOW if _IS_WINDOWS else 0, - stdin=subprocess.DEVNULL, - env=delegated_child_subprocess_env(), + stdin=subprocess.DEVNULL, env=delegated_child_subprocess_env(), ) except (OSError, subprocess.TimeoutExpired, subprocess.SubprocessError): return None @@ -229,10 +196,7 @@ def _is_usable_python(python_path: str) -> bool: cached = _usable_python_cache.get(python_path) if cached is not None: return cached - result = _probe_python( - python_path, - "import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)", - ) + result = _probe_python(python_path, "import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)") if result is None: return False usable = result.returncode == 0 @@ -261,9 +225,7 @@ def _uses_hermes_python_environment(python_path: str) -> bool: sys.executable can never drop the hermes root; the realpath leg also covers venvs whose bin/python resolves to the same binary (``uv run``). """ - if python_path == sys.executable or ( - os.path.realpath(python_path) == os.path.realpath(sys.executable) - ): + if python_path == sys.executable or os.path.realpath(python_path) == os.path.realpath(sys.executable): return True return _python_environment_prefix(python_path) == os.path.realpath(sys.prefix) @@ -275,29 +237,20 @@ def _resolve_child_python(mode: str) -> str: if mode != "project": return sys.executable - if _IS_WINDOWS: - exe_names = ("python.exe", "python3.exe") - subdirs = ("Scripts",) - else: - exe_names = ("python", "python3") - subdirs = ("bin",) - + subdir, exe_names = ("Scripts", ("python.exe", "python3.exe")) if _IS_WINDOWS else ("bin", ("python", "python3")) for var in ("VIRTUAL_ENV", "CONDA_PREFIX"): root = os.environ.get(var, "").strip() if not root: continue - for subdir in subdirs: - for exe in exe_names: - candidate = os.path.join(root, subdir, exe) - if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)): - continue - if _is_usable_python(candidate): - return candidate - logger.info( - "execute_code: skipping %s=%s (Python version < 3.8 or broken). " - "Using sys.executable instead.", var, candidate, - ) - return sys.executable + for exe in exe_names: + candidate = os.path.join(root, subdir, exe) + if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)): + continue + if _is_usable_python(candidate): + return candidate + logger.info("execute_code: skipping %s=%s (Python version < 3.8 or broken). " + "Using sys.executable instead.", var, candidate) + return sys.executable return sys.executable diff --git a/tools/code_execution_rpc.py b/tools/code_execution_rpc.py index 1a49a96f98..9e242e422f 100644 --- a/tools/code_execution_rpc.py +++ b/tools/code_execution_rpc.py @@ -28,32 +28,22 @@ _TERMINAL_BLOCKED_PARAMS = {"background", "pty", "notify", "notify_on_complete", def _default_dispatch(task_id): from model_tools import handle_function_call - def dispatch(tool_name, tool_args): - return handle_function_call(tool_name, tool_args, task_id=task_id) - - return dispatch + return lambda tool_name, tool_args: handle_function_call(tool_name, tool_args, task_id=task_id) def _rpc_token_ok(request: dict, rpc_token: str) -> bool: - """Constant-time token check; an empty server token fails closed.""" - # Compare as bytes: compare_digest raises TypeError on a str with - # non-ASCII characters, and the token comes from script-supplied JSON. + """Constant-time token check; an empty server token fails closed. + + Compared as bytes: compare_digest raises TypeError on a non-ASCII str, and + the token comes from script-supplied JSON.""" return bool(rpc_token) and secrets.compare_digest( str(request.get("token") or "").encode(), rpc_token.encode() ) -def _handle_rpc_request( - request: dict, - *, - allowed_tools: frozenset, - tool_call_counter: list, - max_tool_calls: int, - dispatch, - tool_call_log: list, - call_start: float, - where: str, -) -> str: +def _handle_rpc_request(request: dict, *, allowed_tools: frozenset, tool_call_counter: list, + max_tool_calls: int, dispatch, tool_call_log: list, call_start: float, + where: str) -> str: """Enforce allow-list + budget, then dispatch one authenticated request. Only a dispatched call consumes budget and is logged; refusals are free. @@ -62,16 +52,11 @@ def _handle_rpc_request( tool_args = request.get("args", {}) if tool_name not in allowed_tools: - available = ", ".join(sorted(allowed_tools)) - return tool_error( - f"Tool '{tool_name}' is not available in execute_code. " - f"Available: {available}" - ) + return tool_error(f"Tool '{tool_name}' is not available in execute_code. " + f"Available: {', '.join(sorted(allowed_tools))}") if tool_call_counter[0] >= max_tool_calls: - return tool_error( - f"Tool call limit reached ({max_tool_calls}). " - "No more tool calls allowed in this execution." - ) + return tool_error(f"Tool call limit reached ({max_tool_calls}). " + "No more tool calls allowed in this execution.") if tool_name == "terminal" and isinstance(tool_args, dict): for param in _TERMINAL_BLOCKED_PARAMS: @@ -86,28 +71,18 @@ def _handle_rpc_request( result = tool_error(str(exc)) tool_call_counter[0] += 1 - tool_call_log.append({ - "tool": tool_name, - "args_preview": str(tool_args)[:80], - "duration": round(time.monotonic() - call_start, 2), - }) + tool_call_log.append({"tool": tool_name, "args_preview": str(tool_args)[:80], + "duration": round(time.monotonic() - call_start, 2)}) return result -def _rpc_server_loop( - server_sock: socket.socket, - task_id: str, - tool_call_log: list, - tool_call_counter: list, # mutable [int] so the thread can increment - max_tool_calls: int, - allowed_tools: frozenset, - stop_event: threading.Event, - rpc_token: str, - dispatch=None, -): +def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: list, + tool_call_counter: list, max_tool_calls: int, allowed_tools: frozenset, + stop_event: threading.Event, rpc_token: str, dispatch=None): """Accept one client and serve newline-delimited JSON requests until it disconnects, idles 300s, or the call limit is reached. + ``tool_call_counter`` is a mutable ``[int]`` so the thread can increment it. ``dispatch`` overrides how an allowed, budgeted call runs: per-call sandboxes use the default (the thread already carries the cell's context), while session kernels pass a dispatcher that rebinds each call to the @@ -155,14 +130,9 @@ def _rpc_server_loop( resp = tool_error("Unauthorized RPC request") else: resp = _handle_rpc_request( - request, - allowed_tools=allowed_tools, - tool_call_counter=tool_call_counter, - max_tool_calls=max_tool_calls, - dispatch=dispatch, - tool_call_log=tool_call_log, - call_start=call_start, - where="sandbox", + request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter, + max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log, + call_start=call_start, where="sandbox", ) conn.sendall((resp + "\n").encode()) @@ -178,17 +148,9 @@ def _rpc_server_loop( logger.debug("RPC conn close error: %s", e) -def _rpc_poll_loop( - env, - rpc_dir: str, - task_id: str, - tool_call_log: list, - tool_call_counter: list, - max_tool_calls: int, - allowed_tools: frozenset, - stop_event: threading.Event, - rpc_token: str, -): +def _rpc_poll_loop(env, rpc_dir: str, task_id: str, tool_call_log: list, tool_call_counter: list, + max_tool_calls: int, allowed_tools: frozenset, stop_event: threading.Event, + rpc_token: str): """Poll the remote filesystem for request files and answer them. Runs in a background thread; each ``env.execute()`` is an independent @@ -201,22 +163,16 @@ def _rpc_poll_loop( quoted_rpc_dir = shlex.quote(rpc_dir) while not stop_event.is_set(): try: - ls_result = env.execute( - f"ls -1 {quoted_rpc_dir}/req_* 2>/dev/null || true", - cwd="/", - timeout=10, - ) + ls_result = env.execute(f"ls -1 {quoted_rpc_dir}/req_* 2>/dev/null || true", cwd="/", timeout=10) output = ls_result.get("output", "").strip() if not output: stop_event.wait(poll_interval) continue - req_files = sorted([ - f.strip() for f in output.split("\n") - if f.strip() - and not f.strip().endswith(".tmp") - and "/req_" in f.strip() - ]) + req_files = sorted( + f for f in (line.strip() for line in output.split("\n")) + if f and not f.endswith(".tmp") and "/req_" in f + ) for req_file in req_files: if stop_event.is_set(): @@ -237,28 +193,19 @@ def _rpc_poll_loop( continue tool_result = _handle_rpc_request( - request, - allowed_tools=allowed_tools, - tool_call_counter=tool_call_counter, - max_tool_calls=max_tool_calls, - dispatch=dispatch, - tool_call_log=tool_call_log, - call_start=call_start, - where="remote sandbox", + request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter, + max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log, + call_start=call_start, where="remote sandbox", ) # Write the response atomically (tmp + rename) via echo piping — # Modal doesn't reliably deliver stdin_data to chained commands. - res_file = f"{rpc_dir}/res_{request.get('seq', 0):06d}" - quoted_res_file = shlex.quote(res_file) - encoded_result = base64.b64encode( - tool_result.encode("utf-8") - ).decode("ascii") + quoted_res_file = shlex.quote(f"{rpc_dir}/res_{request.get('seq', 0):06d}") + encoded_result = base64.b64encode(tool_result.encode("utf-8")).decode("ascii") env.execute( f"echo '{encoded_result}' | base64 -d > {quoted_res_file}.tmp" f" && mv {quoted_res_file}.tmp {quoted_res_file}", - cwd="/", - timeout=60, + cwd="/", timeout=60, ) env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5) diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py index ce2a708ba2..dab099d081 100644 --- a/tools/code_execution_tool.py +++ b/tools/code_execution_tool.py @@ -2,30 +2,24 @@ """ Code Execution Tool -- Programmatic Tool Calling (PTC) -Lets the LLM write a Python script that calls Hermes tools via RPC, -collapsing multi-step tool chains into a single inference turn. Only the -script's stdout is returned to the LLM; intermediate tool results never -enter the context window. +Lets the LLM write a Python script that calls Hermes tools via RPC, collapsing +multi-step tool chains into a single inference turn. Only the script's stdout +is returned to the LLM; intermediate tool results never enter the context. -Two transports: - * Local backend: a persistent per-conversation session kernel - (tools/code_kernel.py) talks to the parent's RPC thread over a Unix - domain socket (loopback TCP on Windows, where AF_UNIX is unreliable). - * Remote backends (Docker/SSH/Modal/Daytona/...): a remote session kernel - (tools/code_kernel_remote.py), falling open to a per-call script ship; - tool calls are request files that a polling thread on the parent reads - via env.execute(), dispatches, and answers with response files. - -Sibling modules: tools/code_execution_env.py (env scrubbing, interpreter/cwd -resolution) and tools/code_execution_rpc.py (RPC servers). Remote execution -requires Python 3 in the terminal backend. +Two transports: the local backend runs a persistent per-conversation session +kernel (tools/code_kernel.py) talking to the parent's RPC thread over a Unix +domain socket (loopback TCP on Windows); remote backends (Docker/SSH/Modal/...) +run a remote session kernel (tools/code_kernel_remote.py), falling open to a +per-call script ship, with tool calls as request files that a polling thread on +the parent reads via env.execute(). Sibling modules: tools/code_execution_env.py +(env scrubbing, interpreter/cwd resolution) and tools/code_execution_rpc.py (RPC +servers). Remote execution requires Python 3 in the terminal backend. """ import base64 import json import logging import os -import platform import re import secrets import shlex @@ -66,7 +60,6 @@ from tools.code_execution_rpc import ( # noqa: F401 _rpc_poll_loop, ) -_IS_WINDOWS = platform.system() == "Windows" logger = logging.getLogger(__name__) # Loopback TCP replaces AF_UNIX on Windows, so execute_code is available on @@ -76,13 +69,7 @@ SANDBOX_AVAILABLE = True # Tools allowed inside the sandbox; the intersection with the session's # enabled tools determines which stubs are generated. SANDBOX_ALLOWED_TOOLS = frozenset([ - "web_search", - "web_extract", - "read_file", - "write_file", - "search_files", - "patch", - "terminal", + "web_search", "web_extract", "read_file", "write_file", "search_files", "patch", "terminal", ]) # Resource limit defaults (overridable via config.yaml → code_execution.*) @@ -90,70 +77,45 @@ DEFAULT_TIMEOUT = 300 # 5 minutes DEFAULT_MAX_TOOL_CALLS = 50 MAX_STDOUT_BYTES = 50_000 # 50 KB MAX_STDERR_BYTES = 10_000 # 10 KB - - -def _assemble_stdout_result( - head: bytes, - tail: bytes = b"", - *, - total_bytes: Optional[int] = None, -) -> Tuple[str, Dict[str, Any]]: - """Build display stdout plus explicit truncation metadata. - - The agent receives execute_code results as JSON. A textual truncation - marker can be missed or later re-truncated by a client layer, so keep the - marker for humans and also expose byte counts for deterministic handling. - """ - captured = head + tail - total = len(captured) if total_bytes is None else max(total_bytes, len(captured)) - truncated = total > len(captured) - omitted = max(0, total - len(captured)) - - if truncated: - stdout_text = ( - head.decode("utf-8", errors="replace") - + f"\n\n... [OUTPUT TRUNCATED - {omitted:,} bytes omitted " - f"out of {total:,} total] ...\n\n" - + tail.decode("utf-8", errors="replace") - ) - else: - stdout_text = captured.decode("utf-8", errors="replace") - - metadata: Dict[str, Any] = { - "stdout_truncated": truncated, - "stdout_bytes_captured": len(captured), - "stdout_bytes_total": total, - "stdout_bytes_omitted": omitted, - } - if truncated: - metadata["warning"] = ( - "execute_code stdout was truncated; the script did run, but only " - "the captured head/tail output is included. Re-run only with " - "narrower output if the omitted data is required." - ) - return stdout_text, metadata +# Hard ceiling on the spilled file, mirroring web_tools' MAX_STORED_TEXT_CHARS +# rationale: a runaway print loop must not write unbounded bytes to disk. +MAX_SPILLED_STDOUT_BYTES = 5_000_000 def _truncate_stdout_text(stdout_text: str) -> Tuple[str, Dict[str, Any]]: - """Cap a complete stdout string by bytes using the same head/tail policy. + """Cap stdout by bytes (40% head / 60% tail) with explicit truncation metadata. - When the full text is in hand (this function's callers, unlike the - streaming per-call reader), the omitted middle is not discarded: the - complete output is spilled to cache/exec and the result carries the - path — the same recover-don't-rerun pattern as web_extract's - cache/web full-text store. + The agent receives execute_code results as JSON; a textual marker can be + missed or re-truncated by a client layer, so byte counts ride alongside it. + The omitted middle is not discarded: the complete output is spilled to + cache/exec and the result carries the path — the same recover-don't-rerun + pattern as web_extract's cache/web full-text store. """ stdout_bytes = stdout_text.encode("utf-8", errors="replace") - if len(stdout_bytes) <= MAX_STDOUT_BYTES: - return _assemble_stdout_result(stdout_bytes) + total = len(stdout_bytes) + if total <= MAX_STDOUT_BYTES: + return stdout_bytes.decode("utf-8", errors="replace"), { + "stdout_truncated": False, "stdout_bytes_captured": total, + "stdout_bytes_total": total, "stdout_bytes_omitted": 0, + } head_bytes = int(MAX_STDOUT_BYTES * 0.4) - tail_bytes = MAX_STDOUT_BYTES - head_bytes - text, metadata = _assemble_stdout_result( - stdout_bytes[:head_bytes], - stdout_bytes[-tail_bytes:], - total_bytes=len(stdout_bytes), + omitted = total - MAX_STDOUT_BYTES + text = ( + stdout_bytes[:head_bytes].decode("utf-8", errors="replace") + + f"\n\n... [OUTPUT TRUNCATED - {omitted:,} bytes omitted " + f"out of {total:,} total] ...\n\n" + + stdout_bytes[head_bytes - MAX_STDOUT_BYTES:].decode("utf-8", errors="replace") ) + metadata: Dict[str, Any] = { + "stdout_truncated": True, "stdout_bytes_captured": MAX_STDOUT_BYTES, + "stdout_bytes_total": total, "stdout_bytes_omitted": omitted, + "warning": ( + "execute_code stdout was truncated; the script did run, but only " + "the captured head/tail output is included. Re-run only with " + "narrower output if the omitted data is required." + ), + } spill_path = _spill_full_stdout(stdout_text) if spill_path: metadata["stdout_spill_path"] = spill_path @@ -166,11 +128,6 @@ def _truncate_stdout_text(stdout_text: str) -> Tuple[str, Dict[str, Any]]: return text, metadata -# Hard ceiling on the spilled file, mirroring web_tools' MAX_STORED_TEXT_CHARS -# rationale: a runaway print loop must not write unbounded bytes to disk. -MAX_SPILLED_STDOUT_BYTES = 5_000_000 - - def _spill_full_stdout(stdout_text: str) -> Optional[str]: """Write full stdout to cache/exec; return its path (None on failure). @@ -182,20 +139,15 @@ def _spill_full_stdout(stdout_text: str) -> Optional[str]: try: import hashlib from hermes_constants import get_hermes_dir - - if len(stdout_text) > MAX_SPILLED_STDOUT_BYTES: - stdout_text = ( - stdout_text[:MAX_SPILLED_STDOUT_BYTES] - + f"\n\n[... spill capped at {MAX_SPILLED_STDOUT_BYTES:,} bytes ...]" - ) - cache_dir = get_hermes_dir("cache/exec", "exec_spill") - cache_dir.mkdir(parents=True, exist_ok=True) - digest = hashlib.sha256( - stdout_text.encode("utf-8", errors="replace") - ).hexdigest()[:12] - path = cache_dir / f"stdout-{digest}.txt" from tools.spill_safety import write_text_exclusive + if len(stdout_text) > MAX_SPILLED_STDOUT_BYTES: + stdout_text = (stdout_text[:MAX_SPILLED_STDOUT_BYTES] + + f"\n\n[... spill capped at {MAX_SPILLED_STDOUT_BYTES:,} bytes ...]") + cache_dir = get_hermes_dir("cache/exec", "exec_spill") + cache_dir.mkdir(parents=True, exist_ok=True) + digest = hashlib.sha256(stdout_text.encode("utf-8", errors="replace")).hexdigest()[:12] + path = cache_dir / f"stdout-{digest}.txt" write_text_exclusive(path, stdout_text, private=False, overwrite=True) return str(path) except Exception as exc: # noqa: BLE001 @@ -207,21 +159,15 @@ def check_sandbox_requirements() -> bool: """check_fn: available unless the vercel_sandbox backend fails its own checks.""" if not SANDBOX_AVAILABLE: return False - try: - from tools.terminal_tool import ( - _check_vercel_sandbox_requirements, - _get_env_config, - ) + from tools.terminal_tool import _check_vercel_sandbox_requirements, _get_env_config config = _get_env_config() except Exception: logger.debug("Could not resolve terminal config for execute_code availability", exc_info=True) return False - if config.get("env_type") == "vercel_sandbox": return _check_vercel_sandbox_requirements(config) - return True @@ -270,56 +216,48 @@ _TOOL_STUBS = { } -def _sandbox_failure_hint(stderr_text: str, enabled_tools=None) -> Optional[str]: - """Map well-known sandbox script failures to one actionable recovery hint. +def _missing_hermes_tools_import_hint(m, enabled_tools) -> str: + missing = m.group(1) + if missing in {"json_parse", "shell_quote", "retry"}: + return (f"{missing} is a BUILT-IN helper in the sandbox — no import " + f"needed. Remove it from the import line and call {missing}(...) directly.") + available = sorted(SANDBOX_ALLOWED_TOOLS & set(enabled_tools or SANDBOX_ALLOWED_TOOLS)) + return (f"'{missing}' is not available inside the execute_code sandbox. " + f"Importable tools here: {', '.join(available)}. For anything " + "else, use the normal tool call instead of execute_code.") - Production mining (state.db): the top execute_code failure classes are - hermes_tools import misuse (importing tools that aren't in the sandbox, - 23x in one window), calling the built-in helpers via import, treating - tool results as strings instead of dicts, and importing third-party - packages that don't exist in the sandbox interpreter. Bounded scan, - first match wins, never raises. - """ + +# (regex, formatter(match, enabled_tools)) — first match wins. Production +# mining (state.db) ranked these as the top execute_code failure classes: +# hermes_tools import misuse, importing the built-in helpers, treating tool +# results as strings, importing third-party packages absent from the sandbox. +_FAILURE_HINT_RULES = ( + (r"cannot import name '(\w+)' from 'hermes_tools'", _missing_hermes_tools_import_hint), + (r"NameError: name '(json_parse|shell_quote|retry)' is not defined", + lambda m, _: f"{m.group(1)} is built into the generated sandbox module — " + "call it directly at module scope without importing it."), + (r"ModuleNotFoundError: No module named '([\w.]+)'", + lambda m, _: f"'{m.group(1)}' is not installed in the sandbox interpreter. " + "Use Python stdlib inside execute_code, or run the code via " + "terminal() with the project venv's python instead."), + (r"TypeError: string indices must be integers|AttributeError: 'str' object has no attribute 'get'", + lambda m, _: "Tool functions in the sandbox return DICTS (already parsed) — " + "do not json.loads() them or index them like strings. " + "Example: read_file(path)['content']."), +) + + +def _sandbox_failure_hint(stderr_text: str, enabled_tools=None) -> Optional[str]: + """Map well-known sandbox script failures to one actionable recovery hint + (bounded scan, first match wins, never raises).""" if not stderr_text: return None window = stderr_text[:4000] try: - m = re.search( - r"cannot import name '(\w+)' from 'hermes_tools'", window - ) - if m: - missing = m.group(1) - available = sorted(SANDBOX_ALLOWED_TOOLS & set(enabled_tools or SANDBOX_ALLOWED_TOOLS)) - builtin = {"json_parse", "shell_quote", "retry"} - if missing in builtin: - return ( - f"{missing} is a BUILT-IN helper in the sandbox — no import " - f"needed. Remove it from the import line and call {missing}(...) directly." - ) - return ( - f"'{missing}' is not available inside the execute_code sandbox. " - f"Importable tools here: {', '.join(available)}. For anything " - "else, use the normal tool call instead of execute_code." - ) - m = re.search(r"NameError: name '(json_parse|shell_quote|retry)' is not defined", window) - if m: - return ( - f"{m.group(1)} is built into the generated sandbox module — " - "call it directly at module scope without importing it." - ) - m = re.search(r"ModuleNotFoundError: No module named '([\w.]+)'", window) - if m: - return ( - f"'{m.group(1)}' is not installed in the sandbox interpreter. " - "Use Python stdlib inside execute_code, or run the code via " - "terminal() with the project venv's python instead." - ) - if re.search(r"TypeError: string indices must be integers|AttributeError: 'str' object has no attribute 'get'", window): - return ( - "Tool functions in the sandbox return DICTS (already parsed) — " - "do not json.loads() them or index them like strings. " - "Example: read_file(path)['content']." - ) + for pattern, fmt in _FAILURE_HINT_RULES: + m = re.search(pattern, window) + if m: + return fmt(m, enabled_tools) except Exception: return None return None @@ -355,7 +293,7 @@ def json_parse(text: str): Use this instead of json.loads() when parsing output from terminal() or web_extract() that may contain raw tabs/newlines in strings, or from tools/files that prepend a UTF-8 BOM (salvage #57870, credit @woxinwuhen713-bit).""" - if isinstance(text, str) and text.startswith(""): + if isinstance(text, str) and text.startswith("\ufeff"): text = text[1:] return json.loads(text, strict=False) @@ -541,55 +479,44 @@ def _call(tool_name, args): # Remote execution support (file-based RPC via terminal backend) # --------------------------------------------------------------------------- -# Backends whose environment takes an image; the config/override key is -# f"{env_type}_image". -_IMAGE_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona"}) - - def _get_or_create_env(task_id: str): """Return ``(env, env_type)`` — the same environment the terminal and file tools use for *task_id*, created on first use (same double-checked per-task lock pattern as file_tools._get_file_ops).""" from tools.terminal_tool import ( - _active_environments, _env_lock, _create_environment, - _get_env_config, _last_activity, _start_cleanup_thread, - _creation_locks, _creation_locks_lock, _task_env_overrides, - _resolve_container_task_id, _resolve_task_host_cwd, + _active_environments, _env_lock, _create_environment, _get_env_config, _last_activity, + _start_cleanup_thread, _creation_locks, _creation_locks_lock, _task_env_overrides, + _resolve_container_task_id, _resolve_task_host_cwd, _is_container_backend, _select_image, + _ssh_config_from_config, ) effective_task_id = _resolve_container_task_id(task_id) - with _env_lock: - if effective_task_id in _active_environments: - _last_activity[effective_task_id] = time.time() - return _active_environments[effective_task_id], _get_env_config()["env_type"] + def _cached(): + with _env_lock: + env = _active_environments.get(effective_task_id) + if env is not None: + _last_activity[effective_task_id] = time.time() + return env + + env = _cached() + if env is not None: + return env, _get_env_config()["env_type"] with _creation_locks_lock: - if effective_task_id not in _creation_locks: - _creation_locks[effective_task_id] = threading.Lock() - task_lock = _creation_locks[effective_task_id] + task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock()) with task_lock: - with _env_lock: - if effective_task_id in _active_environments: - _last_activity[effective_task_id] = time.time() - return _active_environments[effective_task_id], _get_env_config()["env_type"] + env = _cached() + if env is not None: + return env, _get_env_config()["env_type"] config = _get_env_config() env_type = config["env_type"] overrides = _task_env_overrides.get(effective_task_id, {}) - image = "" - if env_type in _IMAGE_BACKENDS: - image_key = f"{env_type}_image" - image = overrides.get(image_key) or config[image_key] - - cwd = overrides.get("cwd") or config["cwd"] - container_config = None - from tools.terminal_tool import _is_container_backend as _is_container - - if _is_container(env_type): + if _is_container_backend(env_type): container_config = { "container_cpu": config.get("container_cpu", 1), "container_memory": config.get("container_memory", 5120), @@ -601,32 +528,16 @@ def _get_or_create_env(task_id: str): "docker_network": config.get("docker_network", True), } - ssh_config = None - if env_type == "ssh": - ssh_config = { - "host": config.get("ssh_host", ""), - "user": config.get("ssh_user", ""), - "port": config.get("ssh_port", 22), - "key": config.get("ssh_key", ""), - "persistent": config.get("ssh_persistent", False), - } - - local_config = None - if env_type == "local": - local_config = { - "persistent": config.get("local_persistent", False), - } - logger.info("Creating new %s environment for execute_code task %s...", env_type, effective_task_id[:8]) env = _create_environment( env_type=env_type, - image=image, - cwd=cwd, + image=_select_image(env_type, overrides, config), + cwd=overrides.get("cwd") or config["cwd"], timeout=config["timeout"], - ssh_config=ssh_config, + ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None, container_config=container_config, - local_config=local_config, + local_config={"persistent": config.get("local_persistent", False)} if env_type == "local" else None, task_id=effective_task_id, host_cwd=_resolve_task_host_cwd(config, task_id), ) @@ -646,27 +557,21 @@ def _ship_file_to_remote(env, remote_path: str, content: str) -> None: backends (Modal) don't reliably deliver stdin_data to chained commands, and base64 is shell-safe inside single quotes.""" encoded = base64.b64encode(content.encode("utf-8")).decode("ascii") - quoted_remote_path = shlex.quote(remote_path) - env.execute( - f"echo '{encoded}' | base64 -d > {quoted_remote_path}", - cwd="/", - timeout=30, - ) + env.execute(f"echo '{encoded}' | base64 -d > {shlex.quote(remote_path)}", cwd="/", timeout=30) def _env_temp_dir(env: Any) -> str: """Return a writable temp dir for env-backed execute_code sandboxes.""" + temp_dir = None get_temp_dir = getattr(env, "get_temp_dir", None) if callable(get_temp_dir): try: temp_dir = get_temp_dir() - if isinstance(temp_dir, str) and temp_dir.startswith("/"): - return temp_dir.rstrip("/") or "/" except Exception as exc: logger.debug("Could not resolve execute_code env temp dir: %s", exc) - candidate = tempfile.gettempdir() - if isinstance(candidate, str) and candidate.startswith("/"): - return candidate.rstrip("/") or "/" + for candidate in (temp_dir, tempfile.gettempdir()): + if isinstance(candidate, str) and candidate.startswith("/"): + return candidate.rstrip("/") or "/" return "/tmp" @@ -675,11 +580,7 @@ def _format_interrupted_output(stdout_text: str) -> str: from tools.interrupt import get_interrupt_reason reason = get_interrupt_reason() - marker = ( - f"[execution interrupted — {reason}]" - if reason - else "[execution interrupted]" - ) + marker = f"[execution interrupted — {reason}]" if reason else "[execution interrupted]" return f"{stdout_text}\n{marker}" if stdout_text else marker @@ -687,8 +588,7 @@ def _clean_output(stdout_text: str) -> Tuple[str, Dict[str, Any]]: """Shared output pipeline: byte-cap (with spill), ANSI strip, secret redaction. code_file=True: execution output often echoes source/config — skip the - ENV/JSON/f-string-template false positives while still masking real - credentials. + ENV/JSON/f-string-template false positives while still masking real credentials. """ from tools.ansi_strip import strip_ansi from agent.redact import redact_sensitive_text @@ -712,28 +612,30 @@ def _error_result(error: str, *, tool_calls_made: int = 0, duration: float = 0) }, ensure_ascii=False) +def _remote_failure(exc: BaseException, exec_start: float, tool_calls_made: int) -> str: + duration = round(time.monotonic() - exec_start, 2) + logger.error("execute_code remote failed after %ss with %d tool calls: %s: %s", + duration, tool_calls_made, type(exc).__name__, exc, exc_info=True) + return _error_result(str(exc), tool_calls_made=tool_calls_made, duration=duration) + + _REMOTE_EXIT_STATUS = {124: "timeout", 130: "interrupted"} def _finish_remote_kernel_result(kernel_result: Dict[str, Any], *, timeout: int, exec_start: float) -> str: """Post-process a remote-kernel cell result into the tool's JSON reply. - Timeout messaging mirrors the local kernel contract (kernel killed, state - lost, next call fresh). - """ + lost, next call fresh).""" stdout_text = kernel_result.get("stdout", "") or "" stderr_text = kernel_result.get("stderr", "") or "" traceback_text = kernel_result.get("traceback", "") or "" if stderr_text or traceback_text: # Same joining shape as the local kernel: stderr and traceback ride in # the output under one marker so the model sees the failure inline. - stdout_text = ( - stdout_text + "\n--- stderr ---\n" + stderr_text + traceback_text - ) + stdout_text = stdout_text + "\n--- stderr ---\n" + stderr_text + traceback_text stdout_text, stdout_metadata = _clean_output(stdout_text) - result: Dict[str, Any] = { "status": kernel_result.get("status", "error"), "output": stdout_text, @@ -744,15 +646,12 @@ def _finish_remote_kernel_result(kernel_result: Dict[str, Any], *, result.update(stdout_metadata) if result["status"] == "timeout": - timeout_msg = ( - f"Cell timed out after {timeout}s; the remote session kernel was " - "killed and its state was lost. The next call starts fresh." - ) + timeout_msg = (f"Cell timed out after {timeout}s; the remote session kernel was " + "killed and its state was lost. The next call starts fresh.") result["error"] = timeout_msg result["output"] = _with_timeout_notice(stdout_text, timeout_msg) elif result["status"] == "error" and kernel_result.get("error"): result["error"] = kernel_result["error"] - return json.dumps(result, ensure_ascii=False) @@ -762,12 +661,88 @@ def _sandbox_tools_for(enabled_tools: Optional[List[str]]) -> frozenset: return frozenset(SANDBOX_ALLOWED_TOOLS & set(enabled_tools or ())) or SANDBOX_ALLOWED_TOOLS -def _execute_remote( - code: str, - task_id: Optional[str], - enabled_tools: Optional[List[str]], - reset: bool = False, -) -> str: +def _run_remote_per_call(env, env_type: str, code: str, effective_task_id: str, + sandbox_tools: frozenset, *, timeout: int, max_tool_calls: int, + exec_start: float) -> str: + """Per-call script ship: stage hermes_tools.py + script.py in a fresh remote + sandbox dir, serve file-RPC from a polling thread, run, clean up.""" + sandbox_dir = f"{_env_temp_dir(env)}/hermes_exec_{uuid.uuid4().hex[:12]}" + quoted_sandbox_dir = shlex.quote(sandbox_dir) + quoted_rpc_dir = shlex.quote(f"{sandbox_dir}/rpc") + + tool_call_log: list = [] + tool_call_counter = [0] + stop_event = threading.Event() + rpc_thread = None + try: + env.execute(f"mkdir -p {quoted_rpc_dir}", cwd="/", timeout=10) + rpc_token = secrets.token_urlsafe(32) + _ship_file_to_remote(env, f"{sandbox_dir}/hermes_tools.py", + generate_hermes_tools_module(list(sandbox_tools), transport="file")) + _ship_file_to_remote(env, f"{sandbox_dir}/script.py", code) + + # Wrapped so the thread inherits the turn's approval context + callbacks + # (tools.thread_context) — else sandbox RPC tool calls lose approval routing. + rpc_thread = threading.Thread( + target=propagate_context_to_thread(_rpc_poll_loop), + args=(env, f"{sandbox_dir}/rpc", effective_task_id, tool_call_log, tool_call_counter, + max_tool_calls, sandbox_tools, stop_event, rpc_token), + daemon=True, + ) + rpc_thread.start() + + env_prefix = (f"HERMES_RPC_DIR={quoted_rpc_dir} " + f"HERMES_RPC_TOKEN={shlex.quote(rpc_token)} " + f"PYTHONDONTWRITEBYTECODE=1") + tz = os.getenv("HERMES_TIMEZONE", "").strip() + if tz: + env_prefix += f" TZ={shlex.quote(tz)}" + + logger.info("Executing code on %s backend (task %s)...", env_type, effective_task_id[:8]) + script_result = env.execute(f"cd {quoted_sandbox_dir} && {env_prefix} python3 script.py", + timeout=timeout) + stdout_text = script_result.get("output", "") or "" + exit_code = script_result.get("returncode", -1) + # Backend exit codes: 124 = timeout wrapper, 130 = SIGINT. + status = _REMOTE_EXIT_STATUS.get(exit_code, "success") + except Exception as exc: + return _remote_failure(exc, exec_start, tool_call_counter[0]) + finally: + stop_event.set() + if rpc_thread is not None: + rpc_thread.join(timeout=5) + try: + env.execute(f"rm -rf {quoted_sandbox_dir}", cwd="/", timeout=15) + except Exception: + logger.debug("Failed to clean up remote sandbox %s", sandbox_dir) + + duration = round(time.monotonic() - exec_start, 2) + stdout_text, stdout_metadata = _clean_output(stdout_text) + result: Dict[str, Any] = { + "status": status, + "output": stdout_text, + "exit_code": exit_code, + "tool_calls_made": tool_call_counter[0], + "duration_seconds": duration, + } + result.update(stdout_metadata) + + if status == "timeout": + timeout_msg = f"Script timed out after {timeout}s and was killed." + result["error"] = timeout_msg + result["output"] = _with_timeout_notice(stdout_text, timeout_msg) + logger.warning("execute_code (remote) timed out after %ss (limit %ss) with %d tool calls", + duration, timeout, tool_call_counter[0]) + elif status == "interrupted": + result["output"] = _format_interrupted_output(stdout_text) + elif exit_code != 0: + result["status"] = "error" + result["error"] = f"Script exited with code {exit_code}" + return json.dumps(result, ensure_ascii=False) + + +def _execute_remote(code: str, task_id: Optional[str], enabled_tools: Optional[List[str]], + reset: bool = False) -> str: """Run code on the remote terminal backend. Preferred path: the owner's persistent remote session kernel @@ -783,22 +758,10 @@ def _execute_remote( effective_task_id = task_id or "default" env, env_type = _get_or_create_env(effective_task_id) - - sandbox_dir = f"{_env_temp_dir(env)}/hermes_exec_{uuid.uuid4().hex[:12]}" - quoted_sandbox_dir = shlex.quote(sandbox_dir) - quoted_rpc_dir = shlex.quote(f"{sandbox_dir}/rpc") - - tool_call_log: list = [] - tool_call_counter = [0] exec_start = time.monotonic() - stop_event = threading.Event() - rpc_thread = None try: - py_check = env.execute( - "command -v python3 >/dev/null 2>&1 && echo OK", - cwd="/", timeout=15, - ) + py_check = env.execute("command -v python3 >/dev/null 2>&1 && echo OK", cwd="/", timeout=15) if "OK" not in py_check.get("output", ""): return json.dumps({ "status": "error", @@ -818,119 +781,23 @@ def _execute_remote( from tools.code_kernel_remote import execute_in_remote_kernel kernel_result = execute_in_remote_kernel( - code, - env=env, - env_type=env_type, - task_env_id=effective_task_id, - sandbox_tools=frozenset(sandbox_tools), - timeout=timeout, - max_tool_calls=max_tool_calls, - reset=bool(reset), + code, env=env, env_type=env_type, task_env_id=effective_task_id, + sandbox_tools=frozenset(sandbox_tools), timeout=timeout, + max_tool_calls=max_tool_calls, reset=bool(reset), idle_exit=int(_cfg.get("kernel_idle_timeout", 1800)), ) except Exception: - logger.warning( - "remote session-kernel path failed; falling back to per-call", - exc_info=True, - ) + logger.warning("remote session-kernel path failed; falling back to per-call", exc_info=True) kernel_result = None if kernel_result is not None: - return _finish_remote_kernel_result( - kernel_result, timeout=timeout, exec_start=exec_start, - ) - logger.info( - "remote session kernel unavailable on %s; using per-call path", - env_type, - ) - - env.execute(f"mkdir -p {quoted_rpc_dir}", cwd="/", timeout=10) - rpc_token = secrets.token_urlsafe(32) - _ship_file_to_remote( - env, f"{sandbox_dir}/hermes_tools.py", - generate_hermes_tools_module(list(sandbox_tools), transport="file"), - ) - _ship_file_to_remote(env, f"{sandbox_dir}/script.py", code) - - # Wrapped so the thread inherits the turn's approval context + callbacks - # (tools.thread_context) — else sandbox RPC tool calls lose approval routing. - rpc_thread = threading.Thread( - target=propagate_context_to_thread(_rpc_poll_loop), - args=( - env, f"{sandbox_dir}/rpc", effective_task_id, - tool_call_log, tool_call_counter, max_tool_calls, - sandbox_tools, stop_event, rpc_token, - ), - daemon=True, - ) - rpc_thread.start() - - env_prefix = ( - f"HERMES_RPC_DIR={shlex.quote(f'{sandbox_dir}/rpc')} " - f"HERMES_RPC_TOKEN={shlex.quote(rpc_token)} " - f"PYTHONDONTWRITEBYTECODE=1" - ) - tz = os.getenv("HERMES_TIMEZONE", "").strip() - if tz: - env_prefix += f" TZ={shlex.quote(tz)}" - - logger.info("Executing code on %s backend (task %s)...", - env_type, effective_task_id[:8]) - script_result = env.execute( - f"cd {quoted_sandbox_dir} && {env_prefix} python3 script.py", - timeout=timeout, - ) - - stdout_text = script_result.get("output", "") or "" - exit_code = script_result.get("returncode", -1) - # Backend exit codes: 124 = timeout wrapper, 130 = SIGINT. - status = _REMOTE_EXIT_STATUS.get(exit_code, "success") - + return _finish_remote_kernel_result(kernel_result, timeout=timeout, exec_start=exec_start) + logger.info("remote session kernel unavailable on %s; using per-call path", env_type) except Exception as exc: - duration = round(time.monotonic() - exec_start, 2) - logger.error( - "execute_code remote failed after %ss with %d tool calls: %s: %s", - duration, tool_call_counter[0], type(exc).__name__, exc, - exc_info=True, - ) - return _error_result(str(exc), tool_calls_made=tool_call_counter[0], duration=duration) + return _remote_failure(exc, exec_start, 0) - finally: - stop_event.set() - if rpc_thread is not None: - rpc_thread.join(timeout=5) - try: - env.execute(f"rm -rf {quoted_sandbox_dir}", cwd="/", timeout=15) - except Exception: - logger.debug("Failed to clean up remote sandbox %s", sandbox_dir) - - duration = round(time.monotonic() - exec_start, 2) - stdout_text, stdout_metadata = _clean_output(stdout_text) - - result: Dict[str, Any] = { - "status": status, - "output": stdout_text, - "exit_code": exit_code, - "tool_calls_made": tool_call_counter[0], - "duration_seconds": duration, - } - result.update(stdout_metadata) - - if status == "timeout": - timeout_msg = f"Script timed out after {timeout}s and was killed." - result["error"] = timeout_msg - result["output"] = _with_timeout_notice(stdout_text, timeout_msg) - logger.warning( - "execute_code (remote) timed out after %ss (limit %ss) with %d tool calls", - duration, timeout, tool_call_counter[0], - ) - elif status == "interrupted": - result["output"] = _format_interrupted_output(stdout_text) - elif exit_code != 0: - result["status"] = "error" - result["error"] = f"Script exited with code {exit_code}" - - return json.dumps(result, ensure_ascii=False) + return _run_remote_per_call(env, env_type, code, effective_task_id, sandbox_tools, + timeout=timeout, max_tool_calls=max_tool_calls, exec_start=exec_start) # --------------------------------------------------------------------------- @@ -1005,10 +872,7 @@ def execute_code( # (tool-executor) thread, which holds the session context. A Docker sandbox # with host bind mounts is not isolated, so it gets no container fast-path. from tools.approval import check_execute_code_guard - _guard = check_execute_code_guard( - code, env_type, - has_host_access=_docker_has_host_access(_env_config), - ) + _guard = check_execute_code_guard(code, env_type, has_host_access=_docker_has_host_access(_env_config)) if not _guard.get("approved", False): return _error_result(_guard.get("message") or "execute_code blocked by approval guard.") @@ -1023,17 +887,12 @@ def execute_code( return _execute_remote(code, task_id, enabled_tools, reset=bool(reset)) from tools.interrupt import is_interrupted as _is_interrupted - - _cfg = _load_config() - timeout = _cfg.get("timeout", DEFAULT_TIMEOUT) - max_tool_calls = _cfg.get("max_tool_calls", DEFAULT_MAX_TOOL_CALLS) - sandbox_tools = _sandbox_tools_for(enabled_tools) - # Session kernels are always on locally: one interpreter per conversation; # the guards above already ran for this cell, and the kernel path reuses the # same env builder, RPC server, and output redaction as the remote path. from tools.code_kernel import execute_in_session_kernel + _cfg = _load_config() _mode = _get_execution_mode() return execute_in_session_kernel( code, @@ -1041,9 +900,9 @@ def execute_code( mode=_mode, child_python=_resolve_child_python(_mode), child_cwd=_resolve_child_cwd(_mode, "", task_id=task_id or ""), - sandbox_tools=frozenset(sandbox_tools), - timeout=timeout, - max_tool_calls=max_tool_calls, + sandbox_tools=frozenset(_sandbox_tools_for(enabled_tools)), + timeout=_cfg.get("timeout", DEFAULT_TIMEOUT), + max_tool_calls=_cfg.get("max_tool_calls", DEFAULT_MAX_TOOL_CALLS), reset=bool(reset), is_interrupted=_is_interrupted, ) @@ -1071,9 +930,7 @@ def _kill_process_group(proc, escalate: bool = False): # sig is ignored on Windows (taskkill /F is already forceful). _tree_signal(getattr(_signal, "SIGTERM", None)) - if escalate: - # Give the process 5s to exit after SIGTERM, then SIGKILL try: proc.wait(timeout=5) except subprocess.TimeoutExpired: @@ -1100,20 +957,11 @@ def _load_config() -> dict: # --------------------------------------------------------------------------- # Canonical code_execution.mode values (referenced by tests and the config layer). +# Session kernels are the only local execution model; a leftover +# code_execution.kernel_mode config key is silently ignored. EXECUTION_MODES = ("project", "strict") DEFAULT_EXECUTION_MODE = "project" -# Session kernels are the only local execution model (tools/code_kernel.py). -# The former code_execution.kernel_mode knob is retired: a leftover config key -# is silently ignored; these symbols remain only for external callers. -KERNEL_MODES = ("per-call", "session") -DEFAULT_KERNEL_MODE = "session" - - -def _get_kernel_mode() -> str: - """Legacy compat shim — session kernels are always on for local runs.""" - return "session" - def _get_execution_mode() -> str: """Active execute_code mode from ``code_execution.mode`` (invalid → default @@ -1173,9 +1021,7 @@ def build_execute_code_schema(enabled_sandbox_tools: set = None, if mode is None: mode = _get_execution_mode() - tool_lines = "\n".join( - doc for name, doc in _TOOL_DOC_LINES if name in enabled_sandbox_tools - ) + tool_lines = "\n".join(doc for name, doc in _TOOL_DOC_LINES if name in enabled_sandbox_tools) import_examples = [n for n in ("web_search", "terminal") if n in enabled_sandbox_tools] if not import_examples: @@ -1257,9 +1103,7 @@ def _execute_code_handler(args: dict, **kwargs) -> str: """Redirect misdirected calls (terminal's ``command`` arg, non-string ``code``) with an actionable error before dispatching to ``execute_code``.""" if "code" not in args and "command" in args: - logger.warning( - "execute_code received 'command' instead of the required 'code' argument" - ) + logger.warning("execute_code received 'command' instead of the required 'code' argument") return tool_error( "execute_code received a 'command' parameter, but it requires " "Python source in 'code'. Use terminal(command=...) for shell " diff --git a/tools/code_kernel.py b/tools/code_kernel.py index c3b9420103..6a1f4a7fd1 100644 --- a/tools/code_kernel.py +++ b/tools/code_kernel.py @@ -3,29 +3,23 @@ One Python child stays alive per (owner, mode, interpreter, cwd, tool-set) and runs one code cell per call, so variables/imports/data survive across calls. -Design constraints, in order: - -- **Same security envelope as per-call**: same ``_build_child_env`` (secret - scrubbing, tool whitelist, PYTHONPATH rules), same ``_rpc_server_loop`` with - the same token and per-cell tool budget, same ANSI strip + secret redaction. - Nothing here widens what a script can reach — only how long it lives. -- **A wedged kernel dies, never hangs the agent.** Timeout or interrupt kills - the whole kernel process tree and drops the registry entry; the next call - spawns fresh. Losing state is deliberate: there is no reliable way to - interrupt one cell in place without leaving the interpreter unknown. -- **The env is frozen at spawn.** Env passthrough registered after the kernel - started is invisible until ``reset=true``; the result payload names the - kernel so this is diagnosable. +Design constraints, in order: (1) the SAME security envelope as per-call — +``_build_child_env`` scrubbing, ``_rpc_server_loop`` with the same token and +per-cell tool budget, the same ANSI strip + secret redaction; nothing here widens +what a script can reach, only how long it lives. (2) A wedged kernel dies, never +hangs the agent: timeout or interrupt kills the whole process tree and drops the +registry entry; losing state is deliberate since one cell cannot be interrupted +in place without leaving the interpreter unknown. (3) The env is frozen at spawn: +passthrough registered later is invisible until ``reset=true`` (the result names +the kernel so this is diagnosable). Wire protocol (host <-> child): requests are one JSON object per stdin line ``{"id", "code"}``; responses are framed on stdout as -`` \\n`` with a per-kernel random SENTINEL from -the environment. Bytes outside frames are raw fd-level output (subprocesses -inherit the real stdout) and are attributed to the running cell — calls are -serialized per kernel, so attribution is unambiguous. Python-level -stdout/stderr are captured via ``contextlib.redirect_*`` into the payload; a -script forging a frame can only fake its own cell result (same trust position -as a per-call script printing a forged success message). +`` \\n`` with a per-kernel random SENTINEL from the +environment. Bytes outside frames are raw fd-level output (subprocesses inherit +the real stdout), attributed to the running cell — calls are serialized per +kernel. A script forging a frame can only fake its own cell result (same trust +position as a per-call script printing a forged success message). Also hosts what ``tools.code_kernel_remote`` shares: owner resolution, the registry lifecycle, and the runner's cell-exec core. @@ -157,11 +151,11 @@ class CellAuthority: """The approval/context identity of exactly one execute_code cell. Interpreter state persists across cells; RPC authority must not. Each cell - installs a fresh authority — captured from the CALLING thread at cell - start, exactly what ``propagate_context_to_thread`` would capture for a - per-call RPC thread — and retires it when the cell settles, so a late tool - call (a background thread the cell left behind, a raced client write) is - refused instead of running under a stale approval/session/turn identity. + installs a fresh authority — captured from the CALLING thread at cell start, + exactly what ``propagate_context_to_thread`` would capture for a per-call RPC + thread — and retires it when the cell settles, so a late tool call (a + background thread the cell left behind, a raced client write) is refused + instead of running under a stale approval/session/turn identity. """ def __init__(self, task_id: str): @@ -261,6 +255,25 @@ class SessionKernel: def alive(self) -> bool: return self.proc is not None and self.proc.poll() is None + def teardown(self) -> None: + self.stop_event.set() + if self.alive(): + from tools.code_execution_tool import _kill_process_group + + _kill_process_group(self.proc, escalate=True) + sock, self.server_sock = self.server_sock, None + try: + if sock is not None: + sock.close() + if self.sock_path: + os.unlink(self.sock_path) + except OSError: + pass + if self.tmpdir: + import shutil + + shutil.rmtree(self.tmpdir, ignore_errors=True) + class KernelRegistry: """Key -> kernel map plus its lock (shared with the remote registry). @@ -274,14 +287,12 @@ class KernelRegistry: self.lock = threading.Lock() self._teardown = teardown - def pop_all(self, owner: Optional[str] = None) -> list: - """Pop every kernel, or every kernel one owner (key[0]) holds.""" - with self.lock: - doomed = [key for key in self.kernels if owner is None or key[0] == owner] - return [self.kernels.pop(key) for key in doomed] - def shutdown(self, owner: Optional[str] = None) -> None: - for kernel in self.pop_all(owner): + """Tear down every kernel, or every kernel one owner (key[0]) holds.""" + with self.lock: + doomed = [self.kernels.pop(key) for key in list(self.kernels) + if owner is None or key[0] == owner] + for kernel in doomed: self._teardown(kernel) def discard(self, key: Tuple, kernel: Any) -> None: @@ -291,9 +302,8 @@ class KernelRegistry: self._teardown(kernel) -_REGISTRY = KernelRegistry(lambda kernel: _teardown(kernel)) +_REGISTRY = KernelRegistry(lambda kernel: kernel.teardown()) _KERNELS: Dict[Tuple, SessionKernel] = _REGISTRY.kernels -_KERNELS_LOCK = _REGISTRY.lock # Bounded lifecycle defaults (config: code_execution.max_session_kernels / # code_execution.kernel_idle_timeout). A long-lived gateway must never @@ -353,65 +363,21 @@ def _resolve_owner(task_id: str) -> str: return owner -def _kernel_key(owner: str, mode: str, child_python: str, child_cwd: str, - sandbox_tools: frozenset) -> Tuple: - return (owner or "", mode, child_python, child_cwd, tuple(sorted(sandbox_tools))) - - def shutdown_all_kernels() -> None: """Kill every session kernel. Registered via atexit; also used by tests.""" _REGISTRY.shutdown() def shutdown_kernels_for_owner(owner: str) -> None: - """Dispose every kernel a session owns. - - Wired into ``tools.approval.clear_session`` so kernels die at the same - session boundary that clears the owner's approval and yolo state - (/new and session close). - """ + """Dispose every kernel a session owns — wired into ``tools.approval.clear_session`` + so kernels die at the same boundary that clears approval/yolo state (/new, session close).""" if owner: _REGISTRY.shutdown(owner) -def _reap_unlocked() -> List[SessionKernel]: - """Pop idle-expired kernels; caller tears them down outside the lock.""" - _, idle_timeout = _lifecycle_limits() - now = time.monotonic() - doomed = [key for key, kernel in _KERNELS.items() if now - kernel.last_used > idle_timeout] - return [_KERNELS.pop(key) for key in doomed] - - -def _evict_over_cap_unlocked(keep: Tuple) -> List[SessionKernel]: - """Pop least-recently-used kernels beyond the process-wide cap.""" - cap, _ = _lifecycle_limits() - by_age = sorted((key for key in _KERNELS if key != keep), key=lambda key: _KERNELS[key].last_used) - return [_KERNELS.pop(key) for key in by_age[: max(0, len(_KERNELS) - cap)]] - - atexit.register(shutdown_all_kernels) -def _teardown(kernel: SessionKernel) -> None: - kernel.stop_event.set() - if kernel.proc is not None and kernel.proc.poll() is None: - from tools.code_execution_tool import _kill_process_group - - _kill_process_group(kernel.proc, escalate=True) - sock, kernel.server_sock = kernel.server_sock, None - try: - if sock is not None: - sock.close() - if kernel.sock_path: - os.unlink(kernel.sock_path) - except OSError: - pass - if kernel.tmpdir: - import shutil - - shutil.rmtree(kernel.tmpdir, ignore_errors=True) - - def _rpc_forever(kernel: SessionKernel, max_tool_calls: int, sandbox_tools: frozenset) -> None: """Serve tool RPC for the kernel's whole life. @@ -429,10 +395,8 @@ def _rpc_forever(kernel: SessionKernel, max_tool_calls: int, def _dispatch(tool_name: str, tool_args: dict) -> str: authority = kernel.cell_authority if authority is None: - return tool_error( - "No active execute_code cell: this kernel has no cell " - "authority installed." - ) + return tool_error("No active execute_code cell: this kernel has no cell " + "authority installed.") return authority.dispatch(tool_name, tool_args) while not kernel.stop_event.is_set(): @@ -551,9 +515,8 @@ def _spawn(kernel: SessionKernel, *, child_python: str, child_cwd: str, child_env = _build_child_env(rpc_endpoint=rpc_endpoint, rpc_token=kernel.rpc_token, tmpdir=kernel.tmpdir, child_python=child_python) child_env["HERMES_KERNEL_SENTINEL"] = kernel.sentinel - # Cells clip stdout to the inline cap; the full text spills to the - # kernel's own tmpdir so the agent can read_file the middle instead of - # re-running (host surfaces the path in the result). + # Cells clip stdout to the inline cap; the full text spills to the kernel's + # own tmpdir so the agent can read_file the middle instead of re-running. child_env["HERMES_KERNEL_SPILL_DIR"] = kernel.tmpdir # Tell the generated client to reconnect after the RPC server's idle # timeout — a kernel outlives the 300s window between cells. @@ -580,25 +543,26 @@ def _spawn(kernel: SessionKernel, *, child_python: str, child_cwd: str, def _acquire_kernel(key: Tuple, reset: bool) -> Tuple[SessionKernel, bool]: """Look up or register the kernel for *key*; returns (kernel, state_reset). - Every entry also sweeps idle-expired kernels and enforces the - process-wide cap, so a long-lived host stays bounded even for owners - that never toggle or reset. + Every entry also sweeps idle-expired kernels and enforces the process-wide + LRU cap, so a long-lived host stays bounded even for owners that never + toggle or reset. Doomed kernels are popped under the lock, torn down outside it. """ - with _KERNELS_LOCK: - expired = _reap_unlocked() + cap, idle_timeout = _lifecycle_limits() + with _REGISTRY.lock: + now = time.monotonic() + expired = [_KERNELS.pop(k) for k in list(_KERNELS) if now - _KERNELS[k].last_used > idle_timeout] kernel = _KERNELS.get(key) state_reset = kernel is not None and (reset or not kernel.alive()) if state_reset: - _KERNELS.pop(key, None) - expired.append(kernel) + expired.append(_KERNELS.pop(key)) kernel = None if kernel is None: - kernel = SessionKernel(key) - _KERNELS[key] = kernel + kernel = _KERNELS[key] = SessionKernel(key) kernel.last_used = time.monotonic() - expired.extend(_evict_over_cap_unlocked(keep=key)) + by_age = sorted((k for k in _KERNELS if k != key), key=lambda k: _KERNELS[k].last_used) + expired.extend(_KERNELS.pop(k) for k in by_age[: max(0, len(_KERNELS) - cap)]) for doomed in expired: - _teardown(doomed) + doomed.teardown() return kernel, state_reset @@ -705,19 +669,19 @@ def execute_in_session_kernel( ) -> str: """Run one cell in the (owner, mode, python, cwd, tools) session kernel. - The owner is the conversation's session key (``_resolve_owner``), not - the per-turn task id, so state genuinely survives across user turns of - one conversation and dies with the session. + The owner is the conversation's session key (``_resolve_owner``), not the + per-turn task id, so state survives across user turns of one conversation + and dies with the session. """ - key = _kernel_key(_resolve_owner(task_id), mode, child_python, child_cwd, sandbox_tools) + key = (_resolve_owner(task_id) or "", mode, child_python, child_cwd, tuple(sorted(sandbox_tools))) exec_start = time.monotonic() kernel, state_reset = _acquire_kernel(key, reset) reused = kernel.proc is not None - # Captured on the calling thread BEFORE the cell runs — the same - # snapshot a per-call RPC thread would have received — and installed - # atomically on the kernel so the serving thread dispatches this cell's - # tool calls under this cell's approval/session/turn identity. + # Captured on the calling thread BEFORE the cell runs — the same snapshot a + # per-call RPC thread would have received — and installed atomically on the + # kernel so the serving thread dispatches this cell's tool calls under this + # cell's approval/session/turn identity. authority = CellAuthority(task_id) with kernel.lock: @@ -735,8 +699,7 @@ def execute_in_session_kernel( kernel.stderr.drain() kernel.cell_authority = authority - request = json.dumps({"id": uuid.uuid4().hex, "code": code}) + "\n" - kernel.proc.stdin.write(request.encode("utf-8")) + kernel.proc.stdin.write((json.dumps({"id": uuid.uuid4().hex, "code": code}) + "\n").encode("utf-8")) kernel.proc.stdin.flush() status, payload = _await_cell(kernel, timeout, is_interrupted) @@ -755,7 +718,7 @@ def execute_in_session_kernel( "duration_seconds": round(time.monotonic() - exec_start, 2), }, ensure_ascii=False) finally: - # The cell has settled on every path (success, exception, - # timeout, exit, kernel death): its tool authority retires with - # it, so nothing the cell left running can dispatch under it. + # The cell has settled on every path (success, exception, timeout, + # exit, kernel death): its tool authority retires with it, so + # nothing the cell left running can dispatch under it. authority.retire() diff --git a/tools/code_kernel_remote.py b/tools/code_kernel_remote.py index 3af6cae732..ed26e8427d 100644 --- a/tools/code_kernel_remote.py +++ b/tools/code_kernel_remote.py @@ -2,29 +2,25 @@ Remote backends offer one primitive — ``env.execute(cmd)``, run-to-completion — so the three things the local kernel gets from owning a child are rebuilt: - -1. **A process outliving one env.execute():** the runner starts detached - (``nohup ... &``) with its PID recorded; each cell first probes ``kill -0``. -2. **A conversation channel:** a file-based CELL protocol in the kernel dir - (``cell_req_NNNNNN.json`` / ``cell_res_NNNNNN.json``), sibling to the - file-based TOOL-RPC protocol (req_/res_) reused unchanged — the host-side - ``_rpc_poll_loop`` starts per cell with the calling thread's context, which - is what gives per-cell tool authority. -3. **Death detection:** a failed liveness probe (transport drop, container - restart, OOM-killed runner) reads as *kernel died: state lost*; the next - call respawns and says so — never a hung poll, every wait is bounded by - the cell timeout. +a detached runner (``nohup ... &``, PID recorded, ``kill -0`` probed per cell); +a file-based CELL protocol in the kernel dir (``cell_req_NNNNNN.json`` / +``cell_res_NNNNNN.json``), sibling to the unchanged file-based TOOL-RPC protocol +(req_/res_) whose host-side ``_rpc_poll_loop`` starts per cell with the calling +thread's context (= per-cell tool authority); and death detection — a failed +liveness probe reads as *kernel died: state lost* and the next call respawns, +never a hung poll (every wait is bounded by the cell timeout). Same invariants as local: owner = approval session key with the ``::child::`` -qualifier (one resolver in tools.code_kernel, cannot drift), same generated -tool stubs, same output post-processing in the caller. ``reset=true`` kills -and respawns. Spawn failure fails OPEN to the per-call path with a note. +qualifier (one resolver in tools.code_kernel), same generated tool stubs, same +output post-processing in the caller. ``reset=true`` kills and respawns. Spawn +failure fails OPEN to the per-call path with a note. """ from __future__ import annotations import atexit import json import logging +import secrets import shlex import threading import time @@ -101,6 +97,12 @@ if __name__ == "__main__": ''' +def _sh(env, cmd: str, timeout: int = 15) -> str: + """Run *cmd* on the remote from ``/`` and return its output text.""" + result = env.execute(cmd, cwd="/", timeout=timeout) + return (result.get("output", "") if isinstance(result, dict) else "") or "" + + @dataclass class RemoteKernel: """Host-side record of one detached remote kernel process.""" @@ -111,7 +113,6 @@ class RemoteKernel: pid: str rpc_token: str owner: str - created: float = field(default_factory=time.monotonic) last_used: float = field(default_factory=time.monotonic) execution_count: int = 0 cell_seq: int = 0 @@ -119,50 +120,37 @@ class RemoteKernel: def sh(self, cmd: str, timeout: int = 15) -> str: return _sh(self.env, cmd, timeout) + def is_alive(self) -> bool: + """Bounded liveness probe: kill -0 through the transport. Any transport + failure counts as dead — a dropped ssh connection and a dead runner are + indistinguishable from here, and both have the same correct answer (respawn).""" + try: + return "ALIVE" in self.sh(f"kill -0 {shlex.quote(self.pid)} 2>/dev/null && echo ALIVE") + except Exception: + return False -def _sh(env, cmd: str, timeout: int = 15) -> str: - """Run *cmd* on the remote from ``/`` and return its output text.""" - result = env.execute(cmd, cwd="/", timeout=timeout) - return (result.get("output", "") if isinstance(result, dict) else "") or "" + def kill(self) -> None: + """Best-effort kill of the runner and its subprocesses, then rm -rf.""" + q_pid = shlex.quote(self.pid) + for cmd, failure in ( + # Kill the runner's children if the shell gave it a group, then the PID itself. + (f"pkill -TERM -P {q_pid} 2>/dev/null; kill {q_pid} 2>/dev/null; true", + "remote kernel kill failed (transport?)"), + (f"rm -rf {shlex.quote(self.kernel_dir)}", "remote kernel dir cleanup failed"), + ): + try: + self.sh(cmd) + except Exception: + logger.debug(failure, exc_info=True) def _kernel_key(owner: str, env_type: str, task_env_id: str) -> Tuple: return (owner, "remote", env_type, task_env_id) -def _is_alive(kernel: RemoteKernel) -> bool: - """Bounded liveness probe: kill -0 through the transport. - - Any transport failure counts as dead — the caller respawns. A dropped ssh - connection and a dead runner are indistinguishable from here, and both - have the same correct answer. - """ - try: - return "ALIVE" in kernel.sh(f"kill -0 {shlex.quote(kernel.pid)} 2>/dev/null && echo ALIVE") - except Exception: - return False - - -def _kill(kernel: RemoteKernel) -> None: - """Best-effort kill of the runner and its subprocesses, then rm -rf.""" - q_pid = shlex.quote(kernel.pid) - steps = ( - # Kill the runner's children if the shell gave it a group, then the PID itself. - (f"pkill -TERM -P {q_pid} 2>/dev/null; kill {q_pid} 2>/dev/null; true", - "remote kernel kill failed (transport?)"), - (f"rm -rf {shlex.quote(kernel.kernel_dir)}", "remote kernel dir cleanup failed"), - ) - for cmd, failure in steps: - try: - kernel.sh(cmd) - except Exception: - logger.debug(failure, exc_info=True) - - # Registry + lock shared-shape with code_kernel; teardown runs outside the lock. -_REGISTRY = KernelRegistry(lambda kernel: _kill(kernel)) +_REGISTRY = KernelRegistry(lambda kernel: kernel.kill()) _REMOTE_KERNELS: Dict[Tuple, RemoteKernel] = _REGISTRY.kernels -_REMOTE_KERNELS_LOCK = _REGISTRY.lock def shutdown_all_remote_kernels() -> None: @@ -181,25 +169,19 @@ atexit.register(shutdown_all_remote_kernels) def _spawn_remote_kernel(env, env_type: str, owner: str, task_env_id: str, sandbox_tools: frozenset, *, idle_exit: int) -> Optional[RemoteKernel]: - """Start a detached kernel runner on the remote. None on failure.""" + """Start a detached kernel runner on the remote. None on failure (dir removed).""" from tools.code_execution_tool import ( MAX_STDOUT_BYTES, _ship_file_to_remote, _env_temp_dir, generate_hermes_tools_module, ) - import secrets as _secrets kernel_dir = f"{_env_temp_dir(env)}/hermes_rkernel_{uuid.uuid4().hex[:12]}" q_dir = shlex.quote(kernel_dir) - - def sh(cmd: str, timeout: int = 15) -> str: - return _sh(env, cmd, timeout) - - def start() -> Optional[RemoteKernel]: - sh(f"mkdir -p {q_dir}/cells {q_dir}/rpc") - - rpc_token = _secrets.token_urlsafe(32) - runner_src = REMOTE_KERNEL_RUNNER_SOURCE.format( - cell_source=RUNNER_CELL_SOURCE, capture_limit=MAX_STDOUT_BYTES, idle_exit=idle_exit) - _ship_file_to_remote(env, f"{kernel_dir}/kernel_runner.py", runner_src) + kernel = None + try: + _sh(env, f"mkdir -p {q_dir}/cells {q_dir}/rpc") + rpc_token = secrets.token_urlsafe(32) + _ship_file_to_remote(env, f"{kernel_dir}/kernel_runner.py", REMOTE_KERNEL_RUNNER_SOURCE.format( + cell_source=RUNNER_CELL_SOURCE, capture_limit=MAX_STDOUT_BYTES, idle_exit=idle_exit)) _ship_file_to_remote(env, f"{kernel_dir}/hermes_tools.py", generate_hermes_tools_module(list(sandbox_tools), transport="file")) @@ -209,34 +191,30 @@ def _spawn_remote_kernel(env, env_type: str, owner: str, task_env_id: str, f"HERMES_RPC_TOKEN={shlex.quote(rpc_token)} " f"PYTHONDONTWRITEBYTECODE=1 PYTHONPATH={q_dir}" ) - started = sh(f"cd {q_dir} && nohup env {env_prefix} python3 kernel_runner.py " - f"> {q_dir}/runner.log 2>&1 & echo PID:$!", timeout=20) + started = _sh(env, f"cd {q_dir} && nohup env {env_prefix} python3 kernel_runner.py " + f"> {q_dir}/runner.log 2>&1 & echo PID:$!", timeout=20) pid = next((line.strip()[4:].strip() for line in started.splitlines() if line.strip().startswith("PID:")), "") if not pid.isdigit(): logger.warning("remote kernel spawn returned no PID: %r", started) - return None - kernel = RemoteKernel(env=env, env_type=env_type, kernel_dir=kernel_dir, - pid=pid, rpc_token=rpc_token, owner=owner) - if not _is_alive(kernel): - # Died instantly (missing python3 was pre-checked by the caller, - # so this is unexpected) — surface the runner log. - try: - logger.warning("remote kernel died at spawn: %s", - sh(f"cat {q_dir}/runner.log", timeout=10)[:500]) - except Exception: - pass - return None - return kernel - - kernel = None - try: - kernel = start() + else: + candidate = RemoteKernel(env=env, env_type=env_type, kernel_dir=kernel_dir, + pid=pid, rpc_token=rpc_token, owner=owner) + if candidate.is_alive(): + kernel = candidate + else: + # Died instantly (missing python3 was pre-checked by the caller, + # so this is unexpected) — surface the runner log. + try: + logger.warning("remote kernel died at spawn: %s", + _sh(env, f"cat {q_dir}/runner.log", timeout=10)[:500]) + except Exception: + pass except Exception: logger.warning("remote kernel spawn failed", exc_info=True) if kernel is None: try: - sh(f"rm -rf {q_dir}") + _sh(env, f"rm -rf {q_dir}") except Exception: pass return kernel @@ -249,25 +227,24 @@ def _acquire_remote_kernel(env, env_type: str, owner: str, task_env_id: str, key = _kernel_key(owner, env_type, task_env_id) state_lost = state_reset = False - with _REMOTE_KERNELS_LOCK: + with _REGISTRY.lock: kernel = _REMOTE_KERNELS.get(key) if kernel is not None and reset: _REGISTRY.discard(key, kernel) kernel, state_reset = None, True - if kernel is not None and not _is_alive(kernel): + if kernel is not None and not kernel.is_alive(): # Transport drop, container restart, self-reaped on idle, OOM — all - # the same answer: report the loss, respawn fresh (_kill is then only + # the same answer: report the loss, respawn fresh (kill is then only # best-effort dir cleanup; the process is already gone). _REGISTRY.discard(key, kernel) kernel, state_lost = None, True reused = kernel is not None if kernel is None: - kernel = _spawn_remote_kernel(env, env_type, owner, task_env_id, sandbox_tools, - idle_exit=idle_exit) + kernel = _spawn_remote_kernel(env, env_type, owner, task_env_id, sandbox_tools, idle_exit=idle_exit) if kernel is not None: - with _REMOTE_KERNELS_LOCK: + with _REGISTRY.lock: _REMOTE_KERNELS[key] = kernel return kernel, reused, state_reset, state_lost @@ -279,26 +256,25 @@ def _run_remote_cell(kernel: RemoteKernel, code: str, timeout: int) -> Tuple[str kernel.cell_seq += 1 seq = f"{kernel.cell_seq:06d}" q_cells = shlex.quote(f"{kernel.kernel_dir}/cells") - res_name = f"cell_res_{seq}.json" - request = json.dumps({"id": seq, "code": code}, ensure_ascii=False) - _ship_file_to_remote(kernel.env, f"{kernel.kernel_dir}/cells/cell_req_{seq}.json.tmp", request) + q_res = shlex.quote(f"cell_res_{seq}.json") + _ship_file_to_remote(kernel.env, f"{kernel.kernel_dir}/cells/cell_req_{seq}.json.tmp", + json.dumps({"id": seq, "code": code}, ensure_ascii=False)) kernel.sh(f"mv {q_cells}/cell_req_{seq}.json.tmp {q_cells}/cell_req_{seq}.json", timeout=10) deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: - body = kernel.sh(f"cat {q_cells}/{shlex.quote(res_name)} 2>/dev/null", timeout=20).strip() + body = kernel.sh(f"cat {q_cells}/{q_res} 2>/dev/null", timeout=20).strip() except Exception: # One flaky round-trip is not kernel death; liveness decides. - time.sleep(_CELL_POLL_INTERVAL) - continue + body = "" if body: try: payload = json.loads(body) status = payload.get("status", "error") except ValueError: payload, status = {}, "protocol-error" - kernel.sh(f"rm -f {q_cells}/{shlex.quote(res_name)}", timeout=10) + kernel.sh(f"rm -f {q_cells}/{q_res}", timeout=10) return status, payload time.sleep(_CELL_POLL_INTERVAL) return "timeout", {}