The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into feat/hermes-relay-shared-metrics
Alex Fournier45580cc93ae5
diff --cc agent/auxiliary_client.pyindex bb64d16810e,74ccd578129..b31d90e7880--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@@ -51,10 -50,9 +51,10 @@@ import oimport reimport threadingimport time+import uuidfrom pathlib import Path # noqa: F401 — used by test mocksfrom types import SimpleNamespace--from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING++from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKINGfrom urllib.parse import urlparse, parse_qs, urlunparse# NOTE: `from openai import OpenAI` is deliberately NOT at module top — the@@@ -2393,163 -2463,6 +2465,167 @@@ _RUNTIME_MAIN_AUTH_MODE: str = "_RUNTIME_MAIN_CONTEXT: contextvars.ContextVar[Optional[Dict[str, Any]]] = (contextvars.ContextVar("auxiliary_runtime_main", default=None))++_RELAY_AUX_CALL_CONTEXT: contextvars.ContextVar[Optional[Dict[str, Any]]] = (+ contextvars.ContextVar("auxiliary_relay_call", default=None)+)+++def _relay_auxiliary_call(callback):+ """Give every physical retry in one auxiliary call a shared Relay identity."""++ @functools.wraps(callback)+ def wrapped(*args, **kwargs):+ task = args[0] if args else kwargs.get("task")+ token = _RELAY_AUX_CALL_CONTEXT.set({+ "task": str(task or "unknown"),+ "request_id": f"aux-{uuid.uuid4().hex}",+ "attempt_count": 0,+ "provider": "",+ "model": "",+ "api_mode": "chat_completions",+ })+ try:+ return callback(*args, **kwargs)+ except BaseException:+ _fail_relay_auxiliary_call()+ raise+ finally:+ _RELAY_AUX_CALL_CONTEXT.reset(token)++ return wrapped+++def _relay_auxiliary_call_async(callback):+ """Async counterpart to :func:`_relay_auxiliary_call`."""++ @functools.wraps(callback)+ async def wrapped(*args, **kwargs):+ task = args[0] if args else kwargs.get("task")+ token = _RELAY_AUX_CALL_CONTEXT.set({+ "task": str(task or "unknown"),+ "request_id": f"aux-{uuid.uuid4().hex}",+ "attempt_count": 0,+ "provider": "",+ "model": "",+ "api_mode": "chat_completions",+ })+ try:+ return await callback(*args, **kwargs)+ except BaseException:+ _fail_relay_auxiliary_call()+ raise+ finally:+ _RELAY_AUX_CALL_CONTEXT.reset(token)++ return wrapped+++def _set_relay_auxiliary_route(+ provider: str | None,+ model: str | None,+ api_mode: str | None,+) -> None:+ context = _RELAY_AUX_CALL_CONTEXT.get()+ if context is None:+ return+ context["provider"] = str(provider or "auxiliary")+ context["model"] = str(model or "unknown")+ context["api_mode"] = str(api_mode or "chat_completions")+++def _relay_auxiliary_metadata(+ *,+ provider: str | None = None,+ api_mode: str | None = None,+) -> tuple[str, str, dict[str, Any]] | None:+ context = _RELAY_AUX_CALL_CONTEXT.get()+ if context is None:+ return None+ attempt_count = int(context.get("attempt_count") or 0)+ context["attempt_count"] = attempt_count + 1+ provider_name = str(provider or context.get("provider") or "auxiliary")+ model_name = str(context.get("model") or "unknown")+ return provider_name, model_name, {+ "api_mode": str(api_mode or context.get("api_mode") or "chat_completions"),+ "api_request_id": str(context["request_id"]),+ "call_role": f"auxiliary:{context['task']}",+ "retry_count": attempt_count,+ "auxiliary_task": str(context["task"]),+ }+++def _relay_sync_completion(+ client: Any,+ kwargs: dict[str, Any],+ *,+ provider: str | None = None,+ api_mode: str | None = None,++ create: Callable[[dict[str, Any]], Any] | None = None,+) -> Any:++ callback = create or (lambda request: client.chat.completions.create(**request))+ route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode)+ if route is None:- return client.chat.completions.create(**kwargs)++ return callback(kwargs)+ provider_name, fallback_model, metadata = route+ from agent import relay_llm++ return relay_llm.execute_current(+ kwargs,- lambda request: client.chat.completions.create(**request),++ callback,+ name=provider_name,+ model_name=str(kwargs.get("model") or fallback_model),+ metadata=metadata,+ defer_logical_completion=True,+ )+++async def _relay_async_completion(+ client: Any,+ kwargs: dict[str, Any],+ *,+ provider: str | None = None,+ api_mode: str | None = None,++ create: Callable[[dict[str, Any]], Any] | None = None,+) -> Any:++ callback = create or (lambda request: client.chat.completions.create(**request))+ route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode)+ if route is None:- return await client.chat.completions.create(**kwargs)++ return await callback(kwargs)+ provider_name, fallback_model, metadata = route+ from agent import relay_llm++ return await relay_llm.execute_current_async(+ kwargs,- lambda request: client.chat.completions.create(**request),++ callback,+ name=provider_name,+ model_name=str(kwargs.get("model") or fallback_model),+ metadata=metadata,+ defer_logical_completion=True,+ )+++def _relay_sync_stream(+ client: Any,+ kwargs: dict[str, Any],+ *,+ provider: str | None = None,+ api_mode: str | None = None,+) -> Any:+ route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode)+ if route is None:+ return client.chat.completions.create(**kwargs)+ provider_name, fallback_model, metadata = route+ from agent import relay_llm++ return relay_llm.stream_current(+ kwargs,+ lambda request: client.chat.completions.create(**request),+ name=provider_name,+ model_name=str(kwargs.get("model") or fallback_model),+ finalizer=dict,+ metadata=metadata,+ )_RUNTIME_MAIN_COMPAT_SNAPSHOT: Tuple[Any, ...] = ("", "", "", "", "", "")_RUNTIME_MAIN_COMPAT_LOCK = threading.Lock()@@@ -4101,10 -4033,10 +4208,10 @@@ def _call_fallback_candidate_synctemperature=temperature, max_tokens=max_tokens,tools=tools, timeout=effective_timeout,extra_body=effective_extra_body, reasoning_config=reasoning_config,- base_url=fb_base)+ base_url=fb_base, task=task)try:return _validate_llm_response(- fb_client.chat.completions.create(**fb_kwargs), task)+ _relay_sync_completion(fb_client, fb_kwargs, provider=fb_label), task)except Exception as fb_err:if not _is_auth_error(fb_err):raise@@@ -4118,16 -4050,10 +4225,16 @@@tools=tools, timeout=effective_timeout,extra_body=effective_extra_body,reasoning_config=reasoning_config,- base_url=str(getattr(retry_client, "base_url", "") or fb_base))+ base_url=str(getattr(retry_client, "base_url", "") or fb_base), task=task)try:return _validate_llm_response(- retry_client.chat.completions.create(**retry_kwargs), task)+ _relay_sync_completion(+ retry_client,+ retry_kwargs,+ provider=fb_provider,+ ),+ task,+ )except Exception as retry_err:if not _is_auth_error(retry_err):raise@@@ -4173,16 -4099,10 +4280,16 @@@ async def _call_fallback_candidate_asyntemperature=temperature, max_tokens=max_tokens,tools=tools, timeout=effective_timeout,extra_body=effective_extra_body, reasoning_config=reasoning_config,- base_url=fb_base)+ base_url=fb_base, task=task)try:return _validate_llm_response(- await fb_client.chat.completions.create(**fb_kwargs), task)+ await _relay_async_completion(+ fb_client,+ fb_kwargs,+ provider=fb_label,+ ),+ task,+ )except Exception as fb_err:if not _is_auth_error(fb_err):raise@@@ -4197,16 -4117,10 +4304,16 @@@tools=tools, timeout=effective_timeout,extra_body=effective_extra_body,reasoning_config=reasoning_config,- base_url=str(getattr(retry_client, "base_url", "") or fb_base))+ base_url=str(getattr(retry_client, "base_url", "") or fb_base), task=task)try:return _validate_llm_response(- await retry_client.chat.completions.create(**retry_kwargs), task)+ await _relay_async_completion(+ retry_client,+ retry_kwargs,+ provider=fb_provider,+ ),+ task,+ )except Exception as retry_err:if not _is_auth_error(retry_err):raise@@@ -7266,7 -7176,346 +7395,347 @@@ def _obj_get(obj: Any, key: str, defaulreturn value+ # ── Streamed aggregation for progress-hooked auxiliary calls ─────────────+ # When a forward-progress hook is installed (aux_progress_hook — today only+ # by context compression), the primary chat.completions attempt is upgraded+ # to a streamed request that is aggregated back into a complete response.+ # Two effects, both deliberate:+ # 1. The configured ``timeout`` becomes an INTER-CHUNK idle timeout instead+ # of a total budget (httpx applies the read timeout per stream read), so+ # a slow-but-generating summary model is never killed mid-generation+ # while tokens are moving — only a genuinely silent connection dies.+ # 2. Every arriving chunk ticks the progress hook, letting outer watchdogs+ # (gateway session hygiene) extend their deadlines on liveness instead+ # of guessing with a fixed wall clock.+ # A total ceiling still bounds the pathological 1-token-per-idle-window+ # stream; see _aux_stream_total_ceiling().++ _AUX_STREAM_CEILING_FLOOR_SECONDS = 600.0+ _AUX_STREAM_CEILING_MULTIPLIER = 4.0+++ def _aux_stream_total_ceiling(effective_timeout: Optional[float]) -> float:+ """Absolute wall-clock bound for a progress-hooked streamed aux call.++ Generous by design — the idle timeout is the real guard; this only stops+ a degenerate stream that trickles one token per idle window forever.+ """+ try:+ timeout = float(effective_timeout) if effective_timeout is not None else 0.0+ except (TypeError, ValueError):+ timeout = 0.0+ return max(_AUX_STREAM_CEILING_FLOOR_SECONDS,+ _AUX_STREAM_CEILING_MULTIPLIER * timeout)+++ def _client_streams_internally(client: Any) -> bool:+ """Wire adapters that consume a stream inside .create() already tick the+ progress hook themselves (Codex per SSE event, Anthropic per stream+ event); Bedrock's Converse shim cannot stream at all. None of them+ accept chat-completions ``stream=True`` semantics from us."""+ return isinstance(client, (+ CodexAuxiliaryClient,+ AnthropicAuxiliaryClient,+ BedrockAuxiliaryClient,+ ))+++ def _is_streaming_rejected_error(exc: Exception) -> bool:+ """Provider explicitly refused a streamed chat.completions request."""+ err = str(exc).lower()+ if "stream_options" in err:+ return True+ return "stream" in err and (+ "not supported" in err+ or "unsupported" in err+ or "not allowed" in err+ or "disabled" in err+ )+++ def _provider_requires_stream(provider: str, base_url: Optional[str]) -> bool:+ """Detect providers that only accept streaming (non-stream = HTTP 400).++ Some OpenAI-compatible endpoints reject non-streaming chat requests+ outright — e.g. Tencent Copilot returns+ ``{"code": 11101, "msg": "Non-stream chat request is currently not+ supported"}``. The main conversation loop already streams, so interactive+ chat works; auxiliary tasks (title generation, compression, web extract)+ used the non-streaming path and failed on every call. When this returns+ True the auxiliary client sends ``stream=True`` and aggregates the chunks+ itself (see :func:`_aggregate_chat_stream`). Credit @kudi88 (PR #60686).++ Beyond the known-host list, users can mark ANY custom endpoint as+ stream-only via ``auxiliary.stream_only_base_urls`` in config.yaml+ (list of substrings matched against the endpoint URL).+ """+ _url = str(base_url or "").lower()+ if not _url:+ return False+ # Tencent Copilot — "Non-stream chat request is currently not supported"+ if base_url_host_matches(_url, "copilot.tencent.com"):+ return True+ try:+ from hermes_cli.config import load_config+ aux_cfg = (load_config() or {}).get("auxiliary", {})+ markers = aux_cfg.get("stream_only_base_urls") or []+ if isinstance(markers, (list, tuple)):+ for marker in markers:+ if isinstance(marker, str) and marker.strip() and marker.strip().lower() in _url:+ return True+ except Exception:+ # Config read is best-effort; never break an aux call over it.+ pass+ return False+++ def _create_with_progress(+ client: Any,+ kwargs: Dict[str, Any],+ task: Optional[str] = None,+ *,+ force_stream: bool = False,+ ) -> Any:+ """chat.completions.create() that streams when a progress hook is active+ or the provider only accepts streamed requests.++ Behavior is byte-for-byte identical to a plain ``create(**kwargs)`` when+ neither trigger applies (every existing caller/task) or when the client's+ wire adapter streams internally. With a hook + a chunk-capable client,+ the request is sent with ``stream=True`` and aggregated, ticking the hook+ per chunk — so the configured ``timeout`` acts per stream read (idle)+ rather than as a total budget, and outer liveness watchdogs see tokens+ moving. ``force_stream=True`` (stream-only providers such as Tencent+ Copilot — credit @kudi88, PR #60686) takes the same streamed path even+ without a hook. Providers that reject the streamed request fall back to+ the plain non-streaming call — except under ``force_stream``, where a+ stream-only provider rejects the plain call by definition, so the+ original error is surfaced to the normal recovery chains instead.+ """+ _notify_aux_progress() # request dispatched counts as progress+ if (not _aux_progress_active() and not force_stream) or _client_streams_internally(client):+ return client.chat.completions.create(**kwargs)++ total_ceiling = _aux_stream_total_ceiling(kwargs.get("timeout"))+ stream_kwargs = dict(kwargs)+ stream_kwargs["stream"] = True+ stream_kwargs["stream_options"] = {"include_usage": True}+ try:+ chunks = client.chat.completions.create(**stream_kwargs)+ except Exception as exc:+ # Genuine provider failures (auth, credit, rate limit, network) are+ # not streaming's fault — surface them unchanged so the existing+ # recovery chains (credential refresh, pool rotation, provider+ # fallback) see the same error they would on a plain call.+ if (+ force_stream+ or _is_transient_transport_error(exc)+ or _is_auth_error(exc)+ or _is_payment_error(exc)+ or _is_rate_limit_error(exc)+ ):+ raise+ # Anything else may be a streaming-specific rejection (explicit+ # "stream not supported", stream_options 400, or an idiosyncratic+ # 4xx). Retry non-streaming once; if the request itself is bad the+ # plain call reproduces the real error for the normal except-chains.+ logger.debug(+ "Auxiliary %s: streamed request failed (%s); retrying "+ "non-streaming", task or "call", exc,+ )+ return client.chat.completions.create(**kwargs)++ # Some shims (MoA virtual provider under quiet mode, defensive adapters)+ # return a complete response even when stream=True was requested.+ if hasattr(chunks, "choices"):+ _notify_aux_progress()+ return chunks+ return _aggregate_chat_stream(+ chunks, model=str(kwargs.get("model") or ""), total_ceiling=total_ceiling,+ )+++ def _aggregate_chat_stream(+ chunks: Any,+ *,+ model: str = "",+ total_ceiling: Optional[float] = None,+ ) -> Any:+ """Consume a chat.completions chunk stream into a complete response.++ Ticks the thread-local aux progress hook on every chunk. Raises+ TimeoutError when *total_ceiling* seconds elapse before the stream+ finishes — phrased with "timed out" so existing timeout classification+ (``_is_timeout_error``) treats it exactly like a request timeout.+ Accumulation is shared with the async mirror via+ :class:`_ChatStreamAccumulator`.+ """+ acc = _ChatStreamAccumulator(model=model, total_ceiling=total_ceiling)+ try:+ for chunk in chunks:+ acc.feed(chunk)+ finally:+ close_fn = getattr(chunks, "close", None)+ if callable(close_fn):+ try:+ close_fn()+ except Exception:+ pass+ return acc.finish()+++ class _ChatStreamAccumulator:+ """Shared per-chunk accumulation for sync and async stream aggregation.++ Mirrors :func:`_aggregate_chat_stream`'s chunk handling so the async+ consumer below cannot drift from the sync one (same content/reasoning/+ tool-call delta reassembly, same "timed out" ceiling phrasing).+ """++ def __init__(self, model: str = "", total_ceiling: Optional[float] = None):+ self._started = time.monotonic()+ self._total_ceiling = total_ceiling+ self.content_parts: List[str] = []+ self.reasoning_parts: List[str] = []+ self.tool_calls_acc: Dict[int, Dict[str, Any]] = {}+ self.finish_reason = None+ self.usage = None+ self.resp_id = ""+ self.resp_model = model or ""++ def feed(self, chunk: Any) -> None:+ _notify_aux_progress()+ if (+ self._total_ceiling is not None+ and (time.monotonic() - self._started) >= self._total_ceiling+ ):+ raise TimeoutError(+ f"Auxiliary streamed call timed out after {self._total_ceiling:.0f}s "+ "total ceiling (stream still open but over budget)"+ )+ self.resp_id = getattr(chunk, "id", None) or self.resp_id+ self.resp_model = getattr(chunk, "model", None) or self.resp_model+ chunk_usage = getattr(chunk, "usage", None)+ if chunk_usage:+ self.usage = chunk_usage+ choices = getattr(chunk, "choices", None) or []+ if not choices:+ return+ choice = choices[0]+ self.finish_reason = getattr(choice, "finish_reason", None) or self.finish_reason+ delta = getattr(choice, "delta", None)+ if delta is None:+ return+ piece = getattr(delta, "content", None)+ if piece:+ self.content_parts.append(piece)+ reasoning_piece = (+ getattr(delta, "reasoning", None)+ or getattr(delta, "reasoning_content", None)+ )+ if reasoning_piece and isinstance(reasoning_piece, str):+ self.reasoning_parts.append(reasoning_piece)+ for tc in (getattr(delta, "tool_calls", None) or []):+ idx = getattr(tc, "index", 0) or 0+ acc = self.tool_calls_acc.setdefault(+ idx, {"id": "", "name": "", "arguments": []}+ )+ if getattr(tc, "id", None):+ acc["id"] = tc.id+ fn = getattr(tc, "function", None)+ if fn is not None:+ if getattr(fn, "name", None):+ acc["name"] = fn.name+ if getattr(fn, "arguments", None):+ acc["arguments"].append(fn.arguments)++ def finish(self) -> Any:+ tool_calls = None+ if self.tool_calls_acc:+ tool_calls = [+ SimpleNamespace(+ id=acc["id"],+ type="function",+ function=SimpleNamespace(+ name=acc["name"],+ arguments="".join(acc["arguments"]),+ ),+ )+ for _idx, acc in sorted(self.tool_calls_acc.items())+ ]+ message = SimpleNamespace(+ role="assistant",+ content="".join(self.content_parts),+ tool_calls=tool_calls,+ reasoning="".join(self.reasoning_parts) or None,+ )+ choice = SimpleNamespace(+ index=0,+ message=message,+ finish_reason=self.finish_reason or "stop",+ )+ return SimpleNamespace(+ id=self.resp_id,+ model=self.resp_model,+ object="chat.completion",+ choices=[choice],+ usage=self.usage,+ )+++ async def _aggregate_chat_stream_async(+ chunks: Any,+ *,+ model: str = "",+ total_ceiling: Optional[float] = None,+ ) -> Any:+ """Async mirror of :func:`_aggregate_chat_stream` (``async for`` consumer).++ The AsyncOpenAI stream contract is an async iterator — consuming it with+ the sync helper raises. Same accumulation and ceiling semantics via+ :class:`_ChatStreamAccumulator`.+ """+ acc = _ChatStreamAccumulator(model=model, total_ceiling=total_ceiling)+ try:+ async for chunk in chunks:+ acc.feed(chunk)+ finally:+ close_fn = getattr(chunks, "close", None) or getattr(chunks, "aclose", None)+ if callable(close_fn):+ try:+ result = close_fn()+ if inspect.isawaitable(result):+ await result+ except Exception:+ pass+ return acc.finish()+++ async def _acreate_with_stream(+ client: Any,+ kwargs: Dict[str, Any],+ task: Optional[str] = None,+ ) -> Any:+ """Async chat.completions.create() for stream-only providers.++ Sends ``stream=True`` and aggregates the async chunk stream into a+ complete response (credit @kudi88, PR #60686 — async contract fixed to+ ``async for`` and tool-call deltas preserved per sweeper review).+ """+ total_ceiling = _aux_stream_total_ceiling(kwargs.get("timeout"))+ stream_kwargs = dict(kwargs)+ stream_kwargs["stream"] = True+ stream_kwargs["stream_options"] = {"include_usage": True}+ chunks = await client.chat.completions.create(**stream_kwargs)+ # Defensive: shims may hand back a complete response despite stream=True.+ if hasattr(chunks, "choices"):+ return chunks+ return await _aggregate_chat_stream_async(+ chunks, model=str(kwargs.get("model") or ""), total_ceiling=total_ceiling,+ )+++@_relay_auxiliary_calldef call_llm(task: str = None,*,@@@ -7471,12 -7716,13 +7946,21 @@@# for the transient retry every auxiliary task shares. (PR #16587)try:return _validate_llm_response(- _create_with_progress(- client, kwargs, task,- force_stream=_provider_requires_stream(- resolved_provider, _base_info or resolved_base_url,+ _relay_sync_completion(+ client,+ kwargs,+ provider=resolved_provider,+ api_mode=resolved_api_mode,- ), task,++ create=lambda request: _create_with_progress(++ client,++ request,++ task,++ force_stream=_provider_requires_stream(++ resolved_provider, _base_info or resolved_base_url,++ ),+ ),+ ),+ task,provider=resolved_provider, base_url=_base_info)except Exception as transient_err:if not _is_transient_transport_error(transient_err):@@@ -7509,12 -7755,13 +7993,22 @@@time.sleep(_backoff)try:return _validate_llm_response(- _create_with_progress(- client, kwargs, task,- force_stream=_provider_requires_stream(- resolved_provider, _base_info or resolved_base_url,+ _relay_sync_completion(+ client,+ kwargs,+ provider=resolved_provider,+ api_mode=resolved_api_mode,- ), task)++ create=lambda request: _create_with_progress(++ client,++ request,++ task,++ force_stream=_provider_requires_stream(++ resolved_provider,++ _base_info or resolved_base_url,++ ),+ ),+ ),+ task)except Exception as retry_transient:if not _is_transient_transport_error(retry_transient):raise@@@ -8101,14 -8314,25 +8597,32 @@@ async def async_call_llm# Retry ONCE on the same provider for a transient transport blip# before the except-chain escalates to fallback — see call_llm()# for the rationale. (PR #16587)+ _force_stream_async = (+ _provider_requires_stream(+ resolved_provider, _client_base or resolved_base_url,+ )+ and not isinstance(client, (+ AsyncCodexAuxiliaryClient,+ AsyncAnthropicAuxiliaryClient,+ AsyncBedrockAuxiliaryClient,+ ))+ )++ async def _acreate(_kwargs: Dict[str, Any]) -> Any:+ if _force_stream_async:+ return await _acreate_with_stream(client, _kwargs, task)+ return await client.chat.completions.create(**_kwargs)+try:return _validate_llm_response(- await _acreate(kwargs), task,+ await _relay_async_completion(+ client,+ kwargs,+ provider=resolved_provider,+ api_mode=resolved_api_mode,- ), task,++ create=_acreate,++ ),++ task,provider=resolved_provider, base_url=_client_base)except Exception as transient_err:if not _is_transient_transport_error(transient_err):@@@ -8129,12 -8353,7 +8643,14 @@@task or "call", transient_err,)return _validate_llm_response(- await _acreate(kwargs), task)+ await _relay_async_completion(+ client,+ kwargs,+ provider=resolved_provider,+ api_mode=resolved_api_mode,- ), task)++ create=_acreate,++ ),++ task)except Exception as first_err:if "temperature" in kwargs and _is_unsupported_temperature_error(first_err):retry_kwargs = dict(kwargs)diff --cc agent/chat_completion_helpers.pyindex 409df6604a6,3689b4d5be8..15161ea11d4--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@@ -2844,60 -2881,7 +2951,64 @@@ def interruptible_streaming_api_call(ag"(model=%s).",api_kwargs.get("model", "unknown"),)- break+ return False+ # Record provider activity before Relay processes the chunk. This+ # prevents the stale watchdog from cancelling a live stream while+ # an interceptor or codec is still handling an already-received+ # event.+ last_chunk_time["t"] = time.time()+ return True++ def _relay_final_response() -> dict[str, Any]:+ tool_calls = [tool_calls_acc[index] for index in sorted(tool_calls_acc)]+ return {+ "model": model_name,+ "choices": [+ {+ "message": {+ "role": role,+ "content": "".join(content_parts) or None,+ "reasoning_content": "".join(reasoning_parts) or None,+ "tool_calls": tool_calls or None,+ },+ "finish_reason": finish_reason or "stop",+ }+ ],+ "usage": usage_obj,+ }++ from agent import relay_llm++ stream = _set_managed_stream(+ relay_llm.stream(+ api_kwargs,+ _open_stream,+ session_id=str(getattr(agent, "session_id", "") or ""),+ name=str(getattr(agent, "provider", "") or "provider"),+ model_name=str(getattr(agent, "model", "") or ""),+ finalizer=_relay_final_response,+ on_stream_created=_stream_created,+ accept_chunk=_accept_stream_chunk,+ completed_response_predicate=lambda value: hasattr(value, "choices"),+ metadata={+ "api_mode": "chat_completions",+ "api_request_id": getattr(agent, "_current_api_request_id", None),+ "call_role": (+ "delegated"+ if getattr(agent, "is_subagent", False)+ else "fallback"+ if int(getattr(agent, "_fallback_index", 0) or 0) > 0+ else "primary"+ ),+ },+ defer_logical_completion=True,+ )+ )++ if agent.provider == "moa":++ # Hermes interrupts the managed stream; Relay retains sole++ # ownership of closing the underlying provider stream.++ _set_request_stream_handle(stream)+ for chunk in stream:last_chunk_time["t"] = time.time()agent._touch_activity("receiving stream response")