refactor(exec): centralize process-tree lifecycle (#6623)

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
Xubin Renandchengyongru authored and GitHub committed 2026-11-12 11:44:48 +08:00
1 parent c37af82e3f
commit 8607b6445c
16 files changed
+356 -534

No files matched your search

+15 -38
View File
@@ -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()
+2 -259
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
"""Resource operations used by the gateway's tools."""
File renamed without changes.
+172
View File
@@ -0,0 +1,172 @@
"""Platform subprocess launch and process-tree cleanup for exec sessions."""
from __future__ import annotations
import asyncio
import os
import re
import shutil
import signal
import sys
from contextlib import suppress
from pathlib import Path, PureWindowsPath
from typing import TYPE_CHECKING
from loguru import logger
if TYPE_CHECKING:
from nanobot.execution._windows_job import WindowsJob
_IS_WINDOWS = sys.platform == "win32"
class ProcessTree:
"""Keep the root's streams and its native process-tree ownership together."""
__slots__ = ("process", "_job")
def __init__(self, process: asyncio.subprocess.Process, job: WindowsJob | None = None) -> None:
self.process = process
self._job = job
async def terminate(self) -> None:
"""Stop descendants even if the root has already exited."""
try:
if self._job is not None:
self._job.terminate()
else:
with suppress(ProcessLookupError):
os.killpg(self.process.pid, signal.SIGKILL)
await _stop_root(self.process)
finally:
_reap_pid(self.process.pid)
def finish(self) -> None:
"""Release native ownership once the session has drained the streams."""
if self._job is not None:
self._job.release()
_reap_pid(self.process.pid)
async def spawn_process_tree(
command: str | list[str],
cwd: str,
env: dict[str, str],
shell_program: str | None = None,
login: bool = False,
*,
stdin: int = asyncio.subprocess.DEVNULL,
) -> ProcessTree:
"""Start a prepared command in its own process group or Windows job."""
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]}")
launch = [executable, *command[1:]]
elif _IS_WINDOWS:
program = shell_program or shutil.which("pwsh") or shutil.which("powershell") or "powershell"
if PureWindowsPath(program).name.lower() in ("cmd", "cmd.exe"):
env = {**env, "COMSPEC": program}
launch = command
else:
command = _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 }"
)
launch = [program, "-NoProfile", "-NonInteractive", "-Command", command]
else:
program = shell_program or shutil.which("bash") or "/bin/bash"
launch = [program]
if login and Path(program).name.lower() in {"bash", "bash.exe", "zsh", "zsh.exe"}:
launch.append("-l")
launch.extend(["-c", command])
job = _create_windows_job() if _IS_WINDOWS else None
creationflags = job.creation_flags if job is not None else 0
process = None
try:
if isinstance(launch, str):
process = await asyncio.create_subprocess_shell(
launch, stdin=stdin, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env,
creationflags=creationflags,
)
else:
process = await asyncio.create_subprocess_exec(
*launch, stdin=stdin, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env,
creationflags=creationflags,
start_new_session=not _IS_WINDOWS,
)
if job is not None:
job.assign_and_resume(process.pid)
return ProcessTree(process, job)
except BaseException:
if job is not None:
job.terminate()
if process is not None:
try:
with suppress(asyncio.TimeoutError):
await _stop_root(process)
finally:
_reap_pid(process.pid)
raise
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}"
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 if asyncio has not reaped it.
"""
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)
async def _stop_root(process: asyncio.subprocess.Process) -> None:
if process.returncode is None:
with suppress(ProcessLookupError):
process.kill()
await asyncio.wait_for(process.wait(), timeout=5.0)
def _create_windows_job() -> WindowsJob:
from nanobot.execution._windows_job import WindowsJob
return WindowsJob.create()