Skip to content

The agent that grows with you

fix: preserve task XML encoding and document service binding refusals

Teknium7b904f95bf3a
diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.py
index f785d5873d7..b1137b11162 100644
--- a/hermes_cli/gateway_runtime_service.py
+++ b/hermes_cli/gateway_runtime_service.py
@@ -50,9 +50,9 @@ class ExistingService:
running: bool = False
-def _run(argv: list[str] | tuple[str, ...], deadline: float):
+def _run(argv: list[str] | tuple[str, ...], deadline: float, *, encoding: str | None = "utf-8"):
return subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True,
- text=True, encoding="utf-8", errors="replace",
+ text=encoding is not None, encoding=encoding, errors="strict" if encoding else None,
creationflags=windows_hide_flags(), timeout=remaining(deadline))
@@ -92,7 +92,7 @@ def _systemd(home: Path, deadline: float) -> ExistingService | None:
found = []
for system in (False, True):
command = gw._systemctl_cmd(system)
- result = _run([*command, "show", unit, "--no-pager",
+ result = _run([*command, "show", unit, "--no-pager", "--all",
"--property=LoadState,ActiveState,SubState,UnitFileState," + ",".join(SYSTEMD_IDENTITY_PROPERTIES)], deadline)
props = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
if props.get("LoadState") == "not-found" and not _exists(paths[int(system)]):
@@ -161,10 +161,10 @@ def _launchd(home: Path, deadline: float) -> ExistingService | None:
def _windows(home: Path, deadline: float) -> ExistingService | None:
- from hermes_cli.gateway_windows import _startup_dir
+ from hermes_cli.gateway_windows import _startup_dir, _schtasks_encoding
suffix = service_suffix(home)
name = f"Hermes_Gateway{'_' + suffix if suffix else ''}"
- result = _run(["schtasks.exe", "/Query", "/FO", "CSV", "/NH"], deadline)
+ result = _run(["schtasks.exe", "/Query", "/FO", "CSV", "/NH"], deadline, encoding=_schtasks_encoding())
if result.returncode:
raise RuntimeStartError("service_manager_unavailable")
rows = list(csv.reader(io.StringIO(result.stdout)))
@@ -172,8 +172,8 @@ def _windows(home: Path, deadline: float) -> ExistingService | None:
raise RuntimeStartError("service_state_unknown")
if any(row and row[0].lstrip("\\") == name for row in rows):
from hermes_cli.gateway_runtime_service_identity import verify_windows_task
- definition = _run(["schtasks.exe", "/Query", "/TN", name, "/XML"], deadline)
- identity = _run(["whoami.exe", "/USER", "/FO", "CSV", "/NH"], deadline)
+ definition = _run(["schtasks.exe", "/Query", "/TN", name, "/XML"], deadline, encoding=None)
+ identity = _run(["whoami.exe", "/USER", "/FO", "CSV", "/NH"], deadline, encoding=_schtasks_encoding())
if definition.returncode or identity.returncode:
raise RuntimeStartError("service_identity_unverified")
accounts = list(csv.reader(io.StringIO(identity.stdout)))
diff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.py
index ec3d0f3d205..3ab6fb9f3db 100644
--- a/hermes_cli/gateway_runtime_service_identity.py
+++ b/hermes_cli/gateway_runtime_service_identity.py
@@ -227,10 +227,13 @@ def _vbs_identity(script: str) -> tuple[str, list[str]]:
return env.get("HERMES_HOME", ""), argv
-def verify_windows_task(xml: str, home: Path, account: str, sid: str) -> None:
+def verify_windows_task(xml: str | bytes, home: Path, account: str, sid: str) -> None:
import xml.etree.ElementTree as ET
- task = ET.fromstring(xml)
+ try:
+ task = ET.fromstring(xml)
+ except ET.ParseError:
+ _unverified()
ns = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
principals = task.findall("t:Principals/t:Principal", ns)
actions = task.find("t:Actions", ns)
diff --git a/tests/hermes_cli/test_gateway_runtime_service.py b/tests/hermes_cli/test_gateway_runtime_service.py
index 8fd925b5a04..7dbc9ab7664 100644
--- a/tests/hermes_cli/test_gateway_runtime_service.py
+++ b/tests/hermes_cli/test_gateway_runtime_service.py
@@ -122,10 +122,10 @@ def test_loaded_launchd_identity_is_independent_of_disk(configured, command, rea
@pytest.mark.parametrize("case,reason", [
- ("bound", None), ("wrong_home", "profile_mismatch"),
+ ("bound", None), ("utf16", None), ("wrong_home", "profile_mismatch"),
("wrong_user", "service_account_mismatch"), ("missing_user", "service_identity_unverified"),
("extra_action", "service_identity_unverified"), ("disabled", "service_disabled"),
- ("unknown_script", "service_identity_unverified"),
+ ("unknown_script", "service_identity_unverified"), ("malformed_xml", "service_identity_unverified"),
])
def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):
from hermes_cli.gateway_runtime_service_identity import verify_windows_task
@@ -157,6 +157,10 @@ def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):
xml = xml.replace('</Actions>', '<Exec><Command>other.exe</Command></Exec></Actions>')
if case == 'disabled':
xml = xml.replace('<Enabled>true</Enabled>', '<Enabled>false</Enabled>')
+ if case == 'utf16':
+ xml = xml.encode('utf-16')
+ if case == 'malformed_xml':
+ xml = '<Task>'
if case == 'unknown_script':
script.write_text('MsgBox "not a gateway"', encoding='utf-8')
if reason:
@@ -164,3 +168,91 @@ def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):
verify_windows_task(xml, home, user, 'S-1-5-21-123')
else:
verify_windows_task(xml, home, user, 'S-1-5-21-123')
+
+
[email protected]("case,reason", [("loaded_good_disk_wrong", None), ("loaded_wrong_disk_good", "profile_mismatch"), ("bootstrap", None)])
+def test_native_launchd_checks_loaded_job_before_disk(case, reason, tmp_path, monkeypatch):
+ import plistlib
+ import pwd
+ from types import SimpleNamespace
+ from hermes_cli import gateway_runtime_service as service
+ home = tmp_path / 'profile'
+ home.mkdir(mode=0o700)
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setattr(pwd, 'getpwuid', lambda uid: SimpleNamespace(pw_dir=str(tmp_path)))
+ label = 'ai.hermes.gateway' + ('-' + service.service_suffix(home) if service.service_suffix(home) else '')
+ plist = tmp_path / 'Library/LaunchAgents' / (label + '.plist')
+ plist.parent.mkdir(parents=True)
+ argv = [sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run']
+ disk_home = tmp_path / 'wrong' if case == 'loaded_good_disk_wrong' else home
+ plist.write_bytes(plistlib.dumps(dict(Label=label, ProgramArguments=argv,
+ EnvironmentVariables=dict(HERMES_HOME=str(disk_home), HERMES_SUPERVISED_CHILD='1'))))
+ original = plist.read_bytes()
+ loaded_home = tmp_path / 'wrong' if case == 'loaded_wrong_disk_good' else home
+ output = 'gui/' + str(os.getuid()) + '/' + label + ' = {\n\tstate = not running\n\tprogram = ' + argv[0] + '\n\targuments = {\n' + '\n'.join('\t\t' + arg for arg in argv) + '\n\t}\n\tenvironment = {\n\t\tHERMES_HOME => ' + str(loaded_home) + '\n\t\tHERMES_SUPERVISED_CHILD => 1\n\t}\n}'
+ peer = tmp_path / 'supervisor.py'
+ peer.write_text('import sys\n' + f'output={output!r}\nbootstrap={case == "bootstrap"!r}\n' +
+ 'if "print" in sys.argv:\n sys.exit(113) if bootstrap or any(a.startswith("user/") for a in sys.argv) else print(output)\n', encoding='utf-8')
+ actual = subprocess.run
+ calls = []
+ def boundary(argv, **kw):
+ assert argv[0] == 'launchctl'
+ calls.append(argv)
+ return actual([sys.executable, str(peer), *argv[1:]], **kw)
+ monkeypatch.setattr(subprocess, 'run', boundary)
+ if reason:
+ with pytest.raises(service.RuntimeStartError, match=reason):
+ service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)
+ assert all(a[1] == 'print' for a in calls)
+ else:
+ found = service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)
+ assert found is not None
+ service.start_existing_gateway_service(found, deadline=time.monotonic()+5)
+ assert calls[-1][1] == ('bootstrap' if case == 'bootstrap' else 'kickstart')
+ assert plist.read_bytes() == original
+
+
[email protected]("wrong", [False, True])
+def test_native_task_query_uses_installed_xml_and_vendor_launcher(wrong, tmp_path, monkeypatch):
+ from hermes_cli import gateway_runtime_service as service
+ from hermes_cli.gateway_windows import _build_gateway_vbs_script, _build_scheduled_task_xml
+ home = tmp_path / 'profile'
+ home.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ script = home / 'gateway.vbs'
+ script.write_text(_build_gateway_vbs_script(sys.executable, str(home), str(home), ''), encoding='utf-8')
+ original = script.read_bytes()
+ # whoami is read-only native account evidence; no task-manager mutation.
+ identity = subprocess.run(['whoami.exe', '/USER', '/FO', 'CSV', '/NH'], stdin=subprocess.DEVNULL, capture_output=True, timeout=5)
+ from hermes_cli.gateway_windows import _schtasks_encoding
+ import csv
+ account, sid = next(csv.reader(identity.stdout.decode(_schtasks_encoding()).splitlines()))
+ suffix = service.service_suffix(home)
+ name = 'Hermes_Gateway' + ('_' + suffix if suffix else '')
+ xml = _build_scheduled_task_xml(name, script, 'S-1-5-18' if wrong else sid)
+ peer = tmp_path / 'supervisor.py'
+ row = f'"\\{name}","N/A","Ready"'
+ peer.write_text('import sys\n' + f'xml={xml!r}\n' +
+ 'if "/XML" in sys.argv: sys.stdout.buffer.write(xml.encode("utf-16"))\n'
+ + f'elif "/Query" in sys.argv: print({row!r})\n', encoding='utf-8')
+ actual = subprocess.run
+ calls = []
+ def boundary(argv, **kw):
+ if argv[0] == 'whoami.exe':
+ return actual(argv, **kw)
+ assert argv[0] == 'schtasks.exe'
+ calls.append(argv)
+ return actual([sys.executable, str(peer), *argv[1:]], **kw)
+ monkeypatch.setattr(subprocess, 'run', boundary)
+ if wrong:
+ with pytest.raises(service.RuntimeStartError, match='service_account_mismatch'):
+ service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)
+ assert not any('/Run' in a for a in calls)
+ else:
+ found = service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)
+ assert found is not None
+ service.start_existing_gateway_service(found, deadline=time.monotonic()+5)
+ assert sum('/Run' in a for a in calls) == 1
+ assert script.read_bytes() == original
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index b8c6925c9d4..019a447f49f 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -296,6 +296,30 @@ requested only when no service is found. This command never installs or rewrites
service definitions, enables linger, elevates privileges, or clears update fences.
Ambiguous or inaccessible ownership fails closed.
+Before requesting a service start, `ensure` checks its canonical profile directory
+and execution account, not just its unit/task name. Linux uses the manager's
+loaded command and environment (including effective drop-ins), macOS checks the
+loaded launchd job rather than assuming the on-disk plist is current, and Windows
+queries the actual task XML, principal, and installed launcher.
+
+- `profile_mismatch`: the installed service selects a different home or profile.
+ Inspect the selected service's `HERMES_HOME` and command-line profile selector;
+ use the matching profile or explicitly repair the service configuration.
+- `service_account_mismatch`: the service belongs to another account. Run the
+ client as that account, or explicitly configure a service for the intended user.
+- `service_identity_unverified`: the manager did not expose enough identity data,
+ or the definition uses unsupported dynamic configuration. Inspect it with
+ `systemctl [--user] show <unit> --all`, `launchctl print <domain>/<label>`, or
+ `schtasks /Query /TN <task> /XML`. Linux environment files, PAM/dynamic users,
+ start-time hooks and alternate root filesystems require operator review;
+ arbitrary shell launchers and modified Windows launcher scripts are not
+ interpreted by `ensure`. Restore an explicit supported definition through an
+ intentional service-management operation before retrying.
+
+These refusals do not start a service, rewrite configuration, or launch an
+unmanaged replacement. Standard explicitly bound default and custom-root installs
+remain eligible; a successful start request still must pass live readiness checks.
+
On POSIX, local bootstrap requires an owner-only profile directory. Newly reserved
homes are created with mode `0700`; existing permissions are never changed by
`ensure`. An existing home readable by other users returns