The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway-windows): decode schtasks strictly as UTF-8 first, one localized denial vocabulary, seam tests
teknium1133004ac799b
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex 504274447c5..a472900e235 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -36,18 +36,16 @@ logger = logging.getLogger(__name__)# Short timeouts: schtasks occasionally wedges and we don't want to hang forever._SCHTASKS_TIMEOUT_S = 15# Patterns in schtasks stderr that mean "fall back to the Startup folder".-_FALLBACK_PATTERNS = re.compile(- r"(access is denied|acceso denegado|přístup byl odepřen|"- r"错误\s*:\s*拒绝访问|拒绝访问|アクセスが拒否されました|"- r"액세스가 거부되었습니다|schtasks timed out|schtasks produced no output)",- re.IGNORECASE,+# schtasks' localized "access is denied" (en/es/cs/zh-Hans/zh-Hant/ja/ko): one vocabulary for both+# the elevated-install offer and the Startup-folder fallback.+_ACCESS_DENIED_WORDS = (+ r"access is denied|acceso denegado|přístup byl odepřen|拒绝访问|拒絕存取|アクセスが拒否されました|"+ r"액세스가 거부되었습니다")-_ACCESS_DENIED_PATTERN = re.compile(- r"(access is denied|acceso denegado|přístup byl odepřen|"- r"错误\s*:\s*拒绝访问|拒绝访问|アクセスが拒否されました|"- r"액세스가 거부되었습니다)",- re.IGNORECASE,+_FALLBACK_PATTERNS = re.compile(+ rf"({_ACCESS_DENIED_WORDS}|schtasks timed out|schtasks produced no output)", re.IGNORECASE)+_ACCESS_DENIED_PATTERN = re.compile(rf"({_ACCESS_DENIED_WORDS})", re.IGNORECASE)# Set by _spawn_detached() when the breakaway spawn failed and it retried WITHOUT# CREATE_BREAKAWAY_FROM_JOB — the child stays in the parent's Job Object and may be killed when this@@ -73,22 +71,32 @@ def _schtasks_encoding() -> str:return "utf-8"-def _windows_ansi_encoding() -> str:- """Return the Windows ANSI code page without Python UTF-8 Mode influencing it."""- try:- code_page = int(ctypes.windll.kernel32.GetACP())- if code_page <= 0:- raise ValueError("Windows returned an invalid ANSI code page")- return f"cp{code_page}"- except (AttributeError, OSError, ValueError):- return _schtasks_encoding()---def _decode_schtasks_output(data: bytes | str) -> str:- """Decode captured ``schtasks.exe`` bytes while preserving localized paths and messages."""- if isinstance(data, str):- return data- for encoding in (_windows_ansi_encoding(), "utf-8"):+def _windows_console_encodings() -> list[str]:+ """Code pages a console tool such as ``schtasks.exe`` writes to a pipe, most likely first: the+ console output code page (65001 once ``configure_windows_stdio`` ran, else the OEM page), the OEM+ page, then the ANSI page. Read from kernel32, so Python's UTF-8 mode cannot disguise them."""+ kernel32 = getattr(getattr(ctypes, "windll", None), "kernel32", None)+ if kernel32 is None:+ return [_schtasks_encoding()]+ pages: list[str] = []+ for getter in ("GetConsoleOutputCP", "GetOEMCP", "GetACP"):+ try:+ code_page = int(getattr(kernel32, getter)())+ except (AttributeError, OSError, ValueError):+ continue+ if code_page > 0 and f"cp{code_page}" not in pages:+ pages.append(f"cp{code_page}")+ return pages or [_schtasks_encoding()]+++def _decode_schtasks_output(data: bytes) -> str:+ """Decode captured ``schtasks.exe`` bytes. schtasks writes the console/OEM code page even when this+ process runs in UTF-8 mode (the launcher sets ``PYTHONUTF8=1``), so ``locale.getpreferredencoding``+ is the wrong codec on a non-ASCII account path: ``C:\\Users\\方舟`` came back as ``����`` and the+ Scheduled-Task drift check could never settle (#116193). Strict UTF-8 first (ASCII and genuine+ UTF-8 output pass; legacy multi-byte text fails loudly), then the native code pages, then a lossy+ fallback so a reader thread never raises."""+ for encoding in ("utf-8", *_windows_console_encodings()):try:return data.decode(encoding)except (LookupError, UnicodeDecodeError):@@ -182,8 +190,8 @@ def _exec_schtasks(args: list[str]) -> tuple[int, str, str]:if schtasks is None:return (1, "", "schtasks.exe not found on PATH")try:- # Locale encoding + replace: a non-UTF-8 status line must never surface a UnicodeDecodeError- # from subprocess' reader threads. CREATE_NO_WINDOW: no flashing console under a TUI.+ # Bytes, decoded by _decode_schtasks_output: a non-UTF-8 status line must never surface a+ # UnicodeDecodeError from subprocess' reader threads. CREATE_NO_WINDOW: no flashing console under a TUI.proc = subprocess.run([schtasks, *args], capture_output=True, text=False,timeout=_SCHTASKS_TIMEOUT_S, creationflags=windows_hide_flags(),diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.pyindex 2c8e1cdc30a..c6822124f80 100644--- a/tests/hermes_cli/test_gateway_windows.py+++ b/tests/hermes_cli/test_gateway_windows.py@@ -1,6 +1,7 @@"""Tests for hermes_cli.gateway_windows."""import logging+import osimport subprocessfrom pathlib import Pathfrom types import SimpleNamespace@@ -15,12 +16,52 @@ import hermes_cli.setup as setup_BREAKAWAY_MARKER = "_HERMES_GATEWAY_BREAKAWAY"-def test_decode_schtasks_output_preserves_non_ascii_windows_path(monkeypatch):- """Scheduled Task XML keeps an ANSI-encoded account path intact under UTF-8 mode."""- monkeypatch.setattr(gateway_windows, "_windows_ansi_encoding", lambda: "gbk")- raw = r"<Arguments>C:\\Users\\方舟\\AppData\\Local\\hermes\\gateway.vbs</Arguments>".encode("gbk")+def test_exec_schtasks_decodes_ansi_output_under_utf8_mode(monkeypatch):+ """schtasks emits the ANSI code page even when Python runs in UTF-8 mode; a non-ASCII account+ path in the task XML must survive `_exec_schtasks` intact or `scheduled_task_drift` reports+ "launcher arguments differs" forever (#116193). Drives the production seam with the bytes the+ reporter captured (GBK for 方舟)."""+ monkeypatch.setattr(gateway_windows, "_assert_windows", lambda: None)+ monkeypatch.setattr(gateway_windows.shutil, "which", lambda name: "schtasks.exe")+ monkeypatch.setattr(gateway_windows.locale, "getpreferredencoding", lambda *a, **k: "utf-8")+ monkeypatch.setattr(gateway_windows, "_windows_console_encodings", lambda: ["cp936"], raising=False)+ xml = r'<Arguments>//B //Nologo "C:\Users\方舟\AppData\Local\hermes\gateway-service\Hermes_Gateway.vbs"</Arguments>'++ def fake_run(argv, **kwargs):+ # schtasks writes cp936 bytes; honour text/encoding like the real subprocess would.+ out, err = xml.encode("gbk"), "错误: 拒绝访问。".encode("gbk")+ if kwargs.get("text"):+ enc, errors = kwargs.get("encoding") or "utf-8", kwargs.get("errors") or "strict"+ out, err = out.decode(enc, errors), err.decode(enc, errors)+ return subprocess.CompletedProcess(argv, 0, stdout=out, stderr=err)++ monkeypatch.setattr(gateway_windows.subprocess, "run", fake_run)++ code, out, err = gateway_windows._exec_schtasks(["/Query", "/TN", "Hermes_Gateway", "/XML"])- assert "方舟" in gateway_windows._decode_schtasks_output(raw)+ assert (code, out) == (0, xml)+ assert gateway_windows._is_access_denied(err) and gateway_windows._should_fall_back(1, err)++[email protected]_only+def test_exec_schtasks_round_trips_non_ascii_task_argument_live(monkeypatch):+ """Real schtasks.exe on a real task whose argument carries a non-ASCII (ANSI-representable)+ character, queried from a UTF-8-mode interpreter: the template/live comparison in+ `scheduled_task_drift` needs the exact characters back (#116193)."""+ monkeypatch.setattr(gateway_windows.locale, "getpreferredencoding", lambda *a, **k: "utf-8")+ task = f"Hermes_Test_{os.getpid()}"+ marker = "Zo\u00eb" # ë: one byte in every Western OEM/ANSI code page, invalid as a lone UTF-8 byte+ created = subprocess.run(+ ["schtasks", "/Create", "/F", "/TN", task, "/SC", "ONLOGON", "/TR", f'wscript.exe //B "C:\\{marker}\\x.vbs"'],+ capture_output=True, timeout=30,+ )+ assert created.returncode == 0, created.stderr+ try:+ code, out, _err = gateway_windows._exec_schtasks(["/Query", "/TN", task, "/XML"])+ finally:+ subprocess.run(["schtasks", "/Delete", "/F", "/TN", task], capture_output=True, timeout=30)+ assert code == 0+ assert marker in out, outdef test_localized_access_denied_uses_existing_fallback_paths():