Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14464,9 +14464,15 @@ def new_event_loop(self):

_aio_probe.set_event_loop_policy(_SelectEventLoopPolicy())

# Run the application with patch_stdout for proper output handling
# Run the application with patch_stdout for proper output handling.
# prompt_toolkit only proxies stdout; raw stderr writes from warnings,
# background MCP reconnect paths, or third-party SDKs can still corrupt
# the live prompt. Divert stderr into a side log for the duration of the
# interactive app.
try:
with patch_stdout():
from hermes_logging import redirect_stderr_to_log

with redirect_stderr_to_log(), patch_stdout():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This replaces sys.stderr for the full interactive session, but MCP OAuth intentionally prints its authorization URL and paste fallback to stderr (tools/mcp_oauth.py:567,673). Those user-required instructions would be silently diverted to the side log; scope the redirect to the noisy producer instead.

# Set the custom handler on prompt_toolkit's event loop
try:
import asyncio as _aio
Expand Down Expand Up @@ -14762,6 +14768,20 @@ def main(
except Exception:
pass

# Optional MCP/platform SDKs can emit import-time deprecation warnings to
# raw stderr during tool discovery, before prompt_toolkit takes control of
# the screen. Silence the known lark_oapi/pkg_resources warning so startup
# stays clean; real errors still surface normally.
try:
import warnings
warnings.filterwarnings(
"ignore",
message=r"pkg_resources is deprecated as an API\..*",
category=UserWarning,
)
except Exception:
pass

# Signal to terminal_tool that we're in interactive mode
# This enables interactive sudo password prompts with timeout
os.environ["HERMES_INTERACTIVE"] = "1"
Expand Down
10 changes: 10 additions & 0 deletions hermes_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@

import os
import sys
import warnings

# Optional platform SDKs such as lark_oapi can emit this specific
# pkg_resources deprecation warning at import time, which otherwise goes
# straight to raw stderr before the interactive UI takes over.
warnings.filterwarnings(
"ignore",
message=r"pkg_resources is deprecated as an API\..*",
category=UserWarning,
)


def _set_process_title() -> None:
Expand Down
67 changes: 67 additions & 0 deletions hermes_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import os
import sys
import threading
from contextlib import contextmanager
from pathlib import Path
from typing import Optional, Sequence

Expand Down Expand Up @@ -121,6 +122,9 @@ def _safe_stderr(): # type: ignore[return]
"openai._base_client",
"httpx",
"httpcore",
"mcp",
"mcp.client.streamable_http",
"mcp.client.auth.oauth2",
"asyncio",
"hpack",
"hpack.hpack",
Expand Down Expand Up @@ -152,6 +156,69 @@ def clear_session_context() -> None:
_session_context.session_id = None


class _RedactingTextSink:
"""File-like wrapper that redacts secrets before persisting raw stderr.

The interactive CLI/TUI must not let arbitrary third-party stderr writes hit
the live prompt_toolkit screen. Route them to a side log instead, but keep
the log safe by applying the same secret redaction used for normal logs.
"""

encoding = "utf-8"

def __init__(self, wrapped):
self._wrapped = wrapped

def write(self, data): # type: ignore[override]
if not data:
return 0
from agent.redact import redact_sensitive_text

text = data if isinstance(data, str) else str(data)
return self._wrapped.write(redact_sensitive_text(text, force=True))

def flush(self) -> None:
self._wrapped.flush()

def fileno(self) -> int:
return self._wrapped.fileno()

def isatty(self) -> bool:
return False


@contextmanager
def redirect_stderr_to_log(
*,
hermes_home: Optional[Path] = None,
log_name: str = "cli-stderr.log",
):
"""Temporarily redirect process stderr into a redacted log file.

prompt_toolkit's ``patch_stdout()`` protects stdout, but raw writes to
stderr from warnings, third-party SDKs, and background MCP reconnect paths
can still corrupt the live CLI/TUI prompt. During the interactive app
lifetime we therefore divert stderr to ``~/.hermes/logs/<log_name>``.
"""

home = hermes_home or get_hermes_home()
log_dir = home / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
path = log_dir / log_name

original = sys.stderr
with path.open("a", encoding="utf-8", errors="replace", buffering=1) as fh:
sink = _RedactingTextSink(fh)
sys.stderr = sink # type: ignore[assignment]
try:
yield path
finally:
try:
sink.flush()
finally:
sys.stderr = original


# ---------------------------------------------------------------------------
# Record factory — injects session_tag into every LogRecord at creation
# ---------------------------------------------------------------------------
Expand Down
33 changes: 33 additions & 0 deletions tests/hermes_cli/test_mcp_startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import pytest

import cli as cli_mod
import hermes_logging
from hermes_cli import main as main_mod
from hermes_cli import mcp_startup

Expand Down Expand Up @@ -164,3 +165,35 @@ def _fake_agent(*_a, **_k):
monkeypatch.setattr(cli_mod, "AIAgent", _fake_agent)

assert cli._init_agent() is True


def test_background_mcp_discovery_stderr_can_be_redirected(monkeypatch, tmp_path):
secret_line = "mcp reconnect token=sk-1234567890ABCDE\n"

monkeypatch.setitem(
sys.modules,
"hermes_cli.config",
types.SimpleNamespace(
read_raw_config=lambda: {"mcp_servers": {"demo": {"transport": "stdio"}}},
load_config=lambda: {},
),
)
monkeypatch.setitem(
sys.modules,
"tools.mcp_tool",
types.SimpleNamespace(discover_mcp_tools=lambda: sys.stderr.write(secret_line)),
)

logger = types.SimpleNamespace(debug=lambda *_a, **_k: None)
hermes_home = tmp_path / "hermes_home"

with hermes_logging.redirect_stderr_to_log(hermes_home=hermes_home) as path:
mcp_startup.start_background_mcp_discovery(
logger=logger,
thread_name="test-mcp-discovery",
)
mcp_startup.wait_for_mcp_discovery(timeout=1.0)

text = path.read_text(encoding="utf-8")
assert "mcp reconnect token=" in text
assert "sk-1234567890ABCDE" not in text
26 changes: 26 additions & 0 deletions tests/test_hermes_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,3 +1086,29 @@ def flush(self):
logger.info("Session hygiene: 400 messages — auto-compressing")
finally:
logger.removeHandler(handler)


class TestRedirectStderrToLog:
"""Interactive stderr redirection should protect the live TUI prompt."""

def test_redirects_and_restores_stderr(self, hermes_home):
original = sys.stderr

with hermes_logging.redirect_stderr_to_log(hermes_home=hermes_home) as path:
assert path == hermes_home / "logs" / "cli-stderr.log"
assert sys.stderr is not original
sys.stderr.write("plain stderr line\n")

assert sys.stderr is original
assert "plain stderr line" in path.read_text(encoding="utf-8")

def test_redacts_warning_like_stderr_lines(self, hermes_home):
with hermes_logging.redirect_stderr_to_log(hermes_home=hermes_home) as path:
sys.stderr.write(
f"{__file__}:1111: UserWarning: token=sk-1234567890ABCDE\n"
)

text = path.read_text(encoding="utf-8")
assert "UserWarning" in text
assert "token=" in text
assert "sk-1234567890ABCDE" not in text
42 changes: 42 additions & 0 deletions tests/tools/test_mcp_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
_make_callback_handler,
_redirect_handler,
_paste_callback_reader,
_build_client_metadata,
_configure_callback_port,
_set_oauth_redirect_host,
)


