The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): side-question review findings (runtime pin, extra_body tools, hook bracket, lease cap)
Teknium3f7af72898c9
diff --git a/agent/side_question_lease.py b/agent/side_question_lease.pyindex 8a4b5cf9768..23e74bc5a2d 100644--- a/agent/side_question_lease.py+++ b/agent/side_question_lease.py@@ -17,11 +17,10 @@ import secretsimport threadingimport timeimport weakref-from collections import OrderedDictfrom dataclasses import dataclassfrom typing import Any, Optional-from agent.side_question_request import SideQuestionCapture, ask_text_only+from agent.side_question_request import SideQuestionCapture, ask_text_only, runtime_keylogger = logging.getLogger(__name__)@@ -30,8 +29,6 @@ LEASE_TTL_SECONDS = 60.0MAX_PROMPT_CHARS = 4096DEFAULT_TIMEOUT_SECONDS = 15.0MAX_TIMEOUT_SECONDS = 60.0-# One live lease per active session agent; the bound only caps leaked parents' references.-_MAX_LEASES = 32@dataclass(frozen=True)@@ -40,7 +37,7 @@ class _Lease:expires_at: float-_leases: OrderedDict[str, _Lease] = OrderedDict()+_leases: dict[str, _Lease] = {}_lock = threading.Lock()@@ -78,16 +75,16 @@ def issue_side_question_token(agent: Any, messages: list[dict[str, Any]], turn_itools=copy.deepcopy(agent.tools or []),session_id=agent.session_id,turn_id=turn_id,+ runtime=runtime_key(agent),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).+ # Drop this agent's older leases (a new turn) and every expired or orphaned one (each holds+ # a transcript), so the table holds at most one lease per live session agent._purge_locked(now, agent)_leases[token] = _Lease(capture, now + LEASE_TTL_SECONDS)- while len(_leases) > _MAX_LEASES:- _leases.popitem(last=False)return tokendiff --git a/agent/side_question_request.py b/agent/side_question_request.pyindex cbac4f98661..b228c3b2e79 100644--- a/agent/side_question_request.py+++ b/agent/side_question_request.py@@ -44,9 +44,17 @@ class SideQuestionCapture:tools: list[dict[str, Any]]session_id: strturn_id: str+ runtime: tuple # runtime_key(parent) at capturecontext: contextvars.Context = field(repr=False)+def runtime_key(agent: Any) -> tuple:+ """What decides which model the fork talks to and how: a turn routed elsewhere (voice chat)+ restores the main runtime after ``post_llm_call``, and the captured prompt must not go out+ on it."""+ return tuple(getattr(agent, name, None) for name in ("model", "provider", "base_url", "api_mode", "reasoning_config"))++@dataclassclass _Audit:plugin_id: str@@ -81,11 +89,12 @@ def has_server_side_tools(api_kwargs: dict[str, Any]) -> bool: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 anOpenRouter plugin other than a routing-only one."""- for tool in api_kwargs.get("tools") or ():+ extra_body = api_kwargs.get("extra_body") if isinstance(api_kwargs.get("extra_body"), dict) else {}+ # ``request_overrides`` land in extra_body, whose ``tools`` the SDK merge sends over the top level.+ for tool in [*(api_kwargs.get("tools") or ()), *(extra_body.get("tools") or ())]:tool_type = tool.get("type") if isinstance(tool, dict) else Noneif 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 Trueplugins = [*(api_kwargs.get("plugins") or ()), *(extra_body.get("plugins") or ())]@@ -156,6 +165,8 @@ def _send(fork: Any, capture: SideQuestionCapture, prompt: str, audit: _Audit) -api_mode=str(fork.api_mode or ""), streaming=False,)api_start_time = time.time()+ # One hook bracket around the whole attempt: a reply that fails after the provider returned+ # (accounting, normalization) still closes the observer's pre_auxiliary_call with its error.try:verdict = perform_api_call(fork, api_kwargs=built.api_kwargs, _original_api_kwargs=built._original_api_kwargs,@@ -163,27 +174,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,)+ response = None if verdict.action == "break" else verdict.response+ if response is not None:+ record_response_usage(+ fork, response, messages=messages, api_call_count=1,+ api_duration=time.time() - api_start_time, compression_attempts=0, max_compression_attempts=0,+ )+ assistant_message = normalize_response_for_agent(fork, response)+ # The reply is in the transport's native shape: observers get the normalized view.+ normalized = (assistant_message, assistant_message.finish_reason,+ fork._usage_summary_for_api_request_hook(response))except BaseException as exc:finish_aux_call_hooks(hooks, error=exc)relay_llm.complete_logical_call(api_request_id, outcome="failed")raise- if verdict.action == "break" or verdict.response is None:- finish_aux_call_hooks(hooks)+ if response is None:+ finish_aux_call_hooks(hooks, error=InterruptedError("side question cancelled"))relay_llm.complete_logical_call(api_request_id, outcome="cancelled")audit.outcome = "error"return None- response = verdict.response- record_response_usage(- 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)- # 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),- ))+ finish_aux_call_hooks(hooks, response, normalized=normalized)return assistant_message@@ -230,6 +241,9 @@ def ask_text_only(timer = Nonetry:fork = _build_fork(parent, capture)+ if runtime_key(parent) != capture.runtime:+ audit.outcome = "refused:runtime_changed"+ return Nonedef _on_timeout() -> None:timed_out.set()diff --git a/tests/agent/test_side_question_lease.py b/tests/agent/test_side_question_lease.pyindex 9a0d9261ae9..128bd3a50ef 100644--- a/tests/agent/test_side_question_lease.py+++ b/tests/agent/test_side_question_lease.py@@ -152,6 +152,13 @@ def test_a_new_lease_for_the_same_agent_drops_the_old_one(executor, consented):# ── 4. expiry, turn movement, prompt cap ─────────────────────────────────────────────────+def test_many_live_sessions_keep_their_tokens(executor, consented):+ """A busy gateway finishing many turns at once must not revoke a live session's token."""+ parents = [_agent(session_id=f"sess-{i}") for i in range(40)]+ tokens = [issue_side_question_token(parent, [], "turn-1") for parent in parents]+ assert _ctx(consented, "next-prompt").side_question(tokens[0], "q") == "answer for next-prompt"++def test_expired_lease_is_none(executor, consented, monkeypatch):agent = _agent() # the lease holds its parent weaklytoken = issue_side_question_token(agent, [], "turn-1")@@ -238,9 +245,9 @@ def test_post_llm_call_hook_redeems_its_token_end_to_end(monkeypatch):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'``."""+def _observed_turn_with_side_question(monkeypatch, side_reply) -> list[dict]:+ """Run a real turn whose granted ``observer`` plugin asks a side question and records every+ request event; ``side_reply`` is what the provider returns to the side request."""from run_agent import AIAgentevents = Path(os.environ["HERMES_HOME"]) / "events.jsonl"@@ -252,7 +259,8 @@ def test_side_request_fires_auxiliary_hooks_not_turn_request_hooks(monkeypatch):"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"+ " row = {'event': name, 'aux_task': kw.get('aux_task'), 'usage': kw.get('usage'),\n"+ " 'error_type': kw.get('error_type')}\n"" with EVENTS.open('a') as fh:\n"" fh.write(json.dumps(row, default=str) + '\\n')\n\n""def register(ctx):\n"@@ -267,9 +275,9 @@ def test_side_request_fires_auxiliary_hooks_not_turn_request_hooks(monkeypatch):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.")+ SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="The answer is 42.", tool_calls=None),+ finish_reason="stop")], model="test/model", usage=usage),+ side_reply,]client = MagicMock()client.chat.completions.create.side_effect = lambda **kw: replies.pop(0)@@ -285,11 +293,27 @@ def test_side_request_fires_auxiliary_hooks_not_turn_request_hooks(monkeypatch):parent._cached_system_prompt = "You are helpful."parent.skip_background_review = Trueparent.run_conversation("what is the answer?")-- rows = [json.loads(line) for line in events.read_text().splitlines()]+ side_question_lease._leases.clear()assert replies == [] # the side request was sent+ return [json.loads(line) for line in events.read_text().splitlines()]+++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'``."""+ usage = SimpleNamespace(prompt_tokens=900, completion_tokens=7, total_tokens=907)+ rows = _observed_turn_with_side_question(monkeypatch, SimpleNamespace(+ choices=[SimpleNamespace(message=SimpleNamespace(content="Ask why it is 42.", tool_calls=None),+ finish_reason="stop")], model="test/model", usage=usage))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()+ assert rows[3]["usage"]["output_tokens"] == 7 and rows[3]["error_type"] is None+++def test_unreadable_side_reply_still_closes_the_auxiliary_pair(monkeypatch):+ """A reply that fails after the provider returned (no choices) reports its error in+ ``post_auxiliary_call`` instead of leaving the observer's request open."""+ rows = _observed_turn_with_side_question(monkeypatch, SimpleNamespace(choices=[], model="test/model", usage=None))+ assert [r["event"] for r in rows][-2:] == ["pre_auxiliary_call", "post_auxiliary_call"]+ assert rows[-1]["error_type"]diff --git a/tests/agent/test_side_question_request.py b/tests/agent/test_side_question_request.pyindex 612f858cb60..75cc2de626e 100644--- a/tests/agent/test_side_question_request.py+++ b/tests/agent/test_side_question_request.py@@ -374,6 +374,17 @@ def test_agent_as_provider_is_refused(provider, issued):assert len(provider.requests) == sent+def test_runtime_changed_since_the_turn_is_refused(provider, issued):+ """A turn routed to another model (voice chat) restores the main runtime after+ ``post_llm_call``: the captured prompt must never go out on a different model."""+ parent = _make_parent()+ _run_parent_turn(parent, provider, tool_round=False)+ parent.model = "other/model"+ 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)@@ -399,6 +410,9 @@ def test_server_side_tool_in_final_request_is_refused(provider, issued, monkeypa({"extra_body": {"plugins": [{"id": "pareto-router", "min_coding_score": 0.5}]}}, False),({"extra_body": {"plugins": [{"id": "web"}]}}, True),({"web_search_options": {}}, True),+ # request_overrides land in extra_body, whose ``tools`` the SDK merge sends over the top level.+ ({"extra_body": {"tools": [{"type": "web_search"}]}}, True),+ ({"extra_body": {"tools": [{"type": "function", "function": {"name": "x"}}]}}, False),])def test_server_side_tool_predicate(api_kwargs, server_side):from agent.side_question_request import has_server_side_toolsdiff --git a/website/docs/developer-guide/plugin-llm-access.md b/website/docs/developer-guide/plugin-llm-access.mdindex 11081bcac2f..82e7f235206 100644--- a/website/docs/developer-guide/plugin-llm-access.md+++ b/website/docs/developer-guide/plugin-llm-access.md@@ -583,8 +583,10 @@ capabilities:The text of the agent's reply, or `None`. `None` means the call wasrefused or failed: a Mixture-of-Agents runtime, an agent-as-providerruntime (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+session whose model changed since the turn (a voice-chat turn routed to+`auxiliary.voice_chat` switches back right after it), a request that+carries provider-executed (server-side) tools, a timeout, a provider+error, or an empty reply. There are no retriesand no fallback model.The call never runs a tool (tool calls in the reply are dropped) and