refactor(exec): centralize process-tree lifecycle (#6623)
Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
c37af82e3f
commit
8607b6445c
16 files changed
+356
-534
No files matched your search
@@ -1,216 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
_CREATE_SUSPENDED = 0x00000004
|
||||
_PROCESS_SET_QUOTA = 0x0100
|
||||
_PROCESS_TERMINATE = 0x0001
|
||||
_TH32CS_SNAPTHREAD = 0x00000004
|
||||
_THREAD_SUSPEND_RESUME = 0x0002
|
||||
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
|
||||
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
|
||||
_INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
|
||||
|
||||
|
||||
class _IoCounters(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("ReadOperationCount", ctypes.c_ulonglong),
|
||||
("WriteOperationCount", ctypes.c_ulonglong),
|
||||
("OtherOperationCount", ctypes.c_ulonglong),
|
||||
("ReadTransferCount", ctypes.c_ulonglong),
|
||||
("WriteTransferCount", ctypes.c_ulonglong),
|
||||
("OtherTransferCount", ctypes.c_ulonglong),
|
||||
]
|
||||
|
||||
|
||||
class _BasicLimitInformation(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("PerProcessUserTimeLimit", ctypes.c_longlong),
|
||||
("PerJobUserTimeLimit", ctypes.c_longlong),
|
||||
("LimitFlags", wintypes.DWORD),
|
||||
("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t),
|
||||
("ActiveProcessLimit", wintypes.DWORD),
|
||||
("Affinity", ctypes.c_size_t),
|
||||
("PriorityClass", wintypes.DWORD),
|
||||
("SchedulingClass", wintypes.DWORD),
|
||||
]
|
||||
|
||||
|
||||
class _ExtendedLimitInformation(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("BasicLimitInformation", _BasicLimitInformation),
|
||||
("IoInfo", _IoCounters),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t),
|
||||
("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
||||
("PeakJobMemoryUsed", ctypes.c_size_t),
|
||||
]
|
||||
|
||||
|
||||
class _ThreadEntry32(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("dwSize", wintypes.DWORD),
|
||||
("cntUsage", wintypes.DWORD),
|
||||
("th32ThreadID", wintypes.DWORD),
|
||||
("th32OwnerProcessID", wintypes.DWORD),
|
||||
("tpBasePri", wintypes.LONG),
|
||||
("tpDeltaPri", wintypes.LONG),
|
||||
("dwFlags", wintypes.DWORD),
|
||||
]
|
||||
|
||||
|
||||
_kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
_kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
|
||||
_kernel32.CreateJobObjectW.restype = wintypes.HANDLE
|
||||
_kernel32.SetInformationJobObject.argtypes = [
|
||||
wintypes.HANDLE,
|
||||
ctypes.c_int,
|
||||
ctypes.c_void_p,
|
||||
wintypes.DWORD,
|
||||
]
|
||||
_kernel32.SetInformationJobObject.restype = wintypes.BOOL
|
||||
_kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
_kernel32.OpenProcess.restype = wintypes.HANDLE
|
||||
_kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
||||
_kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
|
||||
_kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
|
||||
_kernel32.TerminateProcess.restype = wintypes.BOOL
|
||||
_kernel32.TerminateJobObject.argtypes = [wintypes.HANDLE, wintypes.UINT]
|
||||
_kernel32.TerminateJobObject.restype = wintypes.BOOL
|
||||
_kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
|
||||
_kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
|
||||
_kernel32.Thread32First.argtypes = [wintypes.HANDLE, ctypes.POINTER(_ThreadEntry32)]
|
||||
_kernel32.Thread32First.restype = wintypes.BOOL
|
||||
_kernel32.Thread32Next.argtypes = [wintypes.HANDLE, ctypes.POINTER(_ThreadEntry32)]
|
||||
_kernel32.Thread32Next.restype = wintypes.BOOL
|
||||
_kernel32.OpenThread.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
_kernel32.OpenThread.restype = wintypes.HANDLE
|
||||
_kernel32.ResumeThread.argtypes = [wintypes.HANDLE]
|
||||
_kernel32.ResumeThread.restype = wintypes.DWORD
|
||||
_kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
_kernel32.CloseHandle.restype = wintypes.BOOL
|
||||
|
||||
|
||||
def _win_error(operation: str) -> OSError:
|
||||
code = ctypes.get_last_error()
|
||||
return OSError(code, f"{operation} failed (Windows error {code})")
|
||||
|
||||
|
||||
def _close_handle(handle: int | None) -> None:
|
||||
if handle:
|
||||
_kernel32.CloseHandle(handle)
|
||||
|
||||
|
||||
def _set_kill_on_close(handle: int, enabled: bool) -> None:
|
||||
info = _ExtendedLimitInformation()
|
||||
if enabled:
|
||||
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if not _kernel32.SetInformationJobObject(
|
||||
handle,
|
||||
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
ctypes.byref(info),
|
||||
ctypes.sizeof(info),
|
||||
):
|
||||
raise _win_error("SetInformationJobObject")
|
||||
|
||||
|
||||
def _resume_primary_thread(pid: int) -> None:
|
||||
snapshot = _kernel32.CreateToolhelp32Snapshot(_TH32CS_SNAPTHREAD, 0)
|
||||
if snapshot == _INVALID_HANDLE_VALUE:
|
||||
raise _win_error("CreateToolhelp32Snapshot")
|
||||
try:
|
||||
entry = _ThreadEntry32()
|
||||
entry.dwSize = ctypes.sizeof(entry)
|
||||
found = _kernel32.Thread32First(snapshot, ctypes.byref(entry))
|
||||
while found:
|
||||
if entry.th32OwnerProcessID == pid:
|
||||
thread = _kernel32.OpenThread(
|
||||
_THREAD_SUSPEND_RESUME,
|
||||
False,
|
||||
entry.th32ThreadID,
|
||||
)
|
||||
if not thread:
|
||||
raise _win_error("OpenThread")
|
||||
try:
|
||||
if _kernel32.ResumeThread(thread) == 0xFFFFFFFF:
|
||||
raise _win_error("ResumeThread")
|
||||
return
|
||||
finally:
|
||||
_close_handle(thread)
|
||||
found = _kernel32.Thread32Next(snapshot, ctypes.byref(entry))
|
||||
raise RuntimeError(f"suspended process {pid} has no resumable thread")
|
||||
finally:
|
||||
_close_handle(snapshot)
|
||||
|
||||
|
||||
class WindowsJob:
|
||||
"""Own a process tree even after its root process exits."""
|
||||
|
||||
creation_flags = _CREATE_SUSPENDED
|
||||
|
||||
def __init__(self, handle: int) -> None:
|
||||
self._handle: int | None = handle
|
||||
|
||||
@classmethod
|
||||
def create(cls) -> WindowsJob:
|
||||
handle = _kernel32.CreateJobObjectW(None, None)
|
||||
if not handle:
|
||||
raise _win_error("CreateJobObjectW")
|
||||
try:
|
||||
_set_kill_on_close(handle, True)
|
||||
except Exception:
|
||||
_close_handle(handle)
|
||||
raise
|
||||
return cls(handle)
|
||||
|
||||
def assign_and_resume(self, pid: int) -> None:
|
||||
"""Atomically establish tree ownership before the root can spawn."""
|
||||
if self._handle is None:
|
||||
raise RuntimeError("Windows job is already closed")
|
||||
process = _kernel32.OpenProcess(
|
||||
_PROCESS_SET_QUOTA | _PROCESS_TERMINATE,
|
||||
False,
|
||||
pid,
|
||||
)
|
||||
if not process:
|
||||
error = _win_error("OpenProcess")
|
||||
self.close()
|
||||
raise error
|
||||
|
||||
if not _kernel32.AssignProcessToJobObject(self._handle, process):
|
||||
error = _win_error("AssignProcessToJobObject")
|
||||
_kernel32.TerminateProcess(process, 1)
|
||||
_close_handle(process)
|
||||
self.close()
|
||||
raise error
|
||||
|
||||
try:
|
||||
_resume_primary_thread(pid)
|
||||
except Exception:
|
||||
self.terminate()
|
||||
raise
|
||||
finally:
|
||||
_close_handle(process)
|
||||
|
||||
def release(self) -> None:
|
||||
"""Release ownership after successful output collection."""
|
||||
if self._handle is None:
|
||||
return
|
||||
_set_kill_on_close(self._handle, False)
|
||||
self.close()
|
||||
|
||||
def terminate(self) -> None:
|
||||
"""Terminate every process in the job and close its handle."""
|
||||
if self._handle is None:
|
||||
return
|
||||
try:
|
||||
_kernel32.TerminateJobObject(self._handle, 1)
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def close(self) -> None:
|
||||
handle = self._handle
|
||||
self._handle = None
|
||||
_close_handle(handle)
|
||||
@@ -26,6 +26,7 @@ from nanobot.agent.tools.schema import (
|
||||
)
|
||||
from nanobot.agent.tools.shell_config import ExecToolConfig
|
||||
from nanobot.agent.tools.shell_output import ShellOutputFilter
|
||||
from nanobot.execution import processes
|
||||
|
||||
DEFAULT_YIELD_MS = 1000
|
||||
MAX_YIELD_MS = 30_000
|
||||
@@ -151,22 +152,21 @@ class _ExecSession:
|
||||
self,
|
||||
*,
|
||||
session_id: str,
|
||||
process: asyncio.subprocess.Process,
|
||||
process_tree: processes.ProcessTree,
|
||||
command: str,
|
||||
cwd: str,
|
||||
timeout: int | None,
|
||||
owner_session_key: str | None = None,
|
||||
process_tree: bool = False,
|
||||
idle_timeout: int = 300,
|
||||
idle_action: Literal["report", "terminate"] = "report",
|
||||
started_at: float | None = None,
|
||||
) -> None:
|
||||
self.session_id = session_id
|
||||
self.process = process
|
||||
self._process_tree = process_tree
|
||||
process = process_tree.process
|
||||
self.command = command
|
||||
self.cwd = cwd
|
||||
self.owner_session_key = owner_session_key
|
||||
self._process_tree = process_tree
|
||||
self.started_at = time.monotonic() if started_at is None else started_at
|
||||
self.deadline = self.started_at + timeout if timeout else float("inf")
|
||||
self.last_output_at: float | None = None
|
||||
@@ -196,6 +196,10 @@ class _ExecSession:
|
||||
if self._timeout_task is not None:
|
||||
self._timeout_task.add_done_callback(self._on_supervisor_done)
|
||||
|
||||
@property
|
||||
def process(self) -> asyncio.subprocess.Process:
|
||||
return self._process_tree.process
|
||||
|
||||
@property
|
||||
def stopping(self) -> bool:
|
||||
return self._stop_reason is not None and self.finished_at is None
|
||||
@@ -236,13 +240,7 @@ class _ExecSession:
|
||||
finally:
|
||||
stopped.cancel()
|
||||
await asyncio.gather(stopped, return_exceptions=True)
|
||||
from nanobot.agent.tools.shell import (
|
||||
ExecTool,
|
||||
_reap_pid, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
|
||||
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
|
||||
_reap_pid(self.process.pid)
|
||||
self._process_tree.finish()
|
||||
self.finish_reason = self._stop_reason or "exit"
|
||||
self.finished_at = time.monotonic()
|
||||
self._state_changed.set()
|
||||
@@ -410,12 +408,7 @@ class _ExecSession:
|
||||
# kill() replaces it on an explicit retry.
|
||||
|
||||
async def _kill(self) -> None:
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
|
||||
if self._process_tree:
|
||||
await ExecTool._kill_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
|
||||
else:
|
||||
await ExecTool._kill_process(self.process) # pyright: ignore[reportPrivateUsage]
|
||||
await self._process_tree.terminate()
|
||||
self._stop_complete.set()
|
||||
|
||||
|
||||
@@ -503,12 +496,14 @@ class ExecSessionManager:
|
||||
session: _ExecSession | None = None
|
||||
try:
|
||||
started_at = time.monotonic()
|
||||
process = await self._spawn(command, cwd, env, shell_program, login, stdin=stdin)
|
||||
process_tree = await processes.spawn_process_tree(
|
||||
command, cwd, env, shell_program, login, stdin=stdin,
|
||||
)
|
||||
session = _ExecSession(
|
||||
session_id=session_id, process=process,
|
||||
session_id=session_id, process_tree=process_tree,
|
||||
command=shlex.join(command) if isinstance(command, list) else command,
|
||||
cwd=cwd, timeout=timeout, owner_session_key=owner_session_key,
|
||||
process_tree=True, idle_timeout=idle_timeout, idle_action=idle_action,
|
||||
idle_timeout=idle_timeout, idle_action=idle_action,
|
||||
started_at=started_at,
|
||||
)
|
||||
async with self._lock:
|
||||
@@ -669,24 +664,6 @@ class ExecSessionManager:
|
||||
for session_id in stale:
|
||||
self._sessions.pop(session_id)
|
||||
|
||||
async def _spawn(
|
||||
self,
|
||||
command: str | list[str],
|
||||
cwd: str,
|
||||
env: dict[str, str],
|
||||
shell_program: str | None,
|
||||
login: bool,
|
||||
*,
|
||||
stdin: int = asyncio.subprocess.PIPE,
|
||||
) -> asyncio.subprocess.Process:
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
|
||||
return await ExecTool._spawn( # pyright: ignore[reportPrivateUsage]
|
||||
command, cwd, env, shell_program, login,
|
||||
stdin=stdin,
|
||||
process_tree=True,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_EXEC_SESSION_MANAGER = ExecSessionManager()
|
||||
|
||||
|
||||
@@ -5,13 +5,11 @@ import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path, PureWindowsPath
|
||||
from typing import Any, Literal, Protocol, cast
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from urllib.parse import unquote
|
||||
|
||||
from loguru import logger
|
||||
@@ -42,41 +40,6 @@ from nanobot.security.workspace_access import current_scope_allows_loopback, cur
|
||||
from nanobot.security.workspace_policy import is_path_within
|
||||
|
||||
_IS_WINDOWS = sys.platform == "win32"
|
||||
_PROCESS_TREE_OWNER_ATTR = "_nanobot_process_tree_owner"
|
||||
|
||||
|
||||
class _ProcessTreeOwner(Protocol):
|
||||
creation_flags: int
|
||||
|
||||
def assign_and_resume(self, pid: int) -> None: ...
|
||||
|
||||
def release(self) -> None: ...
|
||||
|
||||
def terminate(self) -> None: ...
|
||||
|
||||
|
||||
def _reap_pid(pid: int) -> None:
|
||||
"""Best-effort ``waitpid`` to reap a child and prevent zombies.
|
||||
|
||||
Call this after killing or after normal completion of any subprocess
|
||||
as a safety net — asyncio's child-watcher *should* have reaped it,
|
||||
but in containers / edge-cases it sometimes doesn't.
|
||||
|
||||
Uses ``os`` capability checks rather than ``_IS_WINDOWS`` so this is
|
||||
safe when tests patch the platform flag while still running on Windows
|
||||
(``os.waitpid`` / ``os.WNOHANG`` do not exist there).
|
||||
"""
|
||||
waitpid = getattr(os, "waitpid", None)
|
||||
wnohang = getattr(os, "WNOHANG", None)
|
||||
if waitpid is None or wnohang is None:
|
||||
return
|
||||
try:
|
||||
waitpid(pid, wnohang)
|
||||
except (ProcessLookupError, ChildProcessError):
|
||||
# Already reaped, or not our child — both are fine.
|
||||
pass
|
||||
except OSError as exc:
|
||||
logger.debug("_reap_pid({}): {}", pid, exc)
|
||||
|
||||
|
||||
_WORKSPACE_BOUNDARY_NOTE = (
|
||||
@@ -528,146 +491,6 @@ class ExecTool(Tool):
|
||||
path_expr = os.pathsep.join(segments)
|
||||
return f'export PATH="{path_expr}"; {command}'
|
||||
|
||||
@staticmethod
|
||||
async def _spawn(
|
||||
command: str | list[str], cwd: str, env: dict[str, str],
|
||||
shell_program: str | None = None,
|
||||
login: bool = False,
|
||||
*,
|
||||
stdin: int = asyncio.subprocess.DEVNULL,
|
||||
process_tree: bool = False,
|
||||
) -> asyncio.subprocess.Process:
|
||||
"""Launch an argument vector directly or a command string through a shell."""
|
||||
if isinstance(command, list):
|
||||
executable = shutil.which(command[0], path=env.get("PATH", ""))
|
||||
if executable is None:
|
||||
raise FileNotFoundError(f"Executable not found: {command[0]}")
|
||||
windows_job = None
|
||||
process = None
|
||||
try:
|
||||
if process_tree and sys.platform == "win32":
|
||||
windows_job = ExecTool._create_windows_job()
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
executable, *command[1:],
|
||||
stdin=stdin,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
creationflags=windows_job.creation_flags if windows_job else 0,
|
||||
start_new_session=process_tree and sys.platform != "win32",
|
||||
)
|
||||
if windows_job is not None:
|
||||
windows_job.assign_and_resume(process.pid)
|
||||
setattr(process, _PROCESS_TREE_OWNER_ATTR, windows_job)
|
||||
return process
|
||||
except BaseException:
|
||||
if windows_job is not None:
|
||||
windows_job.terminate()
|
||||
if process is not None:
|
||||
await ExecTool._kill_process(process)
|
||||
raise
|
||||
if _IS_WINDOWS:
|
||||
windows_job = None
|
||||
process = None
|
||||
creation_flags = 0
|
||||
if process_tree and sys.platform == "win32":
|
||||
windows_job = ExecTool._create_windows_job()
|
||||
creation_flags = windows_job.creation_flags
|
||||
# Default to PowerShell so single-line and multi-line commands
|
||||
# share the same shell semantics. cmd.exe is reachable via the
|
||||
# explicit shell="cmd" parameter (see _resolve_shell).
|
||||
default_program = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
|
||||
program = shell_program or default_program
|
||||
program_name = PureWindowsPath(program).name.lower()
|
||||
try:
|
||||
if program_name in ("cmd", "cmd.exe"):
|
||||
cmd_env = {**env, "COMSPEC": program}
|
||||
process = await asyncio.create_subprocess_shell(
|
||||
command,
|
||||
stdin=stdin,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=cwd,
|
||||
env=cmd_env,
|
||||
creationflags=creation_flags,
|
||||
)
|
||||
else:
|
||||
command = ExecTool._normalize_powershell_command(command)
|
||||
command = (
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n"
|
||||
"if ($PSVersionTable.PSVersion.Major -lt 6) { $OutputEncoding = [Console]::OutputEncoding }\n"
|
||||
"$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'\n"
|
||||
f"{command}\n"
|
||||
"if ($LASTEXITCODE -ne $null) { exit $LASTEXITCODE }"
|
||||
)
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
program, "-NoProfile", "-NonInteractive", "-Command", command,
|
||||
stdin=stdin,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
creationflags=creation_flags,
|
||||
)
|
||||
if windows_job is not None:
|
||||
windows_job.assign_and_resume(process.pid)
|
||||
setattr(process, _PROCESS_TREE_OWNER_ATTR, windows_job)
|
||||
return process
|
||||
except BaseException:
|
||||
if windows_job is not None:
|
||||
windows_job.terminate()
|
||||
if process is not None:
|
||||
await ExecTool._kill_process(process)
|
||||
raise
|
||||
shell_program = shell_program or shutil.which("bash") or "/bin/bash"
|
||||
args: list[str] = [shell_program]
|
||||
shell_name = Path(shell_program).name.lower()
|
||||
if login and shell_name in {"bash", "bash.exe", "zsh", "zsh.exe"}:
|
||||
args.append("-l")
|
||||
args.extend(["-c", command])
|
||||
if process_tree:
|
||||
return await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdin=stdin,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
start_new_session=True,
|
||||
)
|
||||
return await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdin=stdin,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_powershell_command(command: str) -> str:
|
||||
stripped = command.lstrip()
|
||||
if not stripped or stripped[0] not in {"'", '"'}:
|
||||
return command
|
||||
|
||||
quote = stripped[0]
|
||||
end = stripped.find(quote, 1)
|
||||
if end == -1 or (end + 1 < len(stripped) and not stripped[end + 1].isspace()):
|
||||
return command
|
||||
|
||||
executable = stripped[1:end]
|
||||
looks_like_windows_executable = (
|
||||
bool(re.match(r"^[A-Za-z]:[\\/]", executable))
|
||||
or executable.startswith(r"\\")
|
||||
or executable.lower().endswith((".exe", ".cmd", ".bat", ".ps1"))
|
||||
)
|
||||
if not looks_like_windows_executable:
|
||||
return command
|
||||
|
||||
leading = command[: len(command) - len(stripped)]
|
||||
return f"{leading}& {stripped}"
|
||||
|
||||
@staticmethod
|
||||
def _resolve_shell(shell: str | None) -> tuple[str | None, str | None]:
|
||||
if not shell:
|
||||
@@ -716,86 +539,6 @@ class ExecTool(Tool):
|
||||
return None, ToolResult.error(f"Error: shell not found: {shell}")
|
||||
return resolved, None
|
||||
|
||||
@staticmethod
|
||||
async def _kill_process(process: asyncio.subprocess.Process) -> None:
|
||||
"""Kill a subprocess and reap it to prevent zombies.
|
||||
|
||||
Safe to call when the process has already exited (e.g. generic
|
||||
exception handlers after a successful ``communicate()``): skips
|
||||
``kill()`` and only runs the safety-net reap.
|
||||
"""
|
||||
if process.returncode is not None:
|
||||
_reap_pid(process.pid)
|
||||
return
|
||||
try:
|
||||
with suppress(ProcessLookupError):
|
||||
process.kill()
|
||||
with suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(process.wait(), timeout=5.0)
|
||||
finally:
|
||||
_reap_pid(process.pid)
|
||||
|
||||
@staticmethod
|
||||
async def _kill_process_tree(process: asyncio.subprocess.Process) -> None:
|
||||
"""Kill a session process and descendants, then reap the root process."""
|
||||
owner = ExecTool._process_tree_owner(process)
|
||||
try:
|
||||
if owner is not None:
|
||||
owner.terminate()
|
||||
elif _IS_WINDOWS:
|
||||
if process.returncode is None:
|
||||
with suppress(OSError, asyncio.TimeoutError):
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
subprocess.run,
|
||||
["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
),
|
||||
timeout=5.0,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
if process.returncode is None:
|
||||
with suppress(ProcessLookupError):
|
||||
process.kill()
|
||||
await asyncio.wait_for(process.wait(), timeout=5.0)
|
||||
if owner is not None:
|
||||
ExecTool._drop_process_tree_owner(process)
|
||||
finally:
|
||||
_reap_pid(process.pid)
|
||||
|
||||
@staticmethod
|
||||
def _process_tree_owner(
|
||||
process: asyncio.subprocess.Process,
|
||||
) -> _ProcessTreeOwner | None:
|
||||
# _spawn is the only writer for this private ownership marker.
|
||||
return cast(_ProcessTreeOwner | None, vars(process).get(_PROCESS_TREE_OWNER_ATTR))
|
||||
|
||||
@staticmethod
|
||||
def _create_windows_job() -> _ProcessTreeOwner:
|
||||
from nanobot.agent.tools._windows_job import WindowsJob
|
||||
|
||||
return WindowsJob.create()
|
||||
|
||||
@staticmethod
|
||||
def _drop_process_tree_owner(process: asyncio.subprocess.Process) -> None:
|
||||
with suppress(AttributeError):
|
||||
delattr(process, _PROCESS_TREE_OWNER_ATTR)
|
||||
|
||||
@staticmethod
|
||||
def _release_process_tree(process: asyncio.subprocess.Process) -> None:
|
||||
owner = ExecTool._process_tree_owner(process)
|
||||
if owner is None:
|
||||
return
|
||||
owner.release()
|
||||
ExecTool._drop_process_tree_owner(process)
|
||||
|
||||
def _build_env(self) -> dict[str, str]:
|
||||
"""Use platform defaults plus explicitly allowed environment keys.
|
||||
|
||||
|
||||
Reference in new issue
Block a user