Expand Down Expand Up @@ -231,6 +234,15 @@ def test_find_free_port_unique(self):
# At least 2 different ports out of 5 attempts
assert len(ports) >= 2

def test_find_free_port_supports_localhost_dual_stack_request(self):
port = _find_free_port("localhost")
assert isinstance(port, int)
assert 1024 <= port <= 65535

def test_set_oauth_redirect_host_rejects_unknown_value(self):
with pytest.raises(ValueError):
_set_oauth_redirect_host("example.com")

def test_can_open_browser_false_in_ssh(self, monkeypatch):
monkeypatch.setenv("SSH_CLIENT", "1.2.3.4 1234 22")
assert _can_open_browser() is False
Expand Down Expand Up @@ -272,6 +284,20 @@ def test_ssh_hint_shown_on_ssh_session(self, monkeypatch, capsys):
assert "49200" in err
assert "ssh -N -L" in err
assert "Remote session detected" in err
assert "http://127.0.0.1:49200/callback" in err

def test_ssh_hint_shows_localhost_redirect_host(self, monkeypatch, capsys):
import tools.mcp_oauth as mco
monkeypatch.setattr(mco, "_oauth_port", 49203)
monkeypatch.setattr(mco, "_oauth_uri_host", "localhost")
monkeypatch.setenv("SSH_CLIENT", "1.2.3.4 1234 22")
monkeypatch.delenv("SSH_TTY", raising=False)
monkeypatch.setattr(mco, "_can_open_browser", lambda: False)

self._run(_redirect_handler("https://example.com/auth?foo=bar"))

err = capsys.readouterr().err
assert "http://localhost:49203/callback" in err

def test_ssh_hint_shown_via_ssh_tty(self, monkeypatch, capsys):
import tools.mcp_oauth as mco
Expand Down Expand Up @@ -587,6 +613,22 @@ def test_configure_callback_port_uses_explicit_port():
assert cfg["_resolved_port"] == 54321


def test_build_client_metadata_uses_localhost_redirect_host():
pytest.importorskip("mcp")
cfg = {"redirect_host": "localhost", "redirect_port": 8771}
_configure_callback_port(cfg)
md = _build_client_metadata(cfg)
assert str(md.redirect_uris[0]) == "http://localhost:8771/callback"


def test_build_client_metadata_uses_ipv6_redirect_host():
pytest.importorskip("mcp")
cfg = {"redirect_host": "::1", "redirect_port": 8771}
_configure_callback_port(cfg)
md = _build_client_metadata(cfg)
assert str(md.redirect_uris[0]) == "http://[::1]:8771/callback"


def test_build_oauth_auth_preserves_server_url_path():
"""server_url with path is forwarded to OAuthClientProvider unmodified.

Expand Down
Loading