Skip to content

The agent that grows with you

fix: Windows agent-loop papercuts — path splitting, hashing, autocomplete, screenshots, OS detection (#84419)

Tekniumee472a7fdbbc
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py
index 96488fd7488..a38637f3695 100644
--- a/agent/prompt_builder.py
+++ b/agent/prompt_builder.py
@@ -1104,6 +1104,26 @@ _BACKEND_FALLBACK_DESCRIPTIONS: dict[str, str] = {
_BACKEND_PROBE_CACHE: dict[tuple[str, str], str] = {}
+def _windows_marketing_version() -> str:
+ """Return the marketing Windows version ("10", "11", ...) for the prompt.
+
+ ``platform.release()`` reports the kernel version, which is ``10`` for
+ BOTH Windows 10 and Windows 11 — the prompt then claims "Windows (10)"
+ on Windows 11 hosts and misleads the model about the OS (#51755).
+ Windows 11 is distinguished by build number: >= 22000 is 11.
+ Falls back to ``platform.release()`` on any lookup failure.
+ """
+ try:
+ build = sys.getwindowsversion().build # type: ignore[attr-defined]
+ if build >= 22000:
+ return "11"
+ return "10"
+ except Exception:
+ import platform
+
+ return platform.release()
+
+
_WINDOWS_BASH_SHELL_HINT = (
"Shell: on this Windows host your `terminal` tool runs commands through "
"bash (git-bash / MSYS), NOT PowerShell or cmd.exe. Use POSIX shell "
@@ -1284,7 +1304,7 @@ def build_environment_hints() -> str:
if is_wsl():
host_lines.append("Host: WSL (Windows Subsystem for Linux)")
elif sys.platform == "win32":
- host_lines.append(f"Host: Windows ({platform.release()})")
+ host_lines.append(f"Host: Windows ({_windows_marketing_version()})")
elif sys.platform == "darwin":
mac_ver = platform.mac_ver()[0]
host_lines.append(f"Host: macOS ({mac_ver or platform.release()})")
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index 2bdd9af1335..78a0ad32c7a 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -511,7 +511,10 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]:
"error": None,
}
try:
- argv = shlex.split(os.path.expanduser(spec.command))
+ # Windows-safe: plain shlex.split eats backslashes in paths (#78293).
+ from hermes_cli._subprocess_compat import split_command_line
+
+ argv = split_command_line(os.path.expanduser(spec.command))
except ValueError as exc:
result["error"] = f"command {spec.command!r} cannot be parsed: {exc}"
return result
@@ -950,7 +953,9 @@ def _command_script_path(command: str) -> str:
common bare-path form.
"""
try:
- parts = shlex.split(command)
+ from hermes_cli._subprocess_compat import split_command_line
+
+ parts = split_command_line(command)
except ValueError:
return command
if not parts:
@@ -1037,7 +1042,9 @@ def script_is_executable(command: str) -> bool:
if not os.path.isfile(expanded):
return False
try:
- argv = shlex.split(command)
+ from hermes_cli._subprocess_compat import split_command_line
+
+ argv = split_command_line(command)
except ValueError:
return False
is_bare_invocation = bool(argv) and argv[0] == path
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.py
index 6f8d7f5b802..10076731fa9 100644
--- a/hermes_cli/_subprocess_compat.py
+++ b/hermes_cli/_subprocess_compat.py
@@ -37,6 +37,7 @@ from typing import Mapping, Sequence
__all__ = [
"IS_WINDOWS",
"resolve_node_command",
+ "split_command_line",
"suppress_platform_ver_console",
"windows_detach_flags",
"windows_detach_flags_without_breakaway",
@@ -50,6 +51,39 @@ __all__ = [
IS_WINDOWS = sys.platform == "win32"
+def split_command_line(line: str) -> list[str]:
+ """Split a user-supplied command line into tokens, Windows-safely.
+
+ ``shlex.split(line)`` (posix=True) treats every backslash as an escape
+ character, so Windows paths are silently mangled: ``C:\\Users\\me\\out.txt``
+ becomes ``C:Usersmeout.txt`` — no error, just a wrong path that then
+ "succeeds" against a mangled relative filename (#83934) or makes a valid
+ hook script report "not executable" (#78293).
+
+ On Windows this uses ``posix=False``, which preserves backslashes while
+ still honoring double-quoted tokens ("path with spaces"). The trade-off
+ is that posix=False keeps surrounding quotes on quoted tokens, so we
+ strip one layer of matching double quotes per token — that matches how
+ Windows command lines are conventionally parsed. On POSIX the behavior
+ is exactly ``shlex.split``.
+
+ Raises ValueError for unbalanced quotes, same as ``shlex.split``.
+ """
+ if not IS_WINDOWS:
+ import shlex
+
+ return shlex.split(line)
+ import shlex
+
+ tokens = shlex.split(line, posix=False)
+ out: list[str] = []
+ for tok in tokens:
+ if len(tok) >= 2 and tok[0] == tok[-1] and tok[0] in ("'", '"'):
+ tok = tok[1:-1]
+ out.append(tok)
+ return out
+
+
# -----------------------------------------------------------------------------
# Node ecosystem launcher resolution
# -----------------------------------------------------------------------------
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py
index cb8fb4a0f2d..1f9e70e4308 100644
--- a/hermes_cli/commands.py
+++ b/hermes_cli/commands.py
@@ -1781,7 +1781,14 @@ class SlashCommandCompleter(Completer):
raw = proc.stdout.strip().split("\n")
# Store relative paths
for p in raw[:5000]:
- rel = os.path.relpath(p, cwd) if os.path.isabs(p) else p
+ try:
+ rel = os.path.relpath(p, cwd) if os.path.isabs(p) else p
+ except ValueError:
+ # Windows: relpath raises for paths on a different
+ # mount than cwd — device paths (\\.\nul, \\.\con)
+ # or another drive letter. One bad entry must not
+ # crash the @ autocomplete event loop (#42016).
+ continue
files.append(rel)
break
except (subprocess.TimeoutExpired, OSError):
diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.py
index 18f9f3e0d45..10104b4ece1 100644
--- a/hermes_cli/console_engine.py
+++ b/hermes_cli/console_engine.py
@@ -118,7 +118,12 @@ def _table_summary(summary: str, *, limit: int = 76) -> str:
def _split_line(line: str) -> list[str]:
try:
- return shlex.split(line, comments=False, posix=True)
+ # Windows-safe splitter: plain shlex posix=True eats backslashes, so
+ # `sessions export C:\Users\me\out.jsonl` silently became a mangled
+ # relative filename in the cwd (#83934).
+ from hermes_cli._subprocess_compat import split_command_line
+
+ return split_command_line(line)
except ValueError as exc:
raise ConsoleCommandError(f"Could not parse command: {exc}") from exc
diff --git a/tests/tools/test_windows_agent_loop_papercuts.py b/tests/tools/test_windows_agent_loop_papercuts.py
new file mode 100644
index 00000000000..f327a371e78
--- /dev/null
+++ b/tests/tools/test_windows_agent_loop_papercuts.py
@@ -0,0 +1,176 @@
+"""Windows agent-loop correctness regressions.
+
+Covers the papercut class swept in #84364/#84378's follow-up: silent path
+mangling, crashes, and divergent hashing that made day-to-day agent use on
+Windows unpleasant. Each test names the issue it pins.
+"""
+
+import os
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+from hermes_cli._subprocess_compat import split_command_line
+
+
+class TestSplitCommandLine:
+ """#83934 / #78293 — backslashes in Windows paths must survive splitting."""
+
+ @pytest.mark.windows_only
+ def test_windows_path_backslashes_preserved(self):
+ argv = split_command_line(r"sessions export C:\Users\me\Desktop\out.jsonl")
+ assert argv == ["sessions", "export", r"C:\Users\me\Desktop\out.jsonl"]
+
+ @pytest.mark.windows_only
+ def test_quoted_path_with_spaces(self):
+ argv = split_command_line(r'run "C:\Program Files\App\tool.exe" --flag')
+ assert argv == ["run", r"C:\Program Files\App\tool.exe", "--flag"]
+
+ @pytest.mark.windows_only
+ def test_bare_hook_command_path(self):
+ argv = split_command_line(r"C:\Users\u\.local\bin\dcg.exe --hook pre")
+ assert argv[0] == r"C:\Users\u\.local\bin\dcg.exe"
+
+ @pytest.mark.linux_only
+ def test_posix_behavior_unchanged(self):
+ assert split_command_line("echo 'a b' c") == ["echo", "a b", "c"]
+
+ def test_unbalanced_quote_raises(self):
+ with pytest.raises(ValueError):
+ split_command_line('run "unterminated')
+
+
+class TestShellHooksWindowsPaths:
+ """#78293 — hook script paths with backslashes resolve correctly."""
+
+ @pytest.mark.windows_only
+ def test_command_script_path_keeps_backslashes(self):
+ from agent.shell_hooks import _command_script_path
+
+ path = _command_script_path(r"C:\hooks\guard.py --strict")
+ assert path == r"C:\hooks\guard.py"
+
+ @pytest.mark.windows_only
+ def test_script_is_executable_finds_real_file(self, tmp_path):
+ from agent.shell_hooks import script_is_executable
+
+ script = tmp_path / "hook.py"
+ script.write_text("print('ok')\n", encoding="utf-8")
+ #
+
+ assert script_is_executable(f'python "{script}"') or script_is_executable(
+ f"python {script}"
+ )
+
+
+class TestWindowsMarketingVersion:
+ """#51755 — Windows 11 must not be reported as Windows 10."""
+
+ @pytest.mark.windows_only
+ def test_matches_build_number(self):
+ from agent.prompt_builder import _windows_marketing_version
+
+ build = sys.getwindowsversion().build
+ expected = "11" if build >= 22000 else "10"
+ assert _windows_marketing_version() == expected
+
+ def test_fallback_on_lookup_failure(self, monkeypatch):
+ import agent.prompt_builder as pb
+
+ if sys.platform == "win32":
+ monkeypatch.delattr(sys, "getwindowsversion")
+ assert isinstance(pb._windows_marketing_version(), str)
+
+
+class TestAutocompleteDevicePaths:
+ """#42016 — relpath ValueError on device paths must not escape."""
+
+ def test_relpath_valueerror_pattern(self):
+ # The guarded pattern in _get_project_files: a ValueError from
+ # os.path.relpath (different mount) is skipped, not raised.
+ bad = "\\\\.\\nul" if sys.platform == "win32" else "/dev/null"
+ cwd = os.getcwd()
+ files = []
+ for p in [bad, os.path.join(cwd, "real.txt")]:
+ try:
+ rel = os.path.relpath(p, cwd) if os.path.isabs(p) else p
+ except ValueError:
+ continue
+ files.append(rel)
+ assert "real.txt" in files
+
+
+class TestBrowserScreenshotPathRegex:
+ """#83884 — Windows drive-letter screenshot paths must be detected."""
+
+ def _re(self):
+ from tools.browser_use_cli import _IMAGE_PATH_RE
+
+ return _IMAGE_PATH_RE
+
+ def test_windows_backslash_path(self):
+ m = self._re().findall(r"Saved screenshot to C:\Users\u\shots\page.png done")
+ assert m == [r"C:\Users\u\shots\page.png"]
+
+ def test_windows_forward_slash_path(self):
+ m = self._re().findall("shot: C:/Users/u/shots/page.jpeg")
+ assert m == ["C:/Users/u/shots/page.jpeg"]
+
+ def test_posix_path_still_matches(self):
+ m = self._re().findall("wrote /tmp/bu-task/shot.webp")
+ assert m == ["/tmp/bu-task/shot.webp"]
+
+ def test_plain_words_do_not_match(self):
+ assert self._re().findall("no images here, just prose.png-like text /x") == []
+
+
+class TestSkillHashSymmetry:
+ """#62310 — disk hash and bundle hash must agree on every OS."""
+
+ def _make_skill(self, root: Path) -> Path:
+ skill = root / "demo-skill"
+ (skill / "references" / "methods").mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: demo\n---\nbody\n", encoding="utf-8")
+ (skill / "references" / "methods" / "x.md").write_text("x\n", encoding="utf-8")
+ # Mixed-case name exercises the case-sensitive sort divergence.
+ (skill / "Zeta.md").write_text("z\n", encoding="utf-8")
+ return skill
+
+ def test_disk_and_bundle_hashes_match(self, tmp_path):
+ from tools.skills_guard import content_hash
+ from tools.skills_hub import SkillBundle, bundle_content_hash
+
+ skill = self._make_skill(tmp_path)
+ disk = content_hash(skill)
+
+ files = {}
+ for f in skill.rglob("*"):
+ if f.is_file():
+ # Native separators — what Windows bundle construction produces.
+ files[str(f.relative_to(skill))] = f.read_bytes()
+ bundle = SkillBundle(
+ name="demo-skill", files=files, source="test",
+ identifier="test/demo-skill", trust_level="community",
+ )
+ assert bundle_content_hash(bundle) == disk
+
+ def test_backslash_and_posix_keys_hash_identically(self):
+ from tools.skills_hub import SkillBundle, bundle_content_hash
+
+ posix = SkillBundle(
+ name="s",
+ files={"references/a.md": b"a", "SKILL.md": b"s"},
+ source="test",
+ identifier="t/s",
+ trust_level="community",
+ )
+ windows = SkillBundle(
+ name="s",
+ files={"references\\a.md": b"a", "SKILL.md": b"s"},
+ source="test",
+ identifier="t/s",
+ trust_level="community",
+ )
+ assert bundle_content_hash(posix) == bundle_content_hash(windows)
diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.py
index 62610ded116..10c4468a0f0 100644
--- a/tools/browser_use_cli.py
+++ b/tools/browser_use_cli.py
@@ -32,8 +32,14 @@ _STDERR_CAP_CHARS = 4000
# Filesystem-safe task ids for per-task workspace dirs.
_TASK_ID_SAFE_RE = re.compile(r"[^A-Za-z0-9._-]+")
-# Screenshot paths printed by capture_screenshot() in the exec output
-_IMAGE_PATH_RE = re.compile(r"(/[^\s\"']+?\.(?:png|jpe?g|webp))", re.IGNORECASE)
+# Screenshot paths printed by capture_screenshot() in the exec output.
+# Two alternatives: POSIX absolute (/tmp/shot.png) and Windows drive-letter
+# absolute (C:\Users\...\shot.png or C:/Users/.../shot.png). Browser Use on
+# Windows prints native paths — the POSIX-only pattern silently dropped them
+# and screenshot_path / the multimodal attach never fired (#83884).
+_IMAGE_PATH_RE = re.compile(
+ r"((?:[A-Za-z]:[\\/]|/)[^\s\"']+?\.(?:png|jpe?g|webp))", re.IGNORECASE
+)
# http(s) URL literals in exec code checked against browser_navigate's policy
_URL_RE = re.compile(r"https?://[^\s'\"\\)]+", re.IGNORECASE)
diff --git a/tools/skills_guard.py b/tools/skills_guard.py
index eeaa7be33e0..1f513fab9e4 100644
--- a/tools/skills_guard.py
+++ b/tools/skills_guard.py
@@ -697,14 +697,27 @@ def scan_skill(skill_path: Path, source: str = "community") -> ScanResult:
def _content_digest(skill_path: Path) -> str:
- """Canonical SHA-256 over relative paths and exact file bytes."""
+ """Canonical SHA-256 over relative paths and exact file bytes.
+
+ Files are keyed and ORDERED by their POSIX relative path string,
+ case-sensitively. Ordering by ``sorted(rglob(...))`` diverged from the
+ bundle side on Windows: Path comparison is case-insensitive there
+ (normcase), while ``bundle_content_hash`` sorts plain strings — the
+ same skill hashed to different digests and every installed skill
+ reported ``update_available`` forever (#62310). Sorting the rel-posix
+ strings makes the digest OS-independent and byte-symmetric with
+ ``tools.skills_hub.bundle_content_hash``.
+ """
h = hashlib.sha256()
if skill_path.is_dir():
- for file_path in sorted(skill_path.rglob("*")):
- if file_path.is_file():
- rel = file_path.relative_to(skill_path).as_posix()
- h.update(rel.encode("utf-8") + b"\x00")
- h.update(file_path.read_bytes())
+ entries = sorted(
+ (file_path.relative_to(skill_path).as_posix(), file_path)
+ for file_path in skill_path.rglob("*")
+ if file_path.is_file()
+ )
+ for rel, file_path in entries:
+ h.update(rel.encode("utf-8") + b"\x00")
+ h.update(file_path.read_bytes())
else:
h.update(skill_path.read_bytes())
return h.hexdigest()
diff --git a/tools/skills_hub.py b/tools/skills_hub.py
index 62564840d3b..b4bca1e5c8a 100644
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@ -4055,14 +4055,27 @@ def uninstall_skill(skill_name: str) -> Tuple[bool, str]:
def bundle_content_hash(bundle: SkillBundle) -> str:
- """Compute a deterministic hash for an in-memory skill bundle."""
+ """Compute a deterministic hash for an in-memory skill bundle.
+
+ MUST stay symmetric with ``tools.skills_guard.content_hash`` (which
+ hashes the same skill from disk). That function keys files by
+ ``relative_to(...).as_posix()`` — forward slashes on every OS. Bundle
+ keys built on Windows carry backslashes (``str(f.relative_to(dir))``),
+ which changed both the hashed bytes AND the sort order, so every
+ installed skill reported ``update_available`` forever on Windows
+ (#62310). Normalize to POSIX separators before sorting/hashing.
+ """
h = hashlib.sha256()
- for rel_path in sorted(bundle.files):
+ normalized = {
+ rel_path.replace("\\", "/"): content
+ for rel_path, content in bundle.files.items()
+ }
+ for rel_path in sorted(normalized):
# Include the path so swapping file contents between two paths
# changes the hash (avoids filename-swap evading update detection).
h.update(rel_path.encode("utf-8"))
h.update(b"\x00")
- content = bundle.files[rel_path]
+ content = normalized[rel_path]
if isinstance(content, bytes):
h.update(content)
else: