The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): ctx.side_question reports through pre/post_auxiliary_call
Teknium4047c3ab724d
diff --git a/agent/auxiliary_hooks.py b/agent/auxiliary_hooks.pyindex efcc54ac3e8..a62a0104af6 100644--- a/agent/auxiliary_hooks.py+++ b/agent/auxiliary_hooks.py@@ -138,7 +138,12 @@ class _AuxCallHooks:request=_Sanitize._sanitize_hook_payload({"method": "POST", "body": body}),)- def post(self, response: Any = None, error: Optional[BaseException] = None) -> None:+ def post(+ self, response: Any = None, error: Optional[BaseException] = None, *,+ normalized: Optional[tuple[Any, Any, Optional[dict[str, Any]]]] = None,+ ) -> None:+ """``normalized`` = ``(assistant_message, finish_reason, usage_summary)`` for a response+ that is not chat.completions-shaped (an agent transport's native reply)."""if not _has_hook(POST_AUXILIARY_CALL):returnfrom agent.api_request_hooks import ApiRequestHooksMixin as _Sanitize@@ -155,13 +160,13 @@ class _AuxCallHooks: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)+ message, finish_reason, usage = normalized or (*_first_choice_message(response), _usage_summary(response))content = _field(message, "content") if message is not None else Nonetool_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),+ usage=usage,response=_Sanitize._sanitize_hook_payload({"model": _field(response, "model"),"finish_reason": finish_reason,@@ -199,7 +204,9 @@ def _fire(name: str, **payload: Any) -> None:name, payload.get("aux_task"), exc_info=True)-def _hooks_or_none(**kw: Any) -> Optional[_AuxCallHooks]:+def start_aux_call_hooks(**kw: Any) -> Optional[_AuxCallHooks]:+ """Fire ``pre_auxiliary_call`` for one attempt; the handle for :func:`finish_aux_call_hooks`,+ or None when nothing subscribes. For callers that drive the provider call themselves."""if not (_has_hook(PRE_AUXILIARY_CALL) or _has_hook(POST_AUXILIARY_CALL)):return Nonetry:@@ -211,11 +218,15 @@ def _hooks_or_none(**kw: Any) -> Optional[_AuxCallHooks]:return hooks-def _post_safely(hooks: Optional[_AuxCallHooks], response: Any = None, error: Any = None) -> None:+def finish_aux_call_hooks(+ hooks: Optional[_AuxCallHooks], response: Any = None, error: Any = None, *,+ normalized: Optional[tuple[Any, Any, Optional[dict[str, Any]]]] = None,+) -> None:+ """Fire the ``post_auxiliary_call`` paired with :func:`start_aux_call_hooks`."""if hooks is None:returntry:- hooks.post(response, error)+ hooks.post(response, error, normalized=normalized)except Exception:logger.warning("post_auxiliary_call payload build failed; continuing", exc_info=True)@@ -226,14 +237,14 @@ def run_with_aux_hooks() -> 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,+ hooks = start_aux_call_hooks(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)+ finish_aux_call_hooks(hooks, error=exc)raise- _post_safely(hooks, response=response)+ finish_aux_call_hooks(hooks, response=response)return response@@ -242,12 +253,12 @@ async def arun_with_aux_hooks(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,+ hooks = start_aux_call_hooks(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)+ finish_aux_call_hooks(hooks, error=exc)raise- _post_safely(hooks, response=response)+ finish_aux_call_hooks(hooks, response=response)return responsediff --git a/agent/side_question_request.py b/agent/side_question_request.pyindex 0f23128b027..cbac4f98661 100644--- a/agent/side_question_request.py+++ b/agent/side_question_request.py@@ -3,10 +3,12 @@The fork replays the turn snapshot captured at finalization (system prompt, ``tools[]``,messages) verbatim plus one user prompt, so the request reads the parent's warm prompt cache.-It runs the turn loop's own request phases (assembly, ``build_api_request`` with its-middleware and ``pre_api_request`` hook, ``perform_api_call``) exactly once: no tool dispatch-(tool calls in the response are dropped), no retries, no fallback model, no compression, no-persistence. Usage is attributed to the parent session as ``side_question``.+It runs the turn loop's own request phases (assembly, the payload build with its LLM+middleware, ``perform_api_call``) exactly once: no tool dispatch (tool calls in the response+are dropped), no retries, no fallback model, no compression, no persistence. Like any other+side call it reports through ``pre/post_auxiliary_call`` (``aux_task="side_question"``), never+the turn-scoped ``pre/post_api_request``, and its usage is attributed to the parent session as+``side_question``."""from __future__ import annotations@@ -109,14 +111,15 @@ def _build_fork(parent: Any, capture: SideQuestionCapture) -> Any:def _send(fork: Any, capture: SideQuestionCapture, prompt: str, audit: _Audit) -> Any:- """Assemble, build and perform ONE request on the fork; the response, or None on refusal."""+ """Assemble, build and perform ONE request on the fork; the normalized reply, or None on+ refusal / a cancelled call."""from agent import relay_llm+ from agent.auxiliary_hooks import finish_aux_call_hooks, start_aux_call_hooksfrom agent.side_question import trim_snapshot_for_forkfrom agent.turn_api_call import perform_api_call- from agent.turn_api_request import build_api_request+ from agent.turn_api_request import build_request_payloadfrom agent.turn_context import _PER_TURN_RESET_STATEfrom agent.turn_request_assembly import assemble_api_request- from agent.turn_response_intake import _fire_post_api_request_hookfrom agent.turn_retry_state import TurnRetryStatefrom agent.turn_truncation import normalize_response_for_agentfrom agent.turn_usage import record_response_usage@@ -125,8 +128,8 @@ def _send(fork: Any, capture: SideQuestionCapture, prompt: str, audit: _Audit) -task_id = str(uuid.uuid4())api_request_id = f"{turn_id}:api:1"# Turn state a fork that never ran a turn lacks: the per-turn counters the request phases- # read, the replay-canonicalization clock (build_api_messages), the ids hooks and relay key- # on, and a non-streaming transport.+ # read, the replay-canonicalization clock (build_api_messages), the ids middleware and relay+ # key on, and a non-streaming transport.for name, value in _PER_TURN_RESET_STATE:setattr(fork, name, value)fork._current_turn_timestamp = time.time()@@ -139,18 +142,20 @@ def _send(fork: Any, capture: SideQuestionCapture, prompt: str, audit: _Audit) -_plugin_user_context=None, moa_config=None, active_system_prompt=fork._cached_system_prompt,original_user_message=prompt, pending_moa_prepared_request=None, request_logger=logger,)- api_start_time = time.time()- built = build_api_request(+ built = build_request_payload(fork, api_messages=assembled.api_messages, _moa_prepared_request=None,- tools_for_api=assembled.tools_for_api, system_message=None, messages=messages,- original_user_message=prompt, approx_tokens=assembled.approx_tokens,- total_chars=assembled.total_chars, retry_count=0, api_call_count=1,- api_request_id=api_request_id, api_start_time=api_start_time, effective_task_id=task_id,- turn_id=turn_id,+ tools_for_api=assembled.tools_for_api, system_message=None, api_call_count=1,+ api_request_id=api_request_id, effective_task_id=task_id, turn_id=turn_id,)if has_server_side_tools(built.api_kwargs):audit.outcome = "refused:server_side_tools"return None+ hooks = start_aux_call_hooks(+ aux_task=SIDE_QUESTION_ORIGIN, metadata={"api_request_id": api_request_id}, client=fork.client,+ kwargs=built.api_kwargs, provider=str(fork.provider or ""), model=str(fork.model or ""),+ api_mode=str(fork.api_mode or ""), streaming=False,+ )+ api_start_time = time.time()try:verdict = perform_api_call(fork, api_kwargs=built.api_kwargs, _original_api_kwargs=built._original_api_kwargs,@@ -158,28 +163,27 @@ def _send(fork: Any, capture: SideQuestionCapture, prompt: str, audit: _Audit) -_retry=TurnRetryState(), thinking_spinner=None, retry_count=0, api_call_count=1,api_request_id=api_request_id, effective_task_id=task_id, turn_id=turn_id, interrupted=False,)- except BaseException:+ except BaseException as exc:+ finish_aux_call_hooks(hooks, error=exc)relay_llm.complete_logical_call(api_request_id, outcome="failed")raiseif verdict.action == "break" or verdict.response is None:+ finish_aux_call_hooks(hooks)relay_llm.complete_logical_call(api_request_id, outcome="cancelled")audit.outcome = "error"return Noneresponse = verdict.response- api_duration = time.time() - api_start_timerecord_response_usage(- fork, response, messages=messages, api_call_count=1, api_duration=api_duration,+ fork, response, messages=messages, api_call_count=1, api_duration=time.time() - api_start_time,compression_attempts=0, max_compression_attempts=0,)relay_llm.complete_logical_call(api_request_id, outcome="success")assistant_message = normalize_response_for_agent(fork, response)- # Pair the pre_api_request the build fired, so observers never see a dangling request.- _fire_post_api_request_hook(- fork, response, assistant_message, assistant_message.finish_reason,- api_messages=built.api_messages, api_call_count=1, api_duration=api_duration,- api_start_time=api_start_time, api_request_id=api_request_id, effective_task_id=task_id,- turn_id=turn_id,- )+ # The reply is in the transport's native shape: hand the observers the normalized view.+ finish_aux_call_hooks(hooks, response, normalized=(+ assistant_message, assistant_message.finish_reason,+ fork._usage_summary_for_api_request_hook(response),+ ))return assistant_messagediff --git a/agent/turn_api_request.py b/agent/turn_api_request.pyindex 1be4db0a628..e4468c52756 100644--- a/agent/turn_api_request.py+++ b/agent/turn_api_request.py@@ -90,17 +90,15 @@ def _fire_pre_api_request_hook(pass-def build_api_request(+def build_request_payload(agent: Any, *, api_messages: Any, _moa_prepared_request: Any, tools_for_api: Any,- system_message: Any, messages: Any, original_user_message: Any, approx_tokens: Any,- total_chars: Any, retry_count: Any, api_call_count: Any, api_request_id: Any,- api_start_time: Any, effective_task_id: Any, turn_id: Any,+ system_message: Any, api_call_count: Any, api_request_id: Any, effective_task_id: Any,+ turn_id: Any,) -> ApiRequestBuild:- """Assemble the attempt's request in the original order (every mutation happens BEFORE- middleware/hooks/debug dumps observe the payload)."""- from agent.conversation_loop import (- _moa_client_consumes_prepared_request, _redecorate_prompt_cache_for_provider,- )+ """The provider payload through the LLM request middleware, with no turn hook fired: the+ turn loop's :func:`build_api_request` and off-turn side requests (``ctx.side_question``,+ which reports through ``pre/post_auxiliary_call``) share it."""+ from agent.conversation_loop import _redecorate_prompt_cache_for_provideragent._reset_stream_delivery_tracking()# Per-attempt first-chunk timestamp so a stale value never leaks into post_api_request.@@ -152,11 +150,33 @@ def build_api_request(_original_api_kwargs = _llm_request_mw.original_payload_llm_middleware_trace = _llm_request_mw.traceexcept Exception:+ logger.warning("LLM request middleware failed; sending the request unmodified", exc_info=True)_original_api_kwargs = dict(api_kwargs)_llm_middleware_trace = []+ return ApiRequestBuild(+ "fallthrough", api_messages, _moa_prepared_request, tools_for_api, api_kwargs,+ _original_api_kwargs, _llm_middleware_trace,+ )++def build_api_request(+ agent: Any, *, api_messages: Any, _moa_prepared_request: Any, tools_for_api: Any,+ system_message: Any, messages: Any, original_user_message: Any, approx_tokens: Any,+ total_chars: Any, retry_count: Any, api_call_count: Any, api_request_id: Any,+ api_start_time: Any, effective_task_id: Any, turn_id: Any,+) -> ApiRequestBuild:+ """Assemble the attempt's request in the original order (every mutation happens BEFORE+ middleware/hooks/debug dumps observe the payload)."""+ from agent.conversation_loop import _moa_client_consumes_prepared_request++ built = build_request_payload(+ agent, api_messages=api_messages, _moa_prepared_request=_moa_prepared_request,+ tools_for_api=tools_for_api, system_message=system_message, api_call_count=api_call_count,+ api_request_id=api_request_id, effective_task_id=effective_task_id, turn_id=turn_id,+ )+ api_kwargs, api_messages, _moa_prepared_request = built.api_kwargs, built.api_messages, built._moa_prepared_request_fire_pre_api_request_hook(- agent, api_kwargs, api_messages, _llm_middleware_trace, messages=messages,+ agent, api_kwargs, api_messages, built._llm_middleware_trace, messages=messages,original_user_message=original_user_message, approx_tokens=approx_tokens,total_chars=total_chars, retry_count=retry_count, api_call_count=api_call_count,api_request_id=api_request_id, api_start_time=api_start_time,@@ -179,7 +199,4 @@ def build_api_request("prepared prompt without the MoA handshake",type(agent.client).__name__,)- return ApiRequestBuild(- "fallthrough", api_messages, _moa_prepared_request, tools_for_api, api_kwargs,- _original_api_kwargs, _llm_middleware_trace,- )+ return builtdiff --git a/tests/agent/test_side_question_lease.py b/tests/agent/test_side_question_lease.pyindex e48c982b61f..9a0d9261ae9 100644--- a/tests/agent/test_side_question_lease.py+++ b/tests/agent/test_side_question_lease.py@@ -236,3 +236,60 @@ def test_post_llm_call_hook_redeems_its_token_end_to_end(monkeypatch):assert json.loads(answers.read_text()) == "Ask why it is 42."assert requests[-1]["messages"][-1] == {"role": "user", "content": "Suggest the next prompt."}side_question_lease._leases.clear()+++def test_side_request_fires_auxiliary_hooks_not_turn_request_hooks(monkeypatch):+ """Turn-scoped observers (``pre/post_api_request``) see only the turn's own request; the+ side request reports through ``pre/post_auxiliary_call`` with ``aux_task='side_question'``."""+ from run_agent import AIAgent++ events = Path(os.environ["HERMES_HOME"]) / "events.jsonl"+ plugin_dir = Path(os.environ["HERMES_HOME"]) / "plugins" / "observer"+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "plugin.yaml").write_text(+ yaml.safe_dump({"name": "observer", "capabilities": [CAP]}), encoding="utf-8")+ (plugin_dir / "__init__.py").write_text(+ "import json, pathlib\n\n"+ f"EVENTS = pathlib.Path({str(events)!r})\n\n"+ "def _log(name, **kw):\n"+ " row = {'event': name, 'aux_task': kw.get('aux_task'), 'usage': kw.get('usage')}\n"+ " with EVENTS.open('a') as fh:\n"+ " fh.write(json.dumps(row, default=str) + '\\n')\n\n"+ "def register(ctx):\n"+ " for name in ('pre_api_request', 'post_api_request', 'pre_auxiliary_call', 'post_auxiliary_call'):\n"+ " ctx.register_hook(name, lambda _n=name, **kw: _log(_n, **kw))\n"+ " def _on_post_llm_call(**kwargs):\n"+ " ctx.side_question(kwargs['side_question_token'], 'Suggest the next prompt.')\n"+ " ctx.register_hook('post_llm_call', _on_post_llm_call)\n",+ encoding="utf-8",+ )+ _load(["observer"], granted=["observer"])++ usage = SimpleNamespace(prompt_tokens=900, completion_tokens=7, total_tokens=907)+ replies = [+ SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=text, tool_calls=None),+ finish_reason="stop")], model="test/model", usage=usage)+ for text in ("The answer is 42.", "Ask why it is 42.")+ ]+ client = MagicMock()+ client.chat.completions.create.side_effect = lambda **kw: replies.pop(0)+ monkeypatch.setattr("agent.title_generator.maybe_auto_title", lambda *a, **k: None)+ with (+ patch("model_tools.get_tool_definitions", return_value=[]),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.process_bootstrap.OpenAI", return_value=client),+ patch("agent.model_metadata.fetch_model_metadata", return_value={}),+ ):+ parent = AIAgent(api_key="k", base_url="https://openrouter.ai/api/v1", model="test/model",+ quiet_mode=True, skip_context_files=True, skip_memory=True)+ parent._cached_system_prompt = "You are helpful."+ parent.skip_background_review = True+ parent.run_conversation("what is the answer?")++ rows = [json.loads(line) for line in events.read_text().splitlines()]+ assert replies == [] # the side request was sent+ assert [r["event"] for r in rows] == [+ "pre_api_request", "post_api_request", "pre_auxiliary_call", "post_auxiliary_call"]+ assert rows[2]["aux_task"] == rows[3]["aux_task"] == "side_question"+ assert rows[3]["usage"]["output_tokens"] == 7+ side_question_lease._leases.clear()diff --git a/tests/agent/test_side_question_request.py b/tests/agent/test_side_question_request.pyindex 7413c71edba..612f858cb60 100644--- a/tests/agent/test_side_question_request.py+++ b/tests/agent/test_side_question_request.py@@ -377,14 +377,14 @@ def test_agent_as_provider_is_refused(provider, issued):def test_server_side_tool_in_final_request_is_refused(provider, issued, monkeypatch):parent = _make_parent()_run_parent_turn(parent, provider, tool_round=False)- real_build = __import__("agent.turn_api_request", fromlist=["build_api_request"]).build_api_request+ real_build = __import__("agent.turn_api_request", fromlist=["build_request_payload"]).build_request_payloaddef _with_native_search(*args, **kwargs):built = real_build(*args, **kwargs)built.api_kwargs["tools"] = [*built.api_kwargs["tools"], {"type": "web_search"}]return built- monkeypatch.setattr("agent.turn_api_request.build_api_request", _with_native_search)+ monkeypatch.setattr("agent.turn_api_request.build_request_payload", _with_native_search)sent = len(provider.requests)assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") is Noneassert len(provider.requests) == sentdiff --git a/website/docs/developer-guide/plugin-llm-access.md b/website/docs/developer-guide/plugin-llm-access.mdindex 0add6d9f944..11081bcac2f 100644--- a/website/docs/developer-guide/plugin-llm-access.md+++ b/website/docs/developer-guide/plugin-llm-access.md@@ -593,6 +593,11 @@ and recorded in its usage as `side_question`. You can't pick themodel, tools, system prompt or output length: changing any of themwould miss the warm cache. Ask for brevity in the prompt.+Observability plugins see the call as an auxiliary call:+`pre_auxiliary_call` / `post_auxiliary_call` fire with+`aux_task="side_question"`, and the turn-scoped `pre_api_request` /+`post_api_request` do not fire for it.+## Where this fits in the plugin surfaceExisting `ctx.*` methods extend an existing Hermes subsystem:diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex ac70d66093f..d9041e29dc0 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -1814,7 +1814,7 @@ Fires for a failed provider attempt with status/retry timing, an `error` object,#### `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.+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`, `side_question` for a plugin's [`ctx.side_question`](../../developer-guide/plugin-llm-access.md#asking-the-sessions-own-agent-ctxside_question)). `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`