mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 12:05:34 +08:00
feat(providers): add Hermes agent wrap support (#934)
## Description Adds first-class Hermes Agent support to `headroom wrap` while preserving the current provider architecture. The wrapper prepares both OpenAI- and Anthropic-compatible environment variables, supports argument forwarding and `--prepare-only`, and reports a clear installation error when the Hermes binary is unavailable. This update also changes the missing-binary test to assert the complete CLI output, resolving CodeQL's URL-substring sanitization false positive without weakening coverage. ## Changes Made - integrate Hermes launch-environment construction into the existing provider module - route OpenAI and Anthropic endpoints through Headroom - support Hermes argument forwarding and prepare-only setup - cover missing-binary, launch, and compression/passthrough behavior - use an exact expected error message in the CLI test for CodeQL compatibility **Provider contract:** `headroom wrap hermes` requires `--provider anthropic` or `--provider openai`. Any other selection, or no flag, exits with code 1 before the proxy or Hermes starts. ## Testing - [x] Unit tests pass - [x] Linting and formatting pass - [x] New tests added ### Test Output ```text 20 focused Hermes tests passed ruff check: passed ruff format --check: passed git diff --check: passed ``` - `uv run --extra dev pytest tests/test_providers/test_hermes.py tests/test_cli/test_wrap_hermes.py tests/test_hermes_passthrough_compression.py -q` (20 passed) - `uv run --extra dev ruff check tests/test_cli/test_wrap_hermes.py` - `uv run --extra dev ruff format --check tests/test_cli/test_wrap_hermes.py` - `git diff --check` ## UI evidence Not applicable. This PR changes CLI/provider behavior and tests; it does not alter a graphical UI. ## Checklist - [x] Tests added or updated - [x] Focused tests pass locally - [x] Formatting and lint checks pass - [x] No UI screenshots required - [x] No changelog entry required for this focused provider integration ## Type of Change - [ ] Bug fix - [x] New feature - [ ] Breaking change - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring ## Real Behavior Proof - Environment: current Hermes provider/wrapper test environment. - Exact command / steps: ran the Hermes provider, CLI wrapper, and passthrough/compression suites plus Ruff, formatting, and diff checks. - Observed result: 20 focused tests pass; OpenAI and Anthropic endpoints route through Headroom, arguments and prepare-only work, and missing binaries produce the exact expected error. - Not tested: a live Hermes Agent session against production providers. ## Runtime Rollout Safety - Rollout-managed feature(s): None. This adds a new opt-in `headroom wrap hermes` command. - Minimum rollout channel: N/A - Stable/default behavior changed: No. Other wrap commands and proxy behavior do not change. - Kill switch / disable path: Do not run `headroom wrap hermes`. Hermes can also be started without the wrapper. - Unsafe override required: No - Qualification impact: None - Rollback path: Revert this PR. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/934" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> ### Maintainer current-main requalification Exact head `ef4c2c11cd6359aaf4239f9cc394c28c23985c15`, upstream main `2d3ee51846435ef5b320eea4806af14e602b0d8c`. Clean mechanical synchronization with upstream main 2d3ee51846435ef5b320eea4806af14e602b0d8c; contributor routing policy unchanged. Current author replies and Devin findings reviewed. The previous default-routing blocker is addressed: the wrapper rejects absent/unsupported provider flags before calling _launch_tool, and permits explicitly selected anthropic/openai providers. The launch-boundary regressions exercise both rejected/default and supported paths. Explicit empty environments remain isolated, and the shared port callback is retained. Hermes/provider/port-alignment tests pass; changed-file Ruff lint/format and main-relative whitespace checks pass. Existing native extension supports Python startup, not a fresh native build. The author's Hermes0.22.2 WSL rejected/default and explicit-provider startup evidence is considered; this round does not claim live authenticated provider traffic. Project attribution, retrieval-plugin setup and a possible registry consolidation remain separate follow-ups rather than claims that the wrapper installs the plugin or supports other providers. No remaining finding in the previously requested provider-guard scope. Formal approval awaits exact-head hosted qualification, handled by maintainers. Author readiness state preserved; nothing merged. Exact-head hosted checks are being handled by maintainers. No new finding in the reviewed scope; formal approval awaits exact-head hosted qualification; nothing merged. --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: JD Davis <jd@jds-macbook-air.tail2a279.ts.net> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
JD Davis
JerrettDavis
parent
02c4e922f7
commit
7877241d84
@@ -14,6 +14,7 @@ Usage:
|
||||
headroom wrap antigravity # Start proxy + print Antigravity config instructions
|
||||
headroom wrap grok-build # Start proxy + configure Grok Build
|
||||
headroom wrap openclaw # Install + configure OpenClaw plugin
|
||||
headroom wrap hermes # Start proxy + Hermes agent
|
||||
headroom wrap claude --port 9999 # Custom proxy port
|
||||
headroom wrap claude -- --model opus # Pass args to claude
|
||||
"""
|
||||
@@ -177,6 +178,8 @@ from headroom.providers.grok_build.config import (
|
||||
inject_grok_provider_config,
|
||||
restore_grok_provider_config,
|
||||
)
|
||||
from headroom.providers.hermes import build_launch_env as _build_hermes_launch_env
|
||||
from headroom.providers.hermes import unsupported_provider_error as _hermes_provider_error
|
||||
from headroom.providers.kimi import build_launch_env as _build_kimi_launch_env
|
||||
from headroom.providers.mistral_vibe import build_launch_env as _build_mistral_vibe_launch_env
|
||||
from headroom.providers.omp import build_launch_env as _build_omp_launch_env
|
||||
@@ -8234,7 +8237,71 @@ def continue_dev(
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Hermes (Nous Research)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@proxy_port_option()
|
||||
@click.option("--code-graph", is_flag=True, help="Enable code graph indexing")
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option("--learn", is_flag=True, help="Enable live traffic learning")
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@click.option("--backend", default=None, help="API backend")
|
||||
@click.option("--anyllm-provider", default=None, help="Provider for any-llm backend")
|
||||
@click.option("--region", default=None, help="Cloud region for Bedrock/Vertex")
|
||||
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
|
||||
@click.option("--prepare-only", is_flag=True, hidden=True)
|
||||
@click.argument("hermes_args", nargs=-1, type=click.UNPROCESSED)
|
||||
def hermes(
|
||||
port: int,
|
||||
code_graph: bool,
|
||||
no_proxy: bool,
|
||||
learn: bool,
|
||||
memory: bool,
|
||||
backend: str | None,
|
||||
anyllm_provider: str | None,
|
||||
region: str | None,
|
||||
verbose: bool,
|
||||
prepare_only: bool,
|
||||
hermes_args: tuple,
|
||||
) -> None:
|
||||
"""Launch the Hermes agent through the Headroom proxy."""
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
hermes_bin = shutil.which("hermes")
|
||||
if not hermes_bin:
|
||||
click.echo("Error: 'hermes' not found in PATH.")
|
||||
click.echo("Install Hermes: https://hermes-agent.nousresearch.com/")
|
||||
raise SystemExit(1)
|
||||
|
||||
provider_error = _hermes_provider_error(hermes_args)
|
||||
if provider_error:
|
||||
click.echo(provider_error)
|
||||
raise SystemExit(1)
|
||||
|
||||
env, env_vars_display = _build_hermes_launch_env(port, os.environ)
|
||||
_launch_tool(
|
||||
binary=hermes_bin,
|
||||
args=hermes_args,
|
||||
env=env,
|
||||
port=port,
|
||||
no_proxy=no_proxy,
|
||||
tool_label="HERMES",
|
||||
env_vars_display=env_vars_display,
|
||||
learn=learn,
|
||||
memory=memory,
|
||||
agent_type="hermes",
|
||||
code_graph=code_graph,
|
||||
backend=backend,
|
||||
anyllm_provider=anyllm_provider,
|
||||
region=region,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# OpenClaw
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@@ -9,8 +9,13 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from headroom.providers.claude import proxy_base_url as claude_proxy_base_url
|
||||
from headroom.providers.codex import proxy_base_url as codex_proxy_base_url
|
||||
|
||||
logger = logging.getLogger("headroom.providers.hermes")
|
||||
|
||||
_CHAT_ROLES = frozenset({"user", "assistant"})
|
||||
@@ -22,6 +27,53 @@ _CODEX_RESPONSES_SUFFIX = "/v1/responses"
|
||||
_CLAUDE_MESSAGES_SUFFIX = "/v1/messages"
|
||||
|
||||
|
||||
def build_launch_env(
|
||||
port: int, environ: Mapping[str, str] | None = None
|
||||
) -> tuple[dict[str, str], list[str]]:
|
||||
"""Build the environment used to route the Hermes CLI through Headroom."""
|
||||
env = dict(environ if environ is not None else os.environ)
|
||||
openai_base_url = codex_proxy_base_url(port)
|
||||
anthropic_base_url = claude_proxy_base_url(port)
|
||||
env["OPENAI_BASE_URL"] = openai_base_url
|
||||
env["ANTHROPIC_BASE_URL"] = anthropic_base_url
|
||||
return env, [
|
||||
f"OPENAI_BASE_URL={openai_base_url}",
|
||||
f"ANTHROPIC_BASE_URL={anthropic_base_url}",
|
||||
]
|
||||
|
||||
|
||||
# Hermes honors OPENAI_BASE_URL / ANTHROPIC_BASE_URL only for these providers.
|
||||
# Its default (openrouter) and others such as nous call their own endpoints.
|
||||
_ROUTED_PROVIDERS = frozenset({"anthropic", "openai"})
|
||||
|
||||
|
||||
def unsupported_provider_error(hermes_args: tuple[str, ...] | list[str]) -> str | None:
|
||||
"""Return an error unless ``--provider`` names a provider Headroom can route.
|
||||
|
||||
ponytail: the flag is required on purpose. Hermes also resolves a provider
|
||||
from config.yaml and HERMES_INFERENCE_PROVIDER; mirroring that order here
|
||||
would drift. Parse them only if requiring the flag proves too strict.
|
||||
"""
|
||||
args = list(hermes_args)
|
||||
provider = ""
|
||||
for index, arg in enumerate(args):
|
||||
if arg == "--provider" and index + 1 < len(args):
|
||||
provider = args[index + 1]
|
||||
elif arg.startswith("--provider="):
|
||||
provider = arg.split("=", 1)[1]
|
||||
if provider.strip().lower() in _ROUTED_PROVIDERS:
|
||||
return None
|
||||
selected = f"'{provider}'" if provider else "no --provider flag"
|
||||
return (
|
||||
f"Error: Headroom cannot route this Hermes launch ({selected}).\n"
|
||||
"Only the anthropic and openai providers go through Headroom. Hermes's "
|
||||
"default provider (openrouter) and others such as nous call their own "
|
||||
"endpoints.\n"
|
||||
"Run: headroom wrap hermes -- --provider anthropic\n"
|
||||
"To use another provider, run `hermes` directly, without Headroom."
|
||||
)
|
||||
|
||||
|
||||
def is_scoped_coding_agent_path(path: str) -> bool:
|
||||
"""Return whether *path* is a Hermes scoped coding-agent endpoint."""
|
||||
return (path.startswith("/api/codex-proxy/") and path.endswith(_CODEX_RESPONSES_SUFFIX)) or (
|
||||
|
||||
@@ -41,6 +41,16 @@ This plugin closes the loop by calling the proxy's `POST /v1/retrieve` HTTP endp
|
||||
|
||||
3. Restart the Hermes gateway / TUI (plugin discovery is cached per process).
|
||||
|
||||
## Supported Hermes providers
|
||||
|
||||
`headroom wrap hermes` sets `ANTHROPIC_BASE_URL` and `OPENAI_BASE_URL`. Hermes uses these only for the `anthropic` and `openai` providers. Its default provider (`openrouter`) and others such as `nous` call their own endpoints and skip Headroom. You must pick a routed provider with `--provider`, for example:
|
||||
|
||||
```bash
|
||||
headroom wrap hermes -- --provider anthropic
|
||||
```
|
||||
|
||||
The wrapper stops with an error before it starts the proxy or Hermes when `--provider` is missing or is not `anthropic` or `openai`. This includes a provider set only in `~/.hermes/config.yaml`. To use another provider, run `hermes` directly, without Headroom.
|
||||
|
||||
## Recommended proxy configuration
|
||||
|
||||
Hermes tool names don't match headroom's built-in `DEFAULT_EXCLUDE_TOOLS` (which protects Claude Code's `Read`/`Grep`/`Edit`/...), so two exclusions are strongly recommended on the proxy side:
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Tests for `headroom wrap hermes` command."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from headroom.cli import wrap as wrap_mod
|
||||
from headroom.cli.main import main
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runner() -> CliRunner:
|
||||
return CliRunner()
|
||||
|
||||
|
||||
def test_wrap_hermes_sets_provider_envs(
|
||||
runner: CliRunner,
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""OPENAI_BASE_URL and ANTHROPIC_BASE_URL are set on launch."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_launch_tool(**kwargs): # noqa: ANN003
|
||||
captured.update(kwargs)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="hermes"):
|
||||
with patch.object(wrap_mod, "_launch_tool", side_effect=fake_launch_tool):
|
||||
result = runner.invoke(
|
||||
main, ["wrap", "hermes", "--port", "9000", "--", "--provider", "anthropic"]
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
env = captured["env"]
|
||||
assert isinstance(env, dict)
|
||||
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9000/v1"
|
||||
assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9000"
|
||||
assert captured["tool_label"] == "HERMES"
|
||||
assert captured["agent_type"] == "hermes"
|
||||
assert captured["args"] == ("--provider", "anthropic")
|
||||
|
||||
|
||||
def test_wrap_hermes_missing_binary_errors_clearly(
|
||||
runner: CliRunner,
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""If the hermes binary is missing, fail with a clear error."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
with patch.object(wrap_mod.shutil, "which", return_value=None):
|
||||
result = runner.invoke(main, ["wrap", "hermes"])
|
||||
|
||||
assert result.exit_code == 1
|
||||
assert result.output == (
|
||||
"Error: 'hermes' not found in PATH.\n"
|
||||
"Install Hermes: https://hermes-agent.nousresearch.com/\n"
|
||||
)
|
||||
|
||||
|
||||
def test_wrap_hermes_prepare_only_exits_cleanly(
|
||||
runner: CliRunner,
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""--prepare-only must not attempt to launch Hermes."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
with patch.object(wrap_mod, "_launch_tool") as launch_tool:
|
||||
result = runner.invoke(main, ["wrap", "hermes", "--prepare-only"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
launch_tool.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"hermes_args",
|
||||
[(), ("--provider", "openrouter"), ("--provider=nous",), ("--provider", "custom")],
|
||||
)
|
||||
def test_wrap_hermes_rejects_unrouted_provider_before_launch(
|
||||
runner: CliRunner,
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
hermes_args: tuple[str, ...],
|
||||
) -> None:
|
||||
monkeypatch.chdir(tmp_path)
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="hermes"):
|
||||
with patch.object(wrap_mod, "_launch_tool") as launch:
|
||||
result = runner.invoke(main, ["wrap", "hermes", "--", *hermes_args])
|
||||
|
||||
assert result.exit_code == 1
|
||||
assert "cannot route" in result.output
|
||||
assert "routed through Headroom" not in result.output
|
||||
launch.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("provider", ["anthropic", "openai"])
|
||||
def test_wrap_hermes_launches_routed_provider(
|
||||
runner: CliRunner,
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
provider: str,
|
||||
) -> None:
|
||||
monkeypatch.chdir(tmp_path)
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="hermes"):
|
||||
with patch.object(wrap_mod, "_launch_tool") as launch:
|
||||
result = runner.invoke(main, ["wrap", "hermes", "--", "--provider", provider])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
launch.assert_called_once()
|
||||
assert launch.call_args.kwargs["args"] == ("--provider", provider)
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from headroom.providers.hermes import build_launch_env
|
||||
|
||||
|
||||
def test_build_launch_env_sets_openai_base_url() -> None:
|
||||
env, _ = build_launch_env(9000, {})
|
||||
|
||||
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9000/v1"
|
||||
|
||||
|
||||
def test_build_launch_env_sets_anthropic_base_url() -> None:
|
||||
env, _ = build_launch_env(9000, {})
|
||||
|
||||
assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9000"
|
||||
|
||||
|
||||
def test_build_launch_env_returns_display_strings() -> None:
|
||||
_, lines = build_launch_env(9000, {})
|
||||
|
||||
assert lines == [
|
||||
"OPENAI_BASE_URL=http://127.0.0.1:9000/v1",
|
||||
"ANTHROPIC_BASE_URL=http://127.0.0.1:9000",
|
||||
]
|
||||
|
||||
|
||||
def test_build_launch_env_inherits_base_environ() -> None:
|
||||
env, _ = build_launch_env(9000, {"EXISTING_KEY": "existing-value"})
|
||||
|
||||
assert env["EXISTING_KEY"] == "existing-value"
|
||||
|
||||
|
||||
def test_build_launch_env_empty_mapping_does_not_inherit_host(monkeypatch) -> None:
|
||||
monkeypatch.setenv("HEADROOM_TEST_HOST_ONLY", "1")
|
||||
env, _ = build_launch_env(9000, {})
|
||||
assert "HEADROOM_TEST_HOST_ONLY" not in env
|
||||
|
||||
|
||||
def test_provider_error_for_default_and_unsupported_providers() -> None:
|
||||
from headroom.providers.hermes import unsupported_provider_error
|
||||
|
||||
assert unsupported_provider_error(()) is not None
|
||||
assert unsupported_provider_error(("--provider",)) is not None
|
||||
assert unsupported_provider_error(("--provider", "openrouter")) is not None
|
||||
assert unsupported_provider_error(("--provider=nous",)) is not None
|
||||
assert unsupported_provider_error(("--provider", "custom")) is not None
|
||||
|
||||
|
||||
def test_provider_error_silent_for_routed_providers() -> None:
|
||||
from headroom.providers.hermes import unsupported_provider_error
|
||||
|
||||
assert unsupported_provider_error(("-z", "hi", "--provider", "anthropic")) is None
|
||||
assert unsupported_provider_error(("--provider=OpenAI",)) is None
|
||||
assert unsupported_provider_error(("--provider", "openrouter", "--provider", "openai")) is None
|
||||
Reference in New Issue
Block a user