The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(process): one owner-death supervisor per Hermes process, in sh, owned by process_identity
kshitijk4poord66b9cd9ced3
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.pyindex 6f4a48d7f56..6f04c640221 100644--- a/hermes_cli/process_identity.py+++ b/hermes_cli/process_identity.py@@ -1,10 +1,13 @@-"""Process identity: spawn tags, the machine-wide spawn ledger, and the Windows job-object self-attach.+"""Process identity: spawn tags, the machine-wide spawn ledger, the Windows job-object self-attach,+and the POSIX owner-death supervisor.-Three layers make every long-lived Hermes process positively identifiable, so reapers (``hermes-update``, Desktop startup sweeps) never guess lineage from PPID archaeology or cmdline matching:+Four layers make every long-lived Hermes process positively identifiable, so reapers (``hermes+update``, Desktop startup sweeps) never guess lineage from PPID archaeology or cmdline matching,+and make every long-lived CHILD die with the Hermes process that owns it:1. spawn tags (``HERMES_SPAWN`` env stamped by the spawner); 2. a ``(pid, create_time)`` ledger;3. Windows job-object self-attach with ``KILL_ON_JOB_CLOSE`` so the whole child tree dies with the-root — no launcher→worker chains left holding ``.pyd`` locks.+root — no launcher→worker chains left holding ``.pyd`` locks; 4. on POSIX, one supervisor per+Hermes process that reaps the owned children's process groups the moment Hermes dies."""from __future__ import annotations@@ -770,3 +773,131 @@ def attach_self_to_kill_on_close_job() -> bool:except Exception:logger.debug("job object self-attach failed", exc_info=True)return False+++# Layer 4 — POSIX owner-death supervisor+#+# If this process dies without running its cleanup path (SIGKILL, OOM killer, crash, force-quit),+# its long-lived children reparent to init or the nearest subreaper (systemd --user) and run+# forever; macOS has no PR_SET_PDEATHSIG, and on Linux it fires when the spawning THREAD exits,+# which kills children spawned from short-lived worker threads while the owner is alive. So ONE+# supervisor per Hermes process (``process_supervisor.sh``) holds the read end of a pipe whose only+# write end we hold: EOF means we died, by any cause, and it killpg()s every group still registered.+# A registered group that was never unregistered IS the orphan set, so a clean exit that stopped its+# children first ends with nothing to kill, and one that didn't takes them along.+#+# Callers own process GROUPS: spawn the child as a group leader (``start_new_session=True``) and+# hand its pgid to ``update_supervised_pgids`` (stdio MCP servers, whose pgids the SDK spawns). A+# descendant that leaves the group on purpose must be registered by its own pgid where we learn it.+# POSIX-only: Windows children die through the layer-3 job object instead.++_supervisor = None # Optional[subprocess.Popen]; tests rebind it+_supervisor_lock = threading.Lock()+# Groups the supervisor is reaping on our behalf; replayed verbatim on respawn so a respawn never+# silently drops coverage for children that are still running.+_supervised_pgids: set = set()+_SUPERVISOR_SCRIPT = Path(__file__).with_name("process_supervisor.sh")+# Android (Termux) has no /bin/sh; its system shell is the same POSIX sh the script needs.+_POSIX_SH = "/bin/sh" if os.path.exists("/bin/sh") else "/system/bin/sh"+++def _spawn_supervisor():+ """Start the per-process supervisor, or None if it cannot be started."""+ import subprocess++ try:+ # start_new_session=True is load-bearing: shutdown paths killpg this process's own group,+ # which would kill the supervisor before it could reap anything. close_fds keeps the write+ # end of every OTHER pipe we hold out of it, so it never delays another child's EOF.+ return subprocess.Popen(+ [_POSIX_SH, str(_SUPERVISOR_SCRIPT), str(os.getpgid(0))],+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ start_new_session=True, close_fds=True, text=True)+ except Exception:+ # Never let supervisor bookkeeping block a real child: graceful shutdown paths still reap+ # normally; only the ungraceful-exit safety net is lost.+ logger.debug("Could not start the owner-death supervisor", exc_info=True)+ return None+++def _prune_dead_supervised_pgids() -> set:+ """Forget supervised groups with no members left; return what went. Caller holds+ ``_supervisor_lock``. Signal 0 is a pure existence probe (cannot terminate anything). It+ narrows, but cannot close, the window where a dead group's pgid is recycled before we notice."""+ stale = set()+ for pgid in list(_supervised_pgids):+ try:+ os.killpg(pgid, 0) # windows-footgun: ok — POSIX-only, callers return early on nt+ except ProcessLookupError:+ stale.add(pgid)+ except (PermissionError, OSError):+ # Exists but not ours to signal, or the probe failed: keep it — dropping coverage on+ # an ambiguous answer is the more expensive mistake.+ pass+ _supervised_pgids.difference_update(stale)+ return stale+++def update_supervised_pgids(verb: str, pgids) -> None:+ """Register or unregister process groups (``verb`` is ``"register"``/``"unregister"``) with+ this process's supervisor. Failures are swallowed: losing the safety net must never fail a+ live child."""+ if os.name != "posix":+ return+ wanted = {int(pgid) for pgid in pgids}+ if not wanted:+ return++ global _supervisor+ with _supervisor_lock:+ if verb == "register":+ _supervised_pgids.update(wanted)+ else:+ _supervised_pgids.difference_update(wanted)++ # A registration outlives its child only while some member survives (e.g. an orphaned+ # grandchild teardown failed to kill, deliberately kept registered). Once that group is+ # empty its pgid can be recycled by a stranger, so prune here too.+ stale = _prune_dead_supervised_pgids()++ proc = _supervisor+ if proc is None or proc.poll() is not None:+ if not _supervised_pgids:+ # Nothing left to cover: nothing to tell and nothing to respawn for. Keyed on the+ # SET, not the verb: after a broken-pipe write dropped the supervisor with groups+ # still registered, an unregister must still rebuild coverage for the survivors.+ return+ proc = _spawn_supervisor()+ _supervisor = proc+ if proc is None:+ return+ # A fresh supervisor knows nothing: replay live coverage (already reflects this+ # call's mutation and the prune, so pruned groups never reach the replacement).+ payload = "".join(f"register {pgid}\n" for pgid in _supervised_pgids)+ else:+ payload = "".join(f"{verb} {pgid}\n" for pgid in wanted)+ payload += "".join(f"unregister {pgid}\n" for pgid in stale)++ try:+ proc.stdin.write(payload)+ proc.stdin.flush()+ except (BrokenPipeError, ValueError, OSError):+ # It exited between poll() and write(). Drop it so the next call respawns and replays+ # from ``_supervised_pgids`` (the set, not the pipe, is the record of what to reap).+ _supervisor = None+ return++ if not _supervised_pgids:+ # Nothing left to reap: release the supervisor rather than keep a process and a pipe+ # resident for the life of a gateway. Closing our write end is the same EOF our death+ # sends; with an empty set it exits. The next register respawns and replays.+ try:+ proc.stdin.close()+ except (BrokenPipeError, ValueError, OSError):+ pass+ # Reap it, or the exited supervisor stays a zombie until the next Popen in this process.+ try:+ proc.wait(timeout=5)+ except Exception:+ pass+ _supervisor = Nonediff --git a/hermes_cli/process_supervisor.sh b/hermes_cli/process_supervisor.shnew file mode 100755index 00000000000..c9f61e8563e--- /dev/null+++ b/hermes_cli/process_supervisor.sh@@ -0,0 +1,53 @@+#!/bin/sh+# Hermes process supervisor: one per Hermes process, reaping the process groups it owns once it dies.+#+# Usage: sh process_supervisor.sh <parent-pgid>, spawned with start_new_session=True and stdin a+# pipe whose only write end Hermes holds (hermes_cli/process_identity.py, "owner-death supervisor").+# stdin carries one command per line:+# register <pgid> reap this process group when Hermes dies+# unregister <pgid> stop reaping it (Hermes stopped that child itself)+# EOF means Hermes is gone, by any cause including SIGKILL and the OOM killer: SIGTERM every group+# still registered, wait up to 3 s, SIGKILL the survivors, exit. A clean exit is the same EOF, so a+# child Hermes never unregistered dies with it either way.+#+# POSIX sh, not Python: Hermes keeps this process resident for its whole life, and an idle sh costs+# about 0.5 MB USS where an idle interpreter costs about 8 MB. It must also never import Hermes:+# it runs after Hermes may already be dead.+#+# Malformed lines are skipped: a corrupt line must not cost the reaping guarantee for every other+# group. Groups that are never a valid target (pgid <= 1, our own, Hermes's own) are refused at+# registration, so a caller bug costs one unreaped child, never the Hermes process tree.+# Residual risk: groups are reaped by number, so a registered group that exits on its own can have+# its pgid recycled before Hermes prunes it; Hermes prunes empty groups on every registration change.++trap '' INT HUP # a dying parent's SIGINT/SIGHUP must not preempt the reap: EOF is the only signal+parent=$1+# Run inside the parent's group, a killpg of the parent would take us down before we reap.+kill -0 -$$ 2>/dev/null || {+ echo "hermes process supervisor: not a process-group leader; refusing to run" >&2+ exit 2+}+reg=' '+while IFS=' ' read -r verb pg rest; do+ case $pg in ''|*[!0-9]*) continue ;; esac+ [ -z "$rest" ] && [ ${#pg} -le 10 ] || continue+ case $verb in+ register)+ [ "$pg" -gt 1 ] && [ "$pg" -ne $$ ] && [ "$pg" -ne "$parent" ] || continue+ case $reg in *" $pg "*) ;; *) reg="$reg$pg " ;; esac ;;+ unregister)+ keep=' '+ for g in $reg; do [ "$g" = "$pg" ] || keep="$keep$g "; done+ reg=$keep ;;+ esac+done+for g in $reg; do kill -TERM -"$g" 2>/dev/null; done+for _ in 1 2 3; do+ live=''+ for g in $reg; do kill -0 -"$g" 2>/dev/null && live="$live $g"; done+ reg=$live+ [ -n "$reg" ] || exit 0+ sleep 1+done+for g in $reg; do kill -KILL -"$g" 2>/dev/null; done+exit 0diff --git a/pyproject.toml b/pyproject.tomlindex ab993f3568f..83af45fb90b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -717,6 +717,7 @@ hermes_cli = ["observability/schemas/*.json","data/*.json","local_runtime/*.json",+ "process_supervisor.sh",]# gateway/assets/ ships status_phrases.yaml and the Telegram BotFather# screenshot. Without this, sealed venvs (uv2nix) silently lose both —diff --git a/tests/tools/test_mcp_death_supervisor.py b/tests/hermes_cli/test_process_identity_supervisor.pysimilarity index 71%rename from tests/tools/test_mcp_death_supervisor.pyrename to tests/hermes_cli/test_process_identity_supervisor.pyindex 497c96f745e..106860f5069 100644--- a/tests/tools/test_mcp_death_supervisor.py+++ b/tests/hermes_cli/test_process_identity_supervisor.py@@ -1,7 +1,7 @@-"""Contract tests for the shared parent-death supervisor for stdio MCP servers.+"""Contract tests for the per-process owner-death supervisor (process_identity layer 4).The end-to-end tests here spawn real processes and really SIGKILL a real parent,-because the whole point of this module is behaviour that only exists when a+because the whole point of the supervisor is behaviour that only exists when aprocess dies without running any Python cleanup. A mocked parent death provesnothing about the guarantee."""@@ -19,17 +19,22 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from tools import mcp_death_supervisor, mcp_tool+from hermes_cli import process_identity+from tools import mcp_toolfrom tools import mcp_tool_lifecycle as _mcp_lifecyclepytestmark = pytest.mark.platforms("posix") # the supervisor is POSIX-only (process groups)-SUPERVISOR = os.path.join(os.path.dirname(mcp_tool.__file__), "mcp_death_supervisor.py")+SUPERVISOR = str(process_identity._SUPERVISOR_SCRIPT)# Long enough that nothing here can pass because the victim exited on its own._VICTIM = [sys.executable, "-c", "import time; time.sleep(300)"]+def _supervisor_argv(parent_pgid: int) -> list:+ return ["/bin/sh", SUPERVISOR, str(parent_pgid)]++def _alive(pid: int) -> bool:try:os.kill(pid, 0)@@ -69,110 +74,72 @@ def _kill(pid: int) -> None:# ----------------------------------------------------------------------------# Target safety: this process signals whole process GROUPS, so a bad target is-# unusually expensive. killpg(0, ...) would signal the supervisor's own group.+# Control protocol: run the real script with ``kill`` overridden by a shell+# function that records group signals instead of sending them, so unsafe+# targets (pgid 0/1, our own group) can be asserted on without being signalled.# ---------------------------------------------------------------------------[email protected]("pgid", [0, 1, -1, -5])-def test_refuses_process_groups_that_are_never_a_valid_target(pgid):- assert mcp_death_supervisor._is_safe_target(- pgid, own_pgid=4242, parent_pgid=777- ) is False---def test_refuses_its_own_group_and_the_parents_group():- assert mcp_death_supervisor._is_safe_target(- 4242, own_pgid=4242, parent_pgid=777- ) is False- assert mcp_death_supervisor._is_safe_target(- 777, own_pgid=4242, parent_pgid=777- ) is False---def test_accepts_an_unrelated_group():- assert mcp_death_supervisor._is_safe_target(- 999, own_pgid=4242, parent_pgid=777- ) is True---# ----------------------------------------------------------------------------# Control protocol-# ---------------------------------------------------------------------------+def _terminated_groups(stream: str, *, parent_pgid: int = 777) -> set:+ """Feed ``stream`` to the supervisor, close it, return the groups it SIGTERMed."""+ recorder = (+ 'kill() { case $1 in -0) command kill "$@" ;;'+ ' -TERM) echo "${2#-}" >> "$HERMES_TEST_LOG"; return 1 ;; *) return 1 ;; esac; };'+ ' . "$HERMES_TEST_SCRIPT"'+ )+ log = os.path.join(os.environ.get("TMPDIR") or "/tmp", f"supervisor-{os.getpid()}-{time.monotonic_ns()}")+ try:+ subprocess.run(+ ["/bin/sh", "-c", recorder, "supervisor", str(parent_pgid)],+ input=stream, text=True, timeout=30, check=True, start_new_session=True,+ env={**os.environ, "HERMES_TEST_LOG": log, "HERMES_TEST_SCRIPT": SUPERVISOR},+ )+ with contextlib.suppress(FileNotFoundError):+ with open(log, encoding="utf-8") as f:+ return {int(line) for line in f.read().split()}+ return set()+ finally:+ with contextlib.suppress(FileNotFoundError):+ os.unlink(log)def test_registrations_survive_to_eof_and_unregistrations_are_dropped():- stream = io.StringIO("register 111\nregister 222\nunregister 111\n")-- still_registered = mcp_death_supervisor._serve(- stream, own_pgid=4242, parent_pgid=777- )-- assert still_registered == {222}+ assert _terminated_groups("register 111\nregister 222\nunregister 111\n") == {222}def test_garbage_lines_do_not_cost_us_the_other_registrations():- # A corrupted byte on the control pipe must not take down reaping for every- # other server -- that would turn a cosmetic bug into leaked processes.- stream = io.StringIO(+ # A corrupted line on the control pipe must not take down reaping for every+ # other child -- that would turn a cosmetic bug into leaked processes.+ stream = ("register 111\n""\n""register\n""register notanumber\n""register 222 333\n""explode 444\n"+ "register 99999999999999\n""register 555\n")+ assert _terminated_groups(stream) == {111, 555}- still_registered = mcp_death_supervisor._serve(- stream, own_pgid=4242, parent_pgid=777- )-- assert still_registered == {111, 555}--def test_a_writer_that_never_sends_a_newline_cannot_grow_us_without_bound():- """Found for real: iterating the stream let /dev/zero reach 15 GB.-- The supervisor is the last line of defense against leaked MCP servers, so- it must not be the process that dies under memory pressure -- and a reader- that buffers until a newline arrives is exactly that risk.- """- huge = "register " + ("0" * 10_000_000) + "\nregister 222\n"-- still_registered = mcp_death_supervisor._serve(- io.StringIO(huge), own_pgid=4242, parent_pgid=777- )-- # The overlong line is skipped, and the stream resyncs on the next one.- assert still_registered == {222}---def test_a_line_truncated_by_the_cap_is_never_acted_on():- # Truncation must not turn one pgid into a different, valid-looking one:- # "register 999999" clipped to "register 9" would reap the wrong group.- stream = io.StringIO("register " + "9" * (mcp_death_supervisor._MAX_LINE_CHARS))-- assert mcp_death_supervisor._serve(- stream, own_pgid=4242, parent_pgid=777- ) == set()+def test_an_unterminated_line_at_eof_is_never_acted_on():+ # A line cut off by the writer's death must not turn into a valid-looking+ # command: "register 999999" clipped to "register 9" would reap the wrong group.+ assert _terminated_groups("register 111\nregister 9") == {111}def test_unsafe_targets_are_rejected_at_registration_time():- stream = io.StringIO("register 0\nregister 777\nregister 999\n")-- still_registered = mcp_death_supervisor._serve(- stream, own_pgid=4242, parent_pgid=777- )-- assert still_registered == {999}+ # killpg(0) is our own group and pgid 1 is init; the parent's group is the+ # Hermes process tree itself. A caller bug must cost one unreaped child, never those.+ assert _terminated_groups("register 0\nregister 1\nregister 777\nregister 999\n", parent_pgid=777) == {999}def test_refuses_to_run_inside_the_parents_own_process_group():# Started without start_new_session, a killpg of the parent's group would# take the supervisor out before it could reap. It must not pretend to work.proc = subprocess.run(- [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ _supervisor_argv(os.getpgid(0)),stdin=subprocess.DEVNULL,capture_output=True,text=True,@@ -181,7 +148,7 @@ def test_refuses_to_run_inside_the_parents_own_process_group():)assert proc.returncode == 2- assert "process group" in proc.stderr+ assert "process-group leader" in proc.stderr# ---------------------------------------------------------------------------@@ -192,7 +159,7 @@ def test_refuses_to_run_inside_the_parents_own_process_group():def test_reaps_a_registered_group_when_the_control_pipe_reaches_eof():victim = subprocess.Popen(_VICTIM, start_new_session=True)supervisor = subprocess.Popen(- [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ _supervisor_argv(os.getpgid(0)),stdin=subprocess.PIPE,text=True,start_new_session=True,@@ -213,13 +180,34 @@ def test_reaps_a_registered_group_when_the_control_pipe_reaches_eof():supervisor.wait(timeout=10)+def test_escalates_to_sigkill_for_a_group_that_ignores_sigterm():+ victim = subprocess.Popen(+ [sys.executable, "-c",+ "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); print('armed', flush=True); time.sleep(300)"],+ stdout=subprocess.PIPE, text=True, start_new_session=True,+ )+ supervisor = subprocess.Popen(_supervisor_argv(os.getpgid(0)), stdin=subprocess.PIPE, text=True,+ start_new_session=True)+ try:+ assert victim.stdout.readline().strip() == "armed"+ supervisor.stdin.write(f"register {victim.pid}\n")+ supervisor.stdin.close()+ assert _wait_exited(victim), "a SIGTERM-ignoring group survived the reap"+ assert victim.returncode == -signal.SIGKILL+ finally:+ _kill(victim.pid)+ _kill(supervisor.pid)+ victim.wait(timeout=10)+ supervisor.wait(timeout=10)++def test_leaves_an_unregistered_group_alone_at_eof():# The other failure direction, and the more damaging one: a clean Hermes- # shutdown unregisters as it tears each server down, so EOF must not become- # a kill-everything event for servers that were handed back.+ # shutdown unregisters as it tears each child down, so EOF must not become+ # a kill-everything event for children that were handed back.survivor = subprocess.Popen(_VICTIM, start_new_session=True)supervisor = subprocess.Popen(- [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ _supervisor_argv(os.getpgid(0)),stdin=subprocess.PIPE,text=True,start_new_session=True,@@ -231,7 +219,7 @@ def test_leaves_an_unregistered_group_alone_at_eof():supervisor.stdin.close()supervisor.wait(timeout=15)- assert survivor.poll() is None, "a cleanly unregistered server was killed"+ assert survivor.poll() is None, "a cleanly unregistered child was killed"finally:_kill(survivor.pid)_kill(supervisor.pid)@@ -241,7 +229,7 @@ def test_leaves_an_unregistered_group_alone_at_eof():# A stand-in for Hermes: registers a real child, then blocks forever holding the# only write end of the control pipe. SIGKILLing it is the scenario the whole-# module exists for -- no cleanup code of ours gets to run.+# supervisor exists for -- no cleanup code of ours gets to run._FAKE_PARENT = """import os, subprocess, sys, time@@ -250,7 +238,7 @@ victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"], start_new_session=True)sup = subprocess.Popen(- [sys.executable, supervisor, "--parent-pgid", str(os.getpgid(0))],+ ["/bin/sh", supervisor, str(os.getpgid(0))],stdin=subprocess.PIPE, text=True, start_new_session=True,)sup.stdin.write("register %d\\n" % os.getpgid(victim.pid))@@ -264,9 +252,9 @@ time.sleep(300)# so cleaning them up trips conftest's live-system kill guard. Real signal# delivery to a real orphan is the entire point of these two tests.@pytest.mark.live_system_guard_bypass-def test_reaps_the_server_when_the_registering_parent_is_sigkilled(tmp_path):+def test_reaps_the_child_when_the_registering_parent_is_sigkilled(tmp_path):script = tmp_path / "fake_parent.py"- script.write_text(_FAKE_PARENT)+ script.write_text(_FAKE_PARENT, encoding="utf-8")parent = subprocess.Popen([sys.executable, str(script), SUPERVISOR],@@ -285,7 +273,7 @@ def test_reaps_the_server_when_the_registering_parent_is_sigkilled(tmp_path):parent.wait(timeout=10)assert _wait_gone(victim_pid), (- "stdio MCP server survived kill -9 of its Hermes parent"+ "owned child survived kill -9 of its Hermes parent")finally:for pid in (victim_pid, supervisor_pid):@@ -304,7 +292,8 @@ def test_reaps_a_grandchild_left_in_the_registered_group(tmp_path):"import subprocess, sys\n""child = subprocess.Popen([sys.executable, '-c',"" 'import time; time.sleep(300)'])\n"- "print(child.pid, flush=True)\n"+ "print(child.pid, flush=True)\n",+ encoding="utf-8",)# start_new_session mirrors how the MCP SDK spawns stdio servers.@@ -318,7 +307,7 @@ def test_reaps_a_grandchild_left_in_the_registered_group(tmp_path):server.wait(timeout=10) # the direct child exits; the grandchild does notsupervisor = subprocess.Popen(- [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ _supervisor_argv(os.getpgid(0)),stdin=subprocess.PIPE,text=True,start_new_session=True,@@ -339,7 +328,7 @@ def test_reaps_a_grandchild_left_in_the_registered_group(tmp_path):# ----------------------------------------------------------------------------# Client side: what mcp_tool tells the supervisor+# Client side: what process_identity tells the supervisor# ---------------------------------------------------------------------------@@ -379,8 +368,8 @@ class _FakeSupervisor:@pytest.fixture(autouse=True)def _reset_client_state():yield- mcp_tool._death_supervisor = None- mcp_tool._supervised_pgids.clear()+ process_identity._supervisor = None+ process_identity._supervised_pgids.clear()@pytest.fixture@@ -392,7 +381,7 @@ def all_groups_alive(monkeypatch):before the control stream can be asserted on -- so state the preconditionrather than letting these tests depend on pid-space luck."""- monkeypatch.setattr(mcp_tool.os, "killpg", lambda pgid, sig: None)+ monkeypatch.setattr(process_identity.os, "killpg", lambda pgid, sig: None)def test_register_starts_the_supervisor_once_and_reuses_it(monkeypatch, all_groups_alive):@@ -403,25 +392,21 @@ def test_register_starts_the_supervisor_once_and_reuses_it(monkeypatch, all_grouspawned.append(fake)return fake- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", _spawn)+ monkeypatch.setattr(process_identity, "_spawn_supervisor", _spawn)- mcp_tool._update_death_supervisor("register", [111])- mcp_tool._update_death_supervisor("register", [222])+ process_identity.update_supervised_pgids("register", [111])+ process_identity.update_supervised_pgids("register", [222])assert len(spawned) == 1, "each register spawned its own supervisor"assert spawned[0].lines() == ["register 111", "register 222"]--def test_supervisor_is_released_once_nothing_is_left_to_reap(monkeypatch, all_groups_alive):"""An empty registration set must not keep a supervisor resident.- A gateway that once connected a stdio server would otherwise carry a- ~15 MB process and a live pipe for the rest of its life. Closing our- write end is the same EOF the supervisor treats as parent death; with- nothing registered it exits without reaping. The next register starts a- fresh one, exactly like the dead-supervisor replay path.+ Closing our write end is the same EOF the supervisor treats as parent+ death; with nothing registered it exits without reaping. The next+ register starts a fresh one, exactly like the dead-supervisor replay path."""spawned = []@@ -430,33 +415,31 @@ def test_supervisor_is_released_once_nothing_is_left_to_reap(monkeypatch, all_grspawned.append(fake)return fake- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", _spawn)+ monkeypatch.setattr(process_identity, "_spawn_supervisor", _spawn)- mcp_tool._update_death_supervisor("register", [111, 222])- mcp_tool._update_death_supervisor("unregister", [111])+ process_identity.update_supervised_pgids("register", [111, 222])+ process_identity.update_supervised_pgids("unregister", [111])assert not spawned[0].closed, "released the supervisor while a group was still registered"- mcp_tool._update_death_supervisor("unregister", [222])+ process_identity.update_supervised_pgids("unregister", [222])assert spawned[0].closed, "supervisor kept resident with nothing left to reap"assert getattr(spawned[0], "waited", False), "released supervisor was never wait()ed -> zombie until the next Popen"assert spawned[0].lines()[-1] == "unregister 222", "release happened before the last unregister was sent"- assert mcp_tool._death_supervisor is None+ assert process_identity._supervisor is None- mcp_tool._update_death_supervisor("register", [333])+ process_identity.update_supervised_pgids("register", [333])assert len(spawned) == 2 and spawned[1].lines() == ["register 333"]def test_supervisor_survives_the_real_eof_release():"""End to end: closing the control pipe with nothing registered exits cleanly."""- if os.name != "posix":- pytest.skip("POSIX-only supervisor")child = subprocess.Popen(_VICTIM, start_new_session=True)try:- mcp_tool._update_death_supervisor("register", [os.getpgid(child.pid)])- proc = mcp_tool._death_supervisor+ process_identity.update_supervised_pgids("register", [os.getpgid(child.pid)])+ proc = process_identity._supervisorassert proc is not None and proc.poll() is None- mcp_tool._update_death_supervisor("unregister", [os.getpgid(child.pid)])- assert mcp_tool._death_supervisor is None+ process_identity.update_supervised_pgids("unregister", [os.getpgid(child.pid)])+ assert process_identity._supervisor is Noneassert proc.wait(timeout=10) == 0, "supervisor did not exit on the release EOF"assert child.poll() is None, "release reaped a group that had been unregistered"finally:@@ -467,12 +450,12 @@ def test_supervisor_survives_the_real_eof_release():def test_unregister_alone_does_not_start_a_supervisor(monkeypatch):spawned = []monkeypatch.setattr(- mcp_tool,- "_spawn_death_supervisor",+ process_identity,+ "_spawn_supervisor",lambda: spawned.append(1) or _FakeSupervisor(),)- mcp_tool._update_death_supervisor("unregister", [111])+ process_identity.update_supervised_pgids("unregister", [111])assert spawned == []@@ -481,12 +464,12 @@ def test_a_dead_supervisor_is_replaced_and_live_coverage_replayed(monkeypatch, adead = _FakeSupervisor(exited=True)replacement = _FakeSupervisor()queue = [dead, replacement]- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: queue.pop(0))+ monkeypatch.setattr(process_identity, "_spawn_supervisor", lambda: queue.pop(0))- mcp_tool._update_death_supervisor("register", [111])- mcp_tool._update_death_supervisor("register", [222])+ process_identity.update_supervised_pgids("register", [111])+ process_identity.update_supervised_pgids("register", [222])- # Losing the supervisor must not silently drop the server registered with+ # Losing the supervisor must not silently drop the child registered with# it -- the replacement has to be told about 111 as well as 222.assert set(replacement.lines()) == {"register 111", "register 222"}@@ -495,24 +478,24 @@ def test_replay_does_not_resurrect_an_unregistered_group(monkeypatch, all_groupsdead = _FakeSupervisor(exited=True)replacement = _FakeSupervisor()queue = [dead, replacement]- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: queue.pop(0))+ monkeypatch.setattr(process_identity, "_spawn_supervisor", lambda: queue.pop(0))- mcp_tool._update_death_supervisor("register", [111])- mcp_tool._update_death_supervisor("register", [222])- mcp_tool._update_death_supervisor("unregister", [111])+ process_identity.update_supervised_pgids("register", [111])+ process_identity.update_supervised_pgids("register", [222])+ process_identity.update_supervised_pgids("unregister", [111])- assert mcp_tool._supervised_pgids == {222}+ assert process_identity._supervised_pgids == {222}# 111 was legitimately replayed to the replacement (it was live when the# dead supervisor was swapped out), then unregistered. What must never# happen is a replay AFTER the unregister bringing it back.lines = replacement.lines()assert lines.index("unregister 111") > lines.index("register 111")assert "register 111" not in lines[lines.index("unregister 111") :]- mcp_tool._update_death_supervisor("register", [333]) # any later replay/append+ process_identity.update_supervised_pgids("register", [333]) # any later replay/appendassert "register 111" not in replacement.lines()[len(lines) :]-def test_a_broken_pipe_never_propagates_into_a_live_mcp_session(monkeypatch, all_groups_alive):+def test_a_broken_pipe_never_propagates_into_a_live_child(monkeypatch, all_groups_alive):class _BrokenPipe(_FakeSupervisor):def __init__(self):super().__init__()@@ -526,13 +509,13 @@ def test_a_broken_pipe_never_propagates_into_a_live_mcp_session(monkeypatch, allself.stdin = _Stdin()- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", _BrokenPipe)+ monkeypatch.setattr(process_identity, "_spawn_supervisor", _BrokenPipe)- mcp_tool._update_death_supervisor("register", [111]) # must not raise+ process_identity.update_supervised_pgids("register", [111]) # must not raise# Dropped, so the next registration respawns instead of writing into a# pipe that is known to be dead.- assert mcp_tool._death_supervisor is None+ assert process_identity._supervisor is Nonedef test_unregister_after_a_broken_pipe_rebuilds_coverage_for_survivors(monkeypatch, all_groups_alive):@@ -550,8 +533,8 @@ def test_unregister_after_a_broken_pipe_rebuilds_coverage_for_survivors(monkeypaspawned.append(fake)return fake- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", _spawn)- mcp_tool._update_death_supervisor("register", [111, 222])+ monkeypatch.setattr(process_identity, "_spawn_supervisor", _spawn)+ process_identity.update_supervised_pgids("register", [111, 222])class _DeadStdin:def write(self, _payload):@@ -561,25 +544,25 @@ def test_unregister_after_a_broken_pipe_rebuilds_coverage_for_survivors(monkeypapassspawned[0].stdin = _DeadStdin()- mcp_tool._update_death_supervisor("register", [333]) # the write fails; supervisor dropped- assert mcp_tool._death_supervisor is None- assert mcp_tool._supervised_pgids == {111, 222, 333}+ process_identity.update_supervised_pgids("register", [333]) # the write fails; supervisor dropped+ assert process_identity._supervisor is None+ assert process_identity._supervised_pgids == {111, 222, 333}- mcp_tool._update_death_supervisor("unregister", [222])+ process_identity.update_supervised_pgids("unregister", [222])assert len(spawned) == 2, "unregister after a lost supervisor did not respawn one"assert sorted(spawned[1].lines()) == ["register 111", "register 333"], ("the replacement did not receive the surviving groups")- assert mcp_tool._death_supervisor is spawned[1]+ assert process_identity._supervisor is spawned[1]def test_a_supervisor_that_cannot_start_is_not_fatal(monkeypatch, all_groups_alive):- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: None)+ monkeypatch.setattr(process_identity, "_spawn_supervisor", lambda: None)- mcp_tool._update_death_supervisor("register", [111]) # must not raise+ process_identity.update_supervised_pgids("register", [111]) # must not raise- assert mcp_tool._death_supervisor is None+ assert process_identity._supervisor is None@contextlib.contextmanager@@ -614,7 +597,7 @@ def _stdio_connection(child_pid, fake_supervisor):patch("tools.mcp_tool_config._write_stderr_log_header"),patch("tools.mcp_tool._get_mcp_stderr_log", return_value=None),patch(- "tools.mcp_tool._spawn_death_supervisor",+ "hermes_cli.process_identity._spawn_supervisor",return_value=fake_supervisor,),):@@ -669,7 +652,7 @@ def test_a_server_that_exited_is_released_on_teardown():@pytest.mark.skipif(not mcp_tool._MCP_AVAILABLE, reason="MCP SDK not installed")def test_a_server_that_survived_teardown_stays_registered():- # The case the whole module exists for: teardown did not manage to kill it.+ # The case the supervisor exists for: teardown did not manage to kill it.# Releasing it here would hand the orphan back to nobody.fake = _FakeSupervisor()child = subprocess.Popen(_VICTIM, start_new_session=True)@@ -703,7 +686,7 @@ def test_scoped_teardown_of_one_owner_keeps_the_other_owner_supervised(monkeypatrather than the control protocol alone (review request on #93517)."""fake = _FakeSupervisor()- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: fake)+ monkeypatch.setattr(process_identity, "_spawn_supervisor", lambda: fake)monkeypatch.setattr(_mcp_lifecycle.time, "sleep", lambda _s: None) # skip the SIGTERM grace waita = subprocess.Popen(_VICTIM, start_new_session=True)b = subprocess.Popen(_VICTIM, start_new_session=True)@@ -714,7 +697,7 @@ def test_scoped_teardown_of_one_owner_keeps_the_other_owner_supervised(monkeypat_mcp_lifecycle._stdio_pids[b.pid] = "profile-b"_mcp_lifecycle._stdio_pgids[a.pid] = pg_a_mcp_lifecycle._stdio_pgids[b.pid] = pg_b- mcp_tool._update_death_supervisor("register", [pg_a, pg_b])+ process_identity.update_supervised_pgids("register", [pg_a, pg_b])_mcp_lifecycle._kill_orphaned_mcp_children(include_active=True, server_name="profile-a")a.wait(timeout=10)@@ -724,7 +707,7 @@ def test_scoped_teardown_of_one_owner_keeps_the_other_owner_supervised(monkeypatassert f"unregister {pg_b}" not in fake.lines(), ("scoped teardown released the OTHER owner's group from the supervisor")- assert mcp_tool._supervised_pgids == {pg_b}+ assert process_identity._supervised_pgids == {pg_b}assert b.pid in _mcp_lifecycle._stdio_pids and b.pid in _mcp_lifecycle._stdio_pgidsfinally:for p in (a, b):@@ -747,28 +730,28 @@ def test_a_group_with_nothing_left_alive_is_forgotten_and_unregistered(monkeypatthan a fixture -- the whole point is that we notice actual death."""fake = _FakeSupervisor()- monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: fake)+ monkeypatch.setattr(process_identity, "_spawn_supervisor", lambda: fake)doomed = subprocess.Popen(_VICTIM, start_new_session=True)doomed_pgid = os.getpgid(doomed.pid)survivor = subprocess.Popen(_VICTIM, start_new_session=True)survivor_pgid = os.getpgid(survivor.pid)try:- mcp_tool._update_death_supervisor("register", [doomed_pgid, survivor_pgid])- assert mcp_tool._supervised_pgids == {doomed_pgid, survivor_pgid}+ process_identity.update_supervised_pgids("register", [doomed_pgid, survivor_pgid])+ assert process_identity._supervised_pgids == {doomed_pgid, survivor_pgid}# Reap it fully so the group is genuinely empty, not a zombie.doomed.kill()doomed.wait(timeout=10)# Any later registration change is when we notice.- mcp_tool._update_death_supervisor("register", [survivor_pgid])+ process_identity.update_supervised_pgids("register", [survivor_pgid])- assert doomed_pgid not in mcp_tool._supervised_pgids, (+ assert doomed_pgid not in process_identity._supervised_pgids, ("a group with no members left stayed registered, so a recycled "- "pgid could later be reaped as if it were an MCP server"+ "pgid could later be reaped as if it were an owned child")- assert survivor_pgid in mcp_tool._supervised_pgids, (+ assert survivor_pgid in process_identity._supervised_pgids, ("pruning dropped a group that is still alive")assert f"unregister {doomed_pgid}" in fake.lines(), (@@ -783,29 +766,29 @@ def test_a_group_with_nothing_left_alive_is_forgotten_and_unregistered(monkeypatdef test_pruning_keeps_groups_it_cannot_prove_are_gone(monkeypatch):# An ambiguous probe (EPERM: exists but not ours) must not drop coverage --# losing a real registration is worse than keeping a doubtful one.- monkeypatch.setattr(mcp_tool, "_supervised_pgids", {111, 222}, raising=False)+ monkeypatch.setattr(process_identity, "_supervised_pgids", {111, 222}, raising=False)def _probe(pgid, sig):if pgid == 111:raise PermissionError("exists, not ours")raise ProcessLookupError("gone")- monkeypatch.setattr(mcp_tool.os, "killpg", _probe)+ monkeypatch.setattr(process_identity.os, "killpg", _probe)- stale = mcp_tool._prune_dead_supervised_pgids()+ stale = process_identity._prune_dead_supervised_pgids()assert stale == {222}- assert mcp_tool._supervised_pgids == {111}+ assert process_identity._supervised_pgids == {111}def test_no_pgids_is_a_no_op(monkeypatch):spawned = []monkeypatch.setattr(- mcp_tool,- "_spawn_death_supervisor",+ process_identity,+ "_spawn_supervisor",lambda: spawned.append(1) or _FakeSupervisor(),)- mcp_tool._update_death_supervisor("register", [])+ process_identity.update_supervised_pgids("register", [])assert spawned == []diff --git a/tools/mcp_death_supervisor.py b/tools/mcp_death_supervisor.pydeleted file mode 100644index 87302ae6858..00000000000--- a/tools/mcp_death_supervisor.py+++ /dev/null@@ -1,216 +0,0 @@-#!/usr/bin/env python3-"""One parent-death supervisor per Hermes process, shared by all stdio MCP servers.--Why this exists-----------------When Hermes dies without running its cleanup path (SIGKILL, OOM killer, a hard-crash), stdio MCP servers it spawned are reparented to init and keep running-forever. macOS has no ``PR_SET_PDEATHSIG``, so something has to outlive Hermes-and reap them.--This module is deliberately standard-library-only and must not import anything-from ``tools/``: it runs after Hermes may already be dead, and pulling in-``mcp_tool`` would drag the whole agent with it. The TERM -> grace -> KILL-``killpg`` sweep in ``_reap`` therefore duplicates similar sweeps elsewhere in-the tree on purpose.--The predecessor (``mcp_stdio_watchdog.py``) solved this with one CPython-*per MCP server*, wrapping each server command and polling ``getppid()`` every-two seconds. That costs ~10 MB of resident memory per server and detects death-up to one poll interval late. This module replaces the whole fleet of pollers-with a single supervisor per Hermes process:--* **Death detection is a blocking read on a pipe.** Hermes holds the only write- end. When Hermes dies -- by any means, including SIGKILL -- the write end- closes and the read returns EOF. Exact, instant, and free.-* **Servers are spawned unwrapped.** The MCP SDK already spawns stdio children- with ``start_new_session=True``, so each one is its own process-group leader- and ``killpg`` still reaches its descendants. Removing the wrapper also- removes the signal-forwarding layer the wrapper needed to avoid inverting the- bug it fixed.--Protocol (line-based, on stdin)--------------------------------- register <pgid>\n start reaping this process group on parent death- unregister <pgid>\n stop reaping it (its server shut down cleanly)--On EOF the supervisor SIGTERMs every still-registered process group, waits a-short grace period, SIGKILLs the survivors, and exits. A registered group that-Hermes never unregistered *is* the orphan set, so a clean Hermes shutdown ---which unregisters as it tears each server down -- ends with nothing to kill.--Unparseable lines are ignored rather than fatal: a corrupted byte on the control-pipe must not cost us the reaping guarantee for every other server.--Residual risk: process-group reuse------------------------------------We reap by pgid, so a registration is only as meaningful as the group's-identity. A group we deliberately keep registered -- an orphan that teardown-failed to kill, such as the ``node`` ``mcp-remote`` leaves behind -- can-eventually exit on its own, after which the kernel is free to hand that pgid to-an unrelated process owned by the same user. If Hermes then dies ungracefully-while the registration is still stale, we would signal a stranger.-``_is_safe_target`` cannot catch this: the value is stale, not invalid.--Two things narrow the window. Hermes prunes registrations whose group has no-members left (``_prune_dead_supervised_pgids``) on every registration change,-and the orphan sweep unregisters whatever it reaps. Neither closes it -- a-group can die and its pgid be recycled between two probes -- so the exposure is-real but bounded to that gap, and requires an ungraceful death inside it.--Closing it completely means proving group identity at reap time, e.g. stamping-MCP children with a boot-unique env marker and checking that some member still-carries it before signalling. That was judged not worth putting a ``ps`` parse-into the one process whose job is to stay simple enough to always work; it is-the obvious next step if this class of bug ever actually bites. Note the same-exposure already exists in Hermes's own killpg-based orphan cleanup, which this-module did not introduce (see upstream issue #88350).-"""--from __future__ import annotations--import argparse-import os-import signal-import sys-import time--# Matches the grace period the per-server watchdog used before it escalated.-_TERM_GRACE_S = 3.0-# How often we re-check for survivors during that grace period.-_REAP_POLL_S = 0.1-# A command is "unregister <pgid>" -- around 20 characters. The cap only has to-# be generous enough for a legitimate line; see _serve for why it exists.-_MAX_LINE_CHARS = 256---def _is_safe_target(pgid: int, *, own_pgid: int, parent_pgid: int) -> bool:- """Return True if ``pgid`` is a process group we may signal.-- Defensive only -- Hermes already filters non-MCP children before it- registers anything (see ``_filter_mcp_children`` in ``tools/mcp_tool.py``).- But this process signals whole process *groups*, so a bad value here is- unusually expensive: ``killpg(0, ...)`` signals our own group, and pgid 1- is init. A caller bug should cost us one unreaped server, never the- Hermes process tree or the session.- """- if pgid <= 1:- return False- if pgid == own_pgid or pgid == parent_pgid:- return False- return True---def _reap(pgids: set[int]) -> None:- """SIGTERM every group, then SIGKILL whatever is still alive.-- Every process-group call below is POSIX-only by construction: this whole- module only ever runs as a child of ``_update_death_supervisor``, which- returns early unless ``os.name == "posix"``, so the supervisor is never- spawned on Windows in the first place.- """- if not pgids:- return-- alive = set()- for pgid in pgids:- try:- os.killpg(pgid, signal.SIGTERM) # windows-footgun: ok — POSIX-only process- alive.add(pgid)- except (ProcessLookupError, PermissionError, OSError):- # Already gone, or not ours to signal. Either way, nothing to reap.- pass-- deadline = time.monotonic() + _TERM_GRACE_S- while alive and time.monotonic() < deadline:- time.sleep(_REAP_POLL_S)- for pgid in list(alive):- try:- # Signal 0 probes liveness: succeeds iff some member survives.- os.killpg(pgid, 0) # windows-footgun: ok — POSIX-only process- except (ProcessLookupError, PermissionError, OSError):- alive.discard(pgid)-- for pgid in alive:- try:- os.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — POSIX-only- except (ProcessLookupError, PermissionError, OSError):- pass---def _serve(stream, *, own_pgid: int, parent_pgid: int) -> set[int]:- """Read control lines until EOF; return the groups still registered.-- Reads are length-capped rather than newline-terminated. Iterating the- stream instead lets a writer that never sends a newline grow this process- without bound -- feeding it ``/dev/zero`` reached 15 GB before it was- stopped. Nothing in Hermes can produce that today, but this process is the- last line of defense against leaked servers, so it must not be the thing- that dies under memory pressure. A line truncated by the cap fails to parse- and is skipped; the remainder resyncs at the next newline.- """- registered: set[int] = set()- while True:- line = stream.readline(_MAX_LINE_CHARS)- if not line:- break # EOF: the parent is gone.- if not line.endswith("\n"):- # Truncated by the cap, or an unterminated tail at EOF. Either way- # it is not a command we are willing to act on.- continue- parts = line.split()- if len(parts) != 2:- continue- verb, raw = parts- try:- pgid = int(raw)- except ValueError:- continue- if verb == "register":- if _is_safe_target(pgid, own_pgid=own_pgid, parent_pgid=parent_pgid):- registered.add(pgid)- elif verb == "unregister":- registered.discard(pgid)- return registered---def main(argv=None) -> int:- parser = argparse.ArgumentParser(- description="Reap registered process groups when the parent dies."- )- parser.add_argument(- "--parent-pgid",- type=int,- required=True,- help="Process group of the spawning Hermes process; never signalled.",- )- args = parser.parse_args(argv)-- # The parent may be torn down with killpg on its own group. We are spawned- # with start_new_session=True precisely so that sweep cannot take us with- # it before we have reaped -- assert that here rather than trust the caller.- own_pgid = os.getpgid(0)- if own_pgid == args.parent_pgid:- print(- "mcp_death_supervisor: refusing to run inside the parent's process "- "group (a killpg of the parent would kill us before we can reap)",- file=sys.stderr,- )- return 2-- # A dying parent's SIGINT/SIGHUP must not preempt the reap; the pipe's EOF- # is our only shutdown signal. SIGHUP is POSIX-only, which is fine here --- # this process is never spawned on Windows (see _reap's docstring).- for sig in (signal.SIGINT, signal.SIGHUP): # windows-footgun: ok — POSIX-only process- try:- signal.signal(sig, signal.SIG_IGN)- except (ValueError, OSError):- pass-- registered = _serve(sys.stdin, own_pgid=own_pgid, parent_pgid=args.parent_pgid)- _reap(registered)- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex bd29e0f88dd..d4382b5477a 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -568,130 +568,6 @@ _mcp_thread: Optional[threading.Thread] = None_lock = threading.Lock()-# ---- Shared parent-death supervisor (state lives HERE: tests rebind ``_death_supervisor``) -----# If this process dies without running its cleanup path (kill -9, OOM, crash, force-quit), stdio-# MCP children reparent to init and run forever; macOS has no PR_SET_PDEATHSIG, so something has-# to outlive us and reap them. ONE supervisor process serves all stdio servers and is told which-# process groups to reap over a pipe; it detects our death as EOF on that pipe (exact, instant)-# rather than polling getppid(). Replaced the per-server watchdog wrapper (~10 MB resident per-# server, plus a signal-forwarding layer because wrapping put the server in a different session-# from the pgid tracked for killpg). See tools/mcp_death_supervisor.py. POSIX-only, matching the-# killpg-based orphan cleanup below.-_death_supervisor = None # Optional[subprocess.Popen]-_death_supervisor_lock = threading.Lock()-# Groups the supervisor is reaping on our behalf; replayed verbatim on respawn so a respawn never-# silently drops coverage for servers that are still running.-_supervised_pgids: set = set()---def _spawn_death_supervisor():- """Start the shared supervisor, or None if it cannot be started."""- import subprocess- supervisor = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mcp_death_supervisor.py")- try:- # start_new_session=True is load-bearing: shutdown paths killpg this process's own group,- # which would kill the supervisor before it could reap anything.- return subprocess.Popen(- [sys.executable, supervisor, "--parent-pgid", str(os.getpgid(0))],- stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=_get_mcp_stderr_log(),- start_new_session=True, close_fds=True, text=True)- except Exception:- # Never let supervisor bookkeeping block a real MCP connection: graceful shutdown paths- # still reap normally; only the ungraceful-exit safety net is lost.- logger.debug("Could not start the MCP parent-death supervisor", exc_info=True)- return None---def _prune_dead_supervised_pgids() -> set:- """Forget supervised groups with no members left; return what went. Caller holds- ``_death_supervisor_lock``. Signal 0 is a pure existence probe (cannot terminate anything).- It narrows, but cannot close, the window where a dead group's pgid is recycled before we- notice (residual-risk note in ``tools/mcp_death_supervisor.py``)."""- killpg = getattr(os, "killpg", None)- if killpg is None: # windows-footgun: ok - POSIX-only, guarded- return set()- stale = set()- for pgid in list(_supervised_pgids):- try:- killpg(pgid, 0)- except ProcessLookupError:- stale.add(pgid)- except (PermissionError, OSError):- # Exists but not ours to signal, or the probe failed: keep it — dropping coverage on- # an ambiguous answer is the more expensive mistake.- pass- _supervised_pgids.difference_update(stale)- return stale---def _update_death_supervisor(verb: str, pgids) -> None:- """Register or unregister process groups (``verb`` is ``"register"``/``"unregister"``) with- the shared supervisor. Failures are swallowed: losing the safety net must never fail a live- MCP session."""- if os.name != "posix":- return- wanted = {int(pgid) for pgid in pgids}- if not wanted:- return-- global _death_supervisor- with _death_supervisor_lock:- if verb == "register":- _supervised_pgids.update(wanted)- else:- _supervised_pgids.difference_update(wanted)-- # A registration outlives the server only while some member survives (e.g. an orphaned- # grandchild teardown failed to kill, deliberately kept registered). Once that group is- # empty its pgid can be recycled by a stranger, so prune here too — the orphan sweep- # unregisters what it reaps but is not guaranteed to run in a given process.- stale = _prune_dead_supervised_pgids()-- proc = _death_supervisor- if proc is None or proc.poll() is not None:- if not _supervised_pgids:- # Nothing left to cover: nothing to tell and nothing to respawn for. Keyed on- # the SET, not the verb: after a broken-pipe write dropped the supervisor with- # groups still registered, an unregister must still rebuild coverage for the- # survivors.- return- # See #93517.- proc = _spawn_death_supervisor()- _death_supervisor = proc- if proc is None:- return- # A fresh supervisor knows nothing: replay live coverage (already reflects this- # call's mutation and the prune, so pruned groups never reach the replacement).- payload = "".join(f"register {pgid}\n" for pgid in _supervised_pgids)- else:- payload = "".join(f"{verb} {pgid}\n" for pgid in wanted)- payload += "".join(f"unregister {pgid}\n" for pgid in stale)-- try:- proc.stdin.write(payload)- proc.stdin.flush()- except (BrokenPipeError, ValueError, OSError):- # It exited between poll() and write(). Drop it so the next call respawns and replays- # from ``_supervised_pgids`` (the set, not the pipe, is the record of what needs reaping).- _death_supervisor = None- return-- if not _supervised_pgids:- # Nothing left to reap: release the supervisor rather than keep a ~15 MB process and a- # pipe resident for the life of a gateway. Closing our write end is the same EOF parent- # death sends; with an empty set it exits. The next register respawns and replays.- try:- proc.stdin.close()- except (BrokenPipeError, ValueError, OSError):- pass- # Reap it, or the exited supervisor stays a zombie until the next Popen in this process.- try:- proc.wait(timeout=5)- except Exception:- pass- _death_supervisor = None--def _mcp_registry_scope() -> Optional[str]:"""Registry scope for MCP registrations: the session's own tool scope when one is bound, else aprofile overlay when this process serves profiles, else None. Under ``gateway.multiplex_profiles``diff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.pyindex b593af2fe80..4525a4fc438 100644--- a/tools/mcp_tool_lifecycle.py+++ b/tools/mcp_tool_lifecycle.py@@ -6,6 +6,7 @@ import asyncioimport osimport timefrom typing import Dict, Optional+from hermes_cli.process_identity import update_supervised_pgidsfrom tools.mcp_tool_common import _corefrom tools import mcp_tool_loop as _loop@@ -385,7 +386,7 @@ def _kill_orphaned_mcp_children(include_active: bool = False, server_name: Optiologger.warning("Force-killed MCP process %d (%s) after SIGTERM timeout", pid, owner)# These groups are reaped. Release them last, so a crash partway through the SIGTERM/SIGKILL# dance still leaves the supervisor holding them.- _core._update_death_supervisor("unregister", pgids.values())+ update_supervised_pgids("unregister", pgids.values())def _stop_mcp_loop_if_idle() -> bool:diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex 32a70d2869d..a65da16963f 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -14,6 +14,7 @@ from agent.proxy_bypass import is_loopback_host, should_bypass_proxyfrom agent import runtime_cwd as _runtime_cwdfrom tools.mcp_tool_errors import _MCP_HTTP_MAX_BODY_BYTES, NonMcpEndpointError, _apply_identity_header, _describe_http_failure, _handshake_answered_with_unsupported_version, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_http_rejection_recorder, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_groupfrom tools.mcp_tool_lifecycle import _filter_mcp_children, _leader_start_time, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pids, _stdio_starttimes+from hermes_cli.process_identity import register_child, update_supervised_pgidsfrom tools.mcp_tool_common import _corefrom tools.mcp_tool_node_abi import node_abi_errorfrom tools import mcp_tool_config as _config@@ -330,7 +331,6 @@ class MCPServerTransportMixin:# Machine spawn ledger (startup sweeps reap orphans after an unclean exit); best-effort.for _pid in new_pids:try:- from hermes_cli.process_identity import register_childregister_child(_pid, "mcp-helper")except Exception:logger.debug("spawn-ledger register_child failed for MCP helper pid %s", _pid, exc_info=True)@@ -338,7 +338,7 @@ class MCPServerTransportMixin:# process (kill -9, crash, force-quit) can't leave this server — or its descendants, e.g.# mcp-remote's spawned `node` — running forever. The graceful paths (shutdown,# _kill_orphaned_mcp_children) still reap as before; this only covers when they never run.- _core._update_death_supervisor("register", new_pgids.values())+ update_supervised_pgids("register", new_pgids.values())def _release_spawned_children(self, new_pids: set[int]) -> None:"""Drop the ledger entries; a child (or its pgroup) still alive means SDK teardown failed@@ -360,7 +360,7 @@ class MCPServerTransportMixin:if dropped is not None:released_pgids.append(dropped)_stdio_starttimes.pop(pid, None)- _core._update_death_supervisor("unregister", released_pgids)+ update_supervised_pgids("unregister", released_pgids)async def _run_stdio(self, config: dict):"""Run the server using stdio transport."""