The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): carry a custom provider's extra_body into TUI/Desktop agents and aux calls
Austin Pickett81f481b2db39
diff --git a/acp_adapter/session.py b/acp_adapter/session.pyindex 956baec71ce..e5a868b0cc0 100644--- a/acp_adapter/session.py+++ b/acp_adapter/session.py@@ -544,6 +544,10 @@ class SessionManager:"credential_pool": runtime.get("credential_pool"),"command": runtime.get("command"), "args": list(runtime.get("args") or []),})+ # The resolved provider's request body (a custom entry's extra_body); an explicit base_url pointing+ # elsewhere is another endpoint, which must not inherit it.+ if runtime.get("request_overrides") and (not base_url or base_url == runtime.get("base_url")):+ kwargs["request_overrides"] = runtime["request_overrides"]except Exception as exc:resolve_error = exclogger.debug("ACP session falling back to default provider resolution", exc_info=True)diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 2de9e47b44e..d6520e26a2e 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -6295,6 +6295,34 @@ def _effective_aux_timeout(task: str, timeout: Optional[float]) -> float:return max(effective, _COMPRESSION_TIMEOUT_FLOOR_SECONDS) if task == "compression" else effective+def _with_custom_endpoint_extra_body(+ extra_body: Optional[dict], provider: str, model: Optional[str], base_url: Optional[str],+) -> Optional[dict]:+ """Layer the destination custom provider's ``extra_body`` UNDER the task/caller body.++ The main agent merges a ``custom_providers`` / ``providers:`` entry's ``extra_body`` into every+ request to that endpoint (``agent_init._merge_custom_provider_extra_body``); an aux request routed+ to the same entry must carry it too, or a proxy that 400s without e.g. a ``user`` field breaks+ smart approval, titles and compression (#103738). Resolved per destination with the agent's own+ matcher, so a fallback to another provider never inherits it; ``auxiliary.<task>.extra_body`` and+ caller keys win on conflict, as request_overrides win over the entry on the main path."""+ if not base_url:+ return extra_body+ try:+ from agent.agent_init import _custom_provider_extra_body_for_agent+ from hermes_cli.config import get_compatible_custom_providers, load_config_readonly+ inherited = _custom_provider_extra_body_for_agent(+ provider=provider or "", model=model or "", base_url=str(base_url),+ custom_providers=get_compatible_custom_providers(load_config_readonly()),+ )+ except Exception:+ logger.debug("custom provider extra_body lookup failed for aux request", exc_info=True)+ return extra_body+ if not inherited:+ return extra_body+ return {**inherited, **(extra_body or {})}++def _get_task_extra_body(task: str) -> Dict[str, Any]:"""Shallow copy of ``auxiliary.<task>.extra_body`` with ``reasoning_effort`` folded into``reasoning`` unless one is configured (more specific wins). MoA tasks are excluded: their@@ -6646,6 +6674,7 @@ def _build_call_kwargs(if no_progress_timeout is not None:kwargs["no_progress_timeout"] = no_progress_timeouteffective_base = base_url or (_current_custom_base_url() if provider == "custom" else "")+ extra_body = _with_custom_endpoint_extra_body(extra_body, provider, model, effective_base)# Per-model fixed/omitted temperature, then Opus 4.7+ sampling bans: it rejects any# non-default temperature/top_p/top_k, so drop silently rather than 400 when the aux model flips.fixed_temperature = _fixed_temperature_for_model(model, effective_base, provider)diff --git a/hermes_cli/oneshot.py b/hermes_cli/oneshot.pyindex 96c8227fad4..54f62223288 100644--- a/hermes_cli/oneshot.py+++ b/hermes_cli/oneshot.py@@ -585,6 +585,8 @@ def _run_agent(session_id=resume_sid,credential_pool=runtime.get("credential_pool"),fallback_model=get_fallback_chain(cfg) or None,+ # The resolved provider's request body (a custom entry's extra_body), as `hermes chat` passes it.+ request_overrides=runtime.get("request_overrides"),ephemeral_system_prompt=skills_prompt,reasoning_config=reasoning_config,# The only interactive callback wired: no user sits at a terminal. Sudo prompts gate ondiff --git a/tests/acp_adapter/test_session_reasoning_config.py b/tests/acp_adapter/test_session_reasoning_config.pyindex cb030ad019a..bf6c329ab59 100644--- a/tests/acp_adapter/test_session_reasoning_config.py+++ b/tests/acp_adapter/test_session_reasoning_config.py@@ -52,3 +52,22 @@ def test_acp_agent_receives_configured_reasoning(acp_env):"agent": {"reasoning_effort": "none", "reasoning_overrides": {"gpt-5.6": "high"}}})agent = sm._make_agent(session_id="s2", cwd=".", model="gpt-5.6")assert agent.kwargs["reasoning_config"] == {"enabled": True, "effort": "high"}+++def test_acp_agent_receives_custom_provider_request_body(acp_env, monkeypatch):+ """#103738: the resolver's ``request_overrides`` (a custom entry's ``extra_body``) reach the ACP agent, as+ on the CLI; an explicit base_url naming a different endpoint does not inherit them."""+ monkeypatch.setattr(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ lambda requested=None, **_kwargs: {"provider": "custom", "api_mode": "chat_completions",+ "base_url": "https://proxy.example/v1", "api_key": "k",+ "request_overrides": {"extra_body": {"user": "proxy-user"}}},+ )+ acp_env({"model": {"default": "some-model", "provider": "custom:my-proxy"}})+ sm = SessionManager(db=None)+ sm._get_db = lambda: None+ assert sm._make_agent(session_id="s1", cwd=".").kwargs["request_overrides"] == {"extra_body": {"user": "proxy-user"}}+ same = sm._make_agent(session_id="s2", cwd=".", base_url="https://proxy.example/v1")+ assert same.kwargs["request_overrides"] == {"extra_body": {"user": "proxy-user"}}+ other = sm._make_agent(session_id="s3", cwd=".", base_url="https://elsewhere.example/v1")+ assert "request_overrides" not in other.kwargsdiff --git a/tests/agent/test_auxiliary_named_custom_providers.py b/tests/agent/test_auxiliary_named_custom_providers.pyindex bbe5093bf1f..7457aa4a0ff 100644--- a/tests/agent/test_auxiliary_named_custom_providers.py+++ b/tests/agent/test_auxiliary_named_custom_providers.py@@ -557,3 +557,67 @@ class TestKeyedCustomProviderReasoningWire:reasoning_config={"enabled": True, "effort": "medium"},)assert kwargs["extra_body"] == nested and "reasoning_effort" not in kwargs+++class TestAuxInheritsCustomProviderExtraBody:+ """#103738 hole 3: an aux request routed to a custom provider carries that entry's ``extra_body`` the+ way the main agent's requests do — a proxy that 400s without a ``user`` field must not break smart+ approval just because ``auxiliary.approval.extra_body`` is empty. Task/caller keys still win, and a+ request to any other endpoint never inherits it."""++ _PROXY = "https://proxy.example/v1"++ def _config(self, **auxiliary):+ return {+ "model": {"default": "some-model", "provider": "custom:my-proxy"},+ "custom_providers": [+ {"name": "my-proxy", "base_url": self._PROXY, "model": "some-model", "api_key": "sk-x",+ "extra_body": {"user": "proxy-user", "metadata": {"tier": "entry"}}},+ {"name": "other-proxy", "base_url": "https://other.example/v1", "api_key": "sk-y",+ "extra_body": {"user": "other-user"}},+ ],+ "auxiliary": auxiliary,+ }++ def _sent_extra_body(self, main_runtime=None, **call):+ from agent.auxiliary_client import call_llm+ sent = {}++ def fake_create(**kwargs):+ sent.update(kwargs)+ return MagicMock()++ with patch("openai.resources.chat.completions.Completions.create", side_effect=fake_create), \+ patch("agent.auxiliary_client._validate_llm_response", side_effect=lambda resp, _t, **_kw: resp):+ call_llm(task="approval", messages=[{"role": "user", "content": "hi"}], main_runtime=main_runtime, **call)+ assert sent, "request never reached the transport"+ return sent.get("extra_body") or {}++ @pytest.mark.parametrize("main_runtime", [+ None,+ {"provider": "custom", "model": "some-model", "base_url": _PROXY, "api_key": "sk-x"},+ ], ids=["config-main", "live-runtime"])+ def test_approval_with_empty_task_extra_body_inherits_entry_body(self, tmp_path, main_runtime):+ _write_config(tmp_path, self._config(approval={"extra_body": {}}))+ body = self._sent_extra_body(main_runtime=main_runtime)+ assert body["user"] == "proxy-user"++ def test_task_and_caller_keys_win_over_entry(self, tmp_path):+ _write_config(tmp_path, self._config(approval={"extra_body": {"metadata": {"tier": "task"}}}))+ body = self._sent_extra_body(extra_body={"user": "caller-user"})+ assert body["user"] == "caller-user"+ assert body["metadata"] == {"tier": "task"}++ def test_other_destinations_do_not_inherit(self, tmp_path):+ _write_config(tmp_path, self._config())+ from agent.auxiliary_client import _build_call_kwargs+ msgs = [{"role": "user", "content": "hi"}]+ # A fallback to a built-in never carries the custom entry's body.+ openrouter = _build_call_kwargs("openrouter", "vendor/model", msgs, base_url="https://openrouter.ai/api/v1")+ assert "user" not in (openrouter.get("extra_body") or {})+ # A fallback to another named entry carries ITS body, not the primary's.+ other = _build_call_kwargs("custom:other-proxy", "m", msgs, base_url="https://other.example/v1/")+ assert other["extra_body"]["user"] == "other-user"+ # A custom endpoint no entry describes gets nothing.+ stray = _build_call_kwargs("custom", "some-model", msgs, base_url="https://stray.example/v1")+ assert "user" not in (stray.get("extra_body") or {})diff --git a/tests/hermes_cli/test_oneshot_fallback.py b/tests/hermes_cli/test_oneshot_fallback.pyindex 36607e67477..79a0800561c 100644--- a/tests/hermes_cli/test_oneshot_fallback.py+++ b/tests/hermes_cli/test_oneshot_fallback.py@@ -104,3 +104,40 @@ def test_run_agent_falls_back_when_primary_resolution_raises_auth_error(monkeypaassert text == "pong"assert (captured["provider"], captured["model"]) == ("anthropic", "claude-x")assert captured["api_key"] == "fb"+++def test_run_agent_forwards_resolved_request_overrides(monkeypatch):+ """#103738: ``hermes -z`` hands the resolver's ``request_overrides`` (a custom entry's ``extra_body``) to+ AIAgent like ``hermes chat``, or a proxy that requires a body field 400s on one-shot runs."""+ import hermes_cli.oneshot as oneshot_mod++ captured = {}++ class _FakeAgent:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ def __setattr__(self, name, _value):+ pass++ def run_conversation(self, _prompt, conversation_history=None):+ return {"final_response": "pong", "session_id": "s"}++ def close(self):+ pass++ def fake_resolve(**kw):+ return {"api_key": "k", "base_url": "https://proxy.example/v1", "provider": "custom", "api_mode": "chat_completions",+ "credential_pool": None, "request_overrides": {"extra_body": {"user": "proxy-user"}}}++ cfg = {"model": {"default": "some-model", "provider": "custom:my-proxy"}}+ monkeypatch.setattr(oneshot_mod, "_create_session_db_for_oneshot", lambda: None)+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: cfg)+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", fake_resolve)+ monkeypatch.setattr("hermes_cli.tools_config._get_platform_tools", lambda _cfg, _p: [])+ monkeypatch.setattr("hermes_cli.mcp_startup.ensure_mcp_discovery_before_agent_build", lambda **_kw: None)+ monkeypatch.setattr("run_agent.AIAgent", _FakeAgent)++ oneshot_mod._run_agent("say OK")++ assert captured["request_overrides"] == {"extra_body": {"user": "proxy-user"}}diff --git a/tests/tui_gateway/test_custom_provider_session_persistence.py b/tests/tui_gateway/test_custom_provider_session_persistence.pyindex e5bc118e28b..f49c79b0c06 100644--- a/tests/tui_gateway/test_custom_provider_session_persistence.py+++ b/tests/tui_gateway/test_custom_provider_session_persistence.py@@ -172,6 +172,29 @@ class TestResumeRoundTrip:assert kwargs["api_key"] == MIMO_KEY+class TestMakeAgentForwardsProviderRequestBody:+ """#103738 hole 1: the resolver lifts a custom entry's ``extra_body`` onto ``request_overrides``; the+ TUI/Desktop build must hand it to AIAgent like the CLI and cron do, or a proxy that requires a body field+ (``user``) 400s in the app while ``hermes chat`` works."""++ def test_entry_extra_body_reaches_agent(self, monkeypatch):+ entry = {**LEGACY_LIST_CONFIG["custom_providers"][0], "extra_body": {"user": "proxy-user"}}+ config = {"custom_providers": [entry]}+ override = {"model": "mimo-v2.5-pro", "provider": "custom:mimo-v2.5-pro"}++ kwargs = _make_agent_with_override(override, monkeypatch, config)++ assert kwargs["base_url"] == MIMO_URL+ assert kwargs["request_overrides"] == {"extra_body": {"user": "proxy-user"}}++ def test_entry_without_extra_body_sends_none(self, monkeypatch):+ override = {"model": "mimo-v2.5-pro", "provider": "custom:mimo-v2.5-pro"}++ kwargs = _make_agent_with_override(override, monkeypatch, LEGACY_LIST_CONFIG)++ assert not kwargs["request_overrides"]++# --- Regression: bare "custom" WITHOUT a base_url (GH #44022 / #47714) ------## The recurring Desktop/TUI "No LLM provider configured" regression. Everydiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex ed93a145bf1..39e84f6e885 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2574,6 +2574,8 @@ def _make_agent(checkpoints_enabled=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),+ # The resolved provider's request body (a custom entry's extra_body), as the CLI/cron/gateway pass it.+ request_overrides=runtime.get("request_overrides"),prefill_messages=_load_prefill_messages() or None, **_agent_cbs(sid))if context_cwd_is_launch_artifact is None:context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)