Skip to content

The agent that grows with you

fix(agent): run bare script-path hooks on Windows through their interpreter

Aaron08140829c91aa000e
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index 96ab0751021..424d2d9e6df 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -281,9 +281,34 @@ def _parse_single_entry(event: str, index: int, raw: Any) -> Optional[ShellHookS
# --- Subprocess callback ---
-# Popen failure -> diagnostic; anything else is reported as str(exc).
+# Popen failure -> diagnostic; WinError 193 gets its own below, everything else is str(exc).
_POPEN_ERRORS = ((FileNotFoundError, "command not found"), (PermissionError, "command not executable"))
+# A hook configured as a bare script path runs on POSIX because the kernel reads its shebang.
+# CreateProcess has no such mechanism and answers WinError 193 ("%1 is not a valid Win32
+# application") for a text file, so every ``command: "~/.hermes/agent-hooks/x.sh"`` example in
+# the hooks docs — the canonical shape — fails on Windows while the same config works everywhere
+# else. Map the suffixes that shape uses to their interpreter; unmapped suffixes keep the OS
+# failure so a typo still reads as "command not found" rather than a mystery interpreter error.
+_WINDOWS_SCRIPT_INTERPRETERS = {".sh": "bash", ".bash": "bash", ".py": "python"}
+# WinError 193 raised for a suffix we deliberately do not map.
+_NOT_DIRECTLY_EXECUTABLE = "cannot be run directly on Windows (there is no shebang support): start it with its interpreter, e.g. 'bash <path>'"
+
+
+def _windows_script_argv(argv: list[str]) -> list[str]:
+ """``argv`` with the interpreter prepended when element 0 is an existing script we can name an
+ interpreter for; unchanged otherwise, including on POSIX, where the shebang already works."""
+ suffix = os.path.splitext(argv[0])[1].lower()
+ kind = _WINDOWS_SCRIPT_INTERPRETERS.get(suffix)
+ if kind is None or not os.path.isfile(argv[0]):
+ return argv
+ if kind == "python":
+ return [sys.executable, *argv]
+ # Resolved inside the caller's try: no Git for Windows raises RuntimeError carrying the
+ # installer's own actionable guidance, which is a better diagnostic than any we could add.
+ from tools.environments.local import _find_bash
+ return [_find_bash(), *argv]
+
def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]:
"""The single subprocess site: run ``spec.command`` with ``stdin_json`` on stdin. Same result keys for every outcome."""
@@ -309,11 +334,20 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]:
from agent.secret_scope import is_multiplex_active
from tools.environments.local import build_subprocess_env
try:
+ if IS_WINDOWS:
+ argv = _windows_script_argv(argv)
proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding='utf-8', errors='replace', shell=False,
env=build_subprocess_env(scrub_secrets=is_multiplex_active()), **popen_kwargs)
except Exception as exc:
- return failed(next((msg for cls, msg in _POPEN_ERRORS if isinstance(exc, cls)), str(exc)))
+ for cls, msg in _POPEN_ERRORS:
+ if isinstance(exc, cls):
+ return failed(msg)
+ if getattr(exc, "winerror", None) == 193:
+ # Unmapped suffix (.zsh, .fish, .rb, …) — the raw WinError text is localized, so an
+ # operator on a non-English Windows could not act on it at all.
+ return failed(f"{argv[0]!r} {_NOT_DIRECTLY_EXECUTABLE}")
+ return failed(str(exc))
try:
stdout, stderr = proc.communicate(input=stdin_json, timeout=spec.timeout)
except BaseException as exc:
diff --git a/tests/agent/test_shell_hooks.py b/tests/agent/test_shell_hooks.py
index 1cadf3062df..ab376c5b8a5 100644
--- a/tests/agent/test_shell_hooks.py
+++ b/tests/agent/test_shell_hooks.py
@@ -771,3 +771,43 @@ class TestRoutedProfileEnv:
assert seen["home"] == str(routed)
assert seen["key"] == ""
assert "profile" in payload
+
+
+# ── bare script paths on native Windows ─────────────────────────────────
+# Real subprocesses, no mocked spawn: the failure being guarded is CreateProcess rejecting a text
+# file, which only exists on the host it happens on. Marked per the root AGENTS.md rule against
+# faking ``sys.platform``.
+
+
+def test_bare_script_hook_path_executes_on_windows(tmp_path):
+ """A hook whose command is a bare script path — the shape every example in
+ ``website/docs/user-guide/features/hooks.md`` uses — must run. POSIX gets there through the
+ kernel's shebang handling; CreateProcess has no equivalent, so the same config failed on
+ Windows while working everywhere else. A path that is not a file must still be reported as
+ missing rather than laundered through an interpreter."""
+ script = _write_script(tmp_path, "hook.sh", '#!/usr/bin/env bash\necho "ran" >&2\nexit 7\n')
+
+ def spec(command):
+ return shell_hooks.ShellHookSpec(event="pre_tool_call", command=command)
+
+ result = shell_hooks._spawn(spec(str(script)), "{}")
+ assert result["error"] is None, result["error"]
+ assert result["returncode"] == 7, "the script's own exit code must reach a fail_closed gate"
+ assert "ran" in result["stderr"]
+
+ missing = shell_hooks._spawn(spec(str(tmp_path / "gone.sh")), "{}")
+ assert missing["error"] == "command not found"
+
+
+def test_unroutable_script_hook_names_the_remediation(tmp_path):
+ """A suffix we deliberately do not route still fails, but the diagnostic has to say what to do:
+ the raw WinError text is localized, so a non-English Windows install could not act on it."""
+ script = _write_script(tmp_path, "hook.zsh", "#!/bin/zsh\necho hi\n")
+ spec = shell_hooks.ShellHookSpec(event="pre_tool_call", command=str(script))
+
+ result = shell_hooks._spawn(spec, "{}")
+
+ assert result["returncode"] is None
+ assert "interpreter" in result["error"] and "bash" in result["error"]