The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): fire pre/post_auxiliary_call events on every auxiliary LLM call (#79733)
teknium10e5809566f8e
diff --git a/agent/AGENTS.md b/agent/AGENTS.mdindex a230612e612..9bfd3d135f6 100644--- a/agent/AGENTS.md+++ b/agent/AGENTS.md@@ -98,6 +98,10 @@ cache break — keep it the only one. Full detail:- **Auxiliary (side-LLM) work** — curator, vision, embedding, title generation, session_search,compression — resolves through `agent/auxiliary_client.py::_resolve_auto_route`; each task can pinits own `provider/model/base_url/reasoning_effort` under `auxiliary:` in config.yaml.+ Every physical attempt funnels through `_relay_sync_completion` / `_relay_async_completion` /+ `_relay_sync_stream`, where `agent/auxiliary_hooks.py` emits `pre_auxiliary_call` /+ `post_auxiliary_call` (observer-only, fail-open, `aux_task` set); the main-loop+ `pre/post_api_request` events must NOT fire for aux calls (#79733).- Fallback models and credential pools are resolution-chain code: E2E them with real importsagainst a temp `HERMES_HOME`, not mocks (root rubric).diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 7000f342612..03d1f24a99b 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -2606,10 +2606,16 @@ def _relay_sync_completion(return _run_protected_sync_provider_call(callback, kwargs)provider_name, fallback_model, metadata = routefrom agent import relay_llm- return relay_llm.execute_current(- kwargs, lambda request: _run_protected_sync_provider_call(callback, request),- name=provider_name, model_name=str(kwargs.get("model") or fallback_model),- metadata=metadata, defer_logical_completion=True,+ from agent.auxiliary_hooks import run_with_aux_hooks+ model_name = str(kwargs.get("model") or fallback_model)+ return run_with_aux_hooks(+ lambda: relay_llm.execute_current(+ kwargs, lambda request: _run_protected_sync_provider_call(callback, request),+ name=provider_name, model_name=model_name, metadata=metadata,+ defer_logical_completion=True,+ ),+ aux_task=metadata["auxiliary_task"], metadata=metadata, client=client, kwargs=kwargs,+ provider=provider_name, model=model_name, api_mode=metadata["api_mode"],)@@ -2627,9 +2633,15 @@ async def _relay_async_completion(return await callback(kwargs)provider_name, fallback_model, metadata = routefrom agent import relay_llm- return await relay_llm.execute_current_async(- kwargs, callback, name=provider_name, model_name=str(kwargs.get("model") or fallback_model),- metadata=metadata, defer_logical_completion=True,+ from agent.auxiliary_hooks import arun_with_aux_hooks+ model_name = str(kwargs.get("model") or fallback_model)+ return await arun_with_aux_hooks(+ lambda: relay_llm.execute_current_async(+ kwargs, callback, name=provider_name, model_name=model_name,+ metadata=metadata, defer_logical_completion=True,+ ),+ aux_task=metadata["auxiliary_task"], metadata=metadata, client=client, kwargs=kwargs,+ provider=provider_name, model=model_name, api_mode=metadata["api_mode"],)@@ -2647,10 +2659,15 @@ def _relay_sync_stream(return create(kwargs)provider_name, fallback_model, metadata = routefrom agent import relay_llm- return relay_llm.stream_current(- kwargs, create, name=provider_name,- model_name=str(kwargs.get("model") or fallback_model), finalizer=dict, metadata=metadata,- completed_response_predicate=lambda value: hasattr(value, "choices"),+ from agent.auxiliary_hooks import run_with_aux_hooks+ model_name = str(kwargs.get("model") or fallback_model)+ return run_with_aux_hooks(+ lambda: relay_llm.stream_current(+ kwargs, create, name=provider_name, model_name=model_name, finalizer=dict,+ metadata=metadata, completed_response_predicate=lambda value: hasattr(value, "choices"),+ ),+ aux_task=metadata["auxiliary_task"], metadata=metadata, client=client, kwargs=kwargs,+ provider=provider_name, model=model_name, api_mode=metadata["api_mode"], streaming=True,)diff --git a/agent/auxiliary_hooks.py b/agent/auxiliary_hooks.pynew file mode 100644index 00000000000..613d794ca2f--- /dev/null+++ b/agent/auxiliary_hooks.py@@ -0,0 +1,252 @@+"""Plugin events for auxiliary LLM calls (#79733).++``pre_auxiliary_call`` / ``post_auxiliary_call`` fire once per physical provider attempt at the+relay boundary of ``agent.auxiliary_client`` — the funnel every auxiliary task (titling,+compression, MoA advisors/aggregator, vision, approval, ...) shares, retries and fallbacks+included — carrying the ``pre_api_request`` / ``post_api_request`` payload shape plus+``aux_task``. They are deliberately DISTINCT events: the main-loop ``*_api_request`` events stay+turn-scoped, so observability plugins keyed on turn identity never see auxiliary traffic unless+they subscribe to these. Observer-only (returns ignored) and fail-open: a raising or hung+callback is logged and the auxiliary call proceeds untouched.+"""++from __future__ import annotations++import logging+import time+from typing import Any, Awaitable, Callable, Dict, Optional++logger = logging.getLogger(__name__)++PRE_AUXILIARY_CALL = "pre_auxiliary_call"+POST_AUXILIARY_CALL = "post_auxiliary_call"+++def _parent_turn_identity() -> Dict[str, str]:+ """``session_id`` / ``task_id`` / ``turn_id`` / ``platform`` of the main turn this auxiliary+ call runs under, or empty strings for turn-less callers (cron, gateway idle work)."""+ ident = {"session_id": "", "task_id": "", "turn_id": "", "platform": ""}+ try:+ from agent.relay_runtime import current_turn++ turn = current_turn()+ except Exception:+ return ident+ if turn is None:+ return ident+ lease = getattr(turn, "lease", None)+ ident["session_id"] = str(getattr(lease, "session_id", "") or "")+ ident["platform"] = str(getattr(lease, "platform", "") or "")+ ident["task_id"] = str(getattr(turn, "task_id", "") or "")+ ident["turn_id"] = str(getattr(turn, "turn_id", "") or "")+ return ident+++def _system_prompt(messages: Any, kwargs: Dict[str, Any]) -> str:+ if isinstance(kwargs.get("system"), str): # Anthropic+ return kwargs["system"]+ if isinstance(kwargs.get("instructions"), str): # Responses+ return kwargs["instructions"]+ if isinstance(messages, list) and messages and isinstance(messages[0], dict):+ first = messages[0]+ if first.get("role") == "system" and isinstance(first.get("content"), str):+ return first["content"]+ return ""+++def _usage_summary(response: Any, *, provider: str, api_mode: str) -> Optional[Dict[str, Any]]:+ raw_usage = getattr(response, "usage", None)+ if response is None or not raw_usage:+ return None+ from dataclasses import asdict++ from agent.usage_pricing import normalize_usage++ cu = normalize_usage(raw_usage, provider=provider, api_mode=api_mode)+ summary = asdict(cu)+ summary.pop("raw_usage", None)+ summary["prompt_tokens"] = cu.prompt_tokens+ summary["total_tokens"] = cu.total_tokens+ return summary+++def _first_choice_message(response: Any) -> Any:+ choices = getattr(response, "choices", None)+ if isinstance(response, dict):+ choices = response.get("choices")+ if not choices:+ return None, None+ choice = choices[0]+ if isinstance(choice, dict):+ return choice.get("message"), choice.get("finish_reason")+ return getattr(choice, "message", None), getattr(choice, "finish_reason", None)+++def _field(obj: Any, name: str) -> Any:+ return obj.get(name) if isinstance(obj, dict) else getattr(obj, name, None)+++class _AuxCallHooks:+ """Fires the pre/post pair for one provider attempt; the base payload is built once."""++ def __init__(+ self, *, aux_task: str, metadata: Dict[str, Any], client: Any, kwargs: Dict[str, Any],+ provider: str, model: str, api_mode: str, streaming: bool,+ ) -> None:+ self.provider = provider+ self.api_mode = api_mode+ self.streaming = streaming+ self.kwargs = kwargs+ self.started_at = time.time()+ self.base: Dict[str, Any] = dict(_parent_turn_identity())+ self.base.update(+ aux_task=aux_task,+ api_request_id=str(metadata.get("api_request_id") or ""),+ retry_count=int(metadata.get("retry_count") or 0),+ api_call_count=int(metadata.get("retry_count") or 0) + 1,+ model=model,+ provider=provider,+ base_url=str(getattr(client, "base_url", "") or ""),+ api_mode=api_mode,+ streaming=streaming,+ started_at=self.started_at,+ message_count=len(kwargs.get("messages") or kwargs.get("input") or []),+ )++ def pre(self) -> None:+ if not _has_hook(PRE_AUXILIARY_CALL):+ return+ from agent.api_request_hooks import ApiRequestHooksMixin as _Sanitize++ kwargs = self.kwargs+ messages = kwargs.get("messages")+ if not isinstance(messages, list):+ messages = kwargs.get("input") # Responses API+ if not isinstance(messages, list):+ messages = []+ body = {k: v for k, v in kwargs.items() if k not in {"timeout", "http_client"}}+ total_chars = sum(len(str(_field(m, "content") or "")) for m in messages)+ _fire(+ PRE_AUXILIARY_CALL, **self.base,+ request_messages=list(messages),+ system_prompt=_system_prompt(messages, kwargs),+ tool_count=len(kwargs.get("tools") or []),+ approx_input_tokens=total_chars // 4,+ request_char_count=total_chars,+ max_tokens=kwargs.get("max_tokens") or kwargs.get("max_completion_tokens"),+ request=_Sanitize._sanitize_hook_payload({"method": "POST", "body": body}),+ )++ def post(self, response: Any = None, error: Optional[BaseException] = None) -> None:+ if not _has_hook(POST_AUXILIARY_CALL):+ return+ from agent.api_request_hooks import ApiRequestHooksMixin as _Sanitize++ ended_at = time.time()+ payload: Dict[str, Any] = dict(+ self.base, ended_at=ended_at, api_duration=max(0.0, ended_at - self.started_at),+ error=None if error is None else f"{type(error).__name__}: {error}"[:2000],+ error_type=None if error is None else type(error).__name__,+ )+ # A streamed response is handed back unconsumed (the MoA facade owns reassembly), so+ # there is no usage/finish_reason to report yet; ``streaming`` tells the observer why.+ if error is not None or self.streaming:+ payload.update(finish_reason=None, response_model=None, usage=None, response=None,+ assistant_content_chars=0, assistant_tool_call_count=0)+ else:+ message, finish_reason = _first_choice_message(response)+ content = _field(message, "content") if message is not None else None+ tool_calls = (_field(message, "tool_calls") if message is not None else None) or []+ payload.update(+ finish_reason=finish_reason,+ response_model=_field(response, "model"),+ usage=_usage_summary(response, provider=self.provider, api_mode=self.api_mode),+ response=_Sanitize._sanitize_hook_payload({+ "model": _field(response, "model"),+ "finish_reason": finish_reason,+ "assistant_message": {+ "role": (_field(message, "role") if message is not None else None) or "assistant",+ "content": content,+ "tool_calls": tool_calls,+ },+ "usage": payload.get("usage"),+ }),+ assistant_content_chars=len(content) if isinstance(content, str) else 0,+ assistant_tool_call_count=len(tool_calls),+ )+ _fire(POST_AUXILIARY_CALL, **payload)+++def _has_hook(name: str) -> bool:+ try:+ from hermes_cli.lifecycle import has_hook++ return has_hook(name)+ except Exception:+ return False+++def _fire(name: str, **payload: Any) -> None:+ """Dispatch one event; a failing subscriber is logged, never propagated (the aux task's+ result must not depend on an observer)."""+ try:+ from hermes_cli.lifecycle import invoke_hook++ invoke_hook(name, **payload)+ except Exception:+ logger.warning("%s plugin hook failed for aux_task=%s; continuing",+ name, payload.get("aux_task"), exc_info=True)+++def _hooks_or_none(**kw: Any) -> Optional[_AuxCallHooks]:+ if not (_has_hook(PRE_AUXILIARY_CALL) or _has_hook(POST_AUXILIARY_CALL)):+ return None+ try:+ hooks = _AuxCallHooks(**kw)+ hooks.pre()+ except Exception:+ logger.warning("pre_auxiliary_call payload build failed; continuing", exc_info=True)+ return None+ return hooks+++def _post_safely(hooks: Optional[_AuxCallHooks], response: Any = None, error: Any = None) -> None:+ if hooks is None:+ return+ try:+ hooks.post(response, error)+ except Exception:+ logger.warning("post_auxiliary_call payload build failed; continuing", exc_info=True)+++def run_with_aux_hooks(+ call: Callable[[], Any], *, aux_task: str, metadata: Dict[str, Any], client: Any,+ kwargs: Dict[str, Any], provider: str, model: str, api_mode: str, streaming: bool = False,+) -> Any:+ """Run one synchronous provider attempt between ``pre_auxiliary_call`` and+ ``post_auxiliary_call``; the exception (if any) is reported in ``post`` and re-raised."""+ hooks = _hooks_or_none(aux_task=aux_task, metadata=metadata, client=client, kwargs=kwargs,+ provider=provider, model=model, api_mode=api_mode, streaming=streaming)+ try:+ response = call()+ except BaseException as exc:+ _post_safely(hooks, error=exc)+ raise+ _post_safely(hooks, response=response)+ return response+++async def arun_with_aux_hooks(+ call: Callable[[], Awaitable[Any]], *, aux_task: str, metadata: Dict[str, Any], client: Any,+ kwargs: Dict[str, Any], provider: str, model: str, api_mode: str,+) -> Any:+ """Async twin of :func:`run_with_aux_hooks`."""+ hooks = _hooks_or_none(aux_task=aux_task, metadata=metadata, client=client, kwargs=kwargs,+ provider=provider, model=model, api_mode=api_mode, streaming=False)+ try:+ response = await call()+ except BaseException as exc:+ _post_safely(hooks, error=exc)+ raise+ _post_safely(hooks, response=response)+ return responsediff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.pyindex 7228017ddb8..6c0f3e64ae7 100644--- a/hermes_cli/hooks.py+++ b/hermes_cli/hooks.py@@ -151,6 +151,24 @@ _DEFAULT_PAYLOADS = {# response, so without this an observer cannot see or price the fan-out."moa_references": None,},+ "pre_auxiliary_call": {+ "aux_task": "title_generation", "session_id": "test-session", "task_id": "test-task",+ "turn_id": "test-turn", "api_request_id": "aux-0123abcd", "platform": "cli",+ "model": "claude-haiku-4-5", "provider": "anthropic",+ "base_url": "https://api.anthropic.com", "api_mode": "anthropic_messages",+ "api_call_count": 1, "retry_count": 0, "streaming": False, "message_count": 2,+ "tool_count": 0, "approx_input_tokens": 256, "request_char_count": 1024, "max_tokens": 64,+ },+ "post_auxiliary_call": {+ "aux_task": "title_generation", "session_id": "test-session", "task_id": "test-task",+ "turn_id": "test-turn", "api_request_id": "aux-0123abcd", "platform": "cli",+ "model": "claude-haiku-4-5", "provider": "anthropic",+ "base_url": "https://api.anthropic.com", "api_mode": "anthropic_messages",+ "api_call_count": 1, "retry_count": 0, "streaming": False, "api_duration": 0.42,+ "started_at": 1756000000.0, "ended_at": 1756000000.42, "finish_reason": "stop",+ "response_model": "claude-haiku-4-5", "usage": {"input_tokens": 256, "output_tokens": 12},+ "assistant_content_chars": 40, "assistant_tool_call_count": 0, "error": None, "error_type": None,+ },"subagent_stop": {"parent_session_id": "parent-sess", "child_role": None,"child_summary": "Synthetic summary for hooks test", "child_status": "completed",diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 394fdbe0771..221cbc84be3 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -116,6 +116,11 @@ VALID_HOOKS: Set[str] = {# {"action": "continue", "message"} (or Claude-Code Stop {"decision": "block", "reason"}) to keep# going; anything else finishes. Bounded by agent.max_verify_nudges."pre_verify", "pre_api_request", "post_api_request", "api_request_error",+ # pre/post_auxiliary_call: once per physical provider attempt of an auxiliary LLM call+ # (agent/auxiliary_hooks.py — titling, compression, MoA, vision, approval, ...). Same payload+ # shape as pre/post_api_request plus ``aux_task``; distinct events so turn-scoped+ # ``*_api_request`` subscribers never receive auxiliary traffic (#79733). Observers; fail-open.+ "pre_auxiliary_call", "post_auxiliary_call",# transform_api_error_classification: once per failed API call BEFORE# agent/error_classifier.classify_api_error(). Kwargs: provider, model, status_code, error_type,# error_code, error_message, error_body, error, approx_tokens, context_length, num_messages.diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex d1f1df19edf..78c3927fc4f 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -42,7 +42,7 @@ logger = logging.getLogger("hermes_cli.plugins")_HOOK_TIMEOUT_BOUNDED_HOOKS: Set[str] = {"post_tool_call", "transform_terminal_output", "transform_tool_result", "transform_llm_output","pre_llm_call", "post_llm_call", "pre_api_request", "post_api_request", "api_request_error",- "pre_verify", "on_session_start", "on_session_end",+ "pre_auxiliary_call", "post_auxiliary_call", "pre_verify", "on_session_start", "on_session_end",}# Policy hooks: timeout / still-running must fail closed (block the tool).diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex 71b70ac7fdc..b3f21bacbd9 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -61,7 +61,9 @@ bare names resolve through the catalog or error.**Discovery timing pitfall:** `discover_plugins()` runs only as a side effect of importing`model_tools.py`. Code that reads plugin state without importing `model_tools.py` first must call`discover_plugins()` explicitly (idempotent). Hooks are invoked from `model_tools.py` (pre/post-tool) and `run_agent.py` (lifecycle). When a plugin changes a default, add a migration guard keyed+tool) and `run_agent.py` (lifecycle). Auxiliary LLM calls (titling, compression, MoA, vision, ...)+fire `pre_auxiliary_call`/`post_auxiliary_call` from `agent/auxiliary_hooks.py` (payload = the+`*_api_request` shape + `aux_task`); they never fire the turn-scoped `pre/post_api_request` (#79733). When a plugin changes a default, add a migration guard keyedon an "existing config" signal (`_explicitly_configured`) so existing users keep the old default.**Lifecycle hooks fire under the owning profile's scope, and the caller binds it.**diff --git a/tests/agent/test_auxiliary_hooks.py b/tests/agent/test_auxiliary_hooks.pynew file mode 100644index 00000000000..d5b48c12265--- /dev/null+++ b/tests/agent/test_auxiliary_hooks.py@@ -0,0 +1,72 @@+"""``pre_auxiliary_call`` / ``post_auxiliary_call`` fire for auxiliary LLM calls (#79733).++Two invariants: (1) an auxiliary ``call_llm`` emits the pair with ``aux_task`` set and does NOT+fire the turn-scoped ``pre/post_api_request`` events; (2) a raising subscriber never breaks the+auxiliary call.+"""++from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from agent.auxiliary_client import call_llm+from hermes_cli import plugins as plugins_mod+from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+++def manager(monkeypatch):+ mgr = PluginManager()+ monkeypatch.setattr(plugins_mod, "_plugin_manager", mgr)+ monkeypatch.setattr(plugins_mod, "_plugin_managers_by_home", {})+ return PluginContext(PluginManifest(name="aux-observer", source="user"), mgr)+++def aux_client(monkeypatch):+ client = MagicMock()+ client.base_url = "https://openrouter.ai/api/v1"+ client.chat.completions.create.return_value = SimpleNamespace(+ model="mock-model",+ choices=[SimpleNamespace(message=SimpleNamespace(role="assistant", content="A title", tool_calls=None),+ finish_reason="stop")],+ usage=SimpleNamespace(prompt_tokens=10, completion_tokens=5),+ )+ monkeypatch.setattr("agent.auxiliary_client._resolve_task_provider_model",+ lambda *a, **k: ("openrouter", "mock-model", None, None, None))+ monkeypatch.setattr("agent.auxiliary_client._get_cached_client", lambda *a, **k: (client, "mock-model"))+ monkeypatch.setattr("agent.auxiliary_client._validate_llm_response", lambda resp, _task, **_kw: resp)+ return client+++def test_call_llm_emits_auxiliary_events_not_api_request_events(manager, aux_client): # manager: PluginContext+ fired = []+ for name in ("pre_auxiliary_call", "post_auxiliary_call", "pre_api_request", "post_api_request"):+ manager.register_hook(name, lambda _name=name, **kw: fired.append((_name, kw)))++ response = call_llm(task="title_generation", messages=[{"role": "user", "content": "hello"}])++ assert response is aux_client.chat.completions.create.return_value+ assert [name for name, _ in fired] == ["pre_auxiliary_call", "post_auxiliary_call"]+ pre, post = fired[0][1], fired[1][1]+ assert pre["aux_task"] == post["aux_task"] == "title_generation"+ assert pre["api_request_id"].startswith("aux-") and post["api_request_id"] == pre["api_request_id"]+ assert pre["provider"] == "openrouter" and pre["model"] == "mock-model"+ assert pre["request_messages"] == [{"role": "user", "content": "hello"}]+ assert pre["request"]["body"]["messages"] == [{"role": "user", "content": "hello"}]+ assert post["finish_reason"] == "stop" and post["error"] is None+ assert post["usage"]["input_tokens"] == 10 and post["usage"]["output_tokens"] == 5+ assert post["response"]["assistant_message"]["content"] == "A title"+++def test_raising_subscriber_does_not_break_the_auxiliary_call(manager, aux_client):+ def boom(**_kw):+ raise RuntimeError("observer exploded")++ manager.register_hook("pre_auxiliary_call", boom)+ manager.register_hook("post_auxiliary_call", boom)++ response = call_llm(task="compression", messages=[{"role": "user", "content": "summarize"}])++ assert response is aux_client.chat.completions.create.return_valuediff --git a/website/docs/developer-guide/observer-hooks.md b/website/docs/developer-guide/observer-hooks.mdindex 6a7d1389fb0..075f4f809e4 100644--- a/website/docs/developer-guide/observer-hooks.md+++ b/website/docs/developer-guide/observer-hooks.md@@ -136,6 +136,8 @@ API hooks describe provider attempts inside the agent loop:| `pre_api_request` | Immediately before a provider API request. || `post_api_request` | After a successful provider response. || `api_request_error` | After a failed provider request or retryable error path. |+| `pre_auxiliary_call` | Before each provider attempt of an auxiliary LLM call (titling, compression, MoA, vision, ...). Carries `aux_task`; the `*_api_request` hooks stay main-loop only. |+| `post_auxiliary_call` | After that attempt returns or raises (`error` set on failure). |`pre_api_request` includes:diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex b07a686f2f5..7d859c173b9 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -989,6 +989,8 @@ Each hook is documented in full on the **[Event Hooks reference](../../user-guid| `pre_api_request` | Before each raw provider API request (several per turn when the model calls tools) | `session_id: str, model: str, provider: str, base_url: str, api_mode: str, api_call_count: int, message_count: int, tool_count: int, approx_input_tokens: int, max_tokens: int, request: dict` | ignored || `post_api_request` | After each raw provider API request returns | `pre_api_request` fields plus `api_duration: float, finish_reason: str, response_model: str \| None, usage: dict, response: dict, assistant_content_chars: int, assistant_tool_call_count: int` | ignored || `api_request_error` | A provider API call raised | correlation fields plus `status_code: int \| None, retry_count: int \| None, max_retries: int \| None, retryable: bool \| None, reason: str \| None, error: dict, request: dict` | ignored |+| `pre_auxiliary_call` | Before each provider attempt of an auxiliary LLM call (titling, compression, MoA, vision, approval, ...); not a `pre_api_request` | `aux_task: str` plus the `pre_api_request` fields (`session_id`/`task_id`/`turn_id` are the parent turn's or empty, `api_request_id: str`, `retry_count: int`, `streaming: bool`, `request: dict`) | ignored |+| `post_auxiliary_call` | After that attempt returns or raises | `pre_auxiliary_call` fields plus `api_duration: float, finish_reason, response_model, usage: dict \| None, response: dict \| None, error: str \| None, error_type: str \| None` | ignored || [`on_session_start`](../../user-guide/features/hooks.md#on_session_start) | New session created (first turn only) | `session_id: str, model: str, platform: str` | ignored || [`on_session_end`](../../user-guide/features/hooks.md#on_session_end) | End of every `run_conversation` call + CLI exit | `session_id: str, completed: bool, interrupted: bool, model: str, platform: str` | ignored || [`on_session_finalize`](../../user-guide/features/hooks.md#on_session_finalize) | CLI/gateway tears down an active session | `session_id: str \| None, platform: str` | ignored |diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 9f52d1750e1..59975d14edf 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -460,6 +460,8 @@ Payload fields below are the exact event-specific fields supplied by each call s| `pre_api_request` | Observer | Per provider attempt, immediately before the request; return ignored. | `task_id`, `turn_id`, `api_request_id`, `session_id`, `user_message`, `conversation_history`, `platform`, `model`, `provider`, `base_url`, `api_mode`, `api_call_count`, `retry_count`, `request_messages`, `message_count`, `tool_count`, `approx_input_tokens`, `request_char_count`, `max_tokens`, `started_at`, `middleware_trace`, `request` | High sensitivity: legacy `user_message`, `conversation_history`, and `request_messages` are intentionally raw; prefer sanitized `request`. || `post_api_request` | Observer | After normalized provider success; return ignored. | `task_id`, `turn_id`, `api_request_id`, `session_id`, `platform`, `model`, `provider`, `base_url`, `api_mode`, `api_call_count`, `api_duration`, `started_at`, `ended_at`, `finish_reason`, `message_count`, `response_model`, `response`, `usage`, `assistant_message`, `assistant_content_chars`, `assistant_tool_call_count` | Sanitized `response` is available, but raw normalized `assistant_message` may contain model/user content; `usage` is accounting data. || `api_request_error` | Observer | On each failed provider attempt; return ignored. | `task_id`, `turn_id`, `api_request_id`, `session_id`, `platform`, `model`, `provider`, `base_url`, `api_mode`, `api_call_count`, `api_duration`, `started_at`, `ended_at`, `status_code`, `retry_count`, `max_retries`, `retryable`, `reason`, `error`, `request` | Error text may contain provider/user data; `request` is intended to be sanitized. |+| `pre_auxiliary_call` | Observer | Per provider attempt of an auxiliary LLM call (titling, compression, MoA, vision, approval, ...), immediately before the request; return ignored. | `aux_task`, `task_id`, `turn_id`, `session_id`, `platform` (the parent turn's, empty outside a turn), `api_request_id`, `api_call_count`, `retry_count`, `streaming`, `model`, `provider`, `base_url`, `api_mode`, `request_messages`, `system_prompt`, `message_count`, `tool_count`, `approx_input_tokens`, `request_char_count`, `max_tokens`, `started_at`, `request` | `request_messages` is raw (compression sees the whole transcript); prefer sanitized `request`. |+| `post_auxiliary_call` | Observer | After the same attempt returns or raises; return ignored. | `pre_auxiliary_call` identity fields plus `api_duration`, `ended_at`, `finish_reason`, `response_model`, `usage`, `response`, `assistant_content_chars`, `assistant_tool_call_count`, `error`, `error_type` (`None` on success; `usage`/`response` are `None` on error and for `streaming=True`) | Sanitized `response`; `usage` is accounting data; `error` may contain provider text. || `on_stream_start` | Observer | Dispatched when a streaming LLM response begins; delivered off the token path via a host-owned bounded queue with one worker per callback; return ignored. | `turn_id`, `iteration`, `session_id`, `model`, `provider`, `surface` | Identifiers and routing metadata only. || `on_stream_delta` | Observer | Dispatched per normalized streaming text delta via the bounded observer queue; a stalled callback drops only its own oldest events; return ignored. | `delta`, `kind` (`text` or `reasoning`), `turn_id`, `iteration`, `session_id`, `model`, `provider`, `surface` | Delta text is raw model output; reasoning deltas require the `plugins.stream_reasoning_deltas` opt-in. || `on_stream_end` | Observer | Dispatched when a streaming response finishes or errors, after the stream closes; return ignored. | `final_text`, `finished`, `error`, `turn_id`, `iteration`, `session_id`, `model`, `provider`, `surface` | Full assembled response text; error text may include provider data. |@@ -1633,6 +1635,12 @@ Fires after a provider response has been normalized successfully. This is observFires for a failed provider attempt with status/retry timing, an `error` object, and sanitized `request`. This is observer-only. Error messages may still contain provider or user data.+### Auxiliary-call observer hooks++#### `pre_auxiliary_call` / `post_auxiliary_call`++Auxiliary LLM calls — session titling, context compression, MoA advisors and the aggregator, vision, approval classification, memory and other side tasks — run outside the main tool-calling loop and do **not** fire `pre_api_request` / `post_api_request` (those stay turn-scoped, so a trace-per-turn plugin never sees side traffic by accident). Subscribe to `pre_auxiliary_call` / `post_auxiliary_call` instead: they fire once per physical provider attempt (retries and fallbacks included) with the same payload shape plus `aux_task` (the task name, e.g. `title_generation`, `compression`, `moa_aggregator`, `vision`). `session_id` / `task_id` / `turn_id` are the parent turn's when the call runs under one, empty otherwise; `api_request_id` (`aux-…`) is shared by every attempt of one logical call and `retry_count` distinguishes them. Both are observer-only and fail-open: a raising or timed-out callback is logged and the auxiliary task proceeds. `post_auxiliary_call` carries `error` / `error_type` when the attempt raised and `streaming: True` (with `usage`/`response` `None`) when the response is handed back as a stream.+### `on_skill_lifecycle`Fires after an authoritative skill-usage state change. It is observer-only and exposes the local `skill_name`, provenance, correlation IDs, usage count, and reuse flags.diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 7e9352bc8c7..1d6a1a49e4f 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -317,7 +317,7 @@ Plugins can register the 27 lifecycle events currently accepted by `hermes_cli.p|---|---|| **Directive/control** | `pre_tool_call`, `pre_llm_call`, `pre_verify`, `pre_gateway_dispatch` || **Transform** | `transform_tool_result`, `transform_terminal_output`, `transform_llm_output`, `pre_transcription` |-| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `pre_command`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |+| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `pre_auxiliary_call`, `post_auxiliary_call`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `pre_command`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |These categories describe current behavior rather than defining future naming rules. Plugin middleware remains a separate registry/surface.## Plugin types