Skip to content

The agent that grows with you

fix(windows): key_cmd tests + doctor gh probe survive cmd.exe and shimmed CLIs

etherneta41fdf74ddf7
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.py
index 1af14d38820..b929be4d103 100644
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@ -3231,7 +3231,16 @@ def run_doctor(args):
capture_output=True, timeout=10,
)
return result.returncode == 0
- except (FileNotFoundError, subprocess.TimeoutExpired):
+ except (
+ FileNotFoundError,
+ subprocess.TimeoutExpired,
+ PermissionError,
+ OSError,
+ ):
+ # Unspawnable gh (Windows Store/MSIX reparse-point shims raise
+ # WinError 5; PATH lookups can also land on broken wrappers) is
+ # the same outcome for this check as no gh at all — a diagnostic
+ # command must never crash the whole doctor run.
return False
github_token = get_env_value("GITHUB_TOKEN") or get_env_value("GH_TOKEN")
diff --git a/tests/agent/test_command_token_source.py b/tests/agent/test_command_token_source.py
index 325a310d15c..e528005ebfa 100644
--- a/tests/agent/test_command_token_source.py
+++ b/tests/agent/test_command_token_source.py
@@ -14,6 +14,8 @@ behaviours that make the feature work:
from __future__ import annotations
+import base64
+import sys
import time
from types import SimpleNamespace
@@ -27,21 +29,38 @@ from agent.command_token_source import (
)
+def _pycmd(code: str) -> str:
+ """A key_cmd that works under every host shell.
+
+ ``_mint`` runs the command through ``shell=True``: POSIX sh on Linux/macOS,
+ ``cmd.exe`` on Windows — where ``printf``/``date`` don't exist and
+ single-quote wrapping means something else. Base64-encoding the payload
+ keeps the command pure printable ASCII with no quote characters for either
+ shell to mangle, and ``exec`` runs it unchanged.
+ """
+ encoded = base64.b64encode(code.encode("utf-8")).decode("ascii")
+ return (
+ f'"{sys.executable}" -c '
+ f'"import base64; exec(base64.b64decode(\'{encoded}\').decode())"'
+ )
+
+
class TestMinting:
def test_bare_token_stdout(self):
- source = CommandTokenSource("printf 'tok-abc'", "dbx")
+ source = CommandTokenSource(_pycmd("print('tok-abc')"), "dbx")
assert source() == "tok-abc"
def test_json_access_token(self):
"""The OAuth 2.0 token-endpoint response shape."""
source = CommandTokenSource(
- """printf '{"access_token":"tok-json","expires_in":3600}'""", "dbx"
+ _pycmd("""print('{"access_token":"tok-json","expires_in":3600}')"""),
+ "dbx",
)
assert source() == "tok-json"
def test_trailing_newline_is_stripped(self):
"""A raw newline in the credential would corrupt the auth header."""
- assert CommandTokenSource("echo tok-nl", "dbx")() == "tok-nl"
+ assert CommandTokenSource(_pycmd("print('tok-nl')"), "dbx")() == "tok-nl"
def test_multiline_output_is_rejected_not_guessed(self):
"""Only the token may land on stdout.
@@ -50,26 +69,30 @@ class TestMinting:
warning, two tokens) into a corrupt-credential 401 that is much harder
to diagnose than an explicit refusal.
"""
- source = CommandTokenSource("printf 'banner\\ntok-real'", "dbx")
+ source = CommandTokenSource(
+ _pycmd("print('banner'); print('tok-real')"), "dbx"
+ )
with pytest.raises(CommandTokenError, match="multiple lines"):
source()
def test_json_without_access_token_is_an_error(self):
- source = CommandTokenSource("""printf '{"nope":1}'""", "dbx")
+ source = CommandTokenSource(_pycmd("""print('{"nope":1}')"""), "dbx")
with pytest.raises(CommandTokenError, match="access_token"):
source()
def test_empty_output_is_an_error(self):
with pytest.raises(CommandTokenError, match="no output"):
- CommandTokenSource("true", "dbx")()
+ CommandTokenSource(_pycmd("pass"), "dbx")()
def test_nonzero_exit_is_an_error(self):
with pytest.raises(CommandTokenError, match="exited 3"):
- CommandTokenSource("exit 3", "dbx")()
+ CommandTokenSource(_pycmd("import sys; sys.exit(3)"), "dbx")()
def test_failure_message_is_actionable_without_echoing_the_command(self):
"""Actionable, but never echoes the command (it may embed a secret)."""
- secret_cmd = "print-token --client-secret=SENTINEL-SECRET; exit 1"
+ secret_cmd = _pycmd(
+ "import sys; sys.stderr.write('SENTINEL-SECRET\\n'); sys.exit(1)"
+ )
with pytest.raises(CommandTokenError) as excinfo:
CommandTokenSource(secret_cmd, "dbx")()
message = str(excinfo.value)
@@ -82,7 +105,10 @@ class TestNoCredentialLeak:
def test_failure_message_excludes_command_output(self):
"""A failing auth helper may print a token — it must not be surfaced."""
source = CommandTokenSource(
- "printf 'SENTINEL-SECRET'; printf 'stderr-SENTINEL' >&2; exit 1",
+ _pycmd(
+ "import sys; sys.stdout.write('SENTINEL-SECRET\\n');"
+ " sys.stderr.write('stderr-SENTINEL\\n'); sys.exit(1)"
+ ),
"dbx",
)
with pytest.raises(CommandTokenError) as excinfo:
@@ -131,7 +157,7 @@ class TestCaching:
def test_advertised_ttl_sets_an_expiry(self):
source = CommandTokenSource(
- """printf '{"access_token":"tok","expires_in":3600}'""", "dbx"
+ _pycmd("""print('{"access_token":"tok","expires_in":3600}')"""),
)
source()
assert source._expires_at is not None
@@ -139,7 +165,7 @@ class TestCaching:
def test_ttl_shorter_than_the_leeway_still_caches_briefly(self):
"""A leeway larger than the TTL must not disable caching entirely."""
source = CommandTokenSource(
- """printf '{"access_token":"tok","expires_in":1}'""", "dbx"
+ _pycmd("""print('{"access_token":"tok","expires_in":1}')"""),
)
source()
assert source._expires_at is not None
@@ -152,7 +178,7 @@ class TestBuilder:
assert build_command_token_provider(" ") is None
def test_returns_callable_when_set(self):
- provider = build_command_token_provider("printf tok", "dbx")
+ provider = build_command_token_provider(_pycmd("print('tok')"), "dbx")
assert callable(provider)
assert provider() == "tok"
@@ -169,7 +195,7 @@ class TestResolutionYieldsACallable:
"base_url": "https://example.invalid/v1",
"api_mode": "chat_completions",
"model": "m1",
- "key_cmd": "printf minted-token",
+ "key_cmd": _pycmd("print('minted-token')"),
}
}
}
@@ -191,7 +217,7 @@ class TestResolutionYieldsACallable:
"base_url": "https://example.invalid/v1",
"api_mode": "chat_completions",
"model": "m1",
- "key_cmd": "printf minted-token",
+ "key_cmd": _pycmd("print('minted-token')"),
}
}
}
@@ -252,33 +278,34 @@ class TestAbsoluteExpiry:
def test_iso_expiry_yields_a_ttl(self):
deadline = self._iso(3600)
- _, ttl = _mint(f"printf '%s' '{{\"access_token\":\"t\",\"expiry\":\"{deadline}\"}}'", "p")
+ _, ttl = _mint(_pycmd(f"""print('{{"access_token":"t","expiry":"{deadline}"}}')"""), "p")
assert ttl is not None, "an advertised deadline must produce a TTL"
assert 3500 < ttl <= 3600
def test_azure_expires_on_spelling(self):
deadline = self._iso(1800)
- _, ttl = _mint(f"printf '%s' '{{\"access_token\":\"t\",\"expiresOn\":\"{deadline}\"}}'", "p")
+ _, ttl = _mint(_pycmd(f"""print('{{"access_token":"t","expiresOn":"{deadline}"}}')"""), "p")
assert ttl is not None and 1700 < ttl <= 1800
def test_expires_in_still_wins_when_both_present(self):
"""The RFC 6749 field is authoritative where a helper sends both."""
deadline = self._iso(3600)
_, ttl = _mint(
- f"printf '%s' '{{\"access_token\":\"t\",\"expires_in\":120,\"expiry\":\"{deadline}\"}}'",
+ _pycmd(f"""print('{{"access_token":"t","expires_in":120,"expiry":"{deadline}"}}')"""),
"p",
)
assert ttl == 120.0
def test_unparseable_expiry_is_not_a_ttl(self):
"""Junk must fall back to refresh-on-401, never to a guessed deadline."""
- _, ttl = _mint('printf \'%s\' \'{"access_token":"t","expiry":"whenever"}\'', "p")
+ _, ttl = _mint(_pycmd("""print('{"access_token":"t","expiry":"whenever"}')"""), "p")
assert ttl is None
def test_already_past_expiry_is_not_a_ttl(self):
"""A stale deadline must not become a negative or zero TTL."""
_, ttl = _mint(
- f"printf '%s' '{{\"access_token\":\"t\",\"expiry\":\"{self._iso(-60)}\"}}'", "p"
+ _pycmd(f"""print('{{"access_token":"t","expiry":"{self._iso(-60)}"}}')"""),
+ "p",
)
assert ttl is None
@@ -331,7 +358,7 @@ class TestAuxiliaryResolverHonoursKeyCmd:
BASE = {"base_url": "https://example.invalid/v1", "model": "m1"}
def test_key_cmd_resolves_to_a_callable(self, monkeypatch):
- api_key = self._resolve(monkeypatch, {**self.BASE, "key_cmd": "printf minted-token"})
+ api_key = self._resolve(monkeypatch, {**self.BASE, "key_cmd": _pycmd("print('minted-token')")})
assert callable(api_key), "auxiliary tasks must mint per request too"
assert api_key() == "minted-token"
@@ -339,7 +366,7 @@ class TestAuxiliaryResolverHonoursKeyCmd:
"""Precedence matches the runtime resolver, so both agree on one entry."""
api_key = self._resolve(
monkeypatch,
- {**self.BASE, "api_key": "stale-static", "key_cmd": "printf minted-token"},
+ {**self.BASE, "api_key": "stale-static", "key_cmd": _pycmd("print('minted-token')")},
)
assert callable(api_key) and api_key() == "minted-token"
diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.py
index 9e37dc2cc2f..4fd472b02f7 100644
--- a/tests/hermes_cli/test_doctor.py
+++ b/tests/hermes_cli/test_doctor.py
@@ -318,6 +318,20 @@ class TestDoctorMemoryProviderSection:
except Exception:
pass
+ # Keep doctor from probing the AMBIENT gh CLI. A PATH lookup that
+ # resolves (any dev box has gh) makes doctor shell out to
+ # `gh auth status`, which both leaks the runner's real auth state
+ # into the assertion surface and -- on Windows -- dies with WinError 5
+ # when gh resolves to a Store/MSIX reparse-point shim. The gh-
+ # specific doctor behaviors have their own dedicated tests below,
+ # which mock gh explicitly.
+ real_which = doctor_mod.shutil.which
+ monkeypatch.setattr(
+ doctor_mod.shutil,
+ "which",
+ lambda cmd: None if cmd == "gh" else real_which(cmd),
+ )
+
import io, contextlib
buf = io.StringIO()
with contextlib.redirect_stdout(buf):