Skip to content

The agent that grows with you

fix(cron): lifecycle guard blocks kills aimed at the gateway's own interpreter image

teknium1726bccd28d70
diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.py
index f85c46076ef..7565b02d0f1 100644
--- a/cron/lifecycle_guard.py
+++ b/cron/lifecycle_guard.py
@@ -14,6 +14,7 @@ import os
import re
import shlex
import stat
+import sys
from pathlib import Path
from typing import Callable, Iterator, Optional
@@ -65,16 +66,145 @@ _GATEWAY_LIFECYCLE_PATTERN = re.compile(
r"|(?:\b(?:p?kill|taskkill|stop-process)\b[^\n]*\bgateway\b[^\n]*\bhermes)"
)
-# Branch E: Windows image-name termination of the interpreter that runs the gateway. A gateway
-# process normally has the image name ``python.exe``; unlike a PID-targeted taskkill, ``/IM
-# python.exe`` terminates it even when the agent does not know its PID. Keep this tied to the
-# concrete taskkill command and its ``/IM`` option so other image names remain available to jobs.
-# The tokenized re-scan in ``contains_gateway_lifecycle_command`` applies this pattern after shell
-# quotes and escapes are resolved, just as it does for the other lifecycle branches (#113667).
-_TASKKILL_GATEWAY_INTERPRETER_PATTERN = re.compile(
- r"(?i)(?<![/\w.\-])taskkill(?:\.exe)?\b"
- r"(?=[^;\n|&]*(?:/im(?:\s+|:)\s*(?:['\"]?python\.exe['\"]?)(?=$|[\s,;|&\)])))"
-)
+# Branch E: process killers whose TARGET is the interpreter image hosting the gateway. A supervised
+# gateway is literally `python.exe` / `python3.12` (`python -m hermes_cli.main gateway run`), so
+# `taskkill /F /IM python.exe`, `pkill -9 python3` or `killall python` carry no hermes/gateway token
+# yet terminate it (#113667). Token-aware rather than a line regex: option VALUES are never read as
+# targets (`pkill -u <user> chrome`), `-f` cmdline patterns are judged as patterns, and other image
+# names (`taskkill /F /IM agent-browser.exe`) stay available. Numeric-PID kills are out of scope:
+# the explicit PID / `proc_*` id IS the ownership-scoped route the rejection points to.
+_INTERPRETER_IMAGE_RE = re.compile(r"^pythonw?(?:\d+(?:\.\d+)*)?(?:\.exe)?$")
+_HOST_INTERPRETER_NAME = Path(sys.executable).name.lower() if sys.executable else ""
+_KILLER_VALUE_OPTIONS = {
+ # procps pkill/pgrep options that consume the next token, so the value is never the pattern.
+ "pkill": frozenset({
+ "-g", "--pgroup", "-G", "--group", "-P", "--parent", "-s", "--session", "-t", "--terminal",
+ "-u", "--euid", "-U", "--uid", "-F", "--pidfile", "--ns", "--nslist", "-d", "--delimiter",
+ "--signal", "-O", "--older", "-r", "--runstates", "--cgroup", "-A", "--ignore-ancestors",
+ }),
+ "killall": frozenset({"-s", "--signal", "-u", "--user", "-o", "--older-than", "-y", "--younger-than",
+ "-n", "--ns", "-Z", "--context"}),
+}
+_KILLER_VALUE_OPTIONS["pgrep"] = _KILLER_VALUE_OPTIONS["pkill"]
+_KILLER_VALUE_OPTIONS["pidof"] = frozenset({"-o", "--omit-pid", "-S", "--separator"})
+# Regex metacharacters a pkill/pgrep ERE may carry around the interpreter name (`^python3?$`, `python.*`).
+_ERE_TAIL = re.compile(r"[.*+?\\\[\](){}|].*$")
+_ERE_WILDCARD_ONLY = re.compile(r"^[.*+?$\s]*$")
+_NAME_KILLERS = frozenset({"pkill", "killall", "taskkill", "stop-process"})
+_NAME_ENUMERATORS = frozenset({"pgrep", "pidof", "get-process"})
+_KILL_VERB_RE = re.compile(r"(?i)\b(?:kill|taskkill|stop-process)\b")
+
+
+def _is_interpreter_image(value: str, *, substring: bool = False) -> bool:
+ """True when *value* (a process/image name, `*`-wildcard allowed) denotes the Python interpreter
+ that hosts the gateway. *substring*: pkill/pgrep match an ERE anywhere in the name, so `py`
+ reaches `python3` too."""
+ name = value.strip().strip("\"'").lower().removesuffix(".exe")
+ if not name:
+ return False
+ if name.endswith("*"):
+ prefix = name.rstrip("*")
+ return "python".startswith(prefix) or _HOST_INTERPRETER_NAME.startswith(prefix)
+ if _INTERPRETER_IMAGE_RE.match(name) or name == _HOST_INTERPRETER_NAME.removesuffix(".exe"):
+ return True
+ return substring and len(name) >= 2 and "python".startswith(name)
+
+
+def _pattern_reaches_host_interpreter(pattern: str, *, full_cmdline: bool, exact: bool) -> bool:
+ """pkill/pgrep/killall operand semantics: an ERE against the process NAME (or, with `-f`, the full
+ command line). `python -m hermes_cli.main …` is the gateway's own cmdline, so a `-f` pattern
+ that names the interpreter and then only wildcards or a `hermes` token reaches it, while
+ `python mt_add.py` (a specific script) does not."""
+ core = pattern.strip().strip("\"'").lstrip("^")
+ if core.endswith("$"):
+ core = core[:-1]
+ head, _, rest = core.partition(" ") if full_cmdline else (core, "", "")
+ # A literal interpreter name first (`python3.12`: the dot is a version separator, not an ERE
+ # wildcard); only then read the head as an ERE with a metacharacter tail (`python3?`, `python.*`).
+ match = None if _is_interpreter_image(head, substring=not exact) else _ERE_TAIL.search(head)
+ if match:
+ rest = head[match.start():] + " " + rest
+ head = head[: match.start()]
+ if not _is_interpreter_image(head, substring=not exact):
+ return full_cmdline and "hermes" in core.lower()
+ return not rest.strip() or bool(_ERE_WILDCARD_ONLY.match(rest)) or "hermes" in rest.lower()
+
+
+def _killer_targets_host_interpreter(name: str, args: list[str]) -> bool:
+ """Whether killer/enumerator *name* with argv *args* would select the host interpreter."""
+ if name in ("pkill", "pgrep", "killall", "pidof"):
+ # pkill/pgrep: ERE anywhere in the name unless -x; killall: exact name unless -r; pidof: exact.
+ exact = name == "pidof" or (name == "killall") != any(t in ("-r", "--regexp", "-x", "--exact") for t in args)
+ full_cmdline = name in ("pkill", "pgrep") and any(t in ("-f", "--full") for t in args)
+ operands: list[str] = []
+ position = 0
+ while position < len(args):
+ token = args[position]
+ if token == "--":
+ operands += args[position + 1:]
+ break
+ if token in _KILLER_VALUE_OPTIONS[name]:
+ position += 2
+ continue
+ if not token.startswith("-"):
+ operands.append(token)
+ position += 1
+ return any(_pattern_reaches_host_interpreter(op, full_cmdline=full_cmdline, exact=exact) for op in operands)
+ if name == "taskkill":
+ for position, token in enumerate(args[:-1]):
+ option = token.lower().lstrip("/-")
+ value = args[position + 1]
+ if option == "im" and _is_interpreter_image(value):
+ return True
+ if option == "fi":
+ filter_match = re.match(r"(?i)\s*['\"]?imagename\s+eq\s+(\S+)", value)
+ if filter_match and _is_interpreter_image(filter_match.group(1)):
+ return True
+ return False
+ # Stop-Process / Get-Process: `-Name`/`-ProcessName` (also `-Name:value`), comma lists, positional
+ # names for Get-Process.
+ values: list[str] = []
+ for position, token in enumerate(args):
+ option, _, inline_value = token.partition(":")
+ if option.lower() in ("-name", "-processname", "-n"):
+ values.append(inline_value if inline_value else (args[position + 1] if position + 1 < len(args) else ""))
+ elif name == "get-process" and not token.startswith("-") and (position == 0 or not args[position - 1].startswith("-")):
+ values.append(token)
+ return any(_is_interpreter_image(part) for value in values for part in value.split(","))
+
+
+def _segment_names_host_interpreter(tokens: list[str], killers: frozenset[str]) -> bool:
+ """Whether a tokenized segment runs one of *killers* against the host interpreter. The
+ executable is read at the wrapper-peeled position first, then at the first killer token anywhere
+ in the segment (`xargs kill`, Python argv lists)."""
+ index = _executed_command_index(tokens)
+ candidates = [index] if index is not None else []
+ candidates += [i for i, token in enumerate(tokens) if _executable_name(token).lower().removesuffix(".exe") in killers]
+ for position in candidates:
+ name = _executable_name(tokens[position]).lower().removesuffix(".exe")
+ if name in killers and _killer_targets_host_interpreter(name, tokens[position + 1:]):
+ return True
+ return False
+
+
+def contains_host_interpreter_kill(text: str) -> bool:
+ """Branch E entrypoint: a process killer aimed at the interpreter image hosting the gateway, or a
+ name-derived PID feed into one (`pgrep python | xargs kill`, `kill $(pidof python3)`,
+ `Get-Process python | Stop-Process`). Segment-tokenized, so quoted/spliced spellings and Python
+ argv lists resolve the same way the shell resolves them."""
+ normalized = _SHELL_LINE_CONTINUATION.sub(" ", text)
+ kill_verb_present = bool(_KILL_VERB_RE.search(normalized))
+ for segment in _iter_command_segments(normalized):
+ joined = " ".join(segment)
+ stripped = _ARGV_LIST_PUNCTUATION.sub(" ", joined)
+ # Python argv lists (`subprocess.run(["taskkill", "/IM", "python.exe"])`) re-split only when
+ # list punctuation was present, so a quoted `-f 'python my_script.py'` stays one operand.
+ for tokens in ([segment, stripped.split()] if stripped != joined else [segment]):
+ if _segment_names_host_interpreter(tokens, _NAME_KILLERS):
+ return True
+ if kill_verb_present and _segment_names_host_interpreter(tokens, _NAME_ENUMERATORS):
+ return True
+ return False
# Every branch uses `[^\n]*` between verb and label so matches cannot span unrelated lines. A POSIX
# backslash-newline continuation is therefore collapsed to a space before matching (as the shell
@@ -284,10 +414,7 @@ def contains_gateway_lifecycle_command(text: str) -> bool:
text = strip_inert_heredoc_bodies(text)
normalized = _SHELL_LINE_CONTINUATION.sub(" ", text)
- if (
- _GATEWAY_LIFECYCLE_PATTERN.search(normalized)
- or _TASKKILL_GATEWAY_INTERPRETER_PATTERN.search(normalized)
- ):
+ if _GATEWAY_LIFECYCLE_PATTERN.search(normalized):
return True
# Profile-flag form: blocked only when the named profile IS the one running the guard.
# Profile-flag form (#78028): `hermes -p <profile> gateway restart|stop` bypasses Branch A because the
@@ -308,23 +435,18 @@ def contains_gateway_lifecycle_command(text: str) -> bool:
# passes apply independently.
for segment in _iter_command_segments(normalized):
joined = " ".join(segment)
- if joined and (
- _GATEWAY_LIFECYCLE_PATTERN.search(joined)
- or _TASKKILL_GATEWAY_INTERPRETER_PATTERN.search(joined)
- ):
+ if joined and _GATEWAY_LIFECYCLE_PATTERN.search(joined):
return True
stripped = _ARGV_LIST_PUNCTUATION.sub(" ", joined)
- if stripped != joined and (
- _GATEWAY_LIFECYCLE_PATTERN.search(stripped)
- or _TASKKILL_GATEWAY_INTERPRETER_PATTERN.search(stripped)
- ):
+ if stripped != joined and _GATEWAY_LIFECYCLE_PATTERN.search(stripped):
return True
# The label may be built in an earlier `;`-segment, so no pass above sees verb + label together.
# Order-independent launchctl pass (#77083): a shell loop can build the gateway label from a variable
# defined in an earlier `;`-separated segment (`label=${item%%:*}; launchctl bootout
# "gui/$uid/$label"`), so neither the same-span regex nor same-segment tokenization sees verb and label
# together. Check "verb anywhere AND label anywhere" instead.
- return _contains_launchctl_gateway_lifecycle(normalized)
+ # Branch E (#113667): killers aimed at the interpreter image itself carry no hermes/gateway token.
+ return _contains_launchctl_gateway_lifecycle(normalized) or contains_host_interpreter_kill(normalized)
# Whole-walk work limits. The per-file cap and depth bound above limit one read, not the walk: a
diff --git a/gateway/restart.py b/gateway/restart.py
index 2598feb28c0..05dd27d83bd 100644
--- a/gateway/restart.py
+++ b/gateway/restart.py
@@ -75,13 +75,35 @@ def is_global_startup_conflict(error_code: str | None) -> bool:
def is_gateway_supervisor_process(environ: Mapping[str, str] | None = None) -> bool:
- """Return whether this gateway process is owned by a supervisor."""
+ """Return whether this gateway process is owned by a supervisor that RESTARTS it.
+
+ Selects the exit-75 restart route, so only markers of a manager with a restart policy count:
+ systemd ``INVOCATION_ID``, launchd ``XPC_SERVICE_NAME``, the s6 sentinel, or the explicit
+ ``--external-supervisor`` opt-in. The generalized ``HERMES_SUPERVISED_CHILD`` launcher marker is
+ deliberately NOT read here: the Windows Scheduled-Task launcher sets it without a restart policy
+ (#113670), and routing its ``/restart`` through exit 75 would leave the gateway dead.
+ """
env = os.environ if environ is None else environ
xpc_service = env.get("XPC_SERVICE_NAME", "")
return bool(env.get("INVOCATION_ID") or env.get("HERMES_S6_SUPERVISED_CHILD") or (xpc_service and xpc_service != "0")
or str(env.get(EXTERNAL_GATEWAY_SUPERVISOR_ENV, "")).strip().lower() in _TRUTHY)
+def is_supervised_gateway_launch(environ: Mapping[str, str] | None = None) -> bool:
+ """Return whether this gateway was launched by a generated service/launcher rather than a shell.
+
+ Superset of :func:`is_gateway_supervisor_process` that also honours ``HERMES_SUPERVISED_CHILD``,
+ the marker every generated launcher exports (systemd unit, launchd plist, s6 run script, Windows
+ Scheduled Task — see ``hermes_cli.main._apply_profile_override``). This is the identity the
+ self-targeting guards key on: a kill or lifecycle command issued from inside such a gateway takes
+ down the process hosting the caller with nobody at a terminal to bring it back (#113667).
+ """
+ env = os.environ if environ is None else environ
+ if env.get("HERMES_SUPERVISED_CHILD"):
+ return True
+ return is_gateway_supervisor_process() if environ is None else is_gateway_supervisor_process(environ)
+
+
def is_container_restart_context() -> bool:
"""In a container (Docker/Podman) the detached setsid restart path dies with the cgroup,
so exit-75 service restart is the only viable path. Own function so tests can mock it."""
diff --git a/tests/gateway/test_restart_service_detection.py b/tests/gateway/test_restart_service_detection.py
index aeb1611cf5b..80d84c355a7 100644
--- a/tests/gateway/test_restart_service_detection.py
+++ b/tests/gateway/test_restart_service_detection.py
@@ -76,3 +76,18 @@ async def test_false_external_supervisor_marker_keeps_detached_path(
await runner._handle_restart_command(_make_restart_event())
runner.request_restart.assert_called_once_with(detached=True, via_service=False)
+
+
+def test_supervised_child_marker_is_a_launch_not_a_restart_route():
+ """The Windows Scheduled-Task launcher exports only ``HERMES_SUPERVISED_CHILD``: that must make
+ the gateway a supervised LAUNCH (self-kill guards active, #113667) without selecting the exit-75
+ restart route, which the task cannot honour (#113670)."""
+ from gateway.restart import is_gateway_supervisor_process, is_supervised_gateway_launch
+ from hermes_cli.gateway_windows import _GATEWAY_ENV
+
+ task_env = dict(_GATEWAY_ENV)
+ assert task_env["HERMES_SUPERVISED_CHILD"] == "1"
+ assert is_supervised_gateway_launch(task_env) is True
+ assert is_gateway_supervisor_process(task_env) is False
+ assert is_supervised_gateway_launch({}) is False
+ assert is_supervised_gateway_launch({"INVOCATION_ID": "abc"}) is True
diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.py
index 4a15c8e89de..54c625acb14 100644
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@ -24,82 +24,57 @@ class TestGatewayLifecyclePattern:
"""Verify the regex catches gateway lifecycle commands."""
@pytest.mark.parametrize("text", [
+ # Branch E (#113667): the supervised gateway IS the interpreter image, so a killer aimed at
+ # `python*` carries no hermes/gateway token yet takes it down — on every platform.
"taskkill /F /IM python.exe",
- "taskkill /IM python.exe /F",
- 'taskkill /F /IM "python.exe"',
- '"taskkill" /IM "python.exe" /F',
+ "taskkill /F /IM python.exe 2>/dev/null | head -2; echo done",
+ 'taskkill /F /FI "IMAGENAME eq python.exe"',
+ "taskkill.exe /T /IM pythonw.exe",
'task"kill" /I"M" "python.exe" /F',
- "taskkill.exe /T /IM python.exe",
'subprocess.run(["taskkill", "/IM", "python.exe", "/F"])',
- ])
- def test_taskkill_gateway_interpreter_image_is_blocked(self, text):
- """Image-name taskkill can terminate the gateway's Python process (#113667)."""
- assert _contains_gateway_lifecycle_command(text), f"Should match: {text!r}"
-
- @pytest.mark.parametrize("text", [
- "taskkill /F /IM notepad.exe",
- "taskkill /IM chrome.exe /F",
- ])
- def test_taskkill_other_image_names_are_allowed(self, text):
- assert not _contains_gateway_lifecycle_command(text), f"Should NOT match: {text!r}"
-
- @pytest.mark.parametrize("text", [
- "hermes gateway restart",
- "hermes gateway stop",
- "hermes gateway uninstall",
- "hermes gateway restart", # double spaces
- "Hermez Gateway Restart".lower().replace("z", "s"), # case handled
- "HERMES GATEWAY RESTART", # uppercase
- ])
- def test_hermes_gateway_commands(self, text):
- assert _contains_gateway_lifecycle_command(text), f"Should match: {text!r}"
-
- @pytest.mark.parametrize("text", [
- # Windows spells the CLI with an executable suffix, and npm-style
- # shims install `hermes.cmd` / `hermes.ps1` beside the `.exe`.
- # Anchoring Branch A on the bare name let every one of these walk past
- # a guard that stops `hermes gateway restart`. The guard is gated on
- # PID-file ownership, not on platform, so the bypass was live for any
- # supervised gateway running on Windows.
+ "Stop-Process -Name python -Force",
+ "Stop-Process -ProcessName python3.12",
+ "Get-Process python | Stop-Process -Force",
+ "pkill python",
+ "pkill -9 python3",
+ "pkill -f python",
+ 'pkill -f "python -m hermes_cli.main"',
+ "pkill -f hermes_cli",
+ "killall -9 python3.12",
+ "sudo pkill -9 python3",
+ "pgrep python | xargs kill -9",
+ "kill $(pidof python3)",
+ # Windows spellings of the hermes-gateway forms (salvaged from #94379).
"hermes.exe gateway restart",
"hermes.cmd gateway stop",
- "hermes.bat gateway restart",
- "hermes.ps1 gateway uninstall",
- "HERMES.EXE gateway restart",
- r"C:\tools\hermes.exe gateway stop",
- r".\hermes.exe gateway restart",
- # Quoted and wrapped spellings reach the same place via the
- # tokenizing rescan; pin them so the suffix survives that path too.
r'"C:\Program Files\hermes.exe" gateway restart',
- "cmd /c hermes.exe gateway restart",
- 'powershell -Command "hermes.exe gateway restart"',
- ])
- def test_windows_executable_suffix_is_caught(self, text):
- assert _contains_gateway_lifecycle_command(text), f"Should match: {text!r}"
-
- @pytest.mark.parametrize("text", [
- # `taskkill` / `Stop-Process` are the Windows spellings of pkill.
- # `\bp?kill\b` cannot reach inside `taskkill` — there is no word
- # boundary between the two `k`s — so they need naming outright.
"taskkill /F /IM hermes-gateway.exe",
"Stop-Process -Name hermes-gateway -Force",
- "stop-process -name hermes-gateway",
])
- def test_windows_process_kill_forms_are_caught(self, text):
+ def test_interpreter_and_windows_kill_forms_are_blocked(self, text):
assert _contains_gateway_lifecycle_command(text), f"Should match: {text!r}"
@pytest.mark.parametrize("text", [
- # The suffix must not widen the match. `start` stays deliberately
- # benign, an unrelated process is not the gateway, and the word-tail
- # exclusion still holds once a suffix is attached.
- "hermes.exe gateway start",
- "hermes.exe chat",
+ # Other images stay killable (evals/browser_use/orchestrate.py uses the first one).
+ "taskkill /F /IM agent-browser.exe /T",
"taskkill /F /IM notepad.exe",
"Stop-Process -Name chrome",
+ "killall node",
+ # The ownership-scoped route the rejection points to: explicit PID / proc id.
+ "taskkill /F /PID 46544",
+ "kill -9 46544",
+ "Stop-Process -Id 46544",
+ # Option VALUES are not targets; a `-f` pattern naming a specific script is not the gateway.
+ "pkill -u alice chrome",
+ "pkill -t pts/1 vim",
+ "pkill -f 'python mt_add_paused.py --go'",
+ "pgrep python",
+ "hermes.exe gateway start",
"my-hermes.exe gateway restart",
- "hermesexe gateway restart",
+ "python -m pytest tests/ -k kill",
+ "skill python",
])
- def test_windows_forms_do_not_overmatch(self, text):
+ def test_kill_forms_that_do_not_reach_the_gateway_are_allowed(self, text):
assert not _contains_gateway_lifecycle_command(text), f"Should NOT match: {text!r}"
@pytest.mark.parametrize("text", [
diff --git a/tests/tools/test_launchctl_guard_diagnostic.py b/tests/tools/test_launchctl_guard_diagnostic.py
index 9aeba7f1a28..fa4a6ee7f7e 100644
--- a/tests/tools/test_launchctl_guard_diagnostic.py
+++ b/tests/tools/test_launchctl_guard_diagnostic.py
@@ -29,3 +29,32 @@ def test_bootstrap_rejection_does_not_invent_keepalive(tmp_path, monkeypatch):
assert "does not inspect" in result["error"]
assert "KeepAlive settings" in result["error"]
assert "separate shell outside the gateway" in result["error"]
+
+
+def test_interpreter_kill_rejection_names_the_owned_process_route(tmp_path, monkeypatch):
+ """Scheduled-Task topology (#113667): only ``HERMES_SUPERVISED_CHILD`` marks the launch, and an
+ image-name kill of the interpreter is refused with the ``proc_*`` / explicit-PID route named.
+ Other images and explicit PIDs pass."""
+ import os
+
+ monkeypatch.setenv("_HERMES_GATEWAY", "1")
+ monkeypatch.setenv("HERMES_SUPERVISED_CHILD", "1")
+ for marker in ("INVOCATION_ID", "XPC_SERVICE_NAME", "HERMES_S6_SUPERVISED_CHILD", "HERMES_GATEWAY_EXTERNAL_SUPERVISOR"):
+ monkeypatch.delenv(marker, raising=False)
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda *a, **k: os.getpid())
+
+ def run(command):
+ return gateway_lifecycle_block(
+ command=command, env=None, env_type="local", cwd=str(tmp_path), workdir=None,
+ session_key="diagnostic-test",
+ )
+
+ blocked = json.loads(run("taskkill /F /IM python.exe 2>/dev/null | head -2"))
+ assert blocked["exit_code"] == 1
+ assert "proc_" in blocked["error"] and "explicit PID" in blocked["error"]
+ assert "proc_" in json.loads(run("pkill -9 python3"))["error"]
+ assert run("taskkill /F /IM agent-browser.exe /T") is None
+ assert run("taskkill /F /PID 46544") is None
+ # Absence on the wrong side: a plain foreground `hermes gateway run` carries no launch marker.
+ monkeypatch.delenv("HERMES_SUPERVISED_CHILD")
+ assert run("pkill -9 python3") is None
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 673880e09d5..601f7308aed 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -263,14 +263,17 @@ def _is_supervised_gateway_process() -> bool:
"""Whether this process is the live, supervised Hermes gateway itself.
Supervisor markers and ``_HERMES_GATEWAY`` are inherited by every descendant (and
importing ``gateway.run`` sets the latter), so also require ownership of the live
- gateway PID file — scopes are for the gateway, not terminal children or CLIs."""
+ gateway PID file — scopes are for the gateway, not terminal children or CLIs.
+ Reads the launch marker (``HERMES_SUPERVISED_CHILD`` included), not the restart-route
+ probe: a Windows Scheduled-Task gateway sets only that marker, and the self-kill guards
+ gated here must protect it too (#113667)."""
if os.environ.get("_HERMES_GATEWAY") != "1":
return False
try:
- from gateway.restart import is_gateway_supervisor_process
+ from gateway.restart import is_supervised_gateway_launch
from gateway.status import get_running_pid
- return is_gateway_supervisor_process() and get_running_pid(cleanup_stale=False) == os.getpid()
+ return is_supervised_gateway_launch() and get_running_pid(cleanup_stale=False) == os.getpid()
except Exception as exc:
logger.debug("Could not verify supervised gateway process identity: %s", exc)
return False
diff --git a/tools/terminal_tool_guards.py b/tools/terminal_tool_guards.py
index d01861bb167..954a904427a 100644
--- a/tools/terminal_tool_guards.py
+++ b/tools/terminal_tool_guards.py
@@ -204,6 +204,7 @@ def gateway_lifecycle_block(
return None
from cron.lifecycle_guard import (
_MAX_REFERENCED_SCRIPT_BYTES,
+ contains_host_interpreter_kill,
contains_launchctl_submit_command,
lifecycle_scan_root_within_budget,
scan_gateway_lifecycle,
@@ -244,6 +245,16 @@ def gateway_lifecycle_block(
"error",
)
if unsafe:
+ # Name the ownership-scoped route for image-name kills: the intent is almost always "stop
+ # MY background job", and re-rolling the same over-broad spelling is what takes the gateway down.
+ if lifecycle_scan_root_within_budget(command) and contains_host_interpreter_kill(command):
+ return _blocked_json(
+ "Blocked: this command kills every process whose image/name matches the Python "
+ "interpreter, which is the process hosting this gateway (and this command). "
+ "Stop only the process you own instead: process(action=\"kill\", session_id=\"proc_…\") "
+ "for a background job Hermes started, or kill/taskkill by its explicit PID.",
+ "error",
+ )
return _blocked_json(
"Blocked: command or referenced script cannot restart, stop, or "
"uninstall the gateway from inside the gateway process. The gateway would "
diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.md
index 766befd5191..ba202919b77 100644
--- a/website/docs/user-guide/security.md
+++ b/website/docs/user-guide/security.md
@@ -100,6 +100,18 @@ restarting the gateway from inside its own supervised process. A self-restart ca
terminate the tool before it finishes and cause a supervisor/auto-resume loop.
User approval, YOLO mode, and `force=True` do not bypass this guard.
+The guard also refuses process killers aimed at the interpreter image the gateway
+runs as — `taskkill /F /IM python.exe`, `taskkill /FI "IMAGENAME eq python.exe"`,
+`Stop-Process -Name python`, `pkill -9 python3`, `killall python`, `pkill -f python`,
+and name-derived kills such as `pgrep python | xargs kill` — because a supervised
+gateway is literally a `python` process and such a command takes it (and the agent's
+own turn) down. Kills scoped to a process the agent owns pass: the `proc_*` id of a
+background job (`process(action="kill", …)`) or an explicit PID
+(`taskkill /F /PID <pid>`, `kill <pid>`). Other image names (`taskkill /F /IM notepad.exe`)
+are unaffected. The guard is active under every generated launcher — systemd unit,
+launchd plist, s6 run script and the Windows Scheduled Task — via the
+`HERMES_SUPERVISED_CHILD` marker they export.
+
On macOS, executed `launchctl submit` and `launchctl bootstrap` commands are
restricted **regardless of the job label**. This is a conservative registration
restriction intended to catch indirect restart helpers with neutral labels, not