The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): route ctx.llm.complete(task=) through registered aux slots
hans1176222b7cc9
diff --git a/agent/plugin_llm.py b/agent/plugin_llm.pyindex 8fcd3364b1c..6086636aec2 100644--- a/agent/plugin_llm.py+++ b/agent/plugin_llm.py@@ -46,12 +46,21 @@ override knobs (``provider=``, ``model=``, ``agent_id=``,allowed_models: [openai/gpt-4o-mini] # optionalallow_agent_id_override: falseallow_profile_override: false+ allow_task_override: false # borrow the host's built-in aux tasksUntrusted plugins still get the default surface — they just can'tsteer provider, model, agent, or auth-profile selection. The trustgate is fail-closed: a missing config block means "no overrides,"not "anything goes."+The ``task=`` kwarg on the ``complete``/``acomplete`` family routes a+call through a plugin-registered auxiliary model slot+(``ctx.register_auxiliary_task``). A plugin may always name a slot it+registered itself; ``allow_task_override`` additionally lets it route+through the host's *built-in* auxiliary tasks. A foreign or unknown key+is rejected loudly (error + logged warning), never silently downgraded+to the main model.+Backed by :func:`agent.auxiliary_client.call_llm`, which alreadyhandles every provider, fallback chain, and per-task override Hermessupports.@@ -173,6 +182,11 @@ class _TrustPolicy:allow_any_model: bool = False # True when allowed_models == ["*"]allow_agent_id_override: bool = Falseallow_profile_override: bool = False+ # Gates routing a call through a *built-in* auxiliary task slot via+ # ``ctx.llm.complete(task=...)``. A plugin may always route through a+ # slot it registered itself; this flag additionally lets it borrow the+ # host's built-in aux tasks. Off by default (fail-closed).+ allow_task_override: bool = Falsedef _normalize_ref(raw: str) -> str:@@ -243,6 +257,7 @@ def _resolve_trust_policy(plugin_id: str) -> _TrustPolicy:allow_any_model=allow_any_model,allow_agent_id_override=bool(llm_cfg.get("allow_agent_id_override", False)),allow_profile_override=bool(llm_cfg.get("allow_profile_override", False)),+ allow_task_override=bool(llm_cfg.get("allow_task_override", False)),)@@ -329,6 +344,102 @@ def _check_overrides(return final_provider, final_model, requested_agent_id, final_profile+def _resolve_task_ownership(plugin_id: str) -> tuple[frozenset, frozenset]:+ """Return ``(owned_keys, builtin_keys)`` for the task trust gate.++ ``owned_keys`` are auxiliary-task keys ``plugin_id`` registered itself+ via ``ctx.register_auxiliary_task``; ``builtin_keys`` are the host's+ reserved auxiliary tasks. Both imports are lazy so plugin discovery+ doesn't hit a circular import at module load. A registry that can't be+ read yields empty sets, which fails the gate closed (unknown → rejected).++ Ownership matches on the same canonical id ``ctx.llm`` is bound to+ (``manifest.key or manifest.name``); ``register_auxiliary_task`` stores+ that same id as the entry's ``plugin`` owner.+ """+ owned: set = set()+ builtin: set = set()+ try:+ from hermes_cli.plugins import get_plugin_auxiliary_tasks++ for entry in get_plugin_auxiliary_tasks():+ if entry.get("plugin") == plugin_id:+ key = entry.get("key")+ if isinstance(key, str) and key:+ owned.add(key)+ except Exception: # pragma: no cover — registry unavailable+ pass+ try:+ from hermes_cli.main import _AUX_TASKS++ builtin = {k for k, _name, _desc in _AUX_TASKS}+ except Exception: # pragma: no cover — main import failure+ pass+ return frozenset(owned), frozenset(builtin)+++def _check_task(+ policy: _TrustPolicy,+ *,+ plugin_id: str,+ requested_task: Optional[str],+) -> Optional[str]:+ """Validate a plugin's requested auxiliary ``task`` routing key.++ Returns the normalized key to route through, or ``None`` for the+ default main-model path. Resolution:++ * unset / ``""`` / ``"auto"`` → ``None`` (today's behavior, byte-for-byte).+ * a key the plugin registered itself → allowed.+ * a built-in auxiliary key → allowed only when+ ``plugins.entries.<id>.llm.allow_task_override`` is true.+ * anything else (foreign or unknown) → **rejected loudly**.++ A foreign/unknown key raises :class:`PluginLlmTrustError` and logs a+ warning naming the offending plugin and key. It is deliberately *not*+ silently downgraded to ``auto``: silent fallback masks the+ misconfiguration and could route the call to the main model the user+ may have steered elsewhere on purpose (round-2 design correction,+ tracked in #64182 / #64174).+ """+ if not requested_task:+ return None+ task = requested_task.strip()+ if not task or task.lower() == "auto":+ return None++ owned, builtin = _resolve_task_ownership(plugin_id)+ if task in owned:+ return task+ if task in builtin:+ if policy.allow_task_override:+ return task+ logger.warning(+ "plugin_llm task routing denied: plugin %r requested built-in "+ "auxiliary task %r without plugins.entries.%s.llm.allow_task_override",+ plugin_id,+ task,+ plugin_id,+ )+ raise PluginLlmTrustError(+ f"Plugin {plugin_id!r} cannot route through the built-in auxiliary "+ f"task {task!r} (set plugins.entries.{plugin_id}.llm."+ f"allow_task_override to true to allow)."+ )+ logger.warning(+ "plugin_llm task routing denied: plugin %r requested auxiliary task %r "+ "it did not register",+ plugin_id,+ task,+ )+ raise PluginLlmTrustError(+ f"Plugin {plugin_id!r} cannot route through auxiliary task {task!r} — a "+ f"plugin may only pass a task key it registered itself via "+ f"ctx.register_auxiliary_task() (or a built-in key when plugins.entries."+ f"{plugin_id}.llm.allow_task_override is true)."+ )++# ---------------------------------------------------------------------------# Input normalization# ---------------------------------------------------------------------------@@ -631,6 +742,7 @@ class PluginLlm:agent_id: Optional[str] = None,profile: Optional[str] = None,purpose: Optional[str] = None,+ task: Optional[str] = None,) -> PluginLlmCompleteResult:"""Run a host-owned chat completion against the user's active model.@@ -640,8 +752,15 @@ class PluginLlm:+ ``model.model``). Each is independently gated by``plugins.entries.<id>.llm.allow_*_override`` (see moduledocstring).++ ``task`` optionally routes the call through a plugin-registered+ auxiliary model slot (``ctx.register_auxiliary_task``): unset or+ ``"auto"`` keeps today's main-model behavior, a slot the plugin+ registered itself resolves through ``auxiliary.<task>`` config,+ and a foreign/unknown key is rejected (see :func:`_check_task`)."""policy = self._policy_loader(self._plugin_id)+ eff_task = _check_task(policy, plugin_id=self._plugin_id, requested_task=task)eff_provider, eff_model, eff_agent, eff_profile = _check_overrides(policy,requested_provider=provider,@@ -657,6 +776,7 @@ class PluginLlm:temperature=temperature,max_tokens=max_tokens,timeout=timeout,+ task=eff_task,)text = _extract_text(response)usage = _extract_usage(response)@@ -670,13 +790,14 @@ class PluginLlm:"plugin_id": self._plugin_id,"purpose": purpose or "","profile": eff_profile or "",+ "task": eff_task or "",},)logger.info(- "plugin_llm.complete plugin=%s provider=%s model=%s purpose=%s "- "tokens=%d",- self._plugin_id, real_provider, real_model, purpose or "",- usage.total_tokens,+ "plugin_llm.complete plugin=%s provider=%s model=%s task=%s "+ "purpose=%s tokens=%d",+ self._plugin_id, real_provider, real_model, eff_task or "",+ purpose or "", usage.total_tokens,)return result@@ -697,6 +818,7 @@ class PluginLlm:agent_id: Optional[str] = None,profile: Optional[str] = None,purpose: Optional[str] = None,+ task: Optional[str] = None,) -> PluginLlmStructuredResult:"""Run a bounded host-owned structured completion.@@ -709,6 +831,9 @@ class PluginLlm:Validation requires the optional ``jsonschema`` package. When itisn't installed, JSON mode still works but schema enforcement isskipped with a debug log.++ ``task`` routes through a plugin-registered auxiliary slot (see+ :meth:`complete`)."""if not instructions or not instructions.strip():raise ValueError("complete_structured requires non-empty instructions")@@ -716,6 +841,7 @@ class PluginLlm:raise ValueError("complete_structured requires at least one input block")policy = self._policy_loader(self._plugin_id)+ eff_task = _check_task(policy, plugin_id=self._plugin_id, requested_task=task)eff_provider, eff_model, eff_agent, eff_profile = _check_overrides(policy,requested_provider=provider,@@ -743,6 +869,7 @@ class PluginLlm:max_tokens=max_tokens,timeout=timeout,extra_body=extra_body,+ task=eff_task,)text = _extract_text(response)usage = _extract_usage(response)@@ -762,13 +889,14 @@ class PluginLlm:"purpose": purpose or "","profile": eff_profile or "","schema_name": schema_name or "",+ "task": eff_task or "",},)logger.info("plugin_llm.complete_structured plugin=%s provider=%s model=%s "- "purpose=%s content_type=%s tokens=%d",- self._plugin_id, real_provider, real_model, purpose or "",- content_type, usage.total_tokens,+ "task=%s purpose=%s content_type=%s tokens=%d",+ self._plugin_id, real_provider, real_model, eff_task or "",+ purpose or "", content_type, usage.total_tokens,)return result@@ -786,9 +914,11 @@ class PluginLlm:agent_id: Optional[str] = None,profile: Optional[str] = None,purpose: Optional[str] = None,+ task: Optional[str] = None,) -> PluginLlmCompleteResult:"""Async sibling of :meth:`complete`."""policy = self._policy_loader(self._plugin_id)+ eff_task = _check_task(policy, plugin_id=self._plugin_id, requested_task=task)eff_provider, eff_model, eff_agent, eff_profile = _check_overrides(policy,requested_provider=provider,@@ -804,6 +934,7 @@ class PluginLlm:temperature=temperature,max_tokens=max_tokens,timeout=timeout,+ task=eff_task,)text = _extract_text(response)usage = _extract_usage(response)@@ -817,6 +948,7 @@ class PluginLlm:"plugin_id": self._plugin_id,"purpose": purpose or "","profile": eff_profile or "",+ "task": eff_task or "",},)@@ -837,6 +969,7 @@ class PluginLlm:agent_id: Optional[str] = None,profile: Optional[str] = None,purpose: Optional[str] = None,+ task: Optional[str] = None,) -> PluginLlmStructuredResult:"""Async sibling of :meth:`complete_structured`."""if not instructions or not instructions.strip():@@ -845,6 +978,7 @@ class PluginLlm:raise ValueError("acomplete_structured requires at least one input block")policy = self._policy_loader(self._plugin_id)+ eff_task = _check_task(policy, plugin_id=self._plugin_id, requested_task=task)eff_provider, eff_model, eff_agent, eff_profile = _check_overrides(policy,requested_provider=provider,@@ -870,6 +1004,7 @@ class PluginLlm:max_tokens=max_tokens,timeout=timeout,extra_body=extra_body,+ task=eff_task,)text = _extract_text(response)usage = _extract_usage(response)@@ -889,6 +1024,7 @@ class PluginLlm:"purpose": purpose or "","profile": eff_profile or "","schema_name": schema_name or "",+ "task": eff_task or "",},)@@ -927,10 +1063,15 @@ class PluginLlm:max_tokens: Optional[int],timeout: Optional[float],extra_body: Optional[Dict[str, Any]] = None,+ task: Optional[str] = None,) -> tuple[str, str, Any]:"""Invoke the host's ``call_llm``. Lazy-imports``agent.auxiliary_client`` to avoid circular deps at plugin- discovery time."""+ discovery time.++ ``task`` (already trust-checked by the caller) routes through the+ matching ``auxiliary.<task>`` slot; ``None`` keeps the main model.+ """if self._sync_caller is not None:return self._sync_caller(messages=messages,@@ -941,13 +1082,14 @@ class PluginLlm:max_tokens=max_tokens,timeout=timeout,extra_body=extra_body,+ task=task,)from agent.auxiliary_client import call_llmmerged_extra = dict(extra_body or {})if profile_override:merged_extra.setdefault("metadata", {})["auth_profile"] = profile_overrideresponse = call_llm(- task=None,+ task=task,provider=provider_override,model=model_override,messages=messages,@@ -974,6 +1116,7 @@ class PluginLlm:max_tokens: Optional[int],timeout: Optional[float],extra_body: Optional[Dict[str, Any]] = None,+ task: Optional[str] = None,) -> tuple[str, str, Any]:if self._async_caller is not None:return await self._async_caller(@@ -985,13 +1128,14 @@ class PluginLlm:max_tokens=max_tokens,timeout=timeout,extra_body=extra_body,+ task=task,)from agent.auxiliary_client import async_call_llmmerged_extra = dict(extra_body or {})if profile_override:merged_extra.setdefault("metadata", {})["auth_profile"] = profile_overrideresponse = await async_call_llm(- task=None,+ task=task,provider=provider_override,model=model_override,messages=messages,diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex f05013c4505..54ffde10ee1 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -1171,9 +1171,15 @@ class PluginContext:f"Pick a plugin-namespaced key (e.g. '{self.manifest.name}_{key}').")+ # Owner is the plugin's canonical id (``key or name``) — the same id+ # ``ctx.llm`` is bound to (PluginLlm._plugin_id) — so the task trust+ # gate in agent/plugin_llm.py can match ownership. For the common+ # case where a manifest sets no explicit ``key`` this equals the name.+ owner_id = self.manifest.key or self.manifest.name+# Reject duplicate registrations across pluginsexisting = self._manager._aux_tasks.get(key)- if existing is not None and existing.get("plugin") != self.manifest.name:+ if existing is not None and existing.get("plugin") != owner_id:raise ValueError(f"Plugin '{self.manifest.name}' cannot register auxiliary task "f"{key!r} — already registered by plugin "@@ -1199,7 +1205,7 @@ class PluginContext:"display_name": display_name,"description": description,"defaults": merged_defaults,- "plugin": self.manifest.name,+ "plugin": owner_id,}logger.debug("Plugin %s registered auxiliary task: %s (%s)",diff --git a/tests/agent/test_plugin_llm_task_routing.py b/tests/agent/test_plugin_llm_task_routing.pynew file mode 100644index 00000000000..3757c6e94e1--- /dev/null+++ b/tests/agent/test_plugin_llm_task_routing.py@@ -0,0 +1,399 @@+"""Tests for plugin auxiliary-task routing via ``ctx.llm.complete(task=...)``.++Covers issue #64174 (sub-issue 08/14 of #64182): a plugin can route an+LLM call through an auxiliary model slot it registered, the default path+is unchanged, and a foreign/unknown task key is rejected loudly rather+than silently downgraded to the main model (round-2 design correction).++The auxiliary client is stubbed via ``make_plugin_llm_for_test`` so the+injected caller both captures the ``task`` that would reach+``call_llm`` and stands in for a distinguishable slot model.+"""++from __future__ import annotations++import asyncio+import logging+from types import SimpleNamespace+from typing import Any, Dict, List++import pytest++from agent.plugin_llm import (+ PluginLlmTrustError,+ PluginLlmTextInput,+ _check_task,+ _resolve_task_ownership,+ _TrustPolicy,+ make_plugin_llm_for_test,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _fake_response(text: str = "ok", *, prompt: int = 3, completion: int = 5) -> SimpleNamespace:+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ message=SimpleNamespace(content=text, role="assistant"),+ finish_reason="stop",+ )+ ],+ usage=SimpleNamespace(+ prompt_tokens=prompt,+ completion_tokens=completion,+ total_tokens=prompt + completion,+ ),+ )+++def _capturing_caller(captured: Dict[str, Any]):+ """Sync caller that records kwargs and reports a slot-derived model.++ When a ``task`` is routed it reports ``("aux-provider", "aux-model")``+ so a test can prove the call provably landed on the slot's model+ (acceptance criterion: distinguishable model).+ """++ def caller(**kwargs: Any):+ captured.update(kwargs)+ if kwargs.get("task"):+ return "aux-provider", "aux-model", _fake_response()+ return "main-provider", "main-model", _fake_response()++ return caller+++def _async_capturing_caller(captured: Dict[str, Any]):+ async def caller(**kwargs: Any):+ captured.update(kwargs)+ if kwargs.get("task"):+ return "aux-provider", "aux-model", _fake_response()+ return "main-provider", "main-model", _fake_response()++ return caller+++def _set_registry(monkeypatch, entries: List[Dict[str, Any]]) -> None:+ """Point ``_resolve_task_ownership`` at a controlled plugin registry."""+ monkeypatch.setattr(+ "hermes_cli.plugins.get_plugin_auxiliary_tasks", lambda: list(entries)+ )+++def _set_builtins(monkeypatch, keys: List[str]) -> None:+ monkeypatch.setattr(+ "hermes_cli.main._AUX_TASKS", [(k, k.title(), "") for k in keys]+ )+++def _policy(plugin_id: str = "my-plugin", *, allow_task_override: bool = False) -> _TrustPolicy:+ return _TrustPolicy(plugin_id=plugin_id, allow_task_override=allow_task_override)+++# ---------------------------------------------------------------------------+# _check_task unit behavior+# ---------------------------------------------------------------------------+++class TestCheckTask:+ def test_none_returns_none(self, monkeypatch):+ _set_registry(monkeypatch, [])+ _set_builtins(monkeypatch, [])+ assert _check_task(_policy(), plugin_id="my-plugin", requested_task=None) is None++ @pytest.mark.parametrize("raw", ["auto", "AUTO", " auto ", "", " "])+ def test_auto_and_blank_return_none(self, monkeypatch, raw):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ assert _check_task(_policy(), plugin_id="my-plugin", requested_task=raw) is None++ def test_own_registered_key_allowed(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, ["vision"])+ assert (+ _check_task(_policy(), plugin_id="my-plugin", requested_task="classifier")+ == "classifier"+ )++ def test_own_key_stripped(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ assert (+ _check_task(_policy(), plugin_id="my-plugin", requested_task=" classifier ")+ == "classifier"+ )++ def test_foreign_key_rejected_and_named(self, monkeypatch, caplog):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "other-plugin"}])+ _set_builtins(monkeypatch, ["vision"])+ with caplog.at_level(logging.WARNING):+ with pytest.raises(PluginLlmTrustError) as exc:+ _check_task(_policy(), plugin_id="my-plugin", requested_task="classifier")+ # Error names both offending plugin and key; no silent fallback.+ assert "my-plugin" in str(exc.value)+ assert "classifier" in str(exc.value)+ assert any(+ "my-plugin" in r.getMessage() and "classifier" in r.getMessage()+ for r in caplog.records+ )++ def test_unknown_key_rejected(self, monkeypatch):+ _set_registry(monkeypatch, [])+ _set_builtins(monkeypatch, ["vision"])+ with pytest.raises(PluginLlmTrustError):+ _check_task(_policy(), plugin_id="my-plugin", requested_task="nope")++ def test_builtin_key_denied_without_flag(self, monkeypatch, caplog):+ _set_registry(monkeypatch, [])+ _set_builtins(monkeypatch, ["vision", "compression"])+ with caplog.at_level(logging.WARNING):+ with pytest.raises(PluginLlmTrustError) as exc:+ _check_task(+ _policy(allow_task_override=False),+ plugin_id="my-plugin",+ requested_task="vision",+ )+ assert "allow_task_override" in str(exc.value)+ assert any("vision" in r.getMessage() for r in caplog.records)++ def test_builtin_key_allowed_with_flag(self, monkeypatch):+ _set_registry(monkeypatch, [])+ _set_builtins(monkeypatch, ["vision", "compression"])+ assert (+ _check_task(+ _policy(allow_task_override=True),+ plugin_id="my-plugin",+ requested_task="vision",+ )+ == "vision"+ )++ def test_own_key_wins_over_builtin_flag_requirement(self, monkeypatch):+ # A plugin's own slot never needs allow_task_override, even if a+ # built-in of the same name somehow existed — own ownership is checked+ # first.+ _set_registry(monkeypatch, [{"key": "shared", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, ["shared"])+ assert (+ _check_task(+ _policy(allow_task_override=False),+ plugin_id="my-plugin",+ requested_task="shared",+ )+ == "shared"+ )+++# ---------------------------------------------------------------------------+# End-to-end routing through PluginLlm (sync + async, plain + structured)+# ---------------------------------------------------------------------------+++class TestRouting:+ def test_default_call_passes_task_none(self, monkeypatch):+ _set_registry(monkeypatch, [])+ _set_builtins(monkeypatch, [])+ captured: Dict[str, Any] = {}+ llm = make_plugin_llm_for_test(+ plugin_id="my-plugin",+ policy=_policy(),+ sync_caller=_capturing_caller(captured),+ )+ result = llm.complete([{"role": "user", "content": "hi"}])+ assert captured["task"] is None+ assert result.provider == "main-provider"+ assert result.model == "main-model"+ assert result.audit["task"] == ""++ def test_registered_task_routes_and_reports_slot_model(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, ["vision"])+ captured: Dict[str, Any] = {}+ llm = make_plugin_llm_for_test(+ plugin_id="my-plugin",+ policy=_policy(),+ sync_caller=_capturing_caller(captured),+ )+ result = llm.complete([{"role": "user", "content": "hi"}], task="classifier")+ # Provably routed: the task reached call_llm and the slot model won.+ assert captured["task"] == "classifier"+ assert result.provider == "aux-provider"+ assert result.model == "aux-model"+ assert result.audit["task"] == "classifier"++ def test_foreign_task_raises_before_invoking_caller(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "other-plugin"}])+ _set_builtins(monkeypatch, [])+ captured: Dict[str, Any] = {}+ llm = make_plugin_llm_for_test(+ plugin_id="my-plugin",+ policy=_policy(),+ sync_caller=_capturing_caller(captured),+ )+ with pytest.raises(PluginLlmTrustError):+ llm.complete([{"role": "user", "content": "hi"}], task="classifier")+ # The caller must never run for a rejected task — no wrong-model call.+ assert captured == {}++ def test_structured_routes_task(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ captured: Dict[str, Any] = {}+ llm = make_plugin_llm_for_test(+ plugin_id="my-plugin",+ policy=_policy(),+ sync_caller=_capturing_caller(captured),+ )+ result = llm.complete_structured(+ instructions="classify this",+ input=[PluginLlmTextInput(text="payload")],+ task="classifier",+ )+ assert captured["task"] == "classifier"+ assert result.audit["task"] == "classifier"++ def test_async_routes_task(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ captured: Dict[str, Any] = {}+ llm = make_plugin_llm_for_test(+ plugin_id="my-plugin",+ policy=_policy(),+ async_caller=_async_capturing_caller(captured),+ )+ result = asyncio.run(+ llm.acomplete([{"role": "user", "content": "hi"}], task="classifier")+ )+ assert captured["task"] == "classifier"+ assert result.audit["task"] == "classifier"++ def test_async_structured_routes_task(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ captured: Dict[str, Any] = {}+ llm = make_plugin_llm_for_test(+ plugin_id="my-plugin",+ policy=_policy(),+ async_caller=_async_capturing_caller(captured),+ )+ result = asyncio.run(+ llm.acomplete_structured(+ instructions="classify this",+ input=[PluginLlmTextInput(text="payload")],+ task="classifier",+ )+ )+ assert captured["task"] == "classifier"+ assert result.audit["task"] == "classifier"+++class TestForwardsToCallLlm:+ """Cover the production ``_invoke_*`` path (no injected caller), which is+ where the previously-hardcoded ``task=None`` is replaced by the routed+ key. The injected-caller tests above bypass this line."""++ def test_sync_forwards_task_to_call_llm(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ seen: Dict[str, Any] = {}++ def fake_call_llm(**kwargs: Any):+ seen.update(kwargs)+ return _fake_response()++ monkeypatch.setattr("agent.auxiliary_client.call_llm", fake_call_llm)+ llm = make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy())+ llm.complete([{"role": "user", "content": "hi"}], task="classifier")+ assert seen["task"] == "classifier"++ def test_sync_default_forwards_task_none(self, monkeypatch):+ _set_registry(monkeypatch, [])+ _set_builtins(monkeypatch, [])+ seen: Dict[str, Any] = {}++ def fake_call_llm(**kwargs: Any):+ seen.update(kwargs)+ return _fake_response()++ monkeypatch.setattr("agent.auxiliary_client.call_llm", fake_call_llm)+ llm = make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy())+ llm.complete([{"role": "user", "content": "hi"}])+ assert seen["task"] is None++ def test_async_forwards_task_to_async_call_llm(self, monkeypatch):+ _set_registry(monkeypatch, [{"key": "classifier", "plugin": "my-plugin"}])+ _set_builtins(monkeypatch, [])+ seen: Dict[str, Any] = {}++ async def fake_async_call_llm(**kwargs: Any):+ seen.update(kwargs)+ return _fake_response()++ monkeypatch.setattr("agent.auxiliary_client.async_call_llm", fake_async_call_llm)+ llm = make_plugin_llm_for_test(plugin_id="my-plugin", policy=_policy())+ asyncio.run(+ llm.acomplete([{"role": "user", "content": "hi"}], task="classifier")+ )+ assert seen["task"] == "classifier"+++# ---------------------------------------------------------------------------+# Ownership resolution against the real plugin registry+# ---------------------------------------------------------------------------+++class TestOwnershipIntegration:+ def _make_manager(self):+ from hermes_cli.plugins import PluginManager++ manager = PluginManager()+ manager._discovered = True+ return manager++ def _register(self, manager, *, name: str, key: str, task_key: str):+ from hermes_cli.plugins import PluginContext, PluginManifest++ manifest = PluginManifest(name=name, key=key)+ ctx = PluginContext(manifest, manager)+ ctx.register_auxiliary_task(+ task_key, display_name=task_key.title(), description="x"+ )+ return ctx++ def test_owner_stored_as_canonical_id(self, monkeypatch):+ # A manifest with a distinct key stores the canonical id (key), which+ # is exactly what ctx.llm is bound to — so the trust gate matches.+ manager = self._make_manager()+ self._register(manager, name="Display Name", key="my_key", task_key="classifier")+ monkeypatch.setattr(+ "hermes_cli.plugins._ensure_plugins_discovered", lambda: manager+ )+ _set_builtins(monkeypatch, ["vision"])++ owned, builtin = _resolve_task_ownership("my_key")+ assert "classifier" in owned+ assert "vision" in builtin+ # The name (not the canonical id) does not own it.+ owned_by_name, _ = _resolve_task_ownership("Display Name")+ assert "classifier" not in owned_by_name++ def test_check_task_end_to_end_with_real_registry(self, monkeypatch):+ manager = self._make_manager()+ self._register(manager, name="p", key="", task_key="classifier")+ monkeypatch.setattr(+ "hermes_cli.plugins._ensure_plugins_discovered", lambda: manager+ )+ _set_builtins(monkeypatch, ["vision"])++ assert (+ _check_task(_policy(plugin_id="p"), plugin_id="p", requested_task="classifier")+ == "classifier"+ )+ with pytest.raises(PluginLlmTrustError):+ _check_task(+ _policy(plugin_id="other"), plugin_id="other", requested_task="classifier"+ )