The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): ctx.side_question asks the session's own agent after a turn
Cleoa8db83446f1d
diff --git a/agent/background_review.py b/agent/background_review.pyindex bc1d9a33f40..0bd033df96e 100644--- a/agent/background_review.py+++ b/agent/background_review.py@@ -774,11 +774,13 @@ def _snapshot_review_usage(review_agent: Any) -> dict[str, Any]:}-def _record_review_usage_to_parent(parent_agent: Any, usage: dict[str, Any]) -> None:- """Record a fork's usage against the parent session (best-effort, never raises). The fork has- ``_session_db = None`` so conversation_loop's DB-gated accounting never sees its calls; route- them through the aux-accounting chokepoint, which writes only ``session_model_usage`` — never- the transcript or ``sessions`` row."""+def _record_review_usage_to_parent(+ parent_agent: Any, usage: dict[str, Any], *, task: str = "background_review",+) -> None:+ """Record a fork's usage against the parent session under ``task`` (best-effort, never+ raises). The fork has ``_session_db = None`` so conversation_loop's DB-gated accounting never+ sees its calls; route them through the aux-accounting chokepoint, which writes only+ ``session_model_usage`` — never the transcript or ``sessions`` row."""try:session_db = getattr(parent_agent, "_session_db", None)session_id = getattr(parent_agent, "session_id", None)@@ -786,7 +788,7 @@ def _record_review_usage_to_parent(parent_agent: Any, usage: dict[str, Any]) ->if session_db is None or not session_id or not any(counts.values()):return # no DB, or the fork made no successful API calls (e.g. failed at spawn)session_db.record_auxiliary_usage(- session_id, task="background_review", model=usage.get("model"),+ session_id, task=task, model=usage.get("model"),billing_provider=usage.get("provider"), billing_base_url=usage.get("base_url"),estimated_cost_usd=usage.get("estimated_cost_usd"),api_call_count=counts.pop("api_calls"), **counts,diff --git a/agent/side_question_lease.py b/agent/side_question_lease.pynew file mode 100644index 00000000000..8a4b5cf9768--- /dev/null+++ b/agent/side_question_lease.py@@ -0,0 +1,133 @@+"""Turn leases for plugin side questions (``ctx.side_question``).++At turn finalization, when a loaded plugin holds the ``llm.side_question`` capability, the turn+thread captures the request inputs the side call will replay and hands ``post_llm_call`` an+opaque token. A token buys ONE side request shared by every plugin that receives the hook:+redemption pops the lease whether it succeeds or not. It expires after ``LEASE_TTL_SECONDS`` or+as soon as the parent agent starts its next turn. The captured ``contextvars`` context binds the+owning profile and secret scope on whatever thread redeems the token.+"""++from __future__ import annotations++import contextvars+import copy+import logging+import secrets+import threading+import time+import weakref+from collections import OrderedDict+from dataclasses import dataclass+from typing import Any, Optional++from agent.side_question_request import SideQuestionCapture, ask_text_only++logger = logging.getLogger(__name__)++SIDE_QUESTION_CAPABILITY = "llm.side_question"+LEASE_TTL_SECONDS = 60.0+MAX_PROMPT_CHARS = 4096+DEFAULT_TIMEOUT_SECONDS = 15.0+MAX_TIMEOUT_SECONDS = 60.0+# One live lease per active session agent; the bound only caps leaked parents' references.+_MAX_LEASES = 32+++@dataclass(frozen=True)+class _Lease:+ capture: SideQuestionCapture+ expires_at: float+++_leases: OrderedDict[str, _Lease] = OrderedDict()+_lock = threading.Lock()+++def _consented_plugin_loaded() -> bool:+ """True when a loaded, enabled plugin declares ``llm.side_question`` AND it is granted."""+ from hermes_cli.plugin_capabilities import plugin_capability_granted+ from hermes_cli.plugins import get_plugin_manager++ return any(+ loaded.enabled+ and SIDE_QUESTION_CAPABILITY in loaded.manifest.capabilities+ and plugin_capability_granted(key, SIDE_QUESTION_CAPABILITY)+ for key, loaded in list(get_plugin_manager()._plugins.items())+ )+++def _purge_locked(now: float, agent: Any = None) -> None:+ """Drop expired leases, leases whose parent is gone, and (on a new turn) ``agent``'s older ones."""+ for stale in [t for t, lease in _leases.items()+ if lease.expires_at < now or (parent := lease.capture.parent_ref()) is None or parent is agent]:+ del _leases[stale]+++def issue_side_question_token(agent: Any, messages: list[dict[str, Any]], turn_id: str) -> Optional[str]:+ """Capture the finished turn and lease it under a fresh token; None (nothing captured) for a+ persistence-detached fork or when no consented plugin is loaded. Turn thread only: the+ captured context is the turn's."""+ if getattr(agent, "_persist_disabled", False) or not _consented_plugin_loaded():+ return None+ capture = SideQuestionCapture(+ parent_ref=weakref.ref(agent),+ messages=copy.deepcopy(messages),+ system_prompt=agent._cached_system_prompt,+ system_prompt_static=getattr(agent, "_cached_system_prompt_static", None),+ tools=copy.deepcopy(agent.tools or []),+ session_id=agent.session_id,+ turn_id=turn_id,+ context=contextvars.copy_context(),+ )+ token = secrets.token_urlsafe(24)+ now = time.monotonic()+ with _lock:+ # Drop this agent's older leases (a new turn) and every expired one (each holds a transcript).+ _purge_locked(now, agent)+ _leases[token] = _Lease(capture, now + LEASE_TTL_SECONDS)+ while len(_leases) > _MAX_LEASES:+ _leases.popitem(last=False)+ return token+++def _redeemable(lease: Optional[_Lease], prompt: Any) -> Optional[str]:+ """Why the popped lease cannot be redeemed with ``prompt``, or None."""+ if lease is None:+ return "unknown_token"+ if time.monotonic() > lease.expires_at:+ return "expired"+ parent = lease.capture.parent_ref()+ if parent is None:+ return "parent_gone"+ if getattr(parent, "_current_turn_id", None) != lease.capture.turn_id:+ return "turn_moved_on"+ if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > MAX_PROMPT_CHARS:+ return "bad_prompt"+ return None+++def redeem_side_question(+ token: Any, prompt: Any, *, plugin_id: str, timeout: float = DEFAULT_TIMEOUT_SECONDS,+) -> Optional[str]:+ """Spend the lease behind ``token`` on one text-only question; the answer or None.++ The lease is consumed by this call whatever the outcome."""+ with _lock:+ lease = _leases.pop(token, None) if isinstance(token, str) else None+ _purge_locked(time.monotonic())+ reason = _redeemable(lease, prompt)+ if reason is not None:+ logger.info("side_question plugin=%s outcome=rejected:%s", plugin_id, reason)+ return None+ try:+ timeout = float(timeout)+ except (TypeError, ValueError):+ timeout = DEFAULT_TIMEOUT_SECONDS+ # Clamp to (0, 60]; NaN and non-positive values fall back to the default.+ timeout = min(timeout, MAX_TIMEOUT_SECONDS) if timeout > 0 else DEFAULT_TIMEOUT_SECONDS+ # A copy: the captured Context may already be entered elsewhere, and entering one Context+ # on two threads at once raises.+ return lease.capture.context.copy().run(+ ask_text_only, lease.capture, prompt, plugin_id=plugin_id, timeout=timeout,+ )diff --git a/agent/side_question_request.py b/agent/side_question_request.pynew file mode 100644index 00000000000..1493185ed65--- /dev/null+++ b/agent/side_question_request.py@@ -0,0 +1,268 @@+"""One text-only request on a detached cache-parity fork of the live session agent, for plugins+(``ctx.side_question``).++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``.+"""++from __future__ import annotations++import contextvars+import logging+import threading+import time+import uuid+from dataclasses import dataclass, field+from typing import Any, Optional++logger = logging.getLogger(__name__)++SIDE_QUESTION_ORIGIN = "side_question"++# Tool entries the client executes; any other ``type`` (Responses ``web_search``, Anthropic+# ``web_search_20250305``, ...) runs server-side and could act without Hermes seeing it.+_CLIENT_TOOL_TYPES = frozenset({"function", "custom"})+# OpenRouter request plugins that only pick the model; anything else (``web``, ...) executes.+_ROUTING_ONLY_OPENROUTER_PLUGINS = frozenset({"pareto-router"})+++@dataclass(frozen=True)+class SideQuestionCapture:+ """The parent's request inputs frozen at turn finalization (the live parent moves on).+ ``parent_ref`` is weak: a lease must not keep an evicted session's agent alive."""++ parent_ref: Any # weakref.ref[AIAgent]+ messages: list[dict[str, Any]]+ system_prompt: Optional[str]+ system_prompt_static: Optional[str]+ tools: list[dict[str, Any]]+ session_id: str+ turn_id: str+ context: contextvars.Context = field(repr=False)+++@dataclass+class _Audit:+ plugin_id: str+ started: float = field(default_factory=time.monotonic)+ outcome: str = "error"+ usage: dict[str, Any] = field(default_factory=dict)+++def _agent_provider_refusal(agent: Any) -> Optional[str]:+ """Why ``agent``'s runtime cannot serve a text-only side request, or None.++ MoA fans out to advisor models; an agent-as-provider (ACP CLI shim, external-process+ provider, codex app-server, a client declaring ``SUPPORTS_HERMES_TOOL_CALLS = False``)+ runs its own tools on the remote side, which no client-side drop can stop."""+ from agent.background_review import _parent_can_emit_tool_calls+ from hermes_cli.runtime_provider_backends import _is_external_process_provider++ if agent.provider == "moa":+ return "moa"+ if (+ str(agent.base_url or "").lower().startswith(("acp://", "acp+tcp://"))+ or agent.api_mode == "codex_app_server"+ or _is_external_process_provider(agent.provider)+ or not _parent_can_emit_tool_calls(agent)+ ):+ return "agent_provider"+ return None+++def has_server_side_tools(api_kwargs: dict[str, Any]) -> bool:+ """True when the FINAL request asks the provider to execute something itself: a tool entry+ with a non-client ``type`` (transports rewrite client tools, e.g. Codex/xAI swap a client+ ``web_search`` for ``{"type": "web_search"}``), OpenAI ``web_search_options``, or an+ OpenRouter plugin other than a routing-only one."""+ for tool in api_kwargs.get("tools") or ():+ tool_type = tool.get("type") if isinstance(tool, dict) else None+ if tool_type and tool_type not in _CLIENT_TOOL_TYPES:+ return True+ extra_body = api_kwargs.get("extra_body") if isinstance(api_kwargs.get("extra_body"), dict) else {}+ if "web_search_options" in api_kwargs or "web_search_options" in extra_body:+ return True+ plugins = [*(api_kwargs.get("plugins") or ()), *(extra_body.get("plugins") or ())]+ return any(not (isinstance(p, dict) and p.get("id") in _ROUTING_ONLY_OPENROUTER_PLUGINS) for p in plugins)+++def _build_fork(parent: Any, capture: SideQuestionCapture) -> Any:+ """A never-routed cache-parity fork pinned to the captured request inputs."""+ from agent.background_review import build_cache_parity_fork++ # task_cfg={} = never route: the side question must hit the parent's warm cache.+ fork, _rt, _routed = build_cache_parity_fork(+ parent, {}, max_iterations=1, write_origin=SIDE_QUESTION_ORIGIN,+ )+ fork._cached_system_prompt = capture.system_prompt+ # The static tier decides where the system-prompt cache breakpoint splits; rebuilding it on+ # the fork re-reads prompt files and can land the marker elsewhere.+ fork._cached_system_prompt_static = capture.system_prompt_static+ fork.tools = capture.tools+ fork.valid_tool_names = {tool["function"]["name"] for tool in capture.tools}+ fork.session_id = capture.session_id+ return fork+++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."""+ from agent import relay_llm+ from agent.side_question import trim_snapshot_for_fork+ from agent.turn_api_call import perform_api_call+ from agent.turn_api_request import build_api_request+ from agent.turn_context import _PER_TURN_RESET_STATE+ from agent.turn_request_assembly import assemble_api_request+ from agent.turn_response_intake import _fire_post_api_request_hook+ from agent.turn_retry_state import TurnRetryState+ from agent.turn_truncation import normalize_response_for_agent+ from agent.turn_usage import record_response_usage++ turn_id = f"{capture.turn_id}:{SIDE_QUESTION_ORIGIN}"+ 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.+ for name, value in _PER_TURN_RESET_STATE:+ setattr(fork, name, value)+ fork._current_turn_timestamp = time.time()+ fork._current_turn_id, fork._current_task_id, fork._current_api_request_id = turn_id, task_id, api_request_id+ fork._disable_streaming = True++ messages = trim_snapshot_for_fork(capture.messages) + [{"role": "user", "content": prompt}]+ assembled = assemble_api_request(+ fork, messages=messages, current_turn_user_idx=len(messages) - 1, _ext_prefetch_cache=None,+ _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(+ 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,+ )+ if has_server_side_tools(built.api_kwargs):+ audit.outcome = "refused:server_side_tools"+ return None+ try:+ verdict = perform_api_call(+ fork, api_kwargs=built.api_kwargs, _original_api_kwargs=built._original_api_kwargs,+ _llm_middleware_trace=built._llm_middleware_trace, _moa_prepared_request=None,+ _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:+ relay_llm.complete_logical_call(api_request_id, outcome="failed")+ raise+ if verdict.action == "break" or verdict.response is None:+ relay_llm.complete_logical_call(api_request_id, outcome="cancelled")+ audit.outcome = "error"+ return None+ response = verdict.response+ api_duration = time.time() - api_start_time+ record_response_usage(+ fork, response, messages=messages, api_call_count=1, api_duration=api_duration,+ 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,+ )+ return assistant_message+++def _answer_text(fork: Any, assistant_message: Any) -> Optional[str]:+ """Visible text of the reply; its ``tool_calls`` are dropped, never dispatched."""+ from agent.message_content import flatten_message_text++ content = assistant_message.content+ text = content if isinstance(content, str) else flatten_message_text(content)+ return fork._strip_think_blocks(text or "").strip() or None+++def _teardown(parent: Any, fork: Any, audit: _Audit) -> None:+ """Attribute usage to the parent session, then release the fork; never raises."""+ from agent.background_review import _record_review_usage_to_parent, _snapshot_review_usage++ def _attribute() -> None:+ audit.usage = _snapshot_review_usage(fork)+ _record_review_usage_to_parent(parent, audit.usage, task=SIDE_QUESTION_ORIGIN)++ for step in (_attribute, fork.shutdown_memory_provider, fork.close):+ try:+ step()+ except Exception:+ logger.debug("side question teardown step failed", exc_info=True)+++def _log_audit(audit: _Audit) -> None:+ usage = audit.usage+ logger.info(+ "side_question plugin=%s outcome=%s calls=%d in=%d cache_read=%d cache_write=%d out=%d latency=%.1fs",+ audit.plugin_id or "?", audit.outcome,+ *(int(usage.get(key) or 0) for key in (+ "api_calls", "input_tokens", "cache_read_tokens", "cache_write_tokens", "output_tokens")),+ time.monotonic() - audit.started,+ )+++def ask_text_only(+ capture: SideQuestionCapture, prompt: str, *, plugin_id: str = "", timeout: float = 15.0,+) -> Optional[str]:+ """Ask the session's own agent ``prompt`` after the captured turn; its text answer or None.++ None on refusal (MoA, agent-as-provider, server-side tools in the final request), timeout,+ provider error or an empty / tool-call-only reply. The request parameters (tools, reasoning,+ max_tokens, tool_choice) are the parent's verbatim: changing any of them changes the cache+ key, and an inherited thinking budget 400s against a smaller max_tokens."""+ audit = _Audit(plugin_id)+ parent = capture.parent_ref()+ refusal = "parent_gone" if parent is None else _agent_provider_refusal(parent)+ if refusal is not None:+ audit.outcome = f"refused:{refusal}"+ _log_audit(audit)+ return None+ fork = None+ timed_out = threading.Event()+ timer = None+ try:+ fork = _build_fork(parent, capture)++ def _on_timeout() -> None:+ timed_out.set()+ # Soft interrupt with a system reason: aborts the in-flight request without being+ # recorded as a user Stop.+ fork.interrupt(None, tool_reason="side question timed out")++ timer = threading.Timer(timeout, _on_timeout)+ timer.daemon = True+ timer.start()+ assistant_message = _send(fork, capture, prompt, audit)+ if assistant_message is None:+ return None+ answer = _answer_text(fork, assistant_message)+ audit.outcome = "ok" if answer else "empty"+ return answer+ except Exception:+ # Boundary: a plugin's side question returns None, it never raises into the plugin.+ audit.outcome = "timeout" if timed_out.is_set() else "error"+ logger.warning("side question %s (plugin=%s)", audit.outcome, plugin_id or "?", exc_info=True)+ return None+ finally:+ if timer is not None:+ timer.cancel()+ if fork is not None:+ _teardown(parent, fork, audit)+ _log_audit(audit)diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex c882efb7d61..f54afb2e7c2 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -466,6 +466,14 @@ def _apply_output_hooks()# Detached forks are internal work and must not publish turns under the parent's session ID.if not getattr(agent, "_persist_disabled", False):+ # Leased on the turn thread so the capture holds this turn's context; None unless a+ # loaded plugin holds llm.side_question. The response must survive a failed capture.+ try:+ from agent.side_question_lease import issue_side_question_token+ side_question_token = issue_side_question_token(agent, messages, turn_id)+ except Exception:+ side_question_token = None+ logger.warning("side question lease failed", exc_info=True)_invoke_hook_safely("post_llm_call", logger,session_id=agent.session_id,@@ -476,6 +484,7 @@ def _apply_output_hooks(conversation_history=list(messages),model=agent.model,platform=platform,+ side_question_token=side_question_token,)return final_response, transformed, pre_transformdiff --git a/hermes_cli/plugin_capabilities.py b/hermes_cli/plugin_capabilities.pyindex 9ff779820e7..06eb41a03c7 100644--- a/hermes_cli/plugin_capabilities.py+++ b/hermes_cli/plugin_capabilities.py@@ -42,6 +42,9 @@ _CAPABILITY_ROWS = (("llm.task_override", ("llm", "allow_task_override"),"Route its LLM calls through the host's built-in auxiliary ""task lanes"),+ ("llm.side_question", ("llm", "allow_side_question"),+ "Ask your agent a short question after each turn. It sees the "+ "whole session, including memory, and spends your main model's tokens."),("gateway.platform_actions", ("allow_platform_actions",),"Act on connected chat platforms as the gateway bot ""(add reactions, rename threads) via ctx.platform_actions"))diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 8a6eae1c09d..21513d123bf 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -57,6 +57,7 @@ from hermes_cli.plugins_dispatch import (RenderedPluginSystemPromptSection, _EventSubscription, format_system_prompt_sections,is_valid_system_prompt_section_id, resolve_plugin_command_result,)+from hermes_cli.plugins_capability_ctx import PluginCapabilityCtxMixinfrom hermes_cli.plugins_ledger import PluginLedgerMixin, PluginRegistrationfrom hermes_cli.plugins_registrars import _NAME_NORMALIZERS, _SCOPED_PROVIDER_REGISTRARSfrom hermes_cli.plugins_state import (@@ -226,7 +227,7 @@ class LoadedPlugin:deferred: bool = False-class PluginContext:+class PluginContext(PluginCapabilityCtxMixin):"""Facade given to plugins so they can register tools and hooks."""def __init__(self, manifest: PluginManifest, manager: PluginManager):@@ -498,15 +499,6 @@ class PluginContext:" (override)" if override else "")return handle- # -- capability probing (#64228) ------------------------------------------ def has_capability(self, capability: str) -> bool:- """True when *capability* is live for this plugin (probe, then degrade gracefully). Bundled- plugins are trusted for ``tools.override``; otherwise granted_capabilities or the legacy- ``allow_*`` key decides. Unknown ids / unreadable consent -> False (fail closed)."""- if self.manifest.source == "bundled" and capability == "tools.override":- return True- return plugin_capability_granted(self.plugin_id, capability)-def call_mcp(self, server: str, tool: str, arguments: Optional[dict[str, Any]] = None,timeout: float = 30,diff --git a/hermes_cli/plugins_capability_ctx.py b/hermes_cli/plugins_capability_ctx.pynew file mode 100644index 00000000000..91758850f0b--- /dev/null+++ b/hermes_cli/plugins_capability_ctx.py@@ -0,0 +1,54 @@+"""Capability-gated ``PluginContext`` surface: ``has_capability`` probing and+``side_question`` (ask the session's own agent after a turn, ``llm.side_question``)."""++from __future__ import annotations++import logging+from typing import Optional++from hermes_cli.plugin_capabilities import plugin_capability_granted+from hermes_cli.plugins_loader import _plugin_home_scope++logger = logging.getLogger(__name__)+++class PluginCapabilityCtxMixin:+ """Mixed into :class:`hermes_cli.plugins.PluginContext` (``manifest``, ``_manager``, ``plugin_id``)."""++ # -- capability probing (#64228) -----------------------------------------+ def has_capability(self, capability: str) -> bool:+ """True when *capability* is live for this plugin (probe, then degrade gracefully). Bundled+ plugins are trusted for ``tools.override``; otherwise granted_capabilities or the legacy+ ``allow_*`` key decides. Unknown ids / unreadable consent -> False (fail closed)."""+ if self.manifest.source == "bundled" and capability == "tools.override":+ return True+ return plugin_capability_granted(self.plugin_id, capability)++ def side_question(self, token: str, prompt: str, *, timeout: float = 15.0) -> Optional[str]:+ """Ask the session's own agent ``prompt`` about the turn that just ended; text or None.++ ``token`` is ``post_llm_call``'s ``side_question_token``: one attempt per turn, shared by+ every plugin, valid for 60 s and only until the next turn starts. Same model, the whole+ session (memory included) and its warm prompt cache; tools never run and nothing is+ written to the transcript. Needs the ``llm.side_question`` capability; without it this+ returns None and leaves the attempt to a consented plugin."""+ from agent.side_question_lease import SIDE_QUESTION_CAPABILITY, redeem_side_question++ if not self._side_question_granted(SIDE_QUESTION_CAPABILITY):+ if not getattr(self, "_side_question_denial_logged", False):+ self._side_question_denial_logged = True+ logger.info("Plugin %s called ctx.side_question without the %s capability; returning None",+ self.plugin_id, SIDE_QUESTION_CAPABILITY)+ return None+ return redeem_side_question(token, prompt, plugin_id=self.plugin_id, timeout=timeout)++ def _side_question_granted(self, capability: str) -> bool:+ """Consent read from THIS manager's profile home: plugins call from their own threads,+ where the active profile may be the launch profile's."""+ try:+ from hermes_cli.config import load_config+ with _plugin_home_scope(self._manager.home_path):+ cfg = load_config() or {}+ except Exception: # health: allow BLE001 -- fail closed: unreadable consent state never grants+ return False+ return plugin_capability_granted(self.plugin_id, capability, config=cfg)diff --git a/tests/agent/test_side_question_lease.py b/tests/agent/test_side_question_lease.pynew file mode 100644index 00000000000..e48c982b61f--- /dev/null+++ b/tests/agent/test_side_question_lease.py@@ -0,0 +1,238 @@+"""Turn leases for plugin side questions (``agent/side_question_lease.py``, ``ctx.side_question``).++Plugins load through real discovery from a temp ``HERMES_HOME``. The lease rules (issued only+for a consented plugin, one attempt per turn shared across plugins, expiry, invalid once the+next turn starts, prompt cap) are checked against a recorded executor; the last test runs a real+turn end to end and lets a plugin's ``post_llm_call`` hook redeem its token.+"""++from __future__ import annotations++import json+import os+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import hermes_yaml as yaml+import pytest++import hermes_cli.plugins as plugins_mod+from agent import side_question_lease+from agent.side_question_lease import issue_side_question_token, redeem_side_question+from hermes_cli.plugins import PluginContext++CAP = "llm.side_question"+++def _install_plugin(name: str, *, declares: bool, hook_body: str = "pass") -> None:+ plugin_dir = Path(os.environ["HERMES_HOME"]) / "plugins" / name+ plugin_dir.mkdir(parents=True)+ manifest = {"name": name, **({"capabilities": [CAP]} if declares else {})}+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump(manifest), encoding="utf-8")+ (plugin_dir / "__init__.py").write_text(+ "import json, os, pathlib\n\n"+ "def register(ctx):\n"+ " def _on_post_llm_call(**kwargs):\n"+ f" {hook_body}\n"+ " ctx.register_hook('post_llm_call', _on_post_llm_call)\n",+ encoding="utf-8",+ )+++def _load(enabled: list[str], granted: list[str]) -> plugins_mod.PluginManager:+ entries = {name: {"granted_capabilities": [CAP]} for name in granted}+ (Path(os.environ["HERMES_HOME"]) / "config.yaml").write_text(+ yaml.safe_dump({"plugins": {"enabled": enabled, "entries": entries}}), encoding="utf-8")+ plugins_mod._plugin_manager = plugins_mod.PluginManager()+ plugins_mod.discover_plugins(force=True)+ return plugins_mod.get_plugin_manager()+++def _ctx(manager, name: str) -> PluginContext:+ return PluginContext(manager._plugins[name].manifest, manager)+++class _Agent(SimpleNamespace):+ """A stand-in parent; leases hold their parent weakly, which a bare SimpleNamespace refuses."""+++def _agent(turn_id="turn-1", **overrides):+ return _Agent(**{+ "_persist_disabled": False, "_cached_system_prompt": "sys", "_cached_system_prompt_static": None,+ "tools": [], "session_id": "sess", "_current_turn_id": turn_id, **overrides,+ })+++def executor(monkeypatch):+ """Record every request the lease lets through (the request itself has its own tests)."""+ calls: list = []++ def _ask(capture, prompt, *, plugin_id="", timeout=15.0):+ calls.append({"plugin_id": plugin_id, "prompt": prompt, "timeout": timeout, "capture": capture})+ return f"answer for {plugin_id}"++ monkeypatch.setattr(side_question_lease, "ask_text_only", _ask)+ yield calls+ side_question_lease._leases.clear()+++def consented():+ """``next-prompt`` declares and is granted the capability; ``bystander`` does neither."""+ _install_plugin("next-prompt", declares=True)+ _install_plugin("bystander", declares=False)+ return _load(["next-prompt", "bystander"], granted=["next-prompt"])+++# ── 1. issuance ──────────────────────────────────────────────────────────────────────────+++def test_token_only_for_a_declared_and_granted_plugin(executor):+ _install_plugin("declares-only", declares=True)+ _install_plugin("granted-only", declares=False)+ _load(["declares-only", "granted-only"], granted=["granted-only"])+ assert issue_side_question_token(_agent(), [], "turn-1") is None++ _load(["declares-only", "granted-only"], granted=["declares-only", "granted-only"])+ assert isinstance(issue_side_question_token(_agent(), [], "turn-1"), str)+++def test_no_token_when_the_consented_plugin_is_disabled(executor):+ _install_plugin("next-prompt", declares=True)+ _load([], granted=["next-prompt"])+ assert issue_side_question_token(_agent(), [], "turn-1") is None+++def test_no_token_for_a_persist_disabled_fork(executor, consented):+ assert issue_side_question_token(_agent(_persist_disabled=True), [], "turn-1") is None+++def test_capture_is_frozen_at_issue(executor, consented):+ messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]+ agent = _agent() # the lease holds its parent weakly+ token = issue_side_question_token(agent, messages, "turn-1")+ messages.append({"role": "user", "content": "later"})+ redeem_side_question(token, "q", plugin_id="next-prompt")+ assert executor[0]["capture"].messages == messages[:2]+++# ── 2. capability denied keeps the attempt for the consented plugin ─────────────────────+++def test_denied_plugin_gets_none_and_leaves_the_lease(executor, consented):+ agent = _agent() # the lease holds its parent weakly+ token = issue_side_question_token(agent, [], "turn-1")+ assert _ctx(consented, "bystander").side_question(token, "q") is None+ assert executor == []+ assert _ctx(consented, "next-prompt").side_question(token, "q") == "answer for next-prompt"+++# ── 3. single use across plugins ─────────────────────────────────────────────────────────+++def test_one_attempt_per_turn(executor, consented):+ agent = _agent() # the lease holds its parent weakly+ token = issue_side_question_token(agent, [], "turn-1")+ assert redeem_side_question(token, "q", plugin_id="next-prompt") == "answer for next-prompt"+ assert redeem_side_question(token, "q", plugin_id="other") is None+ assert len(executor) == 1+++def test_a_new_lease_for_the_same_agent_drops_the_old_one(executor, consented):+ agent = _agent()+ old = issue_side_question_token(agent, [], "turn-1")+ agent._current_turn_id = "turn-2"+ new = issue_side_question_token(agent, [], "turn-2")+ assert redeem_side_question(old, "q", plugin_id="next-prompt") is None+ assert redeem_side_question(new, "q", plugin_id="next-prompt") == "answer for next-prompt"+++# ── 4. expiry, turn movement, prompt cap ─────────────────────────────────────────────────+++def test_expired_lease_is_none(executor, consented, monkeypatch):+ agent = _agent() # the lease holds its parent weakly+ token = issue_side_question_token(agent, [], "turn-1")+ real = side_question_lease.time.monotonic+ monkeypatch.setattr(side_question_lease.time, "monotonic",+ lambda: real() + side_question_lease.LEASE_TTL_SECONDS + 1)+ assert redeem_side_question(token, "q", plugin_id="next-prompt") is None+ assert executor == []+++def test_lease_dies_when_the_parent_starts_its_next_turn(executor, consented):+ agent = _agent()+ token = issue_side_question_token(agent, [], "turn-1")+ agent._current_turn_id = "turn-2"+ assert redeem_side_question(token, "q", plugin_id="next-prompt") is None+ assert executor == []+++def test_lease_dies_with_its_parent(executor, consented):+ import gc++ agent = _agent()+ token = issue_side_question_token(agent, [], "turn-1")+ del agent+ gc.collect()+ assert redeem_side_question(token, "q", plugin_id="next-prompt") is None+ assert executor == []++[email protected]("prompt", ["x" * (side_question_lease.MAX_PROMPT_CHARS + 1), "", " ", None, 42])+def test_bad_prompt_is_none_and_consumes_the_lease(executor, consented, prompt):+ agent = _agent() # the lease holds its parent weakly+ token = issue_side_question_token(agent, [], "turn-1")+ assert redeem_side_question(token, prompt, plugin_id="next-prompt") is None+ assert redeem_side_question(token, "fine", plugin_id="next-prompt") is None+ assert executor == []++[email protected]("given, used", [(0.5, 0.5), (600, 60.0), (0, 15.0), (-3, 15.0), (float("nan"), 15.0), ("x", 15.0)])+def test_timeout_is_clamped(executor, consented, given, used):+ agent = _agent() # the lease holds its parent weakly+ token = issue_side_question_token(agent, [], "turn-1")+ redeem_side_question(token, "q", plugin_id="next-prompt", timeout=given)+ assert executor[0]["timeout"] == used+++# ── 5. end to end through real discovery and a real turn ─────────────────────────────────+++def test_post_llm_call_hook_redeems_its_token_end_to_end(monkeypatch):+ from run_agent import AIAgent++ answers = Path(os.environ["HERMES_HOME"]) / "side_answers.json"+ _install_plugin("next-prompt", declares=True, hook_body=(+ "answer = ctx.side_question(kwargs['side_question_token'], 'Suggest the next prompt.')\n"+ f" pathlib.Path({str(answers)!r}).write_text(json.dumps(answer))"+ ))+ _load(["next-prompt"], granted=["next-prompt"])++ client = MagicMock()+ requests: list = []+ replies = [+ SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=text, tool_calls=None),+ finish_reason="stop")], model="test/model", usage=None)+ for text in ("The answer is 42.", "Ask why it is 42.")+ ]+ client.chat.completions.create.side_effect = lambda **kw: (requests.append(kw), replies.pop(0))[1]+ 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+ result = parent.run_conversation("what is the answer?")++ assert result["final_response"] == "The answer is 42."+ 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()diff --git a/tests/agent/test_side_question_request.py b/tests/agent/test_side_question_request.pynew file mode 100644index 00000000000..460ed889be0--- /dev/null+++ b/tests/agent/test_side_question_request.py@@ -0,0 +1,385 @@+"""Plugin side questions on the live session agent (``agent/side_question_request.py``).++A real parent ``AIAgent`` runs a turn against a capturing fake client; the side call then+replays the lease captured at finalization through the turn loop's own request phases. The+contracts: the side request extends the parent's cached prefix byte-for-byte (system, tools,+request parameters, messages), tool calls in its reply never run, nothing but one usage row is+written, and refusals send no request at all.+"""++from __future__ import annotations++import copy+import json+import threading+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from agent import side_question_lease+from agent.side_question_lease import redeem_side_question+from hermes_state import SessionDB+from run_agent import AIAgent++SIDE_PROMPT = "Suggest the user's next prompt in one line."+++def _tool_defs(*names: str) -> list:+ return [{+ "type": "function",+ "function": {"name": name, "description": f"{name} tool", "parameters": {"type": "object", "properties": {}}},+ } for name in names]+++def _usage(prompt=1200, completion=20, cached=1000):+ return SimpleNamespace(+ prompt_tokens=prompt, completion_tokens=completion, total_tokens=prompt + completion,+ prompt_tokens_details=SimpleNamespace(cached_tokens=cached),+ )+++def _response(content="", tool_calls=None, finish_reason="stop", usage=None):+ msg = SimpleNamespace(content=content, tool_calls=tool_calls)+ return SimpleNamespace(+ choices=[SimpleNamespace(message=msg, finish_reason=finish_reason)], model="test/model", usage=usage,+ )+++def _tool_call(name="web_search", call_id="call_1", arguments="{}"):+ return SimpleNamespace(id=call_id, type="function", function=SimpleNamespace(name=name, arguments=arguments))+++class _FakeProvider:+ """One fake client shared by the parent and every fork (``OpenAI(...)`` returns it)."""++ def __init__(self):+ self.client = MagicMock()+ self.requests: list[dict] = []+ self.replies: list = []+ self.client.chat.completions.create.side_effect = self._create++ def _create(self, **kwargs):+ self.requests.append(copy.deepcopy(kwargs))+ reply = self.replies.pop(0)+ if isinstance(reply, BaseException):+ raise reply+ return reply() if callable(reply) else reply+++def provider(tmp_path, monkeypatch):+ fake = _FakeProvider()+ monkeypatch.setattr("agent.title_generator.maybe_auto_title", lambda *a, **k: None)+ # Every agent built during the test (parent and fork) talks to the same fake.+ patches = [+ patch("model_tools.get_tool_definitions", return_value=_tool_defs("web_search", "terminal")),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.process_bootstrap.OpenAI", return_value=fake.client),+ patch("agent.model_metadata.fetch_model_metadata", return_value={}),+ # The side call only runs where a consented plugin holds the capability; that gate has+ # its own tests (test_side_question_lease.py).+ patch.object(side_question_lease, "_consented_plugin_loaded", return_value=True),+ ]+ for p in patches:+ p.start()+ yield fake+ for p in reversed(patches):+ p.stop()+ side_question_lease._leases.clear()+++def _make_parent(model="test/model", **kwargs) -> AIAgent:+ agent = AIAgent(+ api_key="test-key", base_url="https://openrouter.ai/api/v1", model=model, quiet_mode=True,+ skip_context_files=True, skip_memory=True, **kwargs,+ )+ agent._cached_system_prompt = "You are helpful."+ agent.compression_enabled = False+ agent.save_trajectories = False+ agent.skip_background_review = True+ return agent+++def issued(monkeypatch):+ """Tokens the finalizer leased, in order."""+ tokens: list = []+ real = side_question_lease.issue_side_question_token++ def _spy(*args, **kwargs):+ tokens.append(real(*args, **kwargs))+ return tokens[-1]++ monkeypatch.setattr(side_question_lease, "issue_side_question_token", _spy)+ return tokens+++def _run_parent_turn(parent, provider, *, tool_round=True):+ if tool_round:+ provider.replies += [+ _response(tool_calls=[_tool_call()], finish_reason="tool_calls", usage=_usage()),+ _response("Found it: the answer is 42.", usage=_usage()),+ ]+ else:+ provider.replies.append(_response("Found it: the answer is 42.", usage=_usage()))+ with patch("model_tools.handle_function_call", return_value=json.dumps({"result": "42"})):+ return parent.run_conversation("look this up")+++def _canon(value):+ """Drop cache_control markers (they legitimately move to the newest rows) and collapse the+ text-block form a marker forces back to the plain string it wraps."""+ if isinstance(value, list):+ items = [_canon(v) for v in value]+ if items and all(isinstance(i, dict) and set(i) == {"type", "text"} and i["type"] == "text" for i in items):+ return "".join(i["text"] for i in items)+ return items+ if isinstance(value, dict):+ return {k: _canon(v) for k, v in value.items() if k != "cache_control"}+ return value+++# ── 1. prefix parity ─────────────────────────────────────────────────────────────────────++[email protected]("model", ["test/model", "anthropic/claude-sonnet-4"])+def test_side_request_extends_the_parents_cached_prefix(provider, issued, model):+ parent = _make_parent(model=model)+ result = _run_parent_turn(parent, provider)+ assert result["final_response"] == "Found it: the answer is 42."+ parent_last = provider.requests[-1]++ provider.replies.append(_response("Ask: why 42?", usage=_usage()))+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") == "Ask: why 42?"++ side = provider.requests[-1]+ assert len(provider.requests) == 3+ # Everything but the messages — system/tools/reasoning/max_tokens/tool_choice — is verbatim.+ assert _canon({k: v for k, v in side.items() if k != "messages"}) == \+ _canon({k: v for k, v in parent_last.items() if k != "messages"})+ parent_msgs, side_msgs = _canon(parent_last["messages"]), _canon(side["messages"])+ assert side_msgs[:len(parent_msgs)] == parent_msgs+ assert len(side_msgs) == len(parent_msgs) + 2+ assert side_msgs[-2]["role"] == "assistant" and side_msgs[-2]["content"] == "Found it: the answer is 42."+ assert side_msgs[-1] == {"role": "user", "content": SIDE_PROMPT}+++def test_prompt_caching_runtime_marks_the_side_request(provider, issued):+ """The Claude-on-OpenRouter arm really exercises cache markers (else the parity test above+ would compare two unmarked requests)."""+ parent = _make_parent(model="anthropic/claude-sonnet-4")+ assert parent._use_prompt_caching+ _run_parent_turn(parent, provider)+ provider.replies.append(_response("ok", usage=_usage()))+ redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt")+ assert "cache_control" in json.dumps(provider.requests[-1]["messages"])+++# ── 2. tool calls are never dispatched ───────────────────────────────────────────────────+++def dispatch_spy():+ calls: list = []+ lock = threading.Lock()++ def _record(name):+ def _fn(*args, **kwargs):+ with lock:+ calls.append((name, threading.current_thread().name))+ return "{}"+ return _fn++ with (+ patch("model_tools.handle_function_call", side_effect=_record("handle_function_call")),+ patch.object(AIAgent, "_invoke_tool", side_effect=_record("_invoke_tool"), autospec=False),+ patch.object(AIAgent, "_execute_tool_calls", side_effect=_record("_execute_tool_calls"), autospec=False),+ ):+ yield calls+++def _parent_without_tools(provider):+ parent = _make_parent()+ provider.replies.append(_response("Found it: the answer is 42.", usage=_usage()))+ parent.run_conversation("look this up")+ return parent+++def test_tool_calls_in_the_side_reply_are_dropped(provider, issued, dispatch_spy):+ _parent = _parent_without_tools(provider) # alive for the call: the lease holds its parent weakly+ provider.replies.append(_response(+ "Try: rm the cache", tool_calls=[_tool_call("terminal", arguments='{"command": "rm -rf /tmp/x"}')],+ finish_reason="tool_calls", usage=_usage()))+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") == "Try: rm the cache"+ assert dispatch_spy == []+++def test_tool_call_only_side_reply_is_none(provider, issued, dispatch_spy):+ _parent = _parent_without_tools(provider) # alive for the call: the lease holds its parent weakly+ provider.replies.append(_response("", tool_calls=[_tool_call("terminal")], finish_reason="tool_calls"))+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") is None+ assert dispatch_spy == []+++def test_side_call_never_reaches_the_parents_ui_callbacks(provider, issued):+ """A side call is invisible in the live chat: no stream, status, progress or thinking events."""+ parent = _make_parent()+ _run_parent_turn(parent, provider, tool_round=False)+ seen: list = []+ for name in ("stream_delta_callback", "status_callback", "tool_progress_callback", "thinking_callback",+ "reasoning_callback", "step_callback", "interim_assistant_callback", "background_review_callback"):+ setattr(parent, name, lambda *a, _n=name, **k: seen.append(_n))+ parent._stream_callback = lambda *a, **k: seen.append("_stream_callback")+ provider.replies.append(_response("<think>plan</think>Ask: why 42?", usage=_usage()))+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") == "Ask: why 42?"+ assert seen == []+ assert provider.requests[-1].get("stream") is not True+++# ── 3. no writes besides usage ───────────────────────────────────────────────────────────+++def _message_rows(db: SessionDB, session_id: str) -> list:+ with db._lock:+ return [tuple(r) for r in db._conn.execute(+ "SELECT * FROM messages WHERE session_id = ? ORDER BY id", (session_id,)).fetchall()]+++def _usage_rows(db: SessionDB, session_id: str) -> list[dict]:+ with db._lock:+ return [dict(r) for r in db._conn.execute(+ "SELECT * FROM session_model_usage WHERE session_id = ?", (session_id,)).fetchall()]+++def test_side_call_writes_only_one_usage_row(provider, issued, tmp_path):+ from hermes_constants import get_hermes_home++ memories = Path(get_hermes_home()) / "memories"+ memories.mkdir(parents=True, exist_ok=True)+ (memories / "MEMORY.md").write_text("user likes tea\n", encoding="utf-8")+ db = SessionDB(db_path=tmp_path / "state.db")+ parent = _make_parent(session_db=db, session_id="sess-side")+ _run_parent_turn(parent, provider)+ rows_before = _message_rows(db, "sess-side")+ usage_before = [r for r in _usage_rows(db, "sess-side") if r["task"] == "side_question"]+ assert rows_before and usage_before == []+ memory_before = {p.name: p.read_bytes() for p in memories.iterdir()}++ provider.replies.append(_response("Ask: why 42?", usage=_usage()))+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") == "Ask: why 42?"++ assert _message_rows(db, "sess-side") == rows_before+ side_rows = [r for r in _usage_rows(db, "sess-side") if r["task"] == "side_question"]+ assert len(side_rows) == 1 and side_rows[0]["api_call_count"] == 1+ assert {p.name: p.read_bytes() for p in memories.iterdir()} == memory_before+++# ── 4. no recursive post_llm_call ────────────────────────────────────────────────────────+++def test_side_call_fires_no_post_llm_call(provider, issued):+ parent = _make_parent()+ _run_parent_turn(parent, provider, tool_round=False)+ fired: list = []+ real_invoke = __import__("hermes_cli.plugins", fromlist=["invoke_hook"]).invoke_hook++ def _spy(name, **kwargs):+ fired.append(name)+ return real_invoke(name, **kwargs)++ provider.replies.append(_response("Ask: why 42?", usage=_usage()))+ with patch("hermes_cli.plugins.invoke_hook", side_effect=_spy), \+ patch("hermes_cli.lifecycle.invoke_hook", side_effect=_spy, create=True):+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") == "Ask: why 42?"+ assert "post_llm_call" not in fired and "transform_llm_output" not in fired+++# ── 5. refusals send no request ──────────────────────────────────────────────────────────+++def test_moa_runtime_is_refused(provider, issued):+ parent = _make_parent()+ _run_parent_turn(parent, provider, tool_round=False)+ parent.provider = "moa"+ sent = len(provider.requests)+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") is None+ assert len(provider.requests) == sent+++def test_agent_as_provider_is_refused(provider, issued):+ parent = _make_parent()+ _run_parent_turn(parent, provider, tool_round=False)+ provider.client.SUPPORTS_HERMES_TOOL_CALLS = False # an agent CLI shim runs its own tools+ sent = len(provider.requests)+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") is None+ assert len(provider.requests) == sent+++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++ def _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)+ sent = len(provider.requests)+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") is None+ assert len(provider.requests) == sent++[email protected]("api_kwargs, server_side", [+ ({"tools": [{"type": "function", "function": {"name": "x"}}]}, False),+ ({"tools": [{"name": "x", "input_schema": {}}]}, False), # Anthropic client tool: no type+ ({"tools": [{"type": "custom", "name": "x"}]}, False),+ ({"tools": [{"type": "web_search"}]}, True),+ ({"tools": [{"type": "web_search_20250305", "name": "web_search"}]}, True),+ ({"extra_body": {"plugins": [{"id": "pareto-router", "min_coding_score": 0.5}]}}, False),+ ({"extra_body": {"plugins": [{"id": "web"}]}}, True),+ ({"web_search_options": {}}, True),+])+def test_server_side_tool_predicate(api_kwargs, server_side):+ from agent.side_question_request import has_server_side_tools++ assert has_server_side_tools(api_kwargs) is server_side+++# ── 6. timeout and provider errors ───────────────────────────────────────────────────────+++def test_timeout_interrupts_the_inflight_request(provider, issued):+ parent = _make_parent()+ _run_parent_turn(parent, provider, tool_round=False)+ released = threading.Event()+ interrupted: list = []+ real_interrupt = AIAgent.interrupt++ def _spy_interrupt(self, *args, **kwargs):+ interrupted.append(kwargs.get("tool_reason"))+ released.set()+ return real_interrupt(self, *args, **kwargs)++ def _hang():+ # Held until the timer interrupts the fork, then fail like an aborted connection.+ assert released.wait(10)+ raise InterruptedError("aborted")++ provider.replies.append(_hang)+ with patch.object(AIAgent, "interrupt", _spy_interrupt):+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt", timeout=0.5) is None+ assert interrupted == ["side question timed out"]+++def test_provider_error_returns_none_without_fallback(provider, issued):+ parent = _make_parent(fallback_model={"provider": "openrouter", "model": "fallback/model"})+ _run_parent_turn(parent, provider, tool_round=False)+ provider.replies += [RuntimeError("upstream 500"), _response("from the fallback", usage=_usage())]+ sent = len(provider.requests)+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") is None+ assert len(provider.requests) == sent + 1+ assert all(r.get("model") != "fallback/model" for r in provider.requests)diff --git a/website/docs/developer-guide/plugin-llm-access.md b/website/docs/developer-guide/plugin-llm-access.mdindex e4a8063bcc3..0add6d9f944 100644--- a/website/docs/developer-guide/plugin-llm-access.md+++ b/website/docs/developer-guide/plugin-llm-access.md@@ -519,6 +519,80 @@ don't have to:loop on `complete()` for every gateway message without thinkingabout token spend.+## Asking the session's own agent (`ctx.side_question`)++`ctx.llm` runs a fresh call that knows only what the plugin sends it.+`ctx.side_question` asks the session's *own* agent instead: the same+model, the same system prompt (memory included) and the whole+conversation so far, plus one question from the plugin. It replays+the request the turn just sent, so the provider's prompt cache is+still warm and the call is mostly cache reads.++Reach for it when the answer depends on the conversation itself:+suggesting the user's next prompt, labelling what the turn did,+deciding whether the session needs a follow-up. For anything that+doesn't need the session, use `ctx.llm`: it is cheaper and has no+lease rules.++```python+import threading+++def register(ctx):+ def on_post_llm_call(**kwargs):+ token = kwargs.get("side_question_token")+ if token is None: # no consented plugin loaded, or not a user turn+ return+ # post_llm_call is time-bounded: never wait for the model inside the hook.+ threading.Thread(target=_suggest, args=(token,), daemon=True).start()++ def _suggest(token):+ answer = ctx.side_question(+ token, "Suggest the user's most likely next prompt in one short line.")+ if answer:+ ctx.state.set("next_prompt", answer)++ ctx.register_hook("post_llm_call", on_post_llm_call)+```++The plugin must declare the capability in `plugin.yaml` and the user+must grant it (the consent screen shows: "Ask your agent a short+question after each turn. It sees the whole session, including+memory, and spends your main model's tokens."):++```yaml+capabilities:+ - llm.side_question+```++### Lease rules++* `post_llm_call` receives `side_question_token` (a string) when at+ least one loaded plugin holds the capability, else `None`.+* **One attempt per turn, shared by every plugin.** Every plugin's+ hook gets the same token; the first `ctx.side_question` call spends+ it, whether it succeeds or not. A plugin without the capability gets+ `None` back and does not spend it.+* The token expires after **60 seconds**, and as soon as the session+ starts its next turn.+* `prompt` is a non-empty string of at most **4096 characters**.+* `timeout` defaults to **15 seconds** and is capped at 60.++### What you get back++The text of the agent's reply, or `None`. `None` means the call was+refused or failed: a Mixture-of-Agents runtime, an agent-as-provider+runtime (ACP, external-process providers, the Codex app-server), a+request that carries provider-executed (server-side) tools, a+timeout, a provider error, or an empty reply. There are no retries+and no fallback model.++The call never runs a tool (tool calls in the reply are dropped) and+never writes to the transcript. Its tokens are billed to the session+and recorded in its usage as `side_question`. You can't pick the+model, tools, system prompt or output length: changing any of them+would miss the warm cache. Ask for brevity in the prompt.+## Where this fits in the plugin surfaceExisting `ctx.*` methods extend an existing Hermes subsystem:diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex 7c937f03a3b..8ba0e26f4ad 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -407,7 +407,9 @@ def register(ctx):Known capability ids: `tools.override`, `llm.provider_override`,`llm.model_override`, `llm.agent_id_override`, `llm.profile_override`,-`llm.task_override` (see `hermes_cli/plugin_capabilities.py` for the+`llm.task_override`, `llm.side_question` (ask the session's own agent after+a turn, see [Plugin LLM Access](../plugin-llm-access.md#asking-the-sessions-own-agent-ctxside_question)),+`gateway.platform_actions` (see `hermes_cli/plugin_capabilities.py` for thecanonical registry). Unknown ids are ignored. The older per-capabilityconfig keys (`plugins.entries.<id>.allow_tool_override`, …) still work butare deprecated — declare capabilities instead so users get a single,diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex becb4b3807c..ac70d66093f 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -454,7 +454,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `transform_terminal_output` | Transform | After bounded foreground process capture, before final output limiting; first string replaces output. | `command`, `output`, `returncode`, `task_id`, `env_type` | Command/output may contain credentials. || `pre_transcription` | Transform | Fired by the STT dispatcher after provider resolution and before any backend (built-in, command-type, or plugin-registered) is invoked; dict results are applied in registration order, last-writer-wins per field (`prompt`, `language`, `model`; `file_path` is read-only). | `file_path`, `provider`, `model`, `language`, `prompt`, `source` | The final prompt is uploaded to the configured STT provider with the audio — keep secrets out of hook returns. || `pre_llm_call` | Directive/control | Once per turn before the loop; all valid string/`{"context": ...}` returns are joined and injected into the user message. | `session_id`, `task_id`, `turn_id`, `user_message`, `conversation_history`, `is_first_turn`, `model`, `platform`, `parent_session_id`, `sender_id` | Full user message and conversation history. |-| `post_llm_call` | Observer | Successful, non-interrupted turn finalization; return ignored. | `session_id`, `task_id`, `turn_id`, `user_message`, `assistant_response`, `conversation_history`, `model`, `platform` | Full prompt, response, and history. |+| `post_llm_call` | Observer | Successful, non-interrupted turn finalization; return ignored. | `session_id`, `task_id`, `turn_id`, `user_message`, `assistant_response`, `conversation_history`, `model`, `platform`, `side_question_token` | Full prompt, response, and history. || `transform_llm_output` | Transform | Before `post_llm_call` and final delivery; first non-empty string replaces the response. | `response_text`, `session_id`, `model`, `platform` | Full final assistant text. || `pre_verify` | Directive/control | At the bounded edited-code verify gate; first valid continue/block-stop directive keeps the turn going. | `session_id`, `platform`, `model`, `coding`, `attempt`, `final_response`, `changed_paths` | Draft response and changed paths. || `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`. |@@ -778,6 +778,7 @@ def my_callback(session_id: str, user_message: str, assistant_response: str,| `conversation_history` | `list` | Copy of the full message list after the turn completed || `model` | `str` | The model identifier || `platform` | `str` | Where the session is running |+| `side_question_token` | `str \| None` | One-use token for [`ctx.side_question`](../../developer-guide/plugin-llm-access.md#asking-the-sessions-own-agent-ctxside_question), shared by every plugin; `None` unless a loaded plugin holds the `llm.side_question` capability |**Fires:** In `agent/turn_finalizer.py` (`finalize_turn()`, called by `run_conversation()` in `agent/conversation_loop.py`), after the tool loop exits with a final response. Guarded by `if final_response and not interrupted` — so it does **not** fire when the user interrupts mid-turn or the agent hits the iteration limit without producing a response.diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 46d79ded23f..9b8df2ee192 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -603,6 +603,7 @@ working but are **deprecated** in favor of the consent flow:| `llm.agent_id_override` | `llm.allow_agent_id_override` || `llm.profile_override` | `llm.allow_profile_override` || `llm.task_override` | `llm.allow_task_override` |+| `llm.side_question` | `llm.allow_side_question` || `gateway.platform_actions` | `allow_platform_actions` |A gate is open when *either* the capability is granted *or* the legacy key is