
    epjŹ             '       ,0   U d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlmZ ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZmZmZ erddlm Z  da!ee"         e#d<   d	e"fd
Z$ G d d          Z% e%            Z ddl&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4  ej5        e6          Z7 e8            Z9e8e#d<    e8            Z:e8e#d<    e8            Z;e8e#d<    e8            Z<e8e#d<   dee=         d	efdZ>da?dddee=         de@d	ee=ef         fdZAde=de=ded	efdZB ejC                    ZD G d d eE          ZFd	e@fd!ZGd	e@fd"ZHejI        	 	 	 dd$e@fd%            ZJd	eeg ef                  fd&ZKd'eg ef         d	e@fd(ZL G d) d*          ZM ejC                    ZNdd+ZOd	e@fd,ZPejI        d-             ZQd.eeRe=ef         gef         deRe=ef         d	efd/ZSd0ed1ed	e@fd2ZTd3e=fd4ZUdaVi d5d6d7d6d8d6d9d:d;d:d<d:d=d>d?d>d@d>dAd>dBdCdDdCdEdFdGdFdHdIdJdIdKdLdLdMdMdNdNdNdNdOdOdPdPdPdPdQZWdRee=         d	e=fdSZX eY            ZZeYe#dT<   dUee=         d	e@fdVZ[dUee=         d	e@fdWZ\dXZ]dYZ^ddUee=         dRee=         d	e@fdZZ_ddUee=         dRee=         d	e@fd[Z`	 ddUee=         dee=         d	d\fd]Za	 dd#d^dUee=         dRee=         d_e@d	eeb         fd`Zcdae=d	e=fdbZddcdddedfdedgdhdidjdkdldmdndoZeee=e=f         e#dp<   eeZfee=e=f         e#dq<   drdsdtZgee=e=f         e#du<   dRe=d	ee=         fdvZh eidCdFh          Zjeie#dw<   dxdydzd{Zk eih d|          Zld}eRdz  d	eRdz  fd~ZmddeRdz  d	eRfdZnddiZode=dz  d	eRfdZpddlqmrZs dxdydes dZtddlumvZw d	eRfdZx ex            Zydaze@e#d<   dlZ{dlZ|dZ}dZ~ e,            dz  ZdZde=d	ee=e=f         fdZde=d	e=fdZdRe=d	ee@ee         f         fdZdRe=d	ee         fdZded	e=fdZddede=d	e=fdZ eidh          Zd3e=d	e@fdZd	efdZde=d	e=fdZ G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Z G d d          Zde=d	e@fdZ	 ddedUe=de=de=dee=         d	efdĄZd	eeR         fdńZdReRd	e=fdƄZd	e=fdǄZddȜde@d	eee=e=f                  fdʄZddȜde@d	eee=e=f                  fd˄Zd	eee=e=f                  fd̄Zd	ee=         fd̈́Zd	eee          ee=         f         fd΄Z e8            Ze8e#d<   dUee=         d	e@fdЄZd	ee@e=f         fdфZdUe=d	dfd҄Zdde=dUe=d	eee          ee=         f         fdԄZd	e=fdՄZdde@d	eee          ee=         f         fdׄZde@dee=         d	ee=         fdلZd	e=fdڄZd	e=fdۄZd	e=fd܄Zd	e=fd݄Zdee=         d	eee=         ee=         f         fd߄Zd	e=fdZde=d	e=fdZdae=e#d<   dae=e#d<   dae=e#d<   daee#d<   dae=e#d<   dae=e#d<    ej        dd          Zej        eee=ef                           e#d<    ej        dd          Zej        eee=ef                           e#d<   d Zd ZdRe=dz  dUe=dz  de=dz  d	dfdZddddRe=dz  de=dz  d	ee=e=eRe=ef         f         dz  fdZdddddedeRe=ef         dRe=dz  de=dz  deeRe=ef         gef         dz  d	efdZdddddedeRe=ef         dRe=dz  de=dz  deeRe=ef         gef         dz  d	efdZddddedeRe=ef         dRe=dz  de=dz  d	ef
dZdaeedf         e#d<    ej                    Zd	eee=ef                  fdZde=d	efdZdddddddRe=dUe=d e=de=dede=de=d	ej        fdZΐdej        d	dfdZejI        deee=ef                  fd            ZАddZd	eee=         ee=         ee=         f         fdZd	e=fd	ZӐdd
Zde=d	dfdZd	eee         ee=         f         fdZdUe=d	eee         ee=         f         fdZdUe=d	eee         ee=         f         fdZddddddUee=         dee=         dee=         dee=         d	eee         ee=         f         f
dZِdde=d	eee         ee=         f         fdZڐdddddZېdZeܐdz   Zݐdeee=ef                  d	ee=ef         fdZd	ee         fdZߐdZi Zee=ebf         e#d<   i Zee=ebf         e#d<   ddddddd ZdRe=d	e=fd!ZddRe=d"eeb         d	dfd#Zd$e=d	e@fd%Zdd$e=d&ee=         d	dfd'Zdd(Zd)ed	e@fd*Zd	e@fd+Zd)ed	e@fd,Zd)ed	e@fd-Zd)ed	e@fd.Zd)ed	e@fd/Zd0Zd1Zd	efd2Zd)ed	e@fd3Zd)ed4e=d	e@fd5Zd)ed	e@fd6Zd)ed	e@fd7Zd)ed	e@fd8Zd)ed	e@fd9ZdRe=d	dfd:Zd;ed	e@fd<Zdd=dRe=deee=ef                  d	e=fd>Zd)ed	ee=ef         fd?Z	 dd@e=dedeee=ef                  d	ee=         fdAZddBdRe=d)edCe=d	e@fdDZddEd&ee=         d@e=dFee=         dGee=         dHee=         dIee=         deee=ef                  dJee=         dKedLeeb         dMee         dNee         dOebdPeRdQeeR         dReee=e=f                  d	ef"dSZ ddEd&ee=         d@e=dFee=         dGee=         dHee=         dIee=         dJee=         dKedLeeb         dMee         dNee         dOebdPeRdQeeR         dReee=e=f                  d	ef dTZdRe=d	e@fdUZd@ee=         dVe=d	e=fdWZd&ee=         dXe=d	eee=ef                  fdYZd&ee=         dXe=d	eeb         fdZZd$e=d	e=fd[Z G d\ d]e          ZdRe=de=dee=         dUee=         d	ef
d^Zdee=ef         d_ed`ee=         d	efdaZ	d&ee=         d_ed`ee=         dXe=d	ef
dbZ
dKedNee         dced	eeef         fddZd_ed`ee=         dXe=d&ee=         dKedLeeb         dMee         dNee         dOebdPeRdQeeR         d	ee         fdeZd_ed`ee=         dXe=d&ee=         dKedLeeb         dMee         dNee         dOebdPeRdQeeR         d	ee         fdfZ	 	 ddhe=d&e=die=d	eee         ee=         e=f         fdjZ	 	 	 ddhe=d&e=die=dlee=         d	eee         ee=         e=f         f
dmZd&ee=         d	ee         fdnZ	 	 ddRe=dUe=de=de=d	ee         f
doZ	 	 dd&e=dhe=die=dlee=         d	eee         ee=         e=f         f
dpZd&ee=         dhe=d	eee         ee=         e=f         fdqZdee=ef         d	ee=         fdrZdee=ef         d	eee         ee=         f         fdsZ	 	 dd&ee=         dhe=die=d	eee         ee=         e=f         fdtZ	 	 	 ddRe=dUee=         dee=         dee=         d	ee         f
duZ	 	 ddeee=ef                  d&ee=         d	eee          ee=         f         fdvZddUe=dwe@fdxZdyee=         dRe=d	ee=         fdzZ	 	 	 	 	 	 	 	 	 ddRe=dUe=de@d{e@de=de=de=deee=ef                  dwe@d&ee=         d	eee         ee=         f         fd|Z	 ddd=d&e=deee=ef                  d	eee          ee=         f         fd}Zddd=d&e=deee=ef                  fd~ZdZdRe=dUee=         d	e@fdZdRee=         d	e=fdZ 	 ddRe=dUee=         d	eee         ee=         f         fdZ!dRe=d	e@fdZ"d	ee=         fdZ#	 	 dddddddRee=         dUee=         dee=         dee=         de@deee=ef                  d	eee=         ee         ee=         f         fdZ$d	eRfdZ%dddedUee=         d	eRfdZ&i Z'eeef         e#d<    ej                    Z(dZ) G d d          Z*de=ded	efdZ+dddddddddRe=de@dee=         dee=         dee=         deee=ef                  dwe@d&ee=         dUee=         d	efdZ,dddededee=         ded	df
dZ-ddddddde=dUee=         de@dee=         dee=         dee=         deee=ef                  dwe@d	eee         ee=         f         fdZ.ddZ/ded	dfdZ0ded	dfdZ1ddZ2ddZ3ded	e@fdZ4dedee=         d	e@fdZ5dedUee=         dee=         d	ee=         fdZ6	 	 	 	 	 	 	 	 ddRe=dUe=de@de=de=de=deee=ef                  dwe@d&ee=         d	eee         ee=         f         fdZ7ddiZ8ee=e=f         e#d<   	 	 	 	 	 dd&e=dRe=dUe=dee=         dee=         d	ee=ee=         ee=         ee=         ee=         f         fdZ9dZ:dZ;d&e=d	ee=ef         fdZ<e:fd&e=debd	ebfdZ=d&e=deeb         d	ebfdZ>d&e=d	ee=ef         fdZ?i Z@ee=eeejA        f         f         e#d<   i ZBeee=ef         eeef         f         e#d<    ej                    ZCd&ee=         d	ee         fdZDd&ee=         d	eejA                 fdZEd&ee=         fdZFddZG eih d          ZHdRe=de=d	e@fdZIdKed	efdZJh dZKded	e@fdZL	 	 	 	 	 	 	 	 ddRe=dUe=dKedLeeb         dMee         dNee         debdeeR         dQeeR         dee=         d&ee=         d	eRfdZM	 	 	 dded&ee=         dRee=         dee=         d	ef
dZNddde=d	dfdZOddÄZPded	ee         fdĄZQded	e=fdńZRdd0ede=ded	efdǄZSdȐZTdɐZUdOeeb         d	ebfdʄZVded	e@fd˄ZWd)ed	e@fd̄ZXdRe=dee=         d	e@fd̈́ZY	 dddΜdedee=ef         d&ee=         de@d	ef
dЄZZdddќdedUe=deeb         d	efdԄZ[ G dՄ d֦          Z\dddќdedUe=deeb         d	efdׄZ]	 ddedee=ef         d&ee=         d	efd؄Z^e	 dddddddddddddddddٜd&e=dRe=dUe=de=de=deee=ef                  dKedLeeb         dMedNedebdeRdQeeR         dReee=e=f                  de=de@deRd	ef$d܄            Z_dedejA        fdބZ`	 dddddddddddddddddٜd&e=dRe=dUe=de=de=deee=ef                  dKedLeeb         dMedNedebdeRdQeeR         dReee=e=f                  de=de@deRd	ef$d߄Zad	e=fdZbe	 dddddddddddddd&e=dRe=dUe=de=de=deee=ef                  dKedLeeb         dMedNedebdeRdQeeR         d	efd            Zc	 dddddddddddddd&e=dRe=dUe=de=de=deee=ef                  dKedLeeb         dMedNedebdeRdQeeR         d	efdZddS (  u  Shared auxiliary client router for side tasks.

Provides a single resolution chain so every consumer (context compression,
session search, web extraction, vision analysis, browser vision) picks up
the best available backend without duplicating fallback logic.

Resolution order for text tasks (auto mode):
  1. User's main provider + main model (used regardless of provider type —
     aggregators, direct API-key providers, native Anthropic, Codex, etc.)
  2. OpenRouter  (OPENROUTER_API_KEY)
  3. Nous Portal (~/.hermes/auth.json active provider)
  4. Custom endpoint (config.yaml model.base_url + OPENAI_API_KEY)
  5. Native Anthropic
  6. Direct API-key providers (z.ai/GLM, Kimi/Moonshot, MiniMax, MiniMax-CN)
  7. None

OpenRouter fallback cost guard: ``auxiliary.free_only: true`` restricts the
step-2 fallback to ``:free`` SKUs; ``auxiliary.openrouter_model`` overrides
the default. A one-time WARNING is logged for non-``:free`` models.

Resolution order for vision/multimodal tasks (auto mode):
  1. Selected main provider, if it is one of the supported vision backends below
  2. OpenRouter
  3. Nous Portal
  4. Native Anthropic
  5. Custom endpoint (for local vision models: Qwen-VL, LLaVA, Pixtral, etc.)
  6. None

Codex OAuth (ChatGPT-account auth) is intentionally NOT in either
fallback chain: OpenAI gates this endpoint behind an undocumented,
shifting model allow-list, so "just try Codex with a hardcoded model"
rots on its own.  Codex is used only when the user's main provider *is*
openai-codex (Step 1 above) or when a caller explicitly requests it with
a model (auxiliary.<task>.provider + auxiliary.<task>.model).

Per-task overrides are configured in config.yaml under the ``auxiliary:`` section
(e.g. ``auxiliary.vision.provider``, ``auxiliary.compression.model``).
Default "auto" follows the chains above.

Payment / credit exhaustion fallback:
  When a resolved provider returns HTTP 402 or a credit-related error,
  call_llm() automatically retries with the next available provider in the
  auto-detection chain.  This handles the common case where a user depletes
  their OpenRouter balance but has Codex OAuth or another provider available.
    N)Path)SimpleNamespace)AnyCallableDictList
NamedTupleOptionalTupleTYPE_CHECKING)urlparseparse_qs
urlunparseOpenAI_OPENAI_CLS_CACHEreturnc                  .    t           ddlm}  | a t           S )z#Import and cache ``openai.OpenAI``.Nr   r   )r   openair   )_clss    </home/thesage/.hermes/hermes-agent/agent/auxiliary_client.py_load_openai_clsr   T   s(      ))))))     c                   (    e Zd ZdZdZd Zd Zd ZdS )_OpenAIProxyzModule-level proxy that looks like the ``openai.OpenAI`` class.

    Forwards ``OpenAI(...)`` calls and ``isinstance(x, OpenAI)`` checks to the
    real SDK class, importing the SDK lazily on first use.
     c                 *     t                      |i |S N)r   )selfargskwargss      r   __call__z_OpenAIProxy.__call__f   s    !!!426222r   c                 :    t          |t                                S r   )
isinstancer   )r   objs     r   __instancecheck__z_OpenAIProxy.__instancecheck__i   s    #/11222r   c                     dS )Nz<lazy openai.OpenAI proxy>r   r   s    r   __repr__z_OpenAIProxy.__repr__l   s    ++r   N)__name__
__module____qualname____doc__	__slots__r"   r&   r)   r   r   r   r   r   ]   sR          I3 3 33 3 3, , , , ,r   r   )	load_pool)MINIMUM_CONTEXT_LENGTHget_model_context_length)get_hermes_home)OPENROUTER_BASE_URL)base_url_host_matchesbase_url_hostname	env_float"model_forces_max_completion_tokensnormalize_proxy_env_vars_LOGGED_UNKNOWN_PROVIDER_KEYS_LOGGED_UNHANDLED_AUTHTYPE_KEYS _LOGGED_UNSUPPORTED_EXTPROC_KEYS_LOGGED_UNSUPPORTED_OAUTH_KEYSbase_urlc                    	 ddl m} ddlm}m}  |t          | pd           |                      } ||                    d          |                    d          t          | pd                    S # t          $ r Y d	S w xY w)
a  Resolve httpx ``verify`` for an auxiliary-client base_url.

    Mirrors the main client's TLS resolution so auxiliary calls (compression,
    vision, web_extract, title generation, etc.) honor per-provider
    ``ssl_ca_cert`` / ``ssl_verify`` config and the ``HERMES_CA_BUNDLE`` /
    ``SSL_CERT_FILE`` env conventions. Best-effort: any failure falls back to
    the httpx/certifi default (``True``).
    r   )resolve_httpx_verify) get_custom_provider_tls_settingsload_config_readonly )configssl_ca_cert
ssl_verify)	ca_bundlerE   r=   T)agent.ssl_verifyr?   hermes_cli.configr@   rA   strget	Exception)r=   r?   r@   rA   tlss        r   _resolve_aux_verifyrM      s    999999	
 	
 	
 	
 	
 	
 	
 	

 /.B(<(<(>(>
 
 
 $#ggm,,ww|,,R((
 
 
 	

    tts   A4A7 7
BBF
async_moderO   c                    	 ddl m}  |t          | pd          |t          |                     }n<# t          t
          f$ r( t          sdat                              d           d}Y nw xY w|i S d|iS )	zKInject keepalive httpx client with env-only proxy (not macOS system proxy).r   )build_keepalive_http_clientrB   )rO   verifyTu   agent.process_bootstrap.build_keepalive_http_client is unavailable — mixed/stale install detected (#64333). Falling back to the SDK default HTTP client. Run `hermes update` (or reinstall the Desktop app) to resync the runtime.Nhttp_client)	agent.process_bootstraprQ   rI   rM   ImportErrorAttributeError_WARNED_KEEPALIVE_IMPORT_SKEWloggerwarning)r=   rO   rQ   clients       r   _openai_http_client_kwargsr[      s    GGGGGG,,B!&x00
 
 

 (    - 	,0)NND   '* ~	6""s   03 6A,+A,api_keyr!   c                 r    i t          |          |}|                    dd           t          d| |d|S )Nmax_retriesr   r\   r=   r   )r[   
setdefaultr   )r\   r=   r!   s      r   _create_openai_clientra      sM    ?*844??F mQ'''?'H?????r   c                   (     e Zd ZdZdZd fdZ xZS )AuxiliaryExplicitCancellationa  Frozen signal that an auxiliary attempt was explicitly hard-cancelled.

    This deliberately follows ``asyncio.CancelledError`` and inherits directly
    from ``BaseException``: provider retry/fallback code catches ``Exception``
    broadly and must never reinterpret an explicit host stop as a transport
    failure. ``cause`` is immutable class data so downstream compression code
    does not re-query a mutable host Event after the transport has unwound.
    explicit_host_cancelr   Nc                 J    t                                          d           d S )Nz.auxiliary request explicitly cancelled by host)super__init__)r   	__class__s    r   rg   z&AuxiliaryExplicitCancellation.__init__   s"    IJJJJJr   r   N)r*   r+   r,   r-   causerg   __classcell__)rh   s   @r   rc   rc      sX          #EK K K K K K K K K Kr   rc   c                  H    t          t          t          dd                    S )NactiveF)boolgetattr_aux_interrupt_protectionr   r   r   _aux_interrupt_protectedrq      s    18UCCDDDr   c                     t          t          dd          } | O	 t          |                                           S # t          $ r  t
                              dd           Y dS w xY wt          t          dd          }t          |          sdS 	 t           |                      S # t          $ r  t
                              dd           Y dS w xY w)	z@Return whether an explicit host cancel overrides aux protection.cancel_eventNz'aux interrupt cancel event check failedTexc_infoFcancel_checkz!aux interrupt cancel check failed)ro   rp   rn   is_setrK   rX   debugcallable)eventchecks     r   _aux_interrupt_cancel_requestedr|     s    -~tDDE	''' 	 	 	LLBTLRRR55	 -~tDDEE?? uEEGG}}   84HHHuus!    ; &A%$A%B' '&CCTrm   c              #     K   t          t          dd          }t          t          dd          }t          t          dd          }| t          _        t          |          r|t          _        |*t          t          |dd                    r|t          _        	 dV  |t          _        |t          _        |t          _        dS # |t          _        |t          _        |t          _        w xY w)a  Mark the current thread's auxiliary LLM call as interrupt-protected.

    Used by atomic aux tasks (compression) so a mid-flight gateway interrupt
    doesn't abort the call and trigger a degraded fallback. Re-entrant-safe:
    restores the previous value on exit. ``cancel_check`` lets the host retain
    an explicit hard-cancel path; ``cancel_event`` is preferred when the host
    already owns an Event. Nested protection scopes inherit both values.
    rm   Frv   Nrs   rw   )ro   rp   rm   ry   rv   rs   )rm   rv   rs   prevprev_cancel_checkprev_cancel_events         r   aux_interrupt_protectionr     s       ,h>>D 9>4PP 9>4PP'-$ >1=!.HW\8T-R-R$S$S1=!.C+/!(1B!.1B!... ,0!(1B!.1B!.BBBBs   C &C)c                      t          t          dd          } t          | dd          }t          |          r|S t          t          dd          }t          |          r|S dS )zHCapture the current explicit-cancel source on the owning request thread.rs   Nrw   rv   )ro   rp   ry   )rz   rw   r{   s      r   _capture_aux_cancel_checkr   4  sf    -~tDDEUHd++F -~tDDE  4r   rv   c                     	 t           |                       S # t          $ r  t                              dd           Y dS w xY w)zGRead a request-thread cancellation source without leaking its failures.z captured aux cancel check failedTrt   F)rn   rK   rX   rx   rv   s    r   _captured_aux_cancel_requestedr   B  sT    LLNN###   7$GGGuus    &AAc                   J    e Zd ZdZdeg ef         ddfdZdefdZdefdZ	dS )_AuxiliaryCancellationDecisionzHAtomically choose explicit cancellation or provider timeout per attempt.source_cancel_checkr   Nc                 R    || _         t          j                    | _        d| _        d S )Nrm   )_source_cancel_check	threadingLock_lock_outcome)r   r   s     r   rg   z'_AuxiliaryCancellationDecision.__init__N  s$    $7!^%%
 r   c                     | j         5  | j        dk    r	 d d d            dS | j        dk    r	 d d d            dS t          | j                  rd| _        	 d d d            dS 	 d d d            dS # 1 swxY w Y   d S )N	cancelledT	timed_outFr   r   r   r   r(   s    r   r"   z'_AuxiliaryCancellationDecision.__call__S  s,   Z 	 	}++	 	 	 	 	 	 	 	 }++		 	 	 	 	 	 	 	
 .d.GHH  +	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s!   A2A2A2$A22A69A6c                     | j         5  | j        dk    r#t          | j                  rd| _        nd| _        | j        dk    cddd           S # 1 swxY w Y   dS )z@Return whether timeout won and destructive cleanup is permitted.rm   r   r   Nr   r(   s    r   begin_timeout_cleanupz4_AuxiliaryCancellationDecision.begin_timeout_cleanup^  s    Z 	0 	0}((1$2KLL 0$/DMM$/DM=K/	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0s   9AAA)
r*   r+   r,   r-   r   r   rg   rn   r"   r   r   r   r   r   r   K  s{        RR!HRW,= !$ ! ! ! !
	$ 	 	 	 	0t 0 0 0 0 0 0r   r   c                      t          t          dd          } | dS 	  |              dS # t          $ r  t                              dd           Y dS w xY w)z?Tick the installed forward-progress hook, if any. Never raises.hookNzaux progress hook failedTrt   )ro   _aux_progressrK   rX   rx   )r   s    r   _notify_aux_progressr   w  sq    =&$//D|@ @ @ @/$??????@s   
( &AAc                  2    t          t          dd           d uS )Nr   )ro   r   r   r   r   _aux_progress_activer     s    =&$//t;;r   c              #      K   t          t          dd          }t          |           r| n|t          _        	 dV  |t          _        dS # |t          _        w xY w)zInstall *hook* as the current thread's aux forward-progress callback.

    ``hook=None`` is a no-op passthrough so callers can wire it
    unconditionally. Re-entrant-safe: restores the previous hook on exit.
    r   N)ro   r   ry   r   )r   r~   s     r   aux_progress_hookr     s`       =&$//D!)$9TM"!T!!!!s   A	 	Acallbackc                    	 t                      }t                      rt          |          s            S t          |                       rt	                      t          t          dd          	t          j                    }t          j
                    i d 	fd}t          j        |j        |fdd                                           	 t                    rt	                                          d          s4t                    rt	                                          d	          }||                    d
          S )a;  Run one protected provider callback in an attempt-isolated daemon.

    A hard cancel must release the compression-owning thread promptly, but
    auxiliary clients are process-shared and cannot safely be closed or evicted
    to wake one request.  Only protected calls with a captured hard-cancel source
    use this seam.  Their provider callback (including stream aggregation) runs
    in a daemon worker while the owner polls cancellation.  On cancel the owner
    unwinds immediately; the worker is left to finish under the provider timeout
    already present in ``kwargs``.  It owns no transcript or compressor commit
    state and never holds the session lock.

    Ordinary auxiliary calls, and protected calls without a cancellation source,
    retain the historical direct synchronous path with no extra thread.
    r   Nr   c                  X   	 t                    5  t                    5             d<   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   n# t          $ r} | d<   Y d } ~ nd } ~ ww xY w                                 d S #                                  w xY w)Nr   result	exception)r   r   BaseExceptionset)excr   rv   doner!   outcomeprogress_hooks    r   _provider_workerz;_run_protected_sync_provider_call.<locals>._provider_worker  sN   	"=11 5 53K)4 4 4 5 5 %-HV$4$4!5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5  	' 	' 	'#&GK      	' HHJJJJJDHHJJJJsr   A! A>AA	AA	A	A! AA! AA!  B !
A:+A50B 5A::B B)zhermes-protected-aux-providerT)targetr    namedaemong{Gz?r   r   ri   )r   rq   ry   r   rc   ro   r   contextvarscopy_contextr   EventThreadrunstartr   waitrJ   )
r   r!   r   provider_contextr   r   rv   r   r   r   s
   ``    @@@@r   !_run_protected_sync_provider_callr     s   $ 455#%%  X6I-J-J  x
 22EFFL|~~ .+---M6488M"/11?D G	 	 	 	 	 	 	 	 	 	 	 # ,	  
 eggg% *,77 	2/111yy 	),77 	2/111KK,,	 O{{8$$$r   r%   
maybe_typec                 F    	 t          | |          S # t          $ r Y dS w xY w)zDReturn False instead of raising when a patched symbol is not a type.F)r$   	TypeError)r%   r   s     r   _safe_isinstancer     s9    #z***   uus    
  urlc                     t          |           }|j        rWt          |                    d                    }d t	          |j                                                  D             }||fS | dfS )zNExtract query params from URL, return (clean_url, default_query dict or None).rB   )queryc                 &    i | ]\  }}||d          S r   r   .0kvs      r   
<dictcomp>z-_extract_url_query_params.<locals>.<dictcomp>  s"    EEEda!QqTEEEr   N)r   r   r   _replacer   items)r   parsedcleanparamss       r   _extract_url_query_paramsr     so    c]]F| 6???4455EEhv|&<&<&B&B&D&DEEEf}9r   googlegeminigoogle-geminigoogle-ai-studiozx-aixaix.aigrokglmzaizz-aizz.aizhipukimikimi-codingmoonshotzkimi-cnkimi-coding-cnzmoonshot-cnz	gmi-cloudgmigmicloudzminimax-china
minimax-cn	anthropiccopilotcopilot-acptencent-tokenhub)
minimax_cnclaudezclaude-codegithubzgithub-copilotzgithub-modelzgithub-modelszgithub-copilot-acpzcopilot-acp-agenttencenttokenhubztencent-cloudtencentmaasproviderc                    | pd                                                                 }|                    d          r4|                    dd          d                                          }|sdS |}|dk    rdS |dk    r?t	                      pd	                                                                 }|r|d
vr|}ndS t
                              ||          S )Nautocustom::   customcodexopenai-codexmainrB   >   rB   r   r   )striplower
startswithsplit_read_main_provider_PROVIDER_ALIASESrJ   )r   
normalizedsuffix	main_provs       r   _normalize_aux_providerr     s    $f++--3355JY'' !!#q))!,2244 	8
W~V )**0b7799??AA	 	*>>>"JJ8  Z888r   OMIT_TEMPERATUREmodelc                     | pd                                                                                     dd          d         }|                    d          p|dk    S )zHTrue for any Kimi / Moonshot model that manages temperature server-side.rB   /r   zkimi-r   r   r   rsplitr   r   bares     r   _is_kimi_modelr  -  sS    KR  &&((//Q77;D??7##5tv~5r   c                     | pd                                                                                     dd          d         }|dk    S )zATrue for Arcee Trinity Large Thinking (direct or via OpenRouter).rB   r   r   r   ztrinity-large-thinkingr   r   r   r   s     r   _is_arcee_trinity_thinkingr  3  sD    KR  &&((//Q77;D+++r   g333333?gffffff?c                    |pd                                                                 }|dk    rdS | pd                                                                                     dd          d         }|dk    p|                    d          pt|                    d	          p_|d
k    pY|                    d          pD|                    d          p/|dk    p)|                    d          p|                    d          S )u  True for gpt-5.4 / gpt-5.5 / gpt-5.6 on the ChatGPT Codex OAuth backend.

    Matches only the Codex OAuth route (provider ``openai-codex``), not the
    direct OpenAI API, OpenRouter, or GitHub Copilot paths — those expose a
    larger context window for the same slug and must keep the user's default
    compaction threshold. ``-pro`` variants and dated snapshots are matched
    via prefix so the override tracks every 272K-capped family (5.4, 5.5,
    5.6 sol/terra/luna incl. their ``-pro`` modes) without re-listing every
    variant. (Name kept for backward compatibility with the
    ``compression.codex_gpt55_autoraise`` config key.)
    rB   r   Fr   r   r   zgpt-5.4zgpt-5.4-zgpt-5.4.zgpt-5.5zgpt-5.5-zgpt-5.5.zgpt-5.6zgpt-5.6-zgpt-5.6.r   r   r   provr  s       r   _is_codex_gpt54_or_gpt55r	  Q  s    N!!##))++D~uKR  &&((//Q77;D	 	'??:&&	'??:&&	' 9	' ??:&&		'
 ??:&&	' 9	' ??:&&	' ??:&&
r   c                     |pd                                                                 }|dk    rdS | pd                                                                                     dd          d         }|dk    S )u'  True for ``gpt-5.3-codex-spark`` on the ChatGPT Codex OAuth backend.

    The model is Codex-OAuth-only (ChatGPT Pro entitlement) with a native
    128K context window.  Only the Codex OAuth route (provider
    ``openai-codex``) is matched — the slug is not available on other
    routes.
    rB   r   Fr   r   r   zgpt-5.3-codex-sparkr  r  s       r   _is_codex_sparkr  n  sw     N!!##))++D~uKR  &&((//Q77;D(((r   zOptional[float] | objectc                     t          |           r"t                              d|            t          S t	          |           rdS dS )u  Return a temperature directive for models with strict contracts.

    Returns:
        ``OMIT_TEMPERATURE`` — caller must remove the ``temperature`` key so the
            provider chooses its own default.  Used for all Kimi / Moonshot
            models whose gateway selects temperature server-side.
        ``float`` — a specific value the caller must use (reserved for future
            models with fixed-temperature contracts).
        ``None`` — no override; caller should use its own default.
    z7Omitting temperature for Kimi model %r (server-managed)g      ?N)r  rX   rx   r   r  )r   r=   s     r   _fixed_temperature_for_modelr  }  sJ     e  NPUVVV!%(( s4r   )allow_codex_gpt55_autoraiser  c                    t          |           rdS |rt          | |          rt          S t          | |          rt          S dS )u  Return a context-compression threshold override for specific models.

    The threshold is the fraction of the model's context window that must be
    consumed before Hermes triggers summarization.  Higher values delay
    compression and preserve more raw context.

    Per-model/route overrides:
      - Arcee Trinity Large Thinking → 0.75 (preserve reasoning context).
      - gpt-5.4 / gpt-5.5 / gpt-5.6 on the Codex OAuth route → 0.85, because
        Codex caps all three families at 272K and the default 50% trigger
        would compact at ~136K. Gated by ``allow_codex_gpt55_autoraise``
        (historical config-key name kept for backward compatibility) so the
        user can opt back down to the global default (the caller passes the
        config flag through here).
      - gpt-5.3-codex-spark on the Codex OAuth route → 0.70, because the model
        has a native 128K window and the default 50% trigger would compact at
        ~64K — wasting half the usable context. Not gated by the gpt-5.5
        opt-out flag: 128K is the model's native window, so the raise is
        unambiguously correct.

    Returns a float in (0, 1] to override the global ``compression.threshold``
    config value, or ``None`` to leave the user's config value unchanged.
    g      ?N)r  r	  '_CODEX_GPT54_GPT55_COMPACTION_THRESHOLDr  !_CODEX_SPARK_COMPACTION_THRESHOLD)r   r   r  s      r    _compression_threshold_for_modelr    sV    : "%(( t" 7'?x'P'P 766uh'' 1004r   provider_idc                     	 ddl m}  ||           }|r|j        r|j        S n# t          $ r Y nw xY wt                              | d          S )zReturn the cheap auxiliary model for a provider.

    Reads from ProviderProfile.default_aux_model first, falling back to the
    legacy hardcoded dict for providers that predate the profiles system.
    r   get_provider_profilerB   )	providersr  default_aux_modelrK   %_API_KEY_PROVIDER_AUX_MODELS_FALLBACKrJ   )r  r  _ps      r   _get_aux_model_for_providerr    s{    222222!!+.. 	("& 	(''   044["EEEs    $ 
11zgemini-3.6-flashzglm-4.5-flashzkimi-k2-turbo-previewzstep-3.5-flashz$google/gemini-3.1-flash-lite-previewclaude-haiku-4-5-20251001zgoogle/gemini-3-flashzgemini-3-flashzglm-5zgoogle/gemini-3.6-flashznemotron-3-nano:30bzhy3-preview)r   r   r   stepfunr   r   r   z
ai-gatewayzopencode-zenzopencode-gokilocodezollama-cloudr   r  _API_KEY_PROVIDER_AUX_MODELSz	mimo-v2.5zglm-5v-turbo)xiaomir   _PROVIDER_VISION_MODELSc                     t                               |           }|r|S 	 ddlm}  ||           }n# t          $ r Y dS w xY w|dS 	 |                                S # t          $ r Y dS w xY w)u  Return the provider's preferred default vision model id, or None.

    Static entries in :data:`_PROVIDER_VISION_MODELS` win first (xiaomi /
    zai have dedicated vision-only model names that don't live in any
    discoverable catalog). Otherwise the provider's :class:`ProviderProfile`
    gets a chance to supply one via its ``default_vision_model()`` hook —
    that's where catalog-backed providers (DeepInfra) resolve a live default,
    keeping the discovery logic inside their plugin instead of a name-check
    branch here.
    r   r  N)r!  rJ   r  r  rK   default_vision_model)r   staticr  profiles       r    _resolve_provider_vision_defaultr&    s     %((22F 222222&&x00   ttt++---   tts    2 
A A A 
A*)A*_PROVIDERS_WITHOUT_VISIONz%https://hermes-agent.nousresearch.comzHermes Agentzproductivity,cli-agent)HTTP-RefererX-TitlezX-OpenRouter-Categories>   1onyestrueheadersc                 
   	 ddl m}m}  |            } ||dd          } ||dd          }t          |t                    rE|rCi }t          |t                    r|                    |           |                    |           |}n# t          $ r | cY S w xY wt          |t                    r|s| S t	          | pi           }|                                D ]'\  }}	|	t          |	          |t          |          <   (|p| S )u  Merge user-configured ``model.default_headers`` onto resolved headers.

    User values take precedence over provider/SDK defaults, mirroring the main
    agent client (``AIAgent._apply_user_default_headers``). This lets a
    ``custom`` OpenAI-compatible endpoint behind a gateway/WAF that rejects the
    OpenAI SDK's identifying headers (``User-Agent: OpenAI/Python ...``,
    ``X-Stainless-*``) override them for auxiliary calls too — otherwise the
    main turn would succeed but title/compression/vision calls to the same
    endpoint would still fail. (#40033)

    Returns the merged dict, or the original ``headers`` (possibly ``None``)
    when nothing is configured. No allocation when there are no overrides.
    r   cfg_getload_configr   default_headersextra_headers)	rH   r1  r2  r$   dictupdaterK   r   rI   )
r.  r1  r2  _cfguser_headersalias_headersmerged_usermergedkeyvalues
             r   _apply_user_default_headersr>  $  sO   ::::::::{}}wtW.?@@
  g??mT** 	'} 	' "K,-- 1""<000}---&L   lD))  '-R  F"((** & &
U=u::s3xxWs   BB	 	BB	or_configc                 6   t          t                    }| 8	 ddlm}  |                                di           } n# t
          $ r i } Y nw xY wt          j                            dd                                          	                                }|r
|t          v }n|                     dd          }|s|S d	|d
<   t          j                            dd                                          }|rF|                                r1t          |          }d|cxk    rdk    rn ntt          |          |d<   na|                     dd          }t          |t          t          f          r/d|cxk    rdk    r"n nt          t          |                    |d<   |S )u  Build OpenRouter headers, optionally including response-cache headers.

    Precedence for response cache: env var > config.yaml > default (enabled).

    Environment variables:
        ``HERMES_OPENROUTER_CACHE`` — truthy (``1``/``true``/``yes``/``on``)
            enables caching; ``0``/``false``/``no``/``off`` disables.
            Overrides ``openrouter.response_cache`` in config.yaml.
        ``HERMES_OPENROUTER_CACHE_TTL`` — integer seconds (1-86400).
            Overrides ``openrouter.response_cache_ttl`` in config.yaml.

    *or_config* is the ``openrouter`` section from config.yaml.  When *None*,
    falls back to reading config from disk via ``load_config_readonly()``.
    Nr   rA   
openrouterHERMES_OPENROUTER_CACHErB   response_cacheFr-  zX-OpenRouter-CacheHERMES_OPENROUTER_CACHE_TTLr   iQ zX-OpenRouter-Cache-TTLresponse_cache_ttli,  )r5  _OR_HEADERS_BASErH   rA   rJ   rK   osenvironr   r   _TRUTHY_ENV_VALUESisdigitintrI   r$   float)r?  r.  rA   	env_cachecache_enabledenv_ttlttls          r   build_or_headersrR  M  s    #$$G 	>>>>>>,,..22<DDII 	 	 	III	 
8"==CCEEKKMMI ?!%77!&6>> $*G ! jnn:B??EEGGG >?? 	=g,,CC    5     47HH01mm0#66cC<(( 	>Q#->->->->->->->->->03CHHG,-Ns   $= AAzX-BILLING-INVOKE-ORIGINHermesAgentc                 l    t          t          | pd          d          rt          t                    S i S )zIReturn NVIDIA NIM cloud attribution headers for build.nvidia.com traffic.rB   integrate.api.nvidia.com)r4   rI   r5  _NVIDIA_NIM_CLOUD_HEADERS)r=   s    r   build_nvidia_nim_headersrW    s5    SR002LMM /-...Ir   )__version__zHermesAgent/)r(  r)  
User-Agent)nous_portal_tagsc                  "    dt                      iS )zReturn a fresh Nous Portal ``extra_body`` dict.

    Computed at call time so a hot-reloaded ``hermes_cli.__version__`` is
    reflected without restarting long-running processes.
    tags)_nous_portal_tagsr   r   r   _nous_extra_bodyr^    s     %''((r   auxiliary_is_nousz)https://inference-api.nousresearch.com/v1zhttps://api.anthropic.comz	auth.jsonz%https://chatgpt.com/backend-api/codexaccess_tokenc                    ddd}t          | t                    r|                                 s|S 	 ddl}|                     d          }t          |          dk     r|S |d         d	t          |d                    d
z  z  z   }t          j        |                    |                    }|	                    di           	                    d          }t          |t                    r|r||d<   n# t          $ r Y nw xY w|S )u  Headers required to avoid Cloudflare 403s on chatgpt.com/backend-api/codex.

    The Cloudflare layer in front of the Codex endpoint whitelists a small set of
    first-party originators (``codex_cli_rs``, ``codex_vscode``, ``codex_sdk_ts``,
    anything starting with ``Codex``). Requests from non-residential IPs (VPS,
    server-hosted agents) that don't advertise an allowed originator are served
    a 403 with ``cf-mitigated: challenge`` regardless of auth correctness.

    We pin ``originator: codex_cli_rs`` to match the upstream codex-rs CLI, set
    ``User-Agent`` to a codex_cli_rs-shaped string (beats SDK fingerprinting),
    and extract ``ChatGPT-Account-ID`` (canonical casing, from codex-rs
    ``auth.rs``) out of the OAuth JWT's ``chatgpt_account_id`` claim.

    Malformed tokens are tolerated — we drop the account-ID header rather than
    raise, so a bad token still surfaces as an auth error (401) instead of a
    crash at client construction.
    z!codex_cli_rs/0.0.0 (Hermes Agent)codex_cli_rs)rY  
originatorr   N.   r   =   zhttps://api.openai.com/authchatgpt_account_idzChatGPT-Account-ID)r$   rI   r   base64r   lenjsonloadsurlsafe_b64decoderJ   rK   )r`  r.  ri  partspayload_b64claimsacct_ids          r   _codex_cloudflare_headersrr    s%   & :$ G lC(( 0B0B0D0D ""3''u::>>NAhU1X(:!;;F44[AABB**:B??CCDXYYgs## 	4 	4,3G()   Ns   -C2  BC2 2
C?>C?c                    t          | pd                                                              d          }|                    d          rzd|v sd|v r9|dt	          d                    dz   }t
                              d||           |S |dt	          d                    d	z   }t
                              d
||           |S d|v r8|                    d          r#|d	z   }t
                              d||           |S |S )u  Normalize an Anthropic-style base URL to OpenAI-compatible format.

    Some providers (MiniMax, MiniMax-CN) expose an ``/anthropic`` endpoint for
    the Anthropic Messages API and a separate ``/v1`` endpoint for OpenAI chat
    completions.  The auxiliary client uses the OpenAI SDK, so it must hit the
    ``/v1`` surface.  Passing the raw ``inference_base_url`` causes requests to
    land on ``/anthropic/chat/completions`` — a 404.
    rB   r   
/anthropiczopen.bigmodel.cnbigmodelNz/paas/v4u0   Auxiliary client: rewrote ZAI base URL %s → %sz/v1u,   Auxiliary client: rewrote base URL %s → %sapi.kimi.com/codingu1   Auxiliary client: rewrote Kimi base URL %s → %s)rI   r   rstripendswithrj  rX   rx   )r=   r   	rewrittens      r   _to_openai_base_urlr{    s    hn"


#
#
%
%
,
,S
1
1C
||L!! 	 $$
c(9(90s<00001J>ILLKSR[\\\,3|,,,,-5	CS)TTTi!8!8 %K	H#yYYYJr   c                 R   	 t          |           }n4# t          $ r'}t                              d| |           Y d}~dS d}~ww xY w|r|                                sdS 	 d|                                fS # t          $ r'}t                              d| |           Y d}~dS d}~ww xY w)z2Return (pool_exists_for_provider, selected_entry).z0Auxiliary client: could not load pool for %s: %sNFNTz8Auxiliary client: could not select pool entry for %s: %s)TN)r/   rK   rX   rx   has_credentialsselect)r   poolr   s      r   _select_pool_entryr    s    ""   GSVWWW{{{{{  t++-- {T[[]]""   OQY[^___zzzzzs*    
A>AA5 5
B&?B!!B&c                    	 t          |           }n4# t          $ r'}t                              d| |           Y d}~dS d}~ww xY w|r|                                sdS 	 t          |dd          }t          |          r |            }||S t          |dd          }t          |          r
 |            S n3# t          $ r&}t                              d| |           Y d}~nd}~ww xY wdS )zEBest-effort current/next pool entry without mutating selection order.z7Auxiliary client: could not load pool for %s (peek): %sNcurrentpeekz6Auxiliary client: could not peek pool entry for %s: %s)r/   rK   rX   rx   r~  ro   ry   )r   r  r   
current_fnr  peek_fns         r   _peek_pool_entryr    s;   ""   NPXZ]^^^ttttt  t++-- t
^T9d33
J 	 jllG"$--G 	799	 ^ ^ ^MxY\]]]]]]]]^4s0    
A>A-B8 )B8 8
C(C##C(entryc                     | dS t          | dd           pt          | dd          }t          |pd                                          S )NrB   runtime_api_keyr`  )ro   rI   r   )r  r<  s     r   _pool_runtime_api_keyr  4  sN    }r %*D
1
1
WWUNTV5W5WCsyb>>!!!r   rB   fallbackc                    | 6t          |pd                                                              d          S t          | dd           dk    rddlm}  |            }|r|S t          | dd           p#t          | dd           pt          | d	d           p|}t          |pd                                                              d          S )
NrB   r   r   nousr   )_nous_inference_env_overrideruntime_base_urlinference_base_urlr=   )rI   r   rx  ro   hermes_cli.authr  )r  r  r  env_urlr   s        r   _pool_runtime_base_urlr  =  s    }8>r""((**11#666uj$''611 	A@@@@@..00 	N 	)400 	5.55	5*d++	 	  syb>>!!((---r   api.anthropic.comc                     | sdS 	 ddl m}  ||           j        pd                                                                                    d          }|t          v S # t          $ r Y dS w xY w)zRReturn True if ``url``'s hostname is an Anthropic endpoint we trust for aux calls.Fr   r   rB   rd  )urllib.parser   hostnamer   r   rx  _ANTHROPIC_COMPATIBLE_HOSTSrK   )r   r   hosts      r   _is_anthropic_compatible_hostr  ]  s     u))))))&,"3355;;==DDSII222   uus   AA 
A,+A,c            	          	 t          dt          t          j        dd                              S # t          t
          f$ r Y dS w xY w)N<   HERMES_NOUS_MIN_KEY_TTL_SECONDS1800i  )maxrL  rH  getenvr   
ValueErrorr   r   r   _nous_min_key_ttl_secondsr  i  sS    2s29%FOOPPQQQz"   tts   /2 AAr   c                     | sdS 	 ddl m}m} 	  ||           pd                                S # |$ r Y nw xY wn# t          $ r Y nw xY wt          j        |           pd                                S )u  Read a provider API key env var through the profile secret scope.

    Auxiliary-client resolution runs both inside agent turns (secret scope
    installed — its verdict is authoritative under multiplex, so a scoped
    miss must NOT borrow another profile's process-env key) and on unscoped
    startup/CLI probe paths, which keep the legacy ``os.environ`` read via
    the ``UnscopedSecretError`` fallback (Slack pattern, #59739).
    rB   r   )UnscopedSecretError
get_secret)agent.secret_scoper  r  r   rK   rH  r  )r   r  r  s      r   _scoped_key_envr  p  s      rFFFFFFFF	Jt$$*11333" 	 	 	D	   IdOO!r((***s#   : . 6: 6: 
AAc                   .    e Zd ZdZdedefdZdefdZdS )_CodexCompletionsAdapterzyDrop-in shim that accepts chat.completions.create() kwargs and
    routes them through the Codex Responses streaming API.real_clientr   c                 "    || _         || _        d S r   )_client_model)r   r  r   s      r   rg   z!_CodexCompletionsAdapter.__init__  s    "r   r   c                 F   6789:;<=> |                     dg           }|                     d j                  }ddlm} ddlm} d}g }|D ]q}|                     dd          }	|                     d	          pd
}
|	dk    r't          |
t                    r|
nt          |
          }\|                    |           rt          t           j
        dd
          pd
          } ||d          } |||          }|||pdd
dgdd}|                     d          }|||d<   |                     d          pi }t          |t                    ro|                     d          }t          |t                    rE|                     d          du rn-|                     d          pd}|dk    rd}|dd|d<   dg|d<   |                     d          }|r	 dd l}ddlm}m} |                    t#          |                    } ||          \  }} ||          \  }}n2# t$          $ r%}t&                              d |           Y d }~nd }~ww xY wg }|D ]}t          |t                    r|                     d!i           ni }|                     d"          }|sG|                    d!||                     d#d
          |                     d$i           d%           |r||d<   	 dd&lm}m} ddlm} t          t           j
        dd
          pd
          } ||d'          p ||d(          }  ||d          p ||d)          }!| s,|!s*d*|vr& |||                     d                    }"|"r|"|d*<   d+|vr |||          }#|#r|#|d+<   n,# t$          $ r t&                              d,d-.           Y nw xY wg }$g }%d }&t          |t2          t4          f          r|dk    r|nd >>r#t7          j                    t5          >          z   nd ;t;          j                    =d }'t?                      rtA                      nd <t;          j!                    :g 9d/t          f>fd08dV9:< =fd17dV78;=fd26	 >r=t;          j"        t5          >          7          }'d-|'_#        |'$                                  6             dd3l%m&}( t          |          })d-|)d4<   d5tN          d/d f6fd6}*  j
        j(        j)        dWi |)}+:5  9                    |+           d d d            n# 1 swxY w Y   =*                                rvtW          <          rgtY          <          rXt          |+d7d           },tW          |,          r8	  |,             n,# t$          $ r t&                              d8d-.           Y nw xY w	 t[          |+d9          r|+}-n0 |(|+t          |                     d          p|          |*:          }-t          |+d7d           },tW          |,          r	  |,             n# t$          $ r Y nw xY w:5  9.                                 d d d            n# 1 swxY w Y   no# t          |+d7d           },tW          |,          r	  |,             n# t$          $ r Y nw xY w:5  9.                                 d d d            w # 1 swxY w Y   w xY w|-t_          d;          dXd<tN          d=t          d>tN          d/tN          fd?}.t          |-d9d           pg D ]}/ |.|/d@          }0|0dAk    rB |.|/d	          pg D ]2}1 |.|1d@          }2|2dBv r |$                     |.|1dCd
                     3V|0dDk    rU|%                    ta           |.|/dEd
          d!ta           |.|/d"d
           |.|/dFdG          H          I                     t          |-dJd           }3|3rta          t          |3dKd          p,t          |3t                    r|3                     dKd          ndt          |3dLd          p,t          |3t                    r|3                     dLd          ndt          |3dMd          p,t          |3t                    r|3                     dMd          ndN          }&nZ# t$          $ rM}=*                                rtc           8                      |t&                              dO|            d }~ww xY w|'|'2                                 n# |'|'2                                 w w xY wd
3                    |$          4                                pd }
ta          dP|
|%pd Q          }4ta          d|4|%sdRndST          }5ta          |5g||&U          S )YNmessagesr   r   )!_chat_messages_to_responses_input)r4   zYou are a helpful assistant.roleusercontentrB   systemr=   githubcopilot.com)is_github_responses)r  r  F)r   instructionsinputstoretimeout
extra_body	reasoningenabledeffortmediumminimallowr   )r  summaryzreasoning.encrypted_contentincludetools)strip_pattern_and_formatstrip_slash_enumzRAuxiliary client: failed to sanitize tool schemas for Codex/xAI Responses path: %sfunctionr   description
parameters)typer   r  r  )_content_cache_key+_default_prompt_cache_retention_for_requestr   api.x.aizmodels.github.aiprompt_cache_keyprompt_cache_retentionz4Codex auxiliary: prompt_cache_key derivation skippedTrt   r   c                  ,    dt                     ddS )Nz*Codex auxiliary Responses stream exceeded z.1fzs total timeout)rM  )total_timeouts   r   _timeout_messagez9_CodexCompletionsAdapter.create.<locals>._timeout_messageU  s    im@T@Tiiiiir   c                      t          dd           } t          |           rt           |                       }nt                    ot                     }	                                 |s5  rd         nd }d d d            n# 1 swxY w Y   t          |dd           }t          |          r8	  |             n,# t
          $ r t                              dd           Y nw xY wd S t          j        dd           }t          |          r8	  |             n,# t
          $ r t                              dd           Y nw xY w	 t          j                   d S # t
          $ r  t                              dd           Y d S w xY w)	Nr   r   closezECodex auxiliary: cancelled attempt stream close during timeout failedTrt   z3Codex auxiliary: client close during timeout failedz1Codex auxiliary: cache eviction on timeout failed)
ro   ry   rn   r   r   rK   rX   rx   r  _evict_cached_client_instance)
r   timeout_wonstreamclose_streamr  attempt_streamattempt_stream_lockprotected_cancel_checkr   r   s
        r   _close_client_on_timeoutzA_CodexCompletionsAdapter.create.<locals>._close_client_on_timeoutX  sW   $+&(?% %! -.. "#8#8#:#:;; 344 O67MNN MMOOO  ) K K2@J^A..dFK K K K K K K K K K K K K K K&vw==L)) $$   4%) %      DL'488E ggEGGGG  g g gLL!VaeLfffffga-dl;;;;; a a aP[_``````asH   1B

BB6
C &C*)C*
D   &E	E	E# #&FFc                     Lt          j                    k    r5                                s
              t                                 	 ddlm}  t                      rt                       |             rt                      st          d          d S d S # t          t          f$ r  t          $ r Y d S w xY w)Nr   )is_interruptedz,Codex auxiliary Responses stream interrupted)time	monotonicrw   TimeoutErrortools.interruptr  r|   rc   rq   InterruptedErrorrK   )r  r  r  deadliner   s    r   _check_cancelledz9_CodexCompletionsAdapter.create.<locals>._check_cancelled  s   #(8(8H(D(D '')) /,,..."#3#3#5#5666:::::: 344 :7999!>## [,D,F,F [*+YZZZ[ [ [ [$&CD       s   A	B B=<B=)_consume_codex_event_streamr  _eventc                 8    t                                     d S r   r   )r  r  s    r   _on_each_eventz7_CodexCompletionsAdapter.create.<locals>._on_each_event  s&     %&&&  """""r   r  z;Codex auxiliary: late cancelled attempt stream close failedoutput)r   on_eventz@Codex auxiliary Responses stream did not return a final responser%   r<  defaultc                     t          | |d           }|+t          | t                    r|                     ||          }||n|S r   ro   r$   r5  rJ   )r%   r<  r  vals       r   	_item_getz2_CodexCompletionsAdapter.create.<locals>._item_get  sG    c3--;:c4#8#8;''#w//C!oss7:r   r  message>   textoutput_textr  function_callcall_id	argumentsz{}r   r  idr  r  usageinput_tokensoutput_tokenstotal_tokensprompt_tokenscompletion_tokensr   z-Codex auxiliary Responses API call failed: %s	assistant)r  r  
tool_callsstopr  indexr  finish_reasonchoicesr   r  ri   r   r   )5rJ   r  agent.codex_responses_adapterr  utilsr4   r$   rI   appendro   r  r5  copytools.schema_sanitizerr  r  deepcopylistrK   rX   rY   agent.transports.codexr  r  rx   rL  rM  r  r  r   r   rq   r   r   Timerr   r   agent.codex_runtimer  r   	responsescreaterw   ry   r   hasattrclearRuntimeErrorr   r  canceljoinr   )?r   r!   r  r   r  r4   r  replay_messagesmsgr  r  _host_for_input_is_github_for_inputinput_itemsresp_kwargsr  r  reasoning_cfgr  r  _copyr  r  _r   	convertedtfnr   r  r  	_host_src_is_xai
_is_github
_cache_key_cache_retention
text_partstool_calls_rawr  timeout_timerr  stream_kwargsr  event_streamclose_fnfinalr  item	item_typepartptype
resp_usager  choicer  r  r  r  r  r  r  r   r  s?   `                                                     @@@@@@@@@r   r  z_CodexCompletionsAdapter.create  s   ::j"--

7DK00 	TSSSSS//////502 	, 	,C7766**Dggi((.BGx*4Wc*B*BTwwG&&s++++ gdlJCCIrJJ44_FYZZ771E
 
 

 ( Ef%D%D$E	'
 '
 **Y''%,K	" ZZ--3
j$'' 	M&NN;77M-.. M $$Y//588
  +..x88DHF **!&"(#)0 0K, /L-LK	* 

7## %	1$$$$        tE{{3333E::q++E22qq   347       
 I 
 
.8D.A.AIQUU:r***rvvf~~   & #%66-#<#<"$&&r":":	" "      1'0G$	        433333GDL*bAAGRHHI++Iv>>nBWBWXacmBnBnG%%i1DEE H((4FGG   A: A2DK2W2W//koog>V>VWW
 A6@K 23'{::#N#N$ $  $ M<LK 89 	 	 	LLFQU      	 !#
$&#-gU|#D#D^STZ^>KU4>##eM&:&:::QUO%%	37 ,D+E+EO%'''4 	 (n..$&	j# 	j 	j 	j 	j 	j 	j0	a 0	a 0	a 0	a 0	a 0	a 0	a 0	a 0	a 0	ad	 	 	 	 	 	 	 	 	.y	' & )m0D0DF^ _ _'+$##%%% HGGGGG --M&*M(##s #t # # # # # # 94<18II=IIL$ 4 4%%l3334 4 4 4 4 4 4 4 4 4 4 4 4 4 4   ""344 33IJJ
 #<$??H%%  



$   Y%) %     
+ <22 (EE77$!+//'":":"CeDD!/  E #<$??H%%  



$   ( + +"((***+ + + + + + + + + + + + + + + #<$??H%%  



$   ( + +"((***+ + + + + + + + + + + + + + + + }"#efff
; ;s ; ;s ;c ; ; ; ; !$77=2  %IdF33		))!*4!;!;!Ar K K )	$ 7 7 $;;;&--iifb.I.IJJJK /11"))/$9T9b99'!0!*4!<!<&/ik4&H&H" " "+ + +    !66J '")*na"H"H #fAKJX\A]A]dJNN>1===cd&-j/1&M&M 'gBLZY]B^B^eJNN?A>>>de!(^Q!G!G "fAKJX\A]A]dJNN>1===cd    	 	 	!! @"#3#3#5#566C?LLH#NNN		 ($$&&& ($$&&&& ) ''*%%++--5 "%-
 
 

 !(6H&&L
 
 

 H
 
 
 	
sK  A
H& &
I0II.B(N &O ?O ?Bb0 
T, b0 ,T00b0 3T04Ab0 

V b0 &V>;b0 =V>>b0 AY0  b0 &
X1 0b0 1
X>;b0 =X>>b0 Y$b0 $Y((b0 +Y(,b0 0![
Z[
Z*'[)Z**[/[[[[[[Gb0 /d! 0
d:Addd! !d:N)	r*   r+   r,   r-   r   rI   rg   r   r  r   r   r   r  r    sb        > >F 3    X
# X
 X
 X
 X
 X
 X
r   r  c                       e Zd ZdZdefdZdS )_CodexChatShimz>Wraps the adapter to provide client.chat.completions.create().adapterc                     || _         d S r   completionsr   r=  s     r   rg   z_CodexChatShim.__init__3      "r   N)r*   r+   r,   r-   r  rg   r   r   r   r<  r<  0  s6        HH# 8 # # # # # #r   r<  c                   (    e Zd ZdZdedefdZd ZdS )CodexAuxiliaryClientzOpenAI-client-compatible wrapper that routes through Codex Responses API.

    Consumers can call client.chat.completions.create(**kwargs) as normal.
    Also exposes .api_key and .base_url for introspection by async wrappers.
    r  r   c                     || _         t          ||          }t          |          | _        |j        | _        |j        | _        d S r   )_real_clientr  r<  chatr\   r=   )r   r  r   r=  s       r   rg   zCodexAuxiliaryClient.__init__>  s@    '*;>>"7++	"*#,r   c                 8    | j                                          d S r   )rF  r  r(   s    r   r  zCodexAuxiliaryClient.closeE  s    !!!!!r   N)r*   r+   r,   r-   r   rI   rg   r  r   r   r   rD  rD  7  sO         -F -3 - - - -" " " " "r   rD  c                   *    e Zd ZdZdefdZdefdZdS )_AsyncCodexCompletionsAdapterzAsync version of the Codex Responses adapter.

    Wraps the sync adapter via asyncio.to_thread() so async consumers
    (web_tools, session_search) can await it as normal.
    sync_adapterc                     || _         d S r   _syncr   rK  s     r   rg   z&_AsyncCodexCompletionsAdapter.__init__P      !


r   r   c                 J   K   dd l } |j        | j        j        fi | d {V S Nr   asyncio	to_threadrN  r  r   r!   rT  s      r   r  z$_AsyncCodexCompletionsAdapter.createS  A      &W&tz'8CCFCCCCCCCCCr   N)r*   r+   r,   r-   r  rg   r   r  r   r   r   rJ  rJ  I  s\         "%= " " " "D D D D D D Dr   rJ  c                       e Zd ZdefdZdS )_AsyncCodexChatShimr=  c                     || _         d S r   r?  rA  s     r   rg   z_AsyncCodexChatShim.__init__Y  rB  r   N)r*   r+   r,   rJ  rg   r   r   r   rY  rY  X  s0        # = # # # # # #r   rY  c                       e Zd ZdZddZdS )AsyncCodexAuxiliaryClientzHAsync-compatible wrapper matching AsyncOpenAI.chat.completions.create().sync_wrapperrD  c                     |j         j        }t          |          }t          |          | _         |j        | _        |j        | _        |j        | _        d S r   )rG  r@  rJ  rY  r\   r=   rF  r   r]  rK  async_adapters       r   rg   z"AsyncCodexAuxiliaryClient.__init__`  sP    #(45lCC'66	#+$- )5r   N)r]  rD  )r*   r+   r,   r-   rg   r   r   r   r\  r\  ]  s.        RR6 6 6 6 6 6r   r\  c            
       B    e Zd ZdZ	 	 ddededededz  fdZd	efd
ZdS )_AnthropicCompletionsAdapterz<OpenAI-client-compatible adapter for Anthropic Messages API.FNr  r   is_oauthr=   c                     || _         || _        || _        |pd | _        | j        sRt	          t          |dd          pd          pd }|r0	 ddlm}  ||          r	|| _        d S d S # t          $ r Y d S w xY wd S d S )Nr=   rB   r   )_is_nous_portal_endpoint)	r  r  	_is_oauth	_base_urlrI   ro   agent.anthropic_adapterre  rK   )r   r  r   rc  r=   	candidatere  s          r   rg   z%_AnthropicCompletionsAdapter.__init__s  s     #! ")T~ 		GKR@@FBGGO4I PPPPPP//	:: 3)23 3    DD		 		 s   A' '
A54A5r   c           
      &   ddl m}m} ddlm} |                    dg           }|                    d| j                  }|                    d          }|                    d          }|                    d          }	|                    d	d
          }
|
rd }n*|                    d          p|                    d          }|                    d          }d }t          |t                    r|}nt          |t                    rkt          |                    dd                                                    }|dk    r*|                    di                               d          }n|dv r|}|	}|V|                    d          }t          |t                    r,|                    d          }t          |t                    r|} |||||||| j        | j                  }|ddl m}  ||          s||d<   |                    d          }|rlt          |t                    rWd |                                D             }|r7|                    d          pi }t          |t                    si }i |||d<    || j        |t#                      rd nd           } |d          }|                    || j                  }t'          |j        |j        |j                  }|j        }d }t1          |d          rd|j        r]t5          |j        dd          pd}t5          |j        dd          pd}t5          |j        d d          p||z   }t'          |||!          }t'          d||"          } t'          | g||#          S )$Nr   )build_anthropic_kwargscreate_anthropic_message)get_transportr  r   r  tool_choice_reasoning_config_skip_zai_max_tokensF
max_tokensmax_completion_tokenstemperaturer  rB   r  r   >   r   nonerequiredr  r  )r   r  r  rq  reasoning_configrn  rc  r=   _forbids_sampling_paramsc                 j    i | ]0\  }}|d k    t          |                              d          -||1S )r  r%  )rI   r   r   s      r   r   z7_AnthropicCompletionsAdapter.create.<locals>.<dictcomp>  sL       A##CFF,=,=c,B,B# 1###r   c                     t                      S r   r  )r  s    r   <lambda>z5_AnthropicCompletionsAdapter.create.<locals>.<lambda>  s     4 6 6 r   )on_stream_eventanthropic_messages)strip_tool_prefix)r  r  r  r  r  r  r   r  r  r
  )rh  rk  rl  agent.transportsrm  rJ   r  popr$   rI   r5  r   rf  rg  rx  r   r  r   normalize_responser   r  r  r  r	  r  r  ro   )!r   r!   rk  rl  rm  r  r   r  rn  rv  _skip_mtrq  rs  normalized_tool_choicechoice_type_reasoning_cfg_eb_rcanthropic_kwargsrx  caller_extra_bodypassthroughexistingresponse
_transport_nrassistant_messager	  r  r  r  r   r:  s!                                    r   r  z#_AnthropicCompletionsAdapter.create  s[   \\\\\\\\222222::j"--

7DK00

7##jj//!::&9:: ::4e<< 	YJJL11XVZZ@W5X5XJjj//!%k3'' 	5%0""T** 	5koofb99::@@BBKj(()4R)H)H)L)LV)T)T&& <<<)4& *!**\**C#t$$ )ggk**c4(( )%(N11!+.^
 ^
 
 
" "HHHHHH++E22 >2= / #JJ|44 		M,=t!D!D 		M !2!8!8!:!:  K  M+//==C!(D11 "!H1LH1L1L .++L ())4666/3
 
 
 #]#788
++ , 
 
 ,K~m
 
 

 )8W%% 	(. 	#HNNAFFK!M ' K K Pq"8>>1EEl-ZkJkL#+"3)  E !%'
 
 

 H
 
 
 	
r   r}  )	r*   r+   r,   r-   r   rI   rn   rg   r  r   r   r   rb  rb  p  s        FF #   	
 *   6G
# G
 G
 G
 G
 G
 G
r   rb  c                       e Zd ZdefdZdS )_AnthropicChatShimr=  c                     || _         d S r   r?  rA  s     r   rg   z_AnthropicChatShim.__init__  rB  r   N)r*   r+   r,   rb  rg   r   r   r   r  r    s0        # < # # # # # #r   r  c                   6    e Zd ZdZddededededef
dZd	 Zd
S )AnthropicAuxiliaryClientz@OpenAI-client-compatible wrapper over a native Anthropic client.Fr  r   r\   r=   rc  c                 ~    || _         t          ||||          }t          |          | _        || _        || _        d S )N)rc  r=   )rF  rb  r  rG  r\   r=   )r   r  r   r\   r=   rc  r=  s          r   rg   z!AnthropicAuxiliaryClient.__init__   sJ    '.H
 
 
 'w//	 r   c                 h    t          | j        dd           }t          |          r |             d S d S )Nr  )ro   rF  ry   )r   r3  s     r   r  zAnthropicAuxiliaryClient.close)  s?    4,gt<<H 	HJJJJJ	 	r   NF)	r*   r+   r,   r-   r   rI   rn   rg   r  r   r   r   r  r    sf        JJ! !C ! !c !S !\` ! ! ! !    r   r  c                   &    e Zd ZdefdZdefdZdS )!_AsyncAnthropicCompletionsAdapterrK  c                     || _         d S r   rM  rO  s     r   rg   z*_AsyncAnthropicCompletionsAdapter.__init__0  rP  r   r   c                 J   K   dd l } |j        | j        j        fi | d {V S rR  rS  rV  s      r   r  z(_AsyncAnthropicCompletionsAdapter.create3  rW  r   N)r*   r+   r,   rb  rg   r   r  r   r   r   r  r  /  sR        "%A " " " "D D D D D D Dr   r  c                       e Zd ZdefdZdS )_AsyncAnthropicChatShimr=  c                     || _         d S r   r?  rA  s     r   rg   z _AsyncAnthropicChatShim.__init__9  rB  r   N)r*   r+   r,   r  rg   r   r   r   r  r  8  s0        # A # # # # # #r   r  c                       e Zd ZddZdS )AsyncAnthropicAuxiliaryClientr]  r  c                     |j         j        }t          |          }t          |          | _         |j        | _        |j        | _        |j        | _        d S r   )rG  r@  r  r  r\   r=   rF  r_  s       r   rg   z&AsyncAnthropicAuxiliaryClient.__init__>  sP    #(49,GG+M::	#+$- )5r   N)r]  r  r*   r+   r,   rg   r   r   r   r  r  =  s(        6 6 6 6 6 6r   r  c                   .    e Zd ZdZdedefdZdefdZdS )_BedrockCompletionsAdapterzGTranslates ``chat.completions.create(**kwargs)`` into Bedrock Converse.regionr   c                 "    || _         || _        d S r   )_regionr  )r   r  r   s      r   rg   z#_BedrockCompletionsAdapter.__init__L  s    r   r   c                    ddl m} |                    dg           }|                    d| j                  }|                    d          p|                    d          }|                    d          }t	          |t
                    r|g}|                    d          .t                              d	|                    d                     |                    d
          rt                              d|            || j        |||                    d          |rt          |          nd|                    d          |                    d          |          S )Nr   )call_converser  r   rq  rr  r  rn  uV   BedrockAuxiliaryClient: tool_choice=%r not supported by the Converse shim — ignored.r  u   BedrockAuxiliaryClient: stream=True requested for %s — returning a complete response (Converse shim does not stream); caller downgrades to non-streaming.r  i   rs  top_p)r  r   r  r  rq  rs  r  stop_sequences)
agent.bedrock_adapterr  rJ   r  r$   rI   rX   rx   r  rL  )r   r!   r  r  r   rq  r  s          r   r  z!_BedrockCompletionsAdapter.createP  sg   777777::j"--

7DK00ZZ--T<S1T1T
zz&!!dC   	6D::m$$0 LL-.4jj.G.G   ::h 		 LL? 	   }<**W%%*4>s:$

=11**W%%	
 	
 	
 		
r   N)r*   r+   r,   r-   rI   rg   r   r  r   r   r   r  r  I  sW        QQs 3    %
# %
 %
 %
 %
 %
 %
r   r  c                       e Zd ZddZdS )_BedrockChatShimr=  r  c                     || _         d S r   r?  rA  s     r   rg   z_BedrockChatShim.__init__y  rB  r   N)r=  r  r  r   r   r   r  r  x  s(        # # # # # #r   r  c                   (    e Zd ZdZdedefdZd ZdS )BedrockAuxiliaryClientz?OpenAI-client-compatible wrapper over AWS Bedrock Converse API.r  r   c                     || _         || _        t          ||          }t          |          | _        d| _        d| d| _        d S )Naws-sdkhttps://bedrock-runtime..amazonaws.com)r  r  r  r  rG  r\   r=   )r   r  r   r=  s       r   rg   zBedrockAuxiliaryClient.__init__  sK    ,VU;;$W--	 I6IIIr   c                     d S r   r   r(   s    r   r  zBedrockAuxiliaryClient.close  s    r   N)r*   r+   r,   r-   rI   rg   r  r   r   r   r  r  }  sQ        IIJs J3 J J J J    r   r  c                   &    e Zd ZdefdZdefdZdS )_AsyncBedrockCompletionsAdapterrK  c                     || _         d S r   rM  rO  s     r   rg   z(_AsyncBedrockCompletionsAdapter.__init__  rP  r   r   c                 J   K   dd l } |j        | j        j        fi | d {V S rR  rS  rV  s      r   r  z&_AsyncBedrockCompletionsAdapter.create  rW  r   N)r*   r+   r,   r  rg   r   r  r   r   r   r  r    sR        "%? " " " "D D D D D D Dr   r  c                       e Zd ZdefdZdS )_AsyncBedrockChatShimr=  c                     || _         d S r   r?  rA  s     r   rg   z_AsyncBedrockChatShim.__init__  rB  r   N)r*   r+   r,   r  rg   r   r   r   r  r    s0        # ? # # # # # #r   r  c                       e Zd ZddZdS )AsyncBedrockAuxiliaryClientr]  r  c                     |j         j        }t          |          }t          |          | _         |j        | _        |j        | _        d S r   )rG  r@  r  r  r\   r=   r_  s       r   rg   z$AsyncBedrockAuxiliaryClient.__init__  sA    #(47EE)-88	#+$-r   N)r]  r  r  r   r   r   r  r    s(        . . . . . .r   r  c                 p   | pd                                                                                     d          }|sdS t          |          j                            d          }|                    d          s|                    d          rdS t          |          }|dk    rdS |dk    rd	|v rdS dS )
u  True if the endpoint at ``base_url`` speaks the Anthropic Messages
    protocol instead of OpenAI chat.completions.

    Mirrors ``hermes_cli.runtime_provider._detect_api_mode_for_url`` so the
    auxiliary client and the main agent stay in sync on transport selection.
    Covers:

    - Any URL ending in ``/anthropic`` (MiniMax, Zhipu GLM, LiteLLM proxies,
      Anthropic-compatible gateways).
    - ``api.kimi.com/coding`` (Kimi Coding Plan — the /coding route only
      speaks Claude-Code's native Anthropic shape; ``chat.completions``
      returns 404 on Anthropic-only model aliases like ``kimi-for-coding``).
    - ``api.anthropic.com`` (native Anthropic).
    rB   r   Frt  z/anthropic/v1Tr  rv  rw  )r   r   rx  r   pathry  r5   )r=   r   r  r  s       r   #_endpoint_speaks_anthropic_messagesr    s     .b''))//1188==J uJ$++C00D}}\"" dmmO&D&D t ,,H&&&t>!!i:&=&=t5r   
client_objapi_modec                    t          | t                    r| S t          | t                    r| S t          | t                    r| S 	 ddlm} t          | |          r| S n# t          $ r Y nw xY w	 ddlm} t          | |          r| S n# t          $ r Y nw xY w|r|dk    r| S |dk    pt          |          }|s| S 	 ddl
m} n-# t          $ r  t                              d|           | cY S w xY w	  |||          }	n5# t          $ r(}
t                              d||
           | cY d}
~
S d}
~
ww xY wt                              d	||r
|dd
         nd|pd           t          |	|||d          S )a  Rewrap a plain OpenAI client in ``AnthropicAuxiliaryClient`` when
    the endpoint actually speaks Anthropic Messages.

    This is the single chokepoint for aux-client transport correction.
    Runs at the end of every ``resolve_provider_client`` branch so that
    api_key providers (Kimi Coding Plan), the ``custom`` endpoint, and
    future /anthropic gateways all land on the right wire format
    regardless of which branch built the client.

    Returns ``client_obj`` unchanged when:

    - It's already an Anthropic/Codex/Gemini/CopilotACP wrapper.
    - The endpoint is an OpenAI-wire endpoint.
    - ``api_mode`` is explicitly set to a non-Anthropic transport.
    - The ``anthropic`` SDK is not installed (falls back to OpenAI wire).
    r   )GeminiNativeClientCopilotACPClientr}  build_anthropic_clientu   Endpoint %s speaks Anthropic Messages but the anthropic SDK is not installed — falling back to OpenAI-wire (will likely 404).uT   Failed to build Anthropic client for %s (%s) — falling back to OpenAI-wire client.NzeAuxiliary transport: wrapping client in AnthropicAuxiliaryClient (model=%s, base_url=%s, api_mode=%s)r  rB   auto-detectedFrc  )r   r  r  rD  agent.gemini_native_adapterr  rU   agent.copilot_acp_clientr  r  rh  r  rX   rY   rK   rx   )r  r   r\   r=   r  r  r  should_wrapr  r  r   s              r   _maybe_wrap_anthropicr    ss   0 
$<== 
$:;; 
$899 BBBBBBJ(:;; 		   ======J(899 		     H 444 	(( 	9.x88   BBBBBBB   O	
 	
 	

 ,,Wh??   "#+S	
 	
 	
  LL	/0x}}b(2Mo  
 $UGX   sT   A   
A-,A-1B
 

BB>C 'C/.C/3D   
D2
D-'D2-D2c                      t          d          \  } }| r|dS t          |dd          t          |dd          t          |dd          t          |t                    t          |dd          t          |dd          t          |d	d          t          |d
d          dd	S 	 t                                          sdS t          j        t                              d                    }|	                    d          dk    rdS |	                    di           	                    di           }|	                    d          s|	                    d          sdS |S # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)zRead and validate ~/.hermes/auth.json for an active Nous provider.

    Returns the provider state dict if Nous is active with tokens,
    otherwise None.
    r  Nr`  rB   refresh_token	agent_keyportal_base_url	client_idscope
token_typeBearerr  )	r`  r  r  r  r  r  r  r  sourceutf-8)encodingactive_providerr  zCould not read Nous auth: %s)r  ro   r  _NOUS_DEFAULT_BASE_URL_AUTH_JSON_PATHis_filerk  rl  	read_textrJ   rK   rX   rx   )pool_presentr  datar   r   s        r   _read_nous_authr    s    -V44L% 
=4#E>2>>$UOTBB T::"8@V"W"W&u.?FF T::UGT22!%x@@

 

 
	
&&(( 	4z/33W3EEFF88%&&&00488K,,00<<||K(( 	n1M1M 	4   3S999ttttts,   "E =AE AE E 
F'FFc                    ddl m} dD ]|\  }}|                     |          }t          |t                    r|                                sD |||                     d          |                     |                    r|c S }dS )z;Extract a usable Nous inference JWT from stored auth state.r   )_nous_invoke_jwt_is_usable))r  agent_key_expires_at)r`  
expires_atr  )r  r  rB   )r  r  rJ   r$   rI   r   )r   r  	token_key
expiry_keytokens        r   _nous_api_keyr  :  s    ::::::"  	: Y''%%% 	U[[]] 	%%,,w''||J//
 
 
 	
 LLL	 2r   c                  6    t          j        dt                    S )z8Resolve the Nous inference base URL from env or default.NOUS_INFERENCE_BASE_URL)rH  r  r  r   r   r   _nous_base_urlr  N  s    9.0FGGGr   force_refreshr  c           	         	 ddl m} t          d          }n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w|r|                                sdS 	 |                                }n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w|dS t          |dd          t          |dd          t          |d	d          d
}| s ||t                                sP	 |
                                }n4# t          $ r'}t                              d|           d}Y d}~nd}~ww xY w|dS |}t          |dd          t          |dd          t          |dd          t          |dd          t          |d	d          d}t          |          }t          |t                    }	|r|	sdS ||	fS )z@Resolve Nous auxiliary credentials from the selected pool entry.r   )_agent_key_is_usabler  z4Auxiliary Nous pool credential resolution failed: %sNz(Auxiliary Nous pool selection failed: %sr  r  r  )r  r  r  z&Auxiliary Nous pool refresh failed: %sr`  r  )r  r  r`  r  r  )r  r  r/   rK   rX   rx   r~  r  ro   r  try_refresh_currentr  r  r  )
r  r  r  r   r  state	refreshedr   r\   r=   s
             r   _resolve_nous_pool_runtime_apir  S  sS   888888     KSQQQttttt  t++-- t   ?EEEttttt }t UK66 '/Et L L.. E
  008Q8S8STT 	0022II 	 	 	LLA3GGGIIIIII	 4 UK66 '/Et L L~t<<e\488.. H H%%G%e-CDDH ( tHsD    
AAA$A9 9
B)B$$B)>D 
ED??Ec                    t          |           }||S 	 ddlm}  |t          dd          |           }n3# t          $ r&}t
                              d|           Y d}~dS d}~ww xY wt          |                    d	          pd
          	                                }t          |                    d          pd
          	                                
                    d          }|r|sdS ||fS )a9  Return fresh Nous runtime credentials when available.

    This mirrors the main agent's 401 recovery path and keeps auxiliary
    clients aligned with the singleton auth store + JWT refresh flow instead of
    relying only on whatever raw tokens happen to be sitting in auth.json
    or the credential pool.
    r  Nr    resolve_nous_runtime_credentialsHERMES_NOUS_TIMEOUT_SECONDS   timeout_secondsr  z7Auxiliary Nous runtime credential resolution failed: %sr\   rB   r=   r   )r  r  r  r6   rK   rX   rx   rI   rJ   r   rx  )r  pooledr  credsr   r\   r=   s          r   _resolve_nous_runtime_apir    s'    ,-HHHF	DDDDDD00%&CRHH'
 
 
    NPSTTTttttt %))I&&,"--3355G599Z((.B//5577>>sCCH ( tHs   !8 
A(A##A(c            	      :   	 ddl m} m} t          d          }|r|                                rk|                                }|Tt          t          |dd          pt          |dd          pd                                          } |t          j
        dd                                                              d	          pt          j
        d
d                                                              d	          pt          t          |dd          pd                                                              d	          pDt          t          |dd          pd                                                              d	          |           }|r|r||fS n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w	 ddl m}  |            }n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY wt          |                    d          pd                                          }t          |                    d          pd                                                              d	          }|r|sdS ||fS )aW  Resolve a fresh xAI OAuth (api_key, base_url) for auxiliary clients.

    Prefer the credential pool, matching the main runtime/provider status
    path.  Some xAI OAuth logins live only as pool entries; falling straight
    to the singleton auth-store resolver would make auxiliary tasks such as
    compression report "no provider configured" even though ``hermes auth
    status`` shows xAI OAuth as logged in.

    Falls back to ``hermes_cli.auth``'s singleton runtime resolver for older
    auth-store-only logins. Returns ``None`` if the user is not authenticated
    with xAI Grok OAuth.
    r   )DEFAULT_XAI_OAUTH_BASE_URL _xai_validate_inference_base_url	xai-oauthNr  r`  rB   HERMES_XAI_BASE_URLr   XAI_BASE_URLr  r=   )r  z9Auxiliary xAI OAuth pool credential resolution failed: %s%resolve_xai_oauth_runtime_credentialsz<Auxiliary xAI OAuth runtime credential resolution failed: %sr\   )r  r  r  r/   r~  r  rI   ro   r   rH  r  rx  rK   rX   rx   r	  rJ   )	r  r  r  r  r\   r=   r   r	  r   s	            r   _resolve_xai_oauth_for_auxr
    s   W	
 	
 	
 	
 	
 	
 	
 	

 %% 	-D((** 	-KKMME E#4d;; unb99  %''	 
 <;I3R88>>@@GGLL Wy44::<<CCCHHW75*<dCCIrJJPPRRYYZ]^^W 75*d;;ArBBHHJJQQRUVV7    -x -"H,, W W WPRUVVVVVVVVWIIIIII5577   SUXYYYttttt %))I&&,"--3355G599Z((.B//5577>>sCCH ( tHs0   FF 
G'GGG! !
H+HHc                  &   t          d          \  } }| rt          |          }|r|S 	 ddlm}  |            }|                    di           }|                    d          }t          |t                    r|                                sdS 	 ddl}|	                    d          d         }|d	t          |           d
z  z  z  }t          j        |                    |                    }	|	                    dd          }
|
r4t          j                    |
k    rt                              d|
           dS n# t"          $ r Y nw xY w|                                S # t"          $ r&}t                              d|           Y d}~dS d}~ww xY w)a  Read a valid, non-expired Codex OAuth access token from Hermes auth store.

    If a credential pool exists but currently has no selectable runtime entry
    (for example all pool slots are marked exhausted), fall back to the
    profile's auth.json token instead of hard-failing. This keeps explicit
    fallback-to-Codex working when the pool state is stale but the stored OAuth
    token is still valid.
    r   r   )_read_codex_tokenstokensr`  Nrd  r   rf  rg  expz-Codex access token expired (exp=%s), skippingz2Could not read Codex auth for auxiliary client: %s)r  r  r  r  rJ   r$   rI   r   ri  r   rj  rk  rl  rm  r  rX   rx   rK   )r  r  r  r  r  r  r`  ri  payloadrp  r  r   s               r   _read_codex_access_tokenr    s    -^<<L% %e,, 	L666666!!##(B''zz.11,,, 	L4F4F4H4H 	4
	MMM"((--a0Gss7||ma/00GZ 8 8 A ABBF**UA&&C ty{{S((LcRRRt 	 	 	D	 !!###   I3OOOttttts=   A$E  B)D< ;E  <
E	E  E		E   
F*FFc                     	 ddl m} m} n+# t          $ r t                              d           Y dS w xY w|                                 D ]\  }}|j        dk    rt          |          rt                              d|           =|dk    r4	 ddl m	}  |d          sVn# t          $ r Y nw xY wt                      c S t          |          \  }}|rt          |          }|st          ||j                  p|j        }t          |          }	t!          |          pd	}
|
t                              d
|j        |
           |dk    r$ddlm}m}  ||	          r |||	          |
fc S i }t+          |	d          rddi|d<   nt+          |	d          rddlm}  |            |d<   nft+          |	d          rt1          |	          |d<   nC	 ddlm}  ||          }|r|j        rt9          |j                  |d<   n# t:          $ r Y nw xY wt=          |                    d                    }|r||d<   tA          d||	d|}tC          ||
||          }||
fc S  ||          }tE          |                    dd                    #                                }|s`tE          |                    dd                    #                                $                    d          p|j        }t          |          }	t!          |          pd	}
|
t                              d|j        |
           |dk    r$ddlm}m}  ||	          r |||	          |
fc S i }t+          |	d          rddi|d<   nt+          |	d          rddlm}  |            |d<   nft+          |	d          rt1          |	          |d<   nC	 ddlm}  ||          }|r|j        rt9          |j                  |d<   n# t:          $ r Y nw xY wt=          |                    d                    }|r||d<   tA          d||	d|}tC          ||
||          }||
fc S dS )zTry each API-key provider in PROVIDER_REGISTRY order.

    Returns (client, model) for the first provider with usable runtime
    credentials, or (None, None) if none are configured.
    r   )PROVIDER_REGISTRY$resolve_api_key_provider_credentialsz7Could not import PROVIDER_REGISTRY for API-key fallbackNNr\   z2Auxiliary api-key chain: %s is unhealthy, skippingr   )!is_provider_explicitly_configuredNz'Auxiliary text client: %s (%s) via poolr   r  is_native_gemini_base_urlr_   rv  rY  claude-code/0.1.0r3  r  )copilot_default_headersrU  r  rB   r=   r   zAuxiliary text client: %s (%s)r   )%r  r  r  rU   rX   rx   r   	auth_type_is_provider_unhealthyr  _try_anthropicr  r  r  r  r{  r  r   r  r  r  r4   hermes_cli.modelsr  rW  r  r  r3  r5  rK   r>  rJ   ra   r  rI   r   rx  )r  r  r  pconfigr  r  r  r\   raw_base_urlr=   r   r  r  extrar  _gpf_aux_ph_aux_merged_auxr  r   	_gpf_aux2_ph_aux2_merged_aux2s                          r   _resolve_api_key_providerr'  	  s   [[[[[[[[[   NOOOzz !2 7 7 9 9 a aW	))!+.. 	LLM{[[[+%%MMMMMM88EE    !#####0==e &	"+E22G 1%9STTrX_XrL*<88H/<<DE}LLBGLRWXXXh&&eeeeeeee,,X66 Y--gQQQSXXXXXE$X~>> ,8:M+N'((&x1DEE EEEEEE+B+B+D+D'((&x1KLL 	+CH+M+M'((JJJJJJ&h{33G Q7#: Q378O3P3P/0    D5eii@Q6R6RSSK 7+6'(+XGhXXRWXXG+GUG\RRGE>!!!44[AAeii	2..//5577 	599Z4455;;==DDSIIgWMg&|44+K88@D=5w|UKKK(""aaaaaaaa((22 U))'HMMMuTTTT >:: 	(46I'JE#$$"8-@AA 	AAAAAA'>'>'@'@E#$$"8-GHH 		'?'I'IE#$$GGGGGG$9[11 N 8 N/3H4L/M/ME+,   2599=N3O3OPP 	4'3E#$'T(TTeTT'NN~:sB    $33B!!
B.-B.1H
HH
1O<<
P	P	_paid_lane_warnedc                     t          |           o3t          |                                                               d          S )zATrue when ``model`` is an OpenRouter free SKU (``:free`` suffix).z:free)rn   rI   r   ry  r   s    r   _is_free_modelr+  ~	  s3    ;;?3u::++--66w???r   c                  <   	 ddl m} m}  |            }t           | |ddd                    } | |dd          }t	          |t
                    r(|                                r|                                nt          }||fS # t          $ r dt          fcY S w xY w)u   Read free_only and openrouter_model from config in one pass.

    Returns (free_only, model) — defaults (False, _OPENROUTER_MODEL) on any
    config-read failure.
    r   )r1  rA   	auxiliary	free_onlyFr  openrouter_model)	rH   r1  rA   rn   r$   rI   r   _OPENROUTER_MODELrK   )r1  rA   cfgr.  r  r   s         r   _aux_openrouter_settingsr3  	  s    	(CCCCCCCC""$$k;NNNOO	gc;(:;;)#s33Z		Z		IZ% ( ( ('''''(s   BB BBc                     | t           v rdS t                               |            t                              d|            dS )zELog a WARNING the first time a non-:free OpenRouter model is engaged.Nu  Auxiliary client: PAID lane engaged for auxiliary task — OpenRouter fallback model %r is not a :free SKU and may incur real spend. Set auxiliary.free_only: true to restrict auxiliary fallbacks to free models, or auxiliary.openrouter_model to a :free model.)r(  addrX   rY   r*  s    r   _warn_paid_lane_oncer6  	  sR    !!!%   
NN	B 	    r   explicit_api_keyc                    t                      \  }}|p|}|r=t          |          s.t                              d|           t	          dd           dS t          |          st          |           t          d          \  }}|r| pt          |          }|rVt          |t                    pt          }t          
                    d           t          ||t                                |fS t          
                    d           | pt          d	          }|st	          dd           dS t          
                    d
           t          |t          t                                |fS )Nu  Auxiliary client: auxiliary.free_only is enabled but the OpenRouter fallback model %r is not a :free SKU — skipping the OpenRouter fallback. Set auxiliary.openrouter_model to a :free model (e.g. nvidia/nemotron-3-ultra-550b-a55b:free) or disable auxiliary.free_only.rB  r  rQ  r  z%Auxiliary client: OpenRouter via poolr\   r=   r3  zFAuxiliary client: OpenRouter pool exhausted, trying OPENROUTER_API_KEYOPENROUTER_API_KEYzAuxiliary client: OpenRouter)r3  r+  rX   rY   _mark_provider_unhealthyr6  r  r  r  r3   rx   ra   rR  r  )	r7  r   r.  	cfg_modelor_modelr  r  or_keyr=   s	            r   _try_openrouterr@  	  s   355Iy!	H 
11 
#
 	
 	
 	
 	!26666z(## 'X&&&,\::L% 	_!A%:5%A%A 	I-e5HII`M`HLL@AAA((+;+=+=? ? ?@HI I 	]^^^F1E!F!FF  26666z
LL/000 :M#3#5#57 7 78@A Ar   c                  z    t          d          \  } }| r|dS t          |          sdS t          d          sdS dS )z>Return a more precise OpenRouter auth failure reason for logs.rB  NzOOpenRouter credential pool has no usable entries (credentials may be exhausted)z=OpenRouter credential pool entry is missing a runtime API keyr;  zOPENROUTER_API_KEY not setz&no usable OpenRouter credentials found)r  r  r  )r  r  s     r    _describe_openrouter_unavailablerB  	  s\    ,\::L% S=dd$U++ 	SRR/00 ,++33r   visionc                 4   	 ddl m}  |            }|4|dk    r.t                              d|           t	          d|           dS n# t
          $ r Y nw xY wt                      }t          d          }|/|s-t                              d	           t	          dd
           dS ||rt                              d           da	t                              d           t          }	 ddlm}  ||           }|r#|}t                              d| rdnd|           n t                              d| rdnd|           n8# t
          $ r+}t                              d| rdnd||           Y d }~nd }~ww xY w||\  }	}
nt          |pi           }	|	s-t                              d           t	          dd
           dS t          |pi                     d          pt!                                                    d          }
t%          |	|
          |fS )Nr   )nous_rate_limit_remainingz?Auxiliary: skipping Nous Portal (rate-limited, resets in %.0fs)r  r9  r  Fr  zSAuxiliary Nous client unavailable: no Nous authentication found (run: hermes auth).r  zLAuxiliary Nous: runtime JWT refresh failed; checking stored auth.json token.TzAuxiliary client: Nous Portalget_nous_recommended_aux_modelrC  z/Auxiliary/%s: using Portal-recommended model %srC  r  z:Auxiliary/%s: no Portal recommendation, falling back to %szGAuxiliary/%s: recommended-models lookup failed (%s); falling back to %sz]Auxiliary Nous client unavailable: no usable inference JWT found (run: hermes auth add nous).r  r   r_   )agent.nous_rate_guardrE  rX   rx   r<  rK   r  r  rY   r_  _NOUS_MODELr  rG  r  rI   rJ   r  rx  ra   )rC  rE  
_remainingr  runtimer   rG  recommendedr   r\   r=   s              r   	_try_nousrN  	  s   CCCCCC..00
!j1nnLLQ   %V<<<<:    D'e<<<Gt"	
 	
 	
 	!R0000z4	
 	
 	

 
LL0111 E
DDDDDD44FCCC 
	ELLA".   
 LLL".    
 
 
!*HHFC	
 	
 	
 	
 	
 	
 	
 	

 #
++ 	NN/   %V4444:
''(<==QAQAQRRYYZ]^^	
 	
 	
 	 s+   AA	 	
AA*AE 
E7!E22E7stale_modelc                    |pd                                                                 }d}	 ddlm}  || d          }n8# t          $ r+}t
                              d|t                     Y d}~nd}~ww xY w|r,|                                                                 |k    r|S t                                                                           |k    rt          S dS )u  Re-fetch the Nous Portal's recommended model after a stale-model 404.

    Long-lived processes (gateway, watchers) cache the Portal's
    ``recommended-models`` payload for 10 minutes and, in practice, can pin a
    model for the whole process lifetime. When that model is later dropped from
    the Nous → OpenRouter catalog, every auxiliary call 404s with
    "model does not exist". This forces a fresh Portal fetch and returns a
    model name to retry with:

      * the Portal's current recommendation for the task, if it differs from
        the model that just failed; otherwise
      * ``_NOUS_MODEL`` (google/gemini-3-flash-preview), the known-good default,
        if it too differs from the failed model.

    Returns ``None`` when no usable alternative is available (e.g. the Portal
    still recommends the exact model that just 404'd and the default also
    matches it) — callers should then let the original error propagate.
    rB   Nr   rF  T)rC  r  z<Nous recommended-model refresh failed (%s); using default %s)r   r   r  rG  rK   rX   rx   rJ  )rC  rO  stalefreshrG  r   s         r   _refresh_nous_recommended_modelrS  *
  s   * B%%''--//EE
DDDDDD..fDQQQ 
 
 
J	
 	
 	
 	
 	
 	
 	
 	


  $$&&%//   ""e++4s   A   
A5
!A00A5c                  X   t          d          } t          | t                    r(|                                 r|                                 S 	 ddlm}  |            }|                    di           }t          |t                    r(|                                r|                                S t          |t                    rS|                    dd          }t          |t                    r(|                                r|                                S n# t          $ r Y nw xY wdS )a6  Read the user's configured main model from config.yaml.

    config.yaml model.default is the single source of truth for the active
    model. Environment variables are no longer consulted.

    Runtime override: when an AIAgent is active with a CLI/gateway-provided
    model that differs from config.yaml, ``set_runtime_main()`` records the
    override in a process-local global. This is consulted FIRST so tools
    that gate on "the active main model" (e.g. ``vision_analyze``'s native
    fast path) see the live runtime, not the persisted config default.
    r   r   rA  r  rB   )	_runtime_main_valuer$   rI   r   rH   rA   rJ   r5  rK   )overriderA   r2  	model_cfgr  s        r   _read_main_modelrX  S
  s)    #7++H(C    X^^%5%5  ~~::::::""$$GGGR((	i%% 	%)//*;*; 	%??$$$i&& 	'mmIr22G'3'' 'GMMOO '}}&   2s   A"D 1A'D 
D'&D'c                  &   t          d          } t          | t                    r:|                                 r&|                                                                 S 	 ddlm}  |            }|                    di           }t          |t                    re|                    dd          }t          |t                    r:|                                r&|                                                                S n# t          $ r Y nw xY wdS )u  Read the user's configured main provider from config.yaml.

    Returns the lowercase provider id (e.g. "alibaba", "openrouter") or ""
    if not configured.

    Runtime override: see ``_read_main_model`` — same mechanism for the
    provider half of the runtime tuple.
    r   r   rA  r   rB   )
rU  r$   rI   r   r   rH   rA   rJ   r5  rK   )rV  rA   r2  rW  r   s        r   r   r   q
  s    #:..H(C   (X^^%5%5 (~~%%'''	::::::""$$GGGR((	i&& 	0 }}Z44H(C(( 0X^^-=-= 0~~''--///   2s    BD 
DDc                     t          d          } t          | t                    r(|                                 r|                                 S 	 ddlm}  |            }|                    di           }t          |t                    rS|                    dd          }t          |t                    r(|                                r|                                S n# t          $ r Y nw xY wdS )a:  Read the user's main model API key from the runtime override or config.

    Mirrors ``_read_main_model`` / ``_read_main_provider``: checks the
    process-local ``_RUNTIME_MAIN_API_KEY`` override first (set by
    ``set_runtime_main`` when an AIAgent is active), then falls back to
    ``model.api_key`` in config.yaml.

    Used by the ``custom`` provider fallback chain so that auxiliary tasks
    configured with an explicit ``base_url`` but empty ``api_key`` inherit
    the main model's credentials instead of falling to ``no-key-required``
    (issue #9318).
    r\   r   r2  r   rB   	rU  r$   rI   r   rH   r2  rJ   r5  rK   )rV  r2  r2  rW  r<  s        r   _read_main_api_keyr]  
  s     #9--H(C    X^^%5%5  ~~	111111kmmGGGR((	i&& 	#--	2..C#s## #		 #yy{{"   2   BC 
C*)C*c                     t          d          } t          | t                    r(|                                 r|                                 S 	 ddlm}  |            }|                    di           }t          |t                    rS|                    dd          }t          |t                    r(|                                r|                                S n# t          $ r Y nw xY wdS )zRead the main model's base_url from the runtime override or config.

    Same override-then-config pattern as ``_read_main_api_key``.
    r=   r   r[  r   rB   r\  )rV  r2  r2  rW  bases        r   _read_main_base_urlra  
  s    
 #:..H(C    X^^%5%5  ~~	111111kmmGGGR((	i&& 	$==R00D$$$ $ $zz||#   2r^  preset_namec                    	 ddl m} ddlm}  | |                                d          pi | pd          }|                    d          pi }t          |                    d          pd                                          }t          |                    d	          pd                                          }|r|r|                                dk    r||fS n-# t          $ r  t          
                    d
| d           Y nw xY wdS )u  Resolve a MoA preset to its aggregator (provider, model) pair.

    "moa" is a virtual provider — the acting model of a preset is its
    aggregator slot, and there is no real "moa" HTTP endpoint. Auxiliary
    tasks (title generation, compression, vision, commit messages, …) don't
    need the reference fan-out, so every aux resolution layer maps
    provider="moa"/model=<preset> to the aggregator's real provider+model
    through this single helper (shared by ``_resolve_auto``,
    ``_resolve_task_provider_model``, and ``resolve_provider_client`` so the
    preset lookup and validation cannot drift between paths).

    Args:
        preset_name: The MoA preset name (usually carried in the "model"
            field), or None/"" to resolve the user's default preset.

    Returns:
        (aggregator_provider, aggregator_model), or (None, None) when the
        preset cannot be resolved (missing config, renamed/deleted preset,
        or a malformed aggregator slot).
    r   r[  )resolve_moa_presetmoaN
aggregatorr   rB   r   z.MoA aggregator resolution failed for preset %rTrt   r  )rH   r2  hermes_cli.moa_configrd  rJ   rI   r   r   rK   rX   rx   )rb  r2  rd  presetaggagg_provider	agg_models          r   _resolve_moa_aggregatorrl  
  sF   *
111111<<<<<<##KKMM$5$5e$<$<$BKDWSWXXjj&&,"377:..4"55;;==((.B//5577	 	+I 	+,*<*<*>*>%*G*G** 
 
 
<kTX 	 	
 	
 	
 	
 	

 :s   CC 'DDc                      t                      } t                      pd                                                                dk    rt	          |           \  }}|pdS | S )uD  Main model with MoA presets unwrapped to the aggregator's model.

    When the main provider is ``moa``, ``_read_main_model()`` returns a MoA
    *preset name* (e.g. "opus-gpt") — never a valid wire model id on any
    provider. Auxiliary fallback chains that pre-fill a missing model from
    the main model must use this reader instead, so unset aux models default
    to the preset's acting (aggregator) model. Returns "" when the main
    provider is moa but the preset cannot be resolved — sending nothing is
    strictly better than sending a preset name that 400s.
    rB   re  )rX  r   r   r   rl  )r   r%  rk  s      r   _read_main_model_for_auxrn  
  s]     E#**,,2244==.u559BLr   aux_base_urlc                     t          |           }|sdS t          t                                }|r||k    rdS t                      S )u  Return the main api_key only when *aux_base_url* points at the same
    host as the main model's base_url.

    The #9318 use case is an auxiliary task sharing the main model's
    self-hosted gateway (same host, different model) with an empty per-task
    api_key. Inheriting unconditionally would send the main credential to
    ANY host a misconfigured aux base_url names — a cross-host credential
    leak. A host mismatch keeps the previous fail-safe behavior
    (``no-key-required`` → 401).
    rB   )r5   ra  r]  )ro  aux_host	main_hosts      r   _read_main_api_key_if_same_hostrs  
  sU     !..H r!"5"7"788I I--rr   _RUNTIME_MAIN_PROVIDER_RUNTIME_MAIN_MODEL_RUNTIME_MAIN_BASE_URL_RUNTIME_MAIN_API_KEY_RUNTIME_MAIN_API_MODE_RUNTIME_MAIN_AUTH_MODEauxiliary_runtime_mainr/  _RUNTIME_MAIN_CONTEXTauxiliary_relay_call_RELAY_AUX_CALL_CONTEXTc                 F     t          j                    fd            }|S )zHGive every physical retry in one auxiliary call a shared Relay identity.c            	         | r| d         n|                     d          }t                              t          |pd          dt	          j                    j         ddddd          }	  | i |t                              |           S # t          $ r t                        w xY w# t                              |           w xY wNr   taskunknownzaux-rB   chat_completions)r  
request_idattempt_countr   r   r  
rJ   r}  r   rI   uuiduuid4hexresetr   _fail_relay_auxiliary_callr    r!   r  r  r   s       r   wrappedz&_relay_auxiliary_call.<locals>.wrapped  s    6tAwwFJJv$6$6'++)	**3!133*-
 -
  	18T,V,,
 $))%0000	  	 	 	&(((	 $))%0000s   +B B''B* *C	functoolswrapsr   r  s   ` r   _relay_auxiliary_callr    :     _X1 1 1 1 1$ Nr   c                 F     t          j                    fd            }|S )z3Async counterpart to :func:`_relay_auxiliary_call`.c            	        K   | r| d         n|                     d          }t                              t          |pd          dt	          j                    j         ddddd          }	  | i | d {V 	 t                              |           S # t          $ r t                        w xY w# t                              |           w xY wr  r  r  s       r   r  z,_relay_auxiliary_call_async.<locals>.wrapped6  s     6tAwwFJJv$6$6'++)	**3!133*-
 -
  	1!426222222222
 $))%0000	  	 	 	&(((	 $))%0000s   -B B00B3 3Cr  r  s   ` r   _relay_auxiliary_call_asyncr  3  r  r   c                     t                                           }|d S t          | pd          |d<   t          |pd          |d<   t          |pd          |d<   d S )Nr-  r   r  r   r  r  )r}  rJ   rI   )r   r   r  contexts       r   _set_relay_auxiliary_router  L  sk    
 &))++Gh5+66GJ5-I..GGh<*<==GJr   r   r  c           
         t                                           }|d S t          |                    d          pd          }|dz   |d<   t          | p|                    d          pd          }t          |                    d          pd          }||t          |p|                    d          pd	          t          |d
                   d|d          |t          |d                   dfS )Nr  r   r   r   r-  r   r  r  r  r  z
auxiliary:r  )r  api_request_id	call_roleretry_countauxiliary_task)r}  rJ   rL  rI   )r   r  r  r  provider_name
model_names         r   _relay_auxiliary_metadatar  Y  s    
 &))++GtO449::M,q0GOJGKK
$;$;J{KKMW[[))6Y77J*QGKK
$;$;Q?QRRgl3443'&/33$gfo..' '  r   r   r  r  rZ   r  c          
          
 |p fd
t          ||          }|t          
|          S |\  }}}ddlm}	 |	                    |
fd|t          |                    d          p|          |d          S )	Nc                 2     j         j        j        di | S Nr   rG  r@  r  requestrZ   s    r   r{  z(_relay_sync_completion.<locals>.<lambda>v       *H&+*A*H*S*S7*S*S r   r  r   	relay_llmc                 $    t          |           S r   )r   )r  r   s    r   r{  z(_relay_sync_completion.<locals>.<lambda>  s    9(GLL r   r   Tr   r  metadatadefer_logical_completion)r  r   agentr  execute_currentrI   rJ   )rZ   r!   r   r  r  router  fallback_modelr  r  r   s   `         @r   _relay_sync_completionr  n  s     TSSSSH%x(KKKE }06BBB.3+M>8$$LLLLvzz'**<n==!% %   r   c          
          K   |p fd}t          ||          }| ||           d {V S |\  }}}	ddlm}
 |
                    |||t	          |                    d          p|          |	d           d {V S )Nc                 2     j         j        j        di | S r  r  r  s    r   r{  z)_relay_async_completion.<locals>.<lambda>  r  r   r  r   r  r   Tr  )r  r  r  execute_current_asyncrI   rJ   )rZ   r!   r   r  r  r   r  r  r  r  r  s   `          r   _relay_async_completionr    s       TSSSSH%x(KKKE}Xf%%%%%%%%%.3+M>800vzz'**<n==!% 1         r   c          
           t          ||          }|  j        j        j        di |S |\  }}}ddlm} |                    | fd|t          |                    d          p|          t          |d           S )	Nr  r   r  c                 2     j         j        j        di | S r  r  r  s    r   r{  z$_relay_sync_stream.<locals>.<lambda>  s     6/6AAAA r   r   c                 "    t          | d          S )Nr  )r  )r=  s    r   r{  z$_relay_sync_stream.<locals>.<lambda>  s    75)3L3L r   )r   r  	finalizerr  completed_response_predicater   )
r  rG  r@  r  r  r  stream_currentrI   rJ   r5  )	rZ   r!   r   r  r  r  r  r  r  s	   `        r   _relay_sync_streamr    s     &x(KKKE}-v{&-77777.3+M>8##AAAAvzz'**<n==%L%L $   r   rB   rB   rB   rB   rB   rB   ._RUNTIME_MAIN_COMPAT_SNAPSHOTc                      t          j                    t          j                    urdS t          t          t
          t          t          t          f} | t          k    rdS t          t          t          |                     S )a{  Expose deliberately patched legacy globals in a single main context.

    ``set_runtime_main`` mirrors values into the old module attributes for
    introspection, but those mirrors must never become runtime inputs. A direct
    patch is recognized only when it differs from the mirrored snapshot and
    only on the main thread, keeping concurrent session workers isolated.
    N)r   current_threadmain_threadrt  ru  rv  rw  rx  ry  r  r5  zip_MAIN_RUNTIME_FIELDS)valuess    r   _compat_runtime_mainr    sk     !!)>)@)@@@tF ...t(&11222r   fieldc                     t                                           }|t                      }t          |t                    r|                    |           }|r|S dS )zERead one runtime field through context-local/controlled legacy state.NrB   )r{  rJ   r  r$   r5  )r  rL  r=  s      r   rU  rU    sX    #''))G&(('4   E"" 	L2r   )requested_providerr=   r\   r  	auth_moder  r  c                   | pd                                                                 |pd                                                                 |pd                                 |pd                                 t          |t                    r|                                 nt	          |          r|nd|pd                                 |pd                                                                 dt
                                        }t          5  fdt          D             \  a	a
aaaat          fdt          D                       addd           n# 1 swxY w Y   |S )zRecord the current context's live main runtime for auxiliary routing.

    Context-local state prevents concurrent gateway sessions from overwriting
    one another while retaining compatibility mirrors for legacy readers.
    rB   )r   r  r   r=   r\   r  r  c              3   (   K   | ]}|         V  d S r   r   r   r  rL  s     r   	<genexpr>z#set_runtime_main.<locals>.<genexpr>
  s'      >>WU^>>>>>>r   c              3   (   K   | ]}|         V  d S r   r   r  s     r   r  z#set_runtime_main.<locals>.<genexpr>  s8       .
 .
$GEN.
 .
 .
 .
 .
 .
r   N)r   r   r$   rI   ry   r{  r   _RUNTIME_MAIN_COMPAT_LOCKr  rt  ru  rv  rw  rx  ry  tupler  )	r   r   r  r=   r\   r  r  r  rL  s	           @r   set_runtime_mainr    s   & ^**,,224417R>>@@FFHH+2$$&&^**,, '3''6GMMOOO$W--52^**,,o2,,..4466 G "%%g..E	" 
 
 ?>>>)=>>>	
""!"#(- .
 .
 .
 .
(<.
 .
 .
 )
 )
%
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 Ls   ;EE #E r  c                 t    | dS 	 t                               |            dS # t          t          f$ r Y dS w xY w)z:Restore the runtime binding that preceded one scoped turn.N)r{  r  r  r  )r  s    r   reset_runtime_mainr    sT    }##E******%    	s   " 77main_runtimec              #      K   t          |           }t                              |pd          }	 |V  t                              |           dS # t                              |           w xY w)zETemporarily bind an explicit runtime without touching legacy mirrors.N)_normalize_main_runtimer{  r   r  )r  rL  r  s      r   scoped_runtime_mainr    so       &l33G!%%go66E+##E*****##E****s   A A+c                      t                               d           t          5  dadadadadadada	ddd           dS # 1 swxY w Y   dS )z2Clear the runtime override in the current context.NrB   r  )
r{  r   r  rt  ru  rv  rw  rx  ry  r  r   r   r   clear_runtime_mainr  (  s    
 d###	" A A!# !# "!#"$(@%A A A A A A A A A A A A A A A A A As   >AAc                     	 ddl m}   | d          }n4# t          $ r'}t                              d|           d}Y d}~nd}~ww xY wt          |t                    sRt          j        dd          	                                
                    d	          }t          d
          }|sdS ||d}|                    d          }|                    d          }|                    d          }t          |t                    r|	                                sdS |	                                
                    d	          }t          |d          rdS t          |t                    r|	                                sd}t          |t                    r|	                                sd}||	                                |fS )zResolve the active custom/main endpoint the same way the main CLI does.

    This covers both env-driven OPENAI_BASE_URL setups and config-saved custom
    endpoints where the base URL lives in config.yaml instead of the live
    environment.
    r   resolve_runtime_providerr   )	requestedz6Auxiliary client: custom runtime resolution failed: %sNOPENAI_BASE_URLrB   r   OPENAI_API_KEYNNNr=   r\   r=   r\   r  openrouter.aino-key-required)hermes_cli.runtime_providerr  rK   rX   rx   r$   r5  rH  r  r   rx  r  rJ   rI   r4   )r  rL  r   openai_base
openai_keycustom_base
custom_keycustom_modes           r   _resolve_custom_runtimer  8  s   HHHHHH**X>>>   MsSSS gt$$ 
i 1266<<>>EEcJJ$%566
 	$###!
 

 ++j))KY''J++j))Kk3''  {/@/@/B/B  ##%%,,S11K[/::     j#&& 'j.>.>.@.@ '&
k3'' {/@/@/B/B 
((**K77s    
AAAc                  .    t                      \  } }}| pdS NrB   )r  )r  r%  s     r   _current_custom_base_urlr  j  s    /11KA"r   c            	      D   ddl m}  t                       dD ]}t          t          j                            |          pd                                          }|sE	  | |          }|j        r|j	        }`# t          $ r}t          d| d|d          |d}~ww xY wdS )	a  Fail fast with a clear error when proxy env vars have malformed URLs.

    Common cause: shell config (e.g. .zshrc) with a typo like
    ``export HTTP_PROXY=http://127.0.0.1:6153export NEXT_VAR=...``
    which concatenates 'export' into the port number.  Without this
    check the OpenAI/httpx client raises a cryptic ``Invalid port``
    error that doesn't name the offending env var.
    r   r  )HTTPS_PROXY
HTTP_PROXY	ALL_PROXYhttps_proxy
http_proxy	all_proxyrB   z%Malformed proxy environment variable rf  z1. Fix or unset your proxy settings and try again.N)r  r   r8   rI   rH  rI  rJ   r   schemeportr  r  )r   r<  r=  r   r%  r   s         r   _validate_proxy_env_urlsr  o  s     &%%%%%:  BJNN3''-2..4466 		Xe__F}  K 	 	 	B B Be B B B  	 s   A77
BBBc                    ddl m} t          | pd                                          }|r|                    d          rdS 	  ||          }|j        dv r	|j        }dS dS # t          $ r}t          d|d          |d}~ww xY w)	zEReject obviously broken custom endpoint URLs before they reach httpx.r   r  rB   zacp://N>   httphttpszMalformed custom endpoint URL: zJ. Run `hermes setup` or `hermes model` and enter a valid http(s) base URL.)	r  r   rI   r   r   r  r  r  r  )r=   r   ri  r   r%  r   s         r   _validate_base_urlr    s    %%%%%%HN##))++I 	,,X66 )$$=---AAA .-   Wi W W W
 
 	s   A# #
B-BBc                     t                      } t          |           dk    r| \  }}d }n| \  }}}|r|sdS |                                                    t                                                    rdS t                      pd}t                              d||pd           t          |          \  }}|rd|ini }t          d           }|r||d<   |dk    r!t          d||d	|}	t          |	|          |fS |d
k    re	 ddlm}
  |
||          }	n;# t          $ r. t                              d           t          d||d	||fcY S w xY wt!          |	|||d          |fS t          d||d	|}t#          |||||          }||fS )Nre  r  gpt-4o-miniz3Auxiliary client: custom endpoint (%s, api_mode=%s)r  default_queryr3  codex_responsesr_   r}  r   r  u|   Custom endpoint declares api_mode=anthropic_messages but the anthropic SDK is not installed — falling back to OpenAI-wire.Fr  r   )r  rj  r   r   _CODEX_AUX_BASE_URLrn  rX   rx   r   r>  ra   rD  rh  r  rU   rY   r  r  )rL  r  r  r  r   _clean_base_dq_extra_custom_headersr  r  _fallback_clients               r   _try_custom_endpointr
    s=   %''G
7||q")Z/6,Z j z%%&9&?&?&A&ABB z$&&7-E
LLF{Op^pqqq0==K'*2os##F
 2$77O 4$3 !'''+_J__X^__#K77>>***	dFFFFFF00[IIKK 	d 	d 	dNNR   )\k\\U[\\^ccccc	d %[%[[`aaa
 	
 -`Z+``Y_``,%[+  U""s   D 5EEc                    | st                               d           dS t                      }|dS |\  }}t                               d|            ddlm} t          || |                      }t          ||           | fS )u  Build a CodexAuxiliaryClient for an xAI Grok OAuth-authenticated session.

    xAI's ``/v1/responses`` endpoint speaks the OpenAI Responses API, so we
    wrap a plain ``OpenAI`` client in ``CodexAuxiliaryClient`` to translate
    ``chat.completions.create()`` calls into ``responses.stream()`` requests.

    The caller must pass an explicit model — pinning a default for Grok
    would silently rot when xAI's allowlist drifts.  Returns ``(None, None)``
    when the user has not authenticated with xAI Grok OAuth.
    zuAuxiliary client: xai-oauth requested without a model; pass model explicitly (auxiliary.<task>.model in config.yaml).r  Nz2Auxiliary client: xAI OAuth (%s via Responses API)r   hermes_xai_default_headersr:  )rX   rY   r
  rx   tools.xai_httpr  ra   rD  )r   resolvedr\   r=   r  r  s         r   _build_xai_oauth_aux_clientr    s      M	
 	
 	
 z)++Hz GX
LLEuMMM999999'2244  K
  U33U::r   c                    | st                               d           dS t          d          \  }}|rHt          |          }|rt	          |t
                    pt
          }n3t                      }|sdS t
          }nt                      }|sdS t
          }t                               d|            t          ||t          |                    }t          ||           | fS )a  Build a CodexAuxiliaryClient for an explicitly-requested model.

    There is no auto-selection of the Codex model: the ChatGPT-account
    Codex endpoint's accepted model list is an undocumented, drifting
    allow-list, so any hardcoded default we pick goes stale.  The caller
    is responsible for passing the model (e.g. from the user's own
    ``model.model`` or ``auxiliary.<task>.model`` config).

    Returns (None, None) when no Codex OAuth token is available.
    zxAuxiliary client: openai-codex requested without a model; pass model explicitly (auxiliary.<task>.model in config.yaml).r  r   z4Auxiliary client: Codex OAuth (%s via Responses API)r:  )rX   rY   r  r  r  r  r  rx   ra   rr  rD  )r   r  r  codex_tokenr=   r  s         r   _build_codex_clientr    s     M	
 	
 	
 z,^<<L% '+E22 	+-e5HII`M`HH244K "!z*HH.00 	:&
LLGOOO'1+>>  K
  U33U::r   r   r7  explicit_base_urlr  r  c                 l   	 ddl m} ddlm} ddlm} n# t          $ r Y dS w xY w	  |            }t          |t                    r|	                    d          ni }t          |t                    si }n# t          $ r i }Y nw xY w	  |d||||           }	n\# |$ r&}
t                              d	|
           Y d
}
~
dS d
}
~
wt          $ r&}
t                              d|
           Y d
}
~
dS d
}
~
ww xY w|		                    d          }t          |		                    dd          pd          }|p|		                    d          pd}t          |          st          |          nd}|r|sdS t!          | p#t          |	                    d          pd          d          }|s1t                              d| |	                    d                     dS i }t#          |          \  }}|r||d<   t%          d||d|}|dk    rt'          ||          |fS |dk    rt)          |||||          |fS ||fS )u  Resolve an Azure Foundry auxiliary client via the runtime resolver.

    Mirrors the ``_try_anthropic`` / ``_try_nous`` shape but delegates to
    :func:`hermes_cli.runtime_provider._resolve_azure_foundry_runtime` —
    the same resolver the main agent uses — so:

    * ``auth_mode: api_key`` (default) gets the static
      ``AZURE_FOUNDRY_API_KEY`` string.
    * ``auth_mode: entra_id`` gets a callable bearer-token provider
      (``Callable[[], str]`` from
      :mod:`agent.azure_identity_adapter`).
    * Per-model ``api_mode`` auto-routing for GPT-5.x / o-series /
      codex models works.
    * ``model.entra.{tenant_id,client_id,authority,scope}`` config
      fields propagate.
    * Non-default ``model.base_url`` overrides are honored.

    The OpenAI SDK accepts both shapes for ``api_key`` so the caller
    can forward the result without coercion.

    Returns ``(client, model)`` or ``(None, None)`` on failure.
    r   )_resolve_azure_foundry_runtime)	AuthErrorrA  r  r   azure-foundry)r  rW  r7  r  target_modelzAuxiliary azure-foundry: %sNz)Auxiliary azure-foundry runtime error: %sr\   r=   rB   r  r  Tr  zAAuxiliary azure-foundry: no model resolved (model=%r, default=%r)r  r_   r  r}  r   )r  r  r  r  rH   rA   rU   r$   r5  rJ   rK   rX   rx   rI   ry   rn   _normalize_resolved_modelr   ra   rD  r  )r   r7  r  r  r  r  rA   r2  rW  rL  r   r\   r=   runtime_api_mode_has_keyfinal_modelr   r  r  rZ   s                       r   _try_azure_foundryr    s   :NNNNNN------:::::::   zz""$$(23(=(=ECGGG$$$2	)T** 	I   			00.-/
 
 
    2C888zzzzz   @#FFFzzzzz kk)$$G7;;z2..4"55HP7;;z#:#:P>P
 %-W$5$5?tG}}}4H 8 z+4Y]]9--344 K   	O9==++	
 	
 	
 z
 E0::K
 %!$o"R7[RRERRF,,, $FK88+EE///
 %K&
 
  	 ;sB    
##AA5 5BBB C2B??C2C--C2c                    	 ddl m}m} n# t          $ r Y dS w xY wt	          d          \  }}|r|| pt          |          }nd }| p	 |            }|sdS |rt          |t                    nt          }	 ddlm	}  |            }|
                    d          }	t          |	t                    rt          |	
                    d          pd                                                                          }
|
dk    rO|	
                    d	          pd                                                    d
          }|rt#          |          r|}n# t$          $ r Y nw xY wddl m}  ||          }t)          d          pd}t*                              d|||           	  |||          }n# t          $ r Y dS w xY wt/          |||||          |fS )Nr   )r  resolve_anthropic_tokenr  r   rA  r   r   rB   r=   r   )_is_oauth_tokenr  z8Auxiliary client: Anthropic native (%s) at %s (oauth=%s)r  )rh  r  r!  rU   r  r  r  _ANTHROPIC_DEFAULT_BASE_URLrH   rA   rJ   r$   r5  rI   r   r   rx  r  rK   r"  r  rX   rx   r  )r7  r  r!  r  r  r  r=   rA   r2  rW  cfg_providercfg_base_urlr"  rc  r   r  s                   r   r  r    sj   [[[[[[[[[   zz -[99L% >) @$9%$@$@  =$;$;$=$= z NZz%e-HIII_zH::::::""$$GGG$$	i&& 	,y}}Z88>B??EEGGMMOOL{** )j 9 9 ?RFFHHOOPSTT ,$A,$O$O ,+H    877777u%%H'44S8SE
LLKUT\^fggg,,UH==    zz	
 $KxRZ[[[]bbbs1    
5CE 
EEF* *
F87F8rB  r  local/customapi-keyr@  rN  r
  r'  )r   r   r=   r\   r  r  )r  c                 8   | )t                                           } | t                      } t          | t                    si S i }t
          D ]}|                     |          }|dk    r*t          |          rt          |t                    s|||<   Gt          |t                    r+|                                r|                                ||<   dD ]C}|                    |          }t          |t                    r|	                                ||<   D|S )u  Return a sanitized copy of a live main-runtime override.

    Most fields are stripped strings. ``api_key`` may legitimately be a
    zero-arg callable (Azure Foundry Entra ID token provider) — preserve
    those as-is so auxiliary clients inherit the same authentication
    surface as the main agent. The OpenAI SDK accepts ``Callable[[], str]``
    for ``api_key`` and calls it before every request.
    Nr\   )r   r  )
r{  rJ   r  r$   r5  _MAIN_RUNTIME_CONTEXT_FIELDSry   rI   r   r   )r  r   r  r=  identity_fieldidentitys         r   r  r    s    
 -0022/11LlD)) 	!#J- . .  ''I(5//*UC:P:P %JueS!! 	.ekkmm 	. %Ju< : :>>.11h$$ 	:)1)9)9J~&r   c                  F    dt           fdt          fdt          fdt          fgS )aB  Return the ordered provider detection chain.

    Built at call time (not module level) so that test patches
    on the ``_try_*`` functions are picked up correctly.

    NOTE: ``openai-codex`` is deliberately NOT in this chain.  The
    ChatGPT-account Codex endpoint only accepts a shifting, undocumented
    allow-list of model IDs, so falling back to it with a guessed model
    fails more often than not.  Codex is used only when the user's main
    provider *is* openai-codex (see Step 1 of ``_resolve_auto``) or when
    a caller explicitly requests it with a model.
    rB  r  r&  r'  r(  r   r   r   _get_provider_chainr.    s0     
'		-.	-.	 r   X  _aux_unhealthy_until_aux_unhealthy_logged_atr   )rB  r  r   r&  r   r   c                     | sdS t          |                                                                           }t                              ||          S )a  Normalize a resolved_provider value to a chain label used by
    ``_get_provider_chain()``. Falls back to the lowercased input for
    direct API-key providers (deepseek, alibaba, minimax, etc.) which
    each report their own provider name from the api-key chain.
    rB   )rI   r   r   _AUX_UNHEALTHY_LABEL_ALIASESrJ   )r   ps     r   _normalize_chain_labelr5  3  sJ      rH##%%A'++Aq111r   rQ  c                 .   t          |           }|sdS t          j                    ||nt          z   }|t          |<   t                              d|t          ||nt                    t          j        dt          j        |                               dS )zMark ``provider`` as recently-402'd, hidden from chain iteration
    until the TTL expires. Called from the payment-fallback branches in
    ``call_llm`` and ``acall_llm`` after a confirmed payment error.
    NzsAuxiliary: marking %s unhealthy for %ds (payment / credit error). Subsequent auxiliary calls will skip it until %s.z%H:%M:%S)	r5  r  _AUX_UNHEALTHY_TTL_SECONDSr0  rX   rY   rL  strftime	localtime)r   rQ  labelr  s       r   r<  r<  ?  s    
 #8,,E s<VWJ",
NN	<3?CC(BCCj$."<"<==    r   r:  c                     | sdS t                               |           }|dS t          j                    |k    r8t                               | d           t                              | d           dS dS )zTrue iff ``label`` is in the unhealthy cache and the TTL hasn't expired.
    Lazily evicts expired entries so the cache stays small.
    FNT)r0  rJ   r  r  r1  )r:  r  s     r   r  r  R  sv      u%))%00Juy{{j    --- $$UD111u4r   r  c                 <   t          j                     }t                              | d          }||z
  dk    rd|t          | <   t                              | |          }t                              d|pd| t          dt          ||z
                                 dS dS )zEmit a single info-level log per minute when we skip an unhealthy
    provider. Avoids spamming the log on bursty sessions while still
    giving the user a trail.
            r  zIAuxiliary %s: skipping %s (recently returned payment error, retry in %ds)callr   N)r  r1  rJ   r0  rX   infor  rL  )r:  r  nowlastr  s        r   _log_skip_unhealthyrB  b  s    
 )++C#''s33D
TzR*- ')--eS99
WNFE3q#j3.>*?*?#@#@	
 	
 	
 	
 	
 r   c                  j    t                                            t                                           dS )zvClear the unhealthy cache. Used by tests and by a future explicit
    user trigger (e.g. ``hermes config aux reset``).N)r0  r  r1  r   r   r   _reset_aux_unhealthy_cacherD  r  s.        ""$$$$$r   r   c                     t          | dd          }|dk    rdS t          |                                           |dv rt          fddD                       rdS dS )	u
  Detect payment/credit/quota exhaustion errors.

    Returns True for HTTP 402 (Payment Required) and for 429/other errors
    whose message indicates billing exhaustion or daily quota exhaustion
    rather than transient rate limiting.

    Daily token quota errors (e.g. Bedrock "Too many tokens per day",
    Vertex AI "quota exceeded") are functionally equivalent to credit
    exhaustion — the provider cannot serve the request until the quota
    resets — and should trigger the same provider-fallback logic.
    status_codeN  T>   NrG        c              3       K   | ]}|v V  	d S r   r   r   kw	err_lowers     r   r  z$_is_payment_error.<locals>.<genexpr>  s7        2rY      r   )creditsinsufficient fundscan only affordbillingpayment requiredout of fundsrun out of fundsbalance_depletedno usable credits model_not_supported_on_free_tiernot available on the free tierzrequires a subscriptionzupgrade for accesszupgrade for higher limitsz reached your session usage limitzquota exceededquota_exceededztoo many tokens per dayzdaily limitztokens per dayzdaily quotazresource exhaustedzweekly usage limitzweekly limitFro   rI   r   anyr   statusrN  s     @r   _is_payment_errorr_  y  s     S-..F}}tC  I
 +++     *
      	" 45r   c                      	 ddl m}   | d          }|j        du S # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)zMReturn True only when the fresh Nous account API says paid access is allowed.r   )get_nous_portal_account_infoT)force_freshz8Auxiliary Nous paid-entitlement refresh check failed: %sNF)hermes_cli.nous_accountra  paid_service_accessrK   rX   rx   )ra  account_infor   s      r   *_nous_portal_account_has_fresh_paid_accessrf    s|    HHHHHH33EEE/477   OQTUUUuuuuus    
AAAc                     t          | dd          }t          |                                           t          |           j        dk    rdS |dk    r:t          fddD                       rdS t          fdd	D                       sdS d
S )aH  Detect rate-limit errors that warrant provider fallback.

    Returns True for HTTP 429 errors whose message indicates rate limiting
    (as opposed to billing/quota exhaustion, which _is_payment_error handles).
    Also catches OpenAI SDK RateLimitError instances that may not set
    .status_code on the exception object.
    rF  NRateLimitErrorTrJ  c              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z'_is_rate_limit_error.<locals>.<genexpr>  s7        2rY      r   )
rate limit
rate_limitztoo many requestsz	try againzretry afterz	resets inc              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z'_is_rate_limit_error.<locals>.<genexpr>  s7        r2?      r   )rO  rP  rR  rS  rQ  rT  rU  rV  rW  rX  rY  F)ro   rI   r   r  r*   r\  r]  s     @r   _is_rate_limit_errorrm    s     S-..FC  I Cyy---t}}      *
      	 4     .
      	 45r   c                     	 ddl m} t          | |          rdS n# t          $ r Y nw xY wdt	          |           j        v rdS dt          |                                           v S )u  Detect a request timeout — the full-budget stall, distinct from a fast
    connection drop.

    A timeout burns the entire configured ``timeout`` before surfacing, so a
    same-provider retry on the critical compression path doubles the
    user-visible wall time (issue #54465). A streaming-close / dropped
    connection, by contrast, fails fast and is cheap to retry — those stay on
    the retry path even for compression.
    r   )APITimeoutErrorTTimeout	timed out)r   ro  r$   rU   r  r*   rI   r   )r   ro  s     r   _is_timeout_errorrr    s    ******c?++ 	4	   DII&&&t#c((..****s    
((c                 D   	 ddl m}m} t          | ||f          rdS n# t          $ r Y nw xY wt          |           j        t          fddD                       rdS t          |           	                                t          fddD                       rdS dS )	aE  Detect connection/network errors that warrant provider fallback.

    Returns True for errors indicating the provider endpoint is unreachable
    (DNS failure, connection refused, TLS errors, timeouts).  These are
    distinct from API errors (4xx/5xx) which indicate the provider IS
    reachable but returned an error.
    r   )APIConnectionErrorro  Tc              3       K   | ]}|v V  	d S r   r   )r   rM  err_types     r   r  z'_is_connection_error.<locals>.<genexpr>  s'      
L
Lb2>
L
L
L
L
L
Lr   )
Connectionrp  DNSSSLc              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z'_is_connection_error.<locals>.<genexpr>  s7        r2?      r   )zconnection refusedzname or service not knownzno route to hostznetwork is unreachablerq  zconnection resetzincomplete chunked readzpeer closed connectionzresponse ended prematurelyzunexpected eofremoteprotocolerrorlocalprotocolerrorF)
r   rt  ro  r$   rU   r  r*   r\  rI   r   )r   rt  ro  rN  rv  s      @@r   _is_connection_errorr}    s    >>>>>>>>c.@AA 	4	    Cyy!H

L
L
L
L$K
L
L
LLL tC  I
     &       t5s   ! 
..c                     t          |           rdS t          | dd          pt          t          | dd          dd          }t          |t                    o|dk    pd|cxk    odk     nc S )a(  Return True for a one-off transport blip worth retrying ON the
    same provider before any provider/model fallback.

    Covers connection/streaming-close errors (via the canonical
    ``_is_connection_error`` detector, shared so the two cannot drift) plus a
    pure 5xx/408 HTTP status. Deliberately narrow: this is the "retry the
    same target once" gate, distinct from ``_is_payment_error`` /
    ``_is_auth_error`` / ``_is_rate_limit_error`` which the except-chain
    handles by switching provider, refreshing creds, or rotating the pool.
    TrF  Nr  i  i  r/  )r}  ro   r$   rL  )r   r^  s     r   _is_transient_transport_errorr    s     C   tS-.. 'Z&&t3 3F fc""M#(L9L9L9L9L9L9L9L9LMr   re  g      ?c                      	 ddl m} m}  |  |            dd          }|t          S t	          |          }t          dt          |d                    S # t          $ r
 t          cY S w xY w)u  Number of same-provider retries for a transient transport blip.

    Read from ``auxiliary.transient_retries`` in config.yaml (default 2 →
    3 total attempts). Clamped to [0, 6] to bound worst-case wall time. A
    connection blip to a pinned auxiliary target (e.g. a MoA reference
    advisor) has no meaningful provider fallback, so a couple of retries with
    backoff is the difference between recovering and silently losing the call.
    Best-effort: any config-read failure falls back to the default.
    r   r0  r-  transient_retriesN   )rH   r1  r2  _DEFAULT_TRANSIENT_RETRIESrL  r  minrK   )r1  r2  r  ns       r   _transient_retry_countr  (  s    	*::::::::gkkmm[2EFF;--HH1c!Qii    * * *))))*s   %A ,A A)(A)c                    t          | dd          }|dk    rdS t          |                                           }d|v s(dt          |           j                                        v rdS |dk    rd|v rdS d	|v rd|v rdS d
S )zCDetect auth failures that should trigger provider-specific refresh.rF  N  Tzerror code: 401authenticationerrorrH  zbad-credentialsunauthenticatedF)ro   rI   r   r  r*   r]  s      r   _is_auth_errorr  >  s    S-..F}}tC  II%%)>$s))BTBZBZB\B\)\)\t }}*i77tI%%*;y*H*Ht5r   paramc                     |pd                                 }|sdS t          |                                            |vrdS t          fddD                       S )a/  Detect provider 400s for an unsupported request parameter.

    Different OpenAI-compatible endpoints phrase the same class of error a few
    ways: ``Unsupported parameter: X``, ``unsupported_parameter`` with a
    ``param`` field, ``X is not supported``, ``unknown parameter: X``,
    ``unrecognized request argument: X``.  We match on both the parameter
    name and a generic "unsupported/unknown/unrecognized parameter" marker so
    call sites can reactively retry without the offending key instead of
    surfacing a noisy auxiliary failure.

    Generalizes the temperature-specific detector that originally shipped
    with PR #15621 so the same retry strategy can cover ``max_tokens``,
    ``seed``, ``top_p``, and any future quirk. Credit @nicholasrae (PR #15416)
    for the generalization pattern.
    rB   Fc              3       K   | ]}|v V  	d S r   r   )r   markerrN  s     r   r  z2_is_unsupported_parameter_error.<locals>.<genexpr>f  s8       	 	vv" 	 	 	 	 	 	r   )zunsupported parameterunsupported_parameternot supportedzdoes not supportzunknown parameterzunrecognized request argumentzunrecognized parameterzinvalid parameter)r   rI   r\  )r   r  param_lowerrN  s      @r   _is_unsupported_parameter_errorr  P  s      ;B%%''K uC  I)##u 	 	 	 	 	2 	 	 	 	 	 	r   c                 "    t          | d          S )zBack-compat wrapper: detect API errors where the model rejects ``temperature``.

    Delegates to :func:`_is_unsupported_parameter_error`; kept as a separate
    public symbol because existing tests and call sites import it by name.
    rs  )r  )r   s    r   !_is_unsupported_temperature_errorr  r  s     +3>>>r   c                     t          | dd          }t          |                                           t          fddD                       rdS |dvrdS t          fddD                       S )	u!  Detect "the requested model doesn't exist" errors (404 / invalid model).

    This fires when a resolved model name is no longer served by the endpoint
    — most commonly when a long-lived process pinned a Portal-recommended model
    that has since been dropped from the Nous → OpenRouter catalog. The Nous
    proxy returns 404 with a body like::

        Model 'gpt-5.4-mini' not found. The requested model does not exist
        in our configuration or OpenRouter catalog.

    Distinct from :func:`_is_payment_error` (which also matches some 404s for
    free-tier/credit language) — this one keys on "does not exist / not found /
    not a valid model" phrasing, and explicitly excludes the billing keywords
    that the payment path already owns so the two predicates don't overlap.
    rF  Nc              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z,_is_model_not_found_error.<locals>.<genexpr>  s7        r2?      r   )	rO  rP  rR  rT  rV  rW  	free tier	free-tierrY  F>   N  rI  c              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z,_is_model_not_found_error.<locals>.<genexpr>  s7       
 
2rY 
 
 
 
 
 
r   )	zmodel does not existz#does not exist in our configurationzopenrouter catalogzis not a valid modelzno such modelzmodel not foundzthe model `model_not_foundzunknown modelr[  r]  s     @r   _is_model_not_found_errorr  {  s      S-..FC  I
     &      
 u%%%u 
 
 
 
 
* 
 
 
 
 
 
r   c                    t          | dd          }|dvrdS t          |                                           t          |           rdS t	          fddD                       rdS t	          fddD                       S )	u  Detect "this route cannot serve this model" 400s (capability mismatch).

    Distinct from :func:`_is_model_not_found_error` (the model does not exist
    anywhere): here the model name is valid but the *current provider/account*
    is structurally unable to run it. The canonical case is a configured
    fallback that cannot run the main model — e.g. an ``openai-codex`` /
    ChatGPT-account fallback asked to compress a ``glm-5.2`` conversation::

        Error code: 400 - {'detail': "The 'glm-5.2' model is not supported
        when using Codex with a ChatGPT account."}

    The candidate authenticates fine and builds a client, so the auth and
    payment predicates don't fire and the call would otherwise raise and
    abort the whole auxiliary task (commonly compression — which then drops
    middle turns and churns the session, destroying the prompt cache).
    Treating it as a fallback-worthy capability error lets the chain skip the
    incapable route and continue to the next candidate, mirroring the
    context-window feasibility screen (#52392).

    Billing/quota 400s belong to :func:`_is_payment_error`; "model does not
    exist" 400s belong to :func:`_is_model_not_found_error`. This predicate
    explicitly excludes both so the three don't overlap.
    rF  N>   Nr  Fc              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z/_is_model_incompatible_error.<locals>.<genexpr>  s7        r2?      r   )rO  rP  rR  rT  rV  rW  rS  r  r  rY  rX  quotac              3       K   | ]}|v V  	d S r   r   rL  s     r   r  z/_is_model_incompatible_error.<locals>.<genexpr>  s7        2rY      r   )zis not supported when usingzmodel is not supportedznot supported with thisznot supported for this accountmodel_not_supportedzdoes not support this modelzunsupported model)ro   rI   r   r  r\  r]  s     @r   _is_model_incompatible_errorr    s    0 S-..F[  uC  I !%% u
     &       u     *      r   c                     t          | t                    sdS t          |                                           }d|v od|v od|v S )a  Detect provider responses that authenticated but cannot serve aux shape.

    Some OpenAI-compatible routes return HTTP 200 with an empty/malformed
    ChatCompletion instead of a normal provider error.  That is still a
    provider/model capability failure for auxiliary tasks: downstream callers
    need ``choices[0].message`` and should be able to continue through the
    same fallback path as explicit model-incompatibility errors.
    Fz
auxiliary zllm returned invalid responsezchoices[0].message)r$   r  rI   r   )r   r  s     r   _is_invalid_aux_response_errorr    sW     c<(( u
c((..

C 	(+s2	( C'r   c                 2   t          |           t          5  fdt          D             }|D ]O}t                              |d          d         }|t	          |           t                              |d           P	 ddd           dS # 1 swxY w Y   dS )zEDrop cached auxiliary clients for a provider so fresh creds are used.c                 `    g | ]*}t          t          |d                              k    (|+S r   )r   rI   )r   r<  r   s     r   
<listcomp>z)_evict_cached_clients.<locals>.<listcomp>  s@     
 
 
&s3q6{{33zAA AAAr   r  r   N)r   _client_cache_lock_client_cacherJ   _close_cached_clientr  )r   
stale_keysr<  rZ   r   s       @r   _evict_cached_clientsr    s    (22J	 	) 	)
 
 
 
(
 
 

  	) 	)C"&&s,>??BF!$V,,,c4((((		)	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)s   A&BBBr   c                 :   | dS d}t           5  t          t                                                    D ]M}t                              |          }||d         }|*t          |dd          }|| u s|| u r
t          |= d}N	 ddd           n# 1 swxY w Y   |S )u@  Drop the cache entry whose stored client is *target*.

    Used when a specific cached client has been poisoned (closed httpx
    transport after a timeout, broken streaming session, etc.) so the next
    auxiliary call rebuilds rather than reusing the dead instance.

    Walks both sync and async wrappers (``CodexAuxiliaryClient``,
    ``AnthropicAuxiliaryClient``, ``AsyncCodexAuxiliaryClient``, etc.) via
    their ``_real_client`` attribute so a timeout that closes the underlying
    ``OpenAI`` (or native provider) client evicts every cached shim that
    exposed it. Async wrappers must mirror their sync sibling's
    ``_real_client`` for this to work — otherwise the sync entry is evicted
    but the async entry survives and keeps reusing the dead transport.

    Returns True when at least one entry was evicted.
    NFr   rF  T)r  r  r  keysrJ   ro   )r   evictedr<  r  cachedreals         r   r  r    s    " ~uG	  **,,-- 
	 
	C!%%c**E}1XF~6>488D46>>!#&
	               Ns   A5BBBr  c                V   t          |           }|dk    r?t          |          }t          |                    d          pt                                }|dv rdS t	          |          }|dS t          t          |dd          pd                                          }|sdS | d| S )z9Return a stable cache discriminator for pooled providers.r   r   >   rB   r   r   rB   Nr  r   )r   r  rJ   r   r  rI   ro   r   )r   r  r   rL  r  entry_ids         r   _pool_cache_hintr    s     )22JV),77,W[[-D-D-]H[H]H]^^
+++rZ((E}r75$++1r2288::H r%%8%%%r   c                 X    t          | dd           }dt          |           i}|||d<   |S )NrF  r  )ro   rI   )r   r^  r  s      r   _pool_error_contextr  3  s8    S-..F(#c((3G!'Nr   resolved_providerc                    t          |           }|dvr|S t          t          |dd          pd          }t          |d          rdS t          |d          rdS t          |d          rd	S t          |d
          rdS t          |d          rdS t          |d          rdS t          |d          rdS |rt	          |          }|                    dd          }|r|dvr	 ddlm} |                    |          }|rit          |dd          dk    rTt          t          |dd          pd                              d          }	|	rt          |t          |	                    r|S n# t          $ r Y nw xY wdS )zCInfer which provider pool can recover the current auxiliary client.>   rB   r   r   r=   rB   chatgpt.comr   r  rB  inference-api.nousresearch.comr  r  r   r  r   rv  r   r  r  r   r   )r  r  Nr\   r  r   )r   rI   ro   r4   r  rJ   r  r  rx  r5   rK   )
r  rZ   r  r   r`  rtrt_providerr  r  rt_bases
             r   _recoverable_pool_providerr  ;  s    )):;;J///wvz2..4"55DT=11 ~T?33 |T#CDD vT#677 {T#677 yT>22 }T:.. {  $\22ffZ,, 		;.DDD======+//<< +wwTBBiOO!''3G"L"L"RPRSSZZ[^__G +#8?PQX?Y?Y#Z#Z +**   4s   "BE) )
E65E6failed_api_keyr  c                   t          |           }	 t          |          }n4# t          $ r'}t                              d||           Y d}~dS d}~ww xY w|r|                                sdS t          |dd          }t          |          }|pd}t          |          rX|	                                }	|	t          |           dS |                    ||nd||          }
|
t          |           dS dS t          |          st          |          rBt          |          rdnd	}|                    ||n|||          }
|
t          |           dS dS )
av  Try same-provider credential-pool recovery for auxiliary calls.

    ``failed_api_key`` is the API key that was actually used for the failing
    request.  Passing it lets mark_exhausted_and_rotate identify the correct
    pool entry even when another process has already rotated the pool (which
    would leave current() as None, causing the wrong entry to be marked).
    z9Auxiliary client: could not load pool for %s recovery: %sNFrF  Tr  )rF  error_contextapi_key_hintrG  rJ  )r   r/   rK   rX   rx   r~  ro   r  r  r  r  mark_exhausted_and_rotater_  rm  )r   r   r  r   r  load_excrF  r  hintr  
next_entryfallback_statuss               r   _recover_provider_poolr  f  s    )22J$$   PR\^fggguuuuu  t++-- u#}d33K',,M!TDc ,,..	 !*---433'2'>C' 4 
 


 !!*---4u 	!5c!:!: 	!23!7!7@##S33'2'>O' 4 
 


 !!*---45s   ! 
AAA)r4  resolved_modelresolved_base_urlresolved_api_keyresolved_api_moder  r  rs  rq  r  effective_timeouteffective_extra_bodyrv  r4  c                    | dk    rt          ||||d          \  }}}nt          ||||||          \  }}|t          d| pd d| d          t          t	          |d	d
          pd
          }t          ||p|||	|
|||||p||           }|rt          |          |d<   t          ||          rt          |d                   |d<   t          t          ||||          |           S )NrC  Fr   r   r=   r\   rO   r=   r\   r  r  
Auxiliary r>  : provider $ could not be rebuilt after recoveryr=   rB   rs  rq  r  r  r  rv  r=   r  r4  r  r  )resolve_vision_provider_client_get_cached_clientr  rI   ro   _build_call_kwargsr5  _is_anthropic_compat_endpoint#_convert_openai_images_to_anthropic_validate_llm_responser  )r  r  r  r  r  r  r  r  r  rs  rq  r  r  r  rv  r4  r%  retry_clientretry_model
retry_baseretry_kwargss                        r   _retry_same_provider_syncr    sz   & x'E&&$(
 (
 (
$< %7&$&%%
 %
 %
!k kkk4Ekkk
 
 	
 W\:r::@bAAJ%"{!')00  L   <(,](;(;_%$%6
CC a#F|T^G_#`#`Z !&&		
 	
 	
 	  r   c                   K   | dk    rt          ||||d          \  }}}nt          ||d|||          \  }}|t          d| pd d| d          t          t	          |d	d
          pd
          }t          ||p||||	|
||||p||           }|rt          |          |d<   t          ||          rt          |d                   |d<   t          t          ||||           d {V |           S )NrC  Tr  )rO   r=   r\   r  r  r>  r  r  r=   rB   r  r4  r  r  )r  r  r  rI   ro   r  r5  r  r  r  r  )r  r  r  r  r  r  r  r  rs  rq  r  r  r  rv  r4  r%  r  r  r  r  s                       r   _retry_same_provider_asyncr    s     $ x'E&&$(
 (
 (
$< %7&$&%
 %
 %
!k kkk4Ekkk
 
 	
 W\:r::@bAAJ%"{!')00  L  <(,](;(;_%$%6
CC a#F|T^G_#`#`Z !%&&	
 
 
 	
 	
 	
 	
 	
 	
 	  r   c                    t          |           }	 |dk    ryddlm}m}m}m}  |            \  }}t          |pd                                          sdS |                     ||          d            ||           t          |           dS |dk    r\dd	l
m}  |d
          }	t          |	                    dd          pd                                          sdS t          |           dS |dk    rkddl
m}
  |
t          dd          d          }	t          |	                    dd          pd                                          sdS t          |           dS |dk    rddlm}m}m}  |            }	t'          |	t(                    r |	                    d          r ||	          nd}t          |pd                                          s
 |            }t          |pd                                          sdS t          |           dS |dk    rt+          |          }|r|                                rm|                                 |                                }|Ct          t3          |dd          pd                                          rt          |           dS ddl
m}  |d
          }	t          |	                    dd          pd                                          sdS t          |           dS |dk    rzddlm}  |            \  }}t'          |t                    r|                                sdS t'          |t                    r|                                sdS t          |           dS n4# t:          $ r'}t<                              d||           Y d}~dS d}~ww xY wdS )zERefresh short-lived credentials for OAuth-backed auxiliary providers.r   r   )
_jwt_cache_token_fingerprintexchange_copilot_tokenresolve_copilot_tokenrB   FNTr   )!resolve_codex_runtime_credentialsr  r\   r  r  r  r  r  r   )read_claude_code_credentials_refresh_oauth_tokenr!  refreshTokenr  r  r  vertex)get_vertex_configz7Auxiliary provider credential refresh failed for %s: %s) r   hermes_cli.copilot_authr  r  r  r  rI   r   r  r  r  r  rJ   r  r6   rh  r  r  r!  r$   r5  r/   r~  r  r  ro   r	  agent.vertex_adapterr  rK   rX   rx   )r   r   r  r  r  r  	raw_token_sourcer  r   r  r  r  r!  r  r  r  r	  r  r=   r   s                        r   _refresh_provider_credentialsr  '  s   (22JT""            "7!6!8!8IwyB''--// uNN--i88$???""9---!*---4''IIIIII55DIIIEuyyB//5266<<>> u!*---4HHHHHH44 )*G L L"  E uyyB//5266<<>> u!*---4$${{{{{{{{{{0022E3=eT3J3JruyyYgOhOhr((///nrEu{##))++ 2//11u{##))++ u!*---4$$ Z((D  ,,..   4466	(SDUWY1Z1Z1`^`-a-a-g-g-i-i()*5554MMMMMM99MMMEuyyB//5266<<>> u!*---4!! ?>>>>>//11OE8eS))  uh,, HNN4D4D u!*---4# "$    NPZ\_```uuuuu 5sl   AN 9N AN !N 2AN N #B!N N BN /A	N :N AN )N :N 
N=N88N=client_base_urlc                     t          |           }|r|dk    r|S t          |d          rdS t          |d          rdS t          |d          rdS t          |d          rd	S |S )
ud  Return the provider whose short-lived credentials should be refreshed.

    Auto-routed auxiliary calls keep ``resolved_provider == "auto"`` even
    after _get_cached_client() selects a concrete backend. Infer the backend
    from the selected client's base URL so auth refresh works for auto →
    Copilot/Codex/Anthropic/Nous routes too. (#20832)
    r   api.githubcopilot.comr   r  r   r  r   r  r  )r   r4   )r  r  r   s      r    _auth_refresh_provider_for_router    s     )):;;J jF**_.EFF y_m<< ~_.ABB {_.NOO vr   fb_labelc                 Z   | r|sdS t          j        d|          }|sdS 	 t          |                               d          }t	          |t
                    r(|t          |                    d                             nd}n# t          $ r Y dS w xY wt	          |t                    r|ndS )a[  Resolve the configured ``fallback_chain`` entry a label points at.

    Labels minted by :func:`_try_configured_fallback_chain` carry the entry
    index in our own stable format (``fallback_chain[<i>](<provider>)``).
    Returns ``None`` when the label is not a configured-chain candidate or
    the index no longer resolves to a dict entry.
    Nzfallback_chain\[(\d+)\]fallback_chainr   )
rematch_get_auxiliary_task_configrJ   r$   r  rL  grouprK   r5  )r  r  mchainr  s        r   _fallback_chain_entryr    s      x t
+X66A t*400445EFF*4UD*A*AKc!''!**oo&&t   ttud++5555s   A!B 
BBc                     t          | |          }|r|                    d          nd}t          |t          t          f          r*t          |t
                    s|dk    rt	          |          S dS )u,  Resolve a per-entry ``timeout`` for a configured fallback candidate.

    A fallback candidate previously inherited the exact timeout the primary
    provider was called with. When that deadline was tuned for the primary
    (or the primary simply consumed its whole budget before failing over),
    the fallback aborted on the same clock even when independently healthy —
    a 163k-token compression that needs ~90s on the fallback died at the
    primary's 30s deadline every turn (#62452).

    Entries in ``auxiliary.<task>.fallback_chain`` may declare their own
    ``timeout`` (seconds). Returns ``None`` when the label is not a
    configured-chain candidate, the entry has no ``timeout``, or the value
    is invalid — callers then keep the task-level timeout, preserving
    existing behavior.
    r  Nr   )r  rJ   r$   rL  rM  rn   )r  r  r  raws       r   _fallback_entry_timeoutr    sn      "$11E"'
1%))I


TC#U|$$ ZT-B-B sQwwSzz4r   c                     t          j        d| pd          }|r'|                    d                                          n"t	          | pd                                          S )z>Recover the provider identifier from a fallback display label.z0(?:fallback_chain\[\d+\]|main-agent)\(([^)]+)\)$rB   r   )r  r  r   r   rI   )r:  r  s     r   _fallback_provider_from_labelr    sW    HH%+SUVVE%*H5;;q>>!!!EKR0@0@0F0F0H0HHr   c                   P    e Zd ZU eed<   eed<   ee         ed<   ee         ed<   dS )_FallbackDestinationr   r=   r  r   N)r*   r+   r,   rI   __annotations__r
   r   r   r   r
  r
    sD         MMMMMMsmC=r   r
  c                    |stt          |          rd}nb	 ddlm}  || |pd |pd          }t          |                    d          pd                                          pd }n# t          $ r Y nw xY wt          | |||          S )Nr}  r   r  rB   )r  r  r  r  )r  r  r  rI   rJ   r   rK   r
  )r   r=   r  r   r  rL  s         r   _complete_fallback_destinationr    s      .x88 	+HH
PPPPPP22&&.&6$!&"  
 w{{:66<"==CCEEM   (HeDDDs   AA' '
A43A4	fb_clientfb_modelc                 .   t          |                     d          pd                                          }t          |                     d          pt          |dd          pd                                          }t          |                     d          p|                     d          pd                                          pd }|p7t          |                     d          pd                                          pd }t	          ||||          S )Nr   rB   r=   r  	transportr   )rI   rJ   r   ro   r  )r  r  r  r   r=   r  r   s          r    _fallback_destination_from_entryr    s   
 599Z((.B//5577H		*IJ!C!CIr egg  		*=;!7!7=2 egg  EEIIg..4"55;;==EE)(HhNNNr   c                 "   t          |dd          }t          |t                    r|S t          |          }t	          t          |dd          pd          }d}|}t          | |          }	|	t          |	||          S t          ||||          S )z>Return the resolved route identity used by a fallback request._hermes_fallback_destinationNr=   rB   )ro   r$   r
  r  rI   r  r  r  )
r  r  r  r  attachedr   r=   r  r   r  s
             r   _fallback_destinationr    s     y"@$GGH(011 ,X66H79j"55;<<HHE!$11E/y(KKK)(HhNNNr   destinationc                `    ddl m}  || ||j        |j        |j        pd|j        pd          S )zEStrip source decoration and plan one synchronous destination locally.r   )#plan_cache_sections_for_destinationrB   )r   r=   r  r   )agent.agent_runtime_helpersr  r   r=   r  r   )r  r  r  r  s       r   "_replan_synchronous_cache_sectionsr    sY     POOOOO..%%%+%2   r   c                   t          ||          }|(||k    r"t                              d|pd|||           |}t          || ||          }t	          |||          \  }}t          |j        |j        ||||||	|
|j        |          }	 t          t          | ||j        |j                  |          S # t          $ r|}t          |          s t          |j        |j                  }|dvrt          |          rt!          ||j        |j        pd|j                  \  }}|t#          ||j        pt%          t'          |d	d
          pd
          |j        |p|j                  }t	          |||          \  }}t          |j        |j        ||||||	|
|j        |          }	 t          t          |||j        |j                  |          cY d}~S # t          $ r}t          |          s Y d}~nd}~ww xY wt)          |p|           t                              d|pd||           Y d}~dS d}~ww xY w)u5  Call one fallback candidate with stale-credential recovery.

    A fallback candidate can itself carry a stale credential (e.g. an expired
    ``ANTHROPIC_TOKEN`` picked up by ``_try_anthropic``). Before this helper,
    such a 401 propagated out of the fallback site and aborted the auxiliary
    task (for compression: a 60s cooldown + context marker) even though other
    healthy candidates remained. Live case: a Codex-timeout → Anthropic
    fallback 401-looped five times in one session (mattalachia debug dump,
    Jul 2026).

    On an auth error: refresh the candidate's provider credentials and retry
    once with a rebuilt client; if the retry also auth-fails (non-refreshable
    expired token), mark the provider unhealthy and return ``None`` so the
    caller can continue to the next fallback layer. Non-auth errors raise.

    ``effective_timeout`` is the task-level deadline; a configured-chain
    candidate with its own ``timeout`` entry gets that instead, so a
    fallback tuned differently from the primary is allowed its own budget
    (#62452).
    NJAuxiliary %s: %s using its configured timeout %.0fs (task-level was %.0fs)r>  r  r  r  >   NrB   r   )r=   r  r=   rB   uk   Auxiliary %s: fallback candidate %s has a stale/unrefreshable credential (%s) — skipping to next fallback)r  rX   r?  r  r  r  r   r   r=   r  r  r  rK   r  r  r  r  r
  rI   ro   r<  rY   r  r  r  r  r  rs  rq  r  r  r  rv  
fb_timeoutr  fallback_messagesfallback_tools	fb_kwargsfb_errfb_providerr  r  retry_destinationretry_messagesretry_toolsr  	retry_errs                            r   _call_fallback_candidate_syncr*  &  sS   D )x88J*0A"A"A%NFHj2C	
 	
 	

 ''i8LLK(J) ) )%~
 #k/1BJ&7':J%D2 2 2ID%"$-$-	   
 
 	
  : : :f%% 	6 +"6
 
 0005RS^5_5_0(:!$-5$-	) ) )%L+ '$8( H7<R@@FBGG(4;#4% %! /Q 1/ / /+
  2%.%+" +
%/@3%5.7d D  D  D1.((%6%?%6%?	           !   ))44      	!!8999<NFHf	
 	
 	

 tttttu:sC   *B7 7H>C)H9,*GH>
H &G;6H9;H  3H99H>c                  K   t          ||          }|(||k    r"t                              d|pd|||           |}t          || ||          }t	          |||          \  }}t          |j        |j        ||||||	|
|j        |          }	 t          t          | ||j        |j                   d{V |          S # t          $ r}t          |          s t          |j        |j                  }|dvrt          |          r	t!          ||j        d|j        pd|j        	          \  }}|t#          ||j        pt%          t'          |d
d          pd          |j        |p|j                  }t	          |||          \  }}t          |j        |j        ||||||	|
|j        |          }	 t          t          |||j        |j                   d{V |          cY d}~S # t          $ r}t          |          s Y d}~nd}~ww xY wt)          |p|           t                              d|pd||           Y d}~dS d}~ww xY w)z6Async mirror of :func:`_call_fallback_candidate_sync`.Nr  r>  r  r  r  >   NrB   r   T)rO   r=   r  r=   rB   us   Auxiliary %s (async): fallback candidate %s has a stale/unrefreshable credential (%s) — skipping to next fallback)r  rX   r?  r  r  r  r   r   r=   r  r  r  rK   r  r  r  r  r
  rI   ro   r<  rY   r  s                            r   _call_fallback_candidate_asyncr,    s      )x88J*0A"A"A%NFHj2C	
 	
 	

 ''i8LLK(J) ) )%~
 #k/1BJ&7':J%D2 2 2IA%)$-$-	         
 
 	
  7 7 7f%% 	6 +"6
 
 0005RS^5_5_0(:!$-5$-) ) )%L+ '$8( H7<R@@FBGG(4;#4% %! /Q 1/ / /+
  2%.%+" +
%/@3%5.7d D  D  D15((%6%?%6%?	                 !   ))44      	!!8999<NFHf	
 	
 	

 ttttto7sC   0B? ?I
C*I50G+%I+
H5H
I
H3IIpayment errorfailed_providerreasonc           	         |                                                                  }t                      }|h}|r=|                                 |v r'|                    |                                            dddddddfd|D             }g }t	                      D ]\  }}	||v r
t          |          r)t          ||           |                    | d           B |	            \  }
}|
*t          	                    d	|pd
|| ||pd           |
||fc S |                    |           t          
                    d|pd
|| d                    |                     dS )zTry alternative providers after a payment/credit or connection error.

    Iterates the standard auto-detection chain, skipping the provider that
    failed.

    Returns:
        (client, model, provider_label) or (None, None, "") if no fallback.
    rB  r  r   r&  )rB  r  r   r   r   r&  c                 <    h | ]}                     ||          S r   )rJ   )r   s_alias_to_labels     r   	<setcomp>z(_try_payment_fallback.<locals>.<setcomp>#  s)    HHHq,,Q22HHHr    (unhealthy)Nu2   Auxiliary %s: %s on %s — falling back to %s (%s)r>  r  z<Auxiliary %s: %s on %s and no fallback available (tried: %s), NNrB   )r   r   r   r5  r.  r  rB  r  rX   r?  rY   r  )r.  r  r/  skipmain_providerskip_labelsskip_chain_labelstriedr:  try_fnrZ   r   r3  s               @r   _try_payment_fallbackr>  
  s      ""((**D ())M&K /,,..$66++--...%16'5!/Q QO IHHHKHHHE,..  v%%%!%(( 	t,,,LLE///000KKD@R   5%''''U
NNF51A1A   >r   errorfailed_modelc                     t                      pd                                }t                      pd                                }|                                dk    rt	          |          \  }}|r|sdS ||}}|r|r|                                dv rdS ddlm}m}	m}
 |pd                                                                pd} |
|	                    ||          |	                    | |          |r|	j
        n|	j                  rdS t          |          rt          ||           dS 	 t          ||          \  }}n# t          $ r d	\  }}Y nw xY w|dS d
| d}t                               d|pd|| ||p|           ||p||fS )u  Last-resort fallback to the user's main agent provider + model.

    Used after the configured fallback_chain is exhausted (or empty) for
    users with an explicit auxiliary provider.  This is the "safety net"
    layer: if nothing the user asked for can serve the request, try the
    main chat model before giving up.

    ``failed_model`` narrows the same-provider skip to the exact
    (provider, model) pair that just failed, mirroring
    :func:`_try_configured_fallback_chain`.  This matters for self-hosted /
    custom endpoints serving several models behind one provider label: the
    aux compression model timing out says nothing about the health of the
    main agent model deployed on the same URL (real incident: aux
    ``glm-5.2`` hung and timed out while main ``macaron-v1-venti`` on the
    identical endpoint was serving 448K-token turns fine — the
    provider-label skip discarded the one fallback that would have worked).

    - Model-specific runtime failures (timeout, connection, rate limit,
      model-incompatible, invalid response) pass ``failed_model``: skip the
      main model only when it IS the exact model that failed.
    - Provider-wide failures (auth 401, payment 402) and legacy callers
      leave ``failed_model`` as None, keeping the whole-provider skip —
      the shared credentials/account are broken, so the main model on the
      same provider cannot help either.

    Returns:
        (client, model, provider_label) or (None, None, "") if no fallback.
    rB   re  r7  >   rB   r   r   BackendIdentityFailureScopeshould_skip_candidateNr   r   r  zmain-agent()uC   Auxiliary %s: %s on %s — falling back to main agent model %s (%s)r>  )r   r   rX  r   rl  agent.backend_identityrC  rD  rE  buildMODEL
CREDENTIALr  rB  resolve_provider_clientrK   rX   r?  )r.  r  r/  r@  r9  
main_model_agg_provider
_agg_modelrC  rD  rE  
skip_modelrZ   r  r:  s                  r   _try_main_agent_model_fallbackrQ  =  s7   D )**0b7799M"$$*1133J%% %<J$G$G!z 	"J 	"!>$1:z 
 m.A.A.C.C|.S.S~
          $"++--3355=J}JGGjII(El.E   ~m,, M4000~,!8"*"
 "
 "
  , , ,!+, ~~*-***E
KKM8T*   >/Z66s   2E EEc                 (    | sdS | dk    rt           S dS )uj  Return the minimum context length required for an auxiliary task.

    Only ``compression`` carries an explicit minimum today (the same
    ``MINIMUM_CONTEXT_LENGTH`` (64K) floor that
    ``check_compression_model_feasibility`` already enforces at startup).
    Other tasks (``vision``, ``title_generation``, ``web_extract``,
    ``skills_hub``, ``mcp``, ``session_search``) return ``None`` — they
    have no per-task context floor and the runtime chain must remain
    permissive for them.

    Returns ``None`` for an empty/``None`` task name so the helper is a
    safe no-op when called from generic sites.
    Ncompression)r0   )r  s    r   _task_minimum_context_lengthrT    s'      t}%%4r   c                     |sdS 	 t          ||||           }n5# t          $ r(}t                              d| ||           Y d}~dS d}~ww xY wt	          |t
                    r|dk    r|S dS )u9  Resolve the effective context window for a fallback candidate.

    Thin wrapper around :func:`agent.model_metadata.get_model_context_length`
    that swallows probe failures (returns ``None``). Callers treat
    ``None`` as "unknown — pass through" so the existing fallback
    surface is preserved when the context-length resolver chain cannot
    determine a value (custom endpoints, models not in the registry,
    offline endpoints).

    Best-effort, never raises — the runtime fallback chain must keep
    moving even if the resolver hits a probe error.
    N)r=   r\   r   zBAuxiliary fallback: could not resolve context window for %s/%s: %sr   )r1   rK   rX   rx   r$   rL  )r   r   r=   r\   ctxr   s         r   _candidate_context_windowrW    s    $  t&	
 
 
    PeS	
 	
 	
 ttttt #s a
4s    
AAAc                    | sdS t          |           }|                    d          }|rt          |t                    sdS |pd                                                                pd}ddlm}m}m	}	 |
                    ||          }
|r|j        n|j        }g }t          |           }t          |          D ]\  }}t          |t                    st!          |                    dd                                                    }|sTt!          |                    d	d                                                    } |	|
                    ||t!          |                    d
          pd                    |
|          r|pd}d| d| d}	 t#          |          \  }}n# t$          $ r d\  }}Y nw xY w|||rt'          ||t!          |                    d
          pd          t)          |          pd          }|E||k     r?t*                              d| ||||           |                    | d| d| d           t*                              d| ||||p|pd           ||p||fc S |                    |           |r/t*                              d| d                    |                     dS )u  Try user-configured fallback_chain for a specific auxiliary task.

    Reads auxiliary.<task>.fallback_chain from config.yaml and tries each
    entry in order.  Each entry must have at least ``provider``; ``model``,
    ``base_url``, and ``api_key`` are optional.

    ``failed_model`` narrows the skip check to the exact (provider, model)
    pair that just failed, rather than the whole provider. Without it every
    entry sharing the failed provider is skipped (the original behaviour).
    Callers pass it only when a sibling model on the same provider could
    plausibly recover:

    - Model-specific runtime failures (timeout, connection, rate limit,
      model-incompatible, invalid response) pass ``failed_model`` so a
      chain that intentionally lists several models under the same provider
      — e.g. two more NVIDIA NIM models after the primary NIM model times
      out — is not skipped wholesale. Only the exact model that failed is
      skipped; the siblings still run instead of jumping straight to the
      main-agent-model safety net.
    - Provider-wide failures (auth 401, payment 402) and "no client could
      be built" callers leave ``failed_model`` as None, keeping the whole
      provider skipped — the shared credentials/account behind every model
      on that provider are broken, so a sibling can't help and the
      main-agent-model safety net should be reached instead.

    Returns:
        (client, model, provider_label) or (None, None, "") if no fallback.
    r7  r  rB   Nr   rB  rF  r   r   r=   )r   r   r=   zfallback_chain[](rG  r  r  zDAuxiliary %s: skipping %s (%s context=%d < min=%d), continuing chain (context too small: <u9   Auxiliary %s: %s on %s — configured fallback to %s (%s)r  z=Auxiliary %s: configured fallback_chain exhausted (tried: %s)r6  )r  rJ   r$   r  r   r   rH  rC  rD  rE  rI  rJ  rK  rT  	enumerater5  rI   _resolve_fallback_entryrK   rW  _fallback_entry_api_keyrX   r?  r  rx   r  )r  r.  r/  r@  task_configr  rP  rC  rD  rE  failed_identfailure_scoper<  min_ctxir  r%  fb_model_rawr  r:  r  r  fb_ctxs                          r   _try_configured_fallback_chainrf    s   D  ~,T22KOO,--E 
5$// ~$"++--3355=J          #(( 
 )  L )El.E  E*400Ge$$ . .5%&& 	%))J3344::<< 	599Wb112288::  !!$"UYYz228b99 "  
 
 
 		 '45!55{555	3(?(F(F%I~~ 	3 	3 	3(2%I~~~	3  "~"2" :!6!6!<"==3E::@b	   %&7*:*:KK^e^VW   LLE!S!S!S!S!S!S!STTTKKKfoun6]6]T]   n8%????U 
K$))E""	
 	
 	
 >s   F--F?>F?c                     |pd                                                                 }| r|r|dv rdS t          | |d          S )a  Try task fallback_chain when an explicit aux provider cannot build.

    This covers the "no client" case before any request is sent: missing
    raw env key, unavailable OAuth/pool credentials, or provider resolver
    returning ``(None, None)``.  It deliberately stops at the configured
    per-task fallback chain; the main-agent model remains the last-resort
    runtime fallback for request-time capacity errors.
    rB   >   r   r7  zprovider unavailabler/  )r   r   rf  )r  r.  explicits      r   /_try_configured_fallback_for_unavailable_clientrj  \  sd      %2,,..4466H x 8x#7#7~)%   r   c                 $    ddl m}  ||           S )a3  Resolve inline or env-backed API key from a fallback-chain entry.

    Delegates to the centralized, secret-scope-aware resolver so this path
    doesn't leak another profile's credential via a raw ``os.getenv`` under
    gateway multiplexing (see ``hermes_cli.fallback_config.resolve_entry_api_key``).
    r   )resolve_entry_api_key)hermes_cli.fallback_configrl  )r  rl  s     r   r^  r^  r  s(     A@@@@@  '''r   c                    t          |                     d          pd                                          }t          |                     d          pd                                          pd}|r|sdS t          |                     d          pd                                          pd}t          |           }t          |                     d          p|                     d          pd                                          pd}t	          |||||	          \  }}|(	 t          | ||          |_        n# t          $ r Y nw xY w||fS )
z?Resolve one fallback entry through the central provider router.r   rB   r   Nr  r=   r  r  )r   r  r7  r  )rI   rJ   r   r^  rL  r  r  rK   )r  r   r   r=   r\   r  rZ   r  s           r   r]  r]  ~  sj   599Z((.B//5577H		'""(b))//119TE 5 z599Z((.B//5577?4H%e,,G599Z((HEIIk,B,BHbIIOOQQYUYH4"   FN 	2Rv~3 3F//  	 	 	D	>!!s   #D: :
EEc           
         	 ddl m} ddlm}  | |                      }n6# t          $ r)}t
                              d| pd|           Y d}~dS d}~ww xY w|sdS |pd                                                                }t                      pd                                                                }d	 ||d
fD             }	g }
t          |           }t          |          D ]#\  }}t          |t                    st          |                    d          pd                                          }t          |                    d          pd                                          }|r|s|                                }d| d| d}||	v r|
                    | d           t#          |          r)t%          ||            |
                    | d           	 t'          |          \  }}n;# t          $ r.}t
                              d| pd||           d\  }}Y d}~nd}~ww xY w||t)          ||p|t          |                    d          pd          t+          |          pd          }|F||k     r@t
                              d| pd|||           |
                    | d| d| d           t
                              d| pd||pd
||p|           ||p||fc S |
                    |           %|
r1t
                              d| pdd                    |
                     dS )a  Try the top-level main-agent fallback chain for an auxiliary call.

    ``provider: auto`` auxiliary tasks should respect the user's declared
    main fallback policy before dropping into Hermes' built-in discovery
    chain. The top-level chain is read through ``get_fallback_chain`` so
    both modern ``fallback_providers`` and legacy ``fallback_model`` entries
    participate in the same order as the main agent.
    r   rA  )get_fallback_chainz4Auxiliary %s: could not load main fallback chain: %sr>  Nr7  rB   c                     h | ]}||S r   r   )r   r4  s     r   r4  z+_try_main_fallback_chain.<locals>.<setcomp>  s    ===!1=A===r   r   r   r   zfallback_providers[rY  rG  z
 (skipped)r5  z4Auxiliary %s: main fallback %s failed to resolve: %sr  r=   r  zAAuxiliary %s: skipping %s (context=%d < min=%d), continuing chainrZ  r[  u9   Auxiliary %s: %s on %s — main fallback chain to %s (%s)z7Auxiliary %s: main fallback chain exhausted (tried: %s)r6  )rH   rA   rm  rp  rK   rX   rx   r   r   r   rT  r\  r$   r5  rI   rJ   r  r  rB  r]  rW  r^  r?  r  )r  r.  r/  rA   rp  r  r   failed_norm	main_normr8  r<  rb  rc  r  r%  r  fb_normr:  r  r  re  s                        r   _try_main_fallback_chainru    s   ::::::AAAAAA""#7#7#9#9::   KT^U[]`aaa~~~~~  ~"(b//117799K$&&,"3355;;==I==Y7===DE*400Ge$$ * *5%&& 	%))J//5266<<>>uyy))/R006688 	( 	##%%9a99;999d??LLE---...!'** 	...LLE///000	3(?(F(F%I~~ 	3 	3 	3LLOQUQ_Y_afhklll(2%I~~~~~~	3  "2".h :!6!6!<"==3E::@b	   %&7*:*:KK[vw   LLE!S!S!S!S!S!S!STTTKKK(A65*(  
 n8+EEEEU 
ENFDIIe,,	
 	
 	
 >s,   " 
AAA'G::
H2$H--H2c                 2    t          | |||          \  }}|S )zResolve a single provider entry from fallback_chain to an OpenAI client.

    Uses the existing provider resolution infrastructure where possible.
    )r   r   r  r7  )rL  )r   r   r=   r\   rZ   r  s         r   _resolve_single_providerrw    s0     5" 	  FN Mr   c           	      P   da t          |           }|                    dd          }t          |                    d          pd          }t          |                    d          pd          }|                    dd          }t          |                    d          pd          }t          stt          j        dd                                          }|pt                      }	|r;|	r9|	d	k    r3|		                    d
          st                              d||	           dat          |pt                      pd          }
t          |pt                      pd          }|
dk    r t          |          \  }}|r|r
|}
|}d}d}d}|
r|r|
dvr|
}|pd}d}|r|
d	k    r	d	}|}|pd}nW|
	                    d
          r>d}	 ddlm}  ||
          du}n# t           $ r Y nw xY w|r|
}d}n|r	d	}|}|pd}n	|r|}n|r|}t#          |          }|rt%          |          rt'          |           n?t)          |||||pd          \  }}|$t                              d|
|p|           ||p|fS |rt-          ||
pdd          \  }}}|||fS t/          ||
pdd          \  }}}|||fS g }t1                      D ]\  }}t%          |          r(t'          |           |                    | d           < |            \  }}|Y|r3t                              d||pdd                    |                     nt                              d||pd           ||fc S |                    |           t                              dd                    |                     dS )u  Full auto-detection chain.

    Priority:
      1. User's main provider + main model, regardless of provider type.
         This means auxiliary tasks (compression, vision, web extraction,
         session search, etc.) use the same model the user configured for
         chat.  Users on OpenRouter/Nous get their chosen chat model; users
         on DeepSeek/ZAI/Alibaba get theirs; etc.  Running aux tasks on the
         user's picked model keeps behavior predictable — no surprise
         switches to a cheap fallback model for side tasks.
      2. OpenRouter → Nous → custom → Codex → API-key providers (fallback
         chain, only used when the main provider has no working client).
    Fr   rB   r   r=   r\   r  r  r   r   zOPENAI_BASE_URL is set (%s) but model.provider is '%s'. Auxiliary clients may route to the wrong endpoint. Run: hermes model to reconfigure, or remove OPENAI_BASE_URL from ~/.hermes/.envTre  >   rB   r   Nr   _get_named_custom_provider)r  r7  r  z2Auxiliary auto-detect: using main provider %s (%s)r   zmain provider unavailablerh  r5  u4   Auxiliary auto-detect: using %s (%s) — skipped: %sr  r6  z$Auxiliary auto-detect: using %s (%s)zAuxiliary auto-detect: no provider available (tried: %s). Compression, summarization, and memory flush will not work. Set OPENROUTER_API_KEY or configure a local model in config.yaml.r  )r_  r  rJ   rI   _stale_base_url_warnedrH  r  r   r   r   rX   rY   rX  rl  r  rz  rU   r5  r  rB  rL  r?  rf  ru  r.  r  r  )r  r  rL  runtime_providerruntime_modelr  r  r  	_env_base_cfg_providerr9  rM  rN  rO  r  r  r7  _has_named_entryrz  main_chain_labelrZ   r  r  r  	_fb_labelr<  r:  r=  r   s                                r   _resolve_autor    s6   $ %l33G{{:r22G,,233M7;;z228b99kk)R00O7;;z228b99 " *I/44::<<	(A,?,A,A 
	*- 
	*!X--%00;; .NN6 =   &*" (G,?,A,AGRHHM]>&6&8&8>B??J $;J$G$G!z 		"Z 		")M#J
  " O! @6* @6\11),4 '	/ 9 9 !) 0.6$%%i00 !	/$RRRRRR#=#=m#L#LTX#X      3 %2!$(!!! 3 %-!$4!#2#:d    3#2  	/  / 22CDD 	6 67G H H 	6 011116!"3!1)1T     FH !P)8+AzC C Cx5:55  ')G-)62M*O *O *O&	8Y h&&%=m%v.I&K &K &K"Ix("" E,..  v!%(( 	&&&LLE///000 _R!5#5Ityy7G7GI I I I BE5K]T]^^^5=   U
NN W 99U##% % % :s   G 
G#"G#	is_visionc                    ddl m} t          | t                    rt	          |           |fS t          | t
                    rt          |           |fS t          | t                    rt          |           |fS 	 ddl	m
}m} t          | |          r ||           |fS n# t          $ r Y nw xY w	 ddlm} t          | |          r| |fS n# t          $ r Y nw xY w| j        t!          | j                  d}t!          | j                  }t%          |d          rt'                      |d<   nt%          |d          rdd	lm}	  |	d
|          |d<   nt%          |d          rddi|d<   nt%          |d          rt-          |          |d<   nzt%          |d          rddlm}
  |
            |d<   nV	 ddlm} ddlm}  ||          }|r+ ||          }|r|j        rt=          |j                  |d<   n# t>          $ r Y nw xY wtA          |!                    d                    }|r||d<   i tE          |d
          |}|#                    dd            |di ||fS )aa  Convert a sync client to its async counterpart, preserving Codex routing.

    When ``is_vision=True`` and the underlying base URL is Copilot, the
    resulting async client carries the ``Copilot-Vision-Request: true``
    header so the request is routed to Copilot's vision-capable
    infrastructure (otherwise vision payloads silently time out).
    r   )AsyncOpenAI)r  AsyncGeminiNativeClientr  r_   r  r3  r  copilot_request_headersTis_agent_turnr  rv  rY  r  rU  r   r  )_infer_provider_from_urlr  rN   r^   r   )$r   r  r$   rD  r\  r  r  r  r  r  r  r  rU   r  r  r\   rI   r=   r4   rR  r  r  rW  r  r  agent.model_metadatar  r  r  r3  r5  rK   r>  rJ   r[   r`   )sync_clientr   r  r  r  r  r  async_kwargssync_base_urlr  r  r  
_gpf_async	_inferred	_ph_async_merged_asyncs                   r   _to_async_clientr    s    #"""""+344 =(55u<<+788 A,[995@@+566 ?*;77>>[[[[[[[[k#566 	?**;77>>	?   ======k#344 	&%%	&    &,-- L ,--M]O<< *:*<*<&''	}.A	B	B CCCCCC*A*A)+
 +
 +
&'' 
}n	=	= +79L*M&''	}.H	I	I *B=*Q*Q&''	}f	5	5 ======*D*D*F*F&''
		EEEEEEDDDDDD00??I V&Jy11	 V!: V6:9;T6U6UL!23 	 	 	D	/0@0@AR0S0STTM 8*7&'
$]t
D
D
D
L M1---;&&&&--s7   :$B   
B-,B-1C 
CC5AG: :
HHr  c                 T    | s| S 	 ddl m}  || |          S # t          $ r | cY S w xY w)zANormalize a resolved model for the provider that will receive it.r   )normalize_model_for_provider)hermes_cli.model_normalizer  rK   )r  r   r  s      r   r  r    sa     KKKKKK++JAAA   s    ''	raw_codexc
                 j*  [ t                       | pd                                                                }
t          |           } | dk    rt	          |          \  }}|rs|rq|                                                                }
t          |          } |}|r8t          |                                                              d          rd}d}| dk    o|}|s'| dk    r!|st          |           pt                      p|}dt
          dt
          d	t          ffd
[	 	 dydt
          dt
          dt
          f[fd}| dk    r^t          ||	          \  }}|dS |r(d|v r$|r"d|vrt                              d||           d}|p|}|rt          |||          n||fS | dk    rht          |          \  }}|)t                              dt!                                 dS t#          |p||           }|rt          |||          n||fS | dk    r|pF|t$                                          v p+|pd                                                                dk    }t)          |          \  }}|t                              d           dS t#          |p||           }ddlm}  ||          }t          t/          |dd          pd          }t          t/          |dd          pd          }t1          |||||          }|rt          |||          n||fS | dk    r|st                              d           dS rdt3                      }|st                              d           dS t#          ||           }t5          |t6          t9          |                     }||fS t;          |          \  }}|t                              d           dS t#          |p||           }|rt          |||          n||fS | d!k    rZt=          |          \  }}|t                              d"           dS t#          |p||           }|rt          |||          n||fS | d#k    r2d}d}|rvt?          |                                          }|pd                                ptA          d$          ptC          |          pd%}|st                              d&           dS n|rt          |"                    d          pd                                          #                    d          }t          |"                    d          pd                                          }|r|r|}|}|rL|rIt#          |p|r|"                    d'          ndpd(|           }i }tI          |          \  }} | r| |d)<   tK          |d*          rd+d,i|d-<   ntK          |d.          rdd/l&m'}!  |!d0|1          |d-<   nftK          |d2          rtQ          |          |d-<   nC	 dd3l)m*}"  |"|           }#|#r|#j+        rtY          |#j+                  |d-<   n# tZ          $ r Y nw xY wt]          |"                    d-                    }$|$r|$|d-<   t5          dz||d4|} |||||          }|rt          |||          n||fS t^          t`          fD ]}% |%            \  }}|t#          |p||           }t          t/          |dd          pd          }&t/          |dd          }'tc          |'          rte          |'t
                    sdnt          |'pd          }( ||||&|(          }|rt          |||          n||fc S t                              d5           dS 	 dd6l3m4}) d}*|
r|
| k    r |)|
          }*|* |)|           }*|*r>|*"                    d          pd                                }|*"                    d          pd                                }|*"                    d7          p|*"                    d8          pd                                }+|s|+rtA          |+          }|pd%}|d%k    r0t                              d9|*"                    d:          p|            p|*"                    d;          pd                                },|rt#          |p=|*"                    d'          p(|r|"                    d'          ndpt                      pd(|           }|,d<k    r|}-|}.nt?          |          }-|}.tI          |-          \  }/}0|0rd)|0ini }1t]          |1"                    d-                    }2|2r|2|1d-<   t                              d=| ||,pd>           |,d<k    r	 dd?l5m6}3  |3||          }4n# tn          $ r t                              d@|            t?          |          }5tI          |5          \  }6}7|7rd)|7ini }8t]          |8"                    d-                    }9|9r|9|8d-<   t5          dz||6d4|8}|rt          |||          n||fcY S w xY wtq          |4|||dAB          }:|rts          |:          |fS |:|fS t5          dz||/d4|1}|,dCk    r&te          |tt                    stu          ||          }n ||||.|          }|rt          |||          n||fS t                              dD|            dS n# tn          $ r Y nw xY w| dEk    r^tw          |||F          \  }};|t                              dG           dS t#          |p|;|           }|rt          |||          n||fS 	 ddHl<m=}<m>}=m?}> n,# tn          $ r t                              dI|            Y dS w xY w|<"                    |           }?|?@| t          vr5t          A                    |            t                              dJ|            dS |?jB        dk    r| dKk    r[t          |          \  }};|t                              dL           dS t#          |p|;|           }|rt          |||          n||fS  |=|           }@t          |@"                    dd                                                    }A|r|                                p|A}A|As`t          |?jE                  }B| dMk    r|BF                    dN           t                              dO| dPG                    |B                     dS t          |@"                    dd                                                    #                    d          p|?jH        }Ct?          |C          }D|r4t?          |                                #                    d                    }Dt          |           };t#          |p|;|           }| dQk    rTddRlImJ}EmK}F  |F|D          rA |E|A|D4          }t                              dS| |           |rt          |||          n||fS i }GtK          |Dd*          rd,|Gd+<   ntK          |Dd.          r'dd/l&m'}! |GL                     |!d0|1                     ntK          |Dd2          r#|GL                    tQ          |D                     nztK          |DdT          r$ddUlMmN}H |GL                     |H                       nF	 dd3l)m*}I  |I|           }J|Jr!|Jj+        r|GL                    |Jj+                   n# tZ          $ r Y nw xY wt]          |G          }K|Kr|K}Gt5          dz|A|Dd4|Grd-|Gini }| dMk    rR|rPsN	 ddVlOmP}L  |L|          r+t                              dW|           tu          ||          }n# tn          $ r Y nw xY w ||||C|A          }t                              dS| |           |rt          |||          n||fS |?jB        dXk    r |>|           }@t#          |p&|r|"                    d'          ndpt                      |           }| dYk    rLt          |@"                    dd                                                    }At          |@"                    dd                                                    }Dt          |@"                    dZd                                                    pd}Mt          |@"                    d[          pg           }N|st                              d\           dS |Ar|Dst                              d]           dS dd^lQmR}O  |O|A|D|M|N_          }t                              dS| |           |rt          |||          n||fS | t          vr5t          A                    |            t                              d`|            dS |?jB        dak    r	 ddblTmU}PmV}Q n+# tn          $ r t                              dc           Y dS w xY w |Q            st                              dd           dS  |P            \  }R}D|Rr|Dst                              de           dS df};t#          |p|;|           }	 ddglWmX}S  |S|R|D4          }n3# tZ          $ r&}Tt                              dh|T           Y d}T~TdS d}T~Tww xY wt                              di|           |rt          |||          n||fS |?jB        djk    rF	 ddklYmZ}Um[}Vm\}W ddll5m]}X n+# tn          $ r t                              dm           Y dS w xY w |U            st                              dn           dS  |W            }Ydo};t#          |p|;|           }dp|Y dq}D |V|          rp	  |X|Y          }4n3# tn          $ r&}Tt                              dr|T           Y d}T~TdS d}T~Tww xY wtq          |4|ds|D4          }t                              dt||Y           n,t          |Y|          }t                              du||Y           |rt          |||          n||fS |?jB        dvv r| dk    rt          d||          S | dk    rt          d||          S | d!k    rt          d!||          S | t          vr5t          A                    |            t                              dw|            dS |?jB        | f}Z|Zt          vr;t          A                    |Z           t                              dx|?jB        |            dS ){u  Central router: given a provider name and optional model, return a
    configured client with the correct auth, base URL, and API format.

    The returned client always exposes ``.chat.completions.create()`` — for
    Codex/Responses API providers, an adapter handles the translation
    transparently.

    Args:
        provider: Provider identifier.  One of:
            "openrouter", "nous", "openai-codex" (or "codex"),
            "zai", "kimi-coding", "minimax", "minimax-cn",
            "custom" (OPENAI_BASE_URL + OPENAI_API_KEY),
            "auto" (full auto-detection chain).
        model: Model slug override.  If None, uses the provider's default
               auxiliary model.
        async_mode: If True, return an async-compatible client.
        raw_codex: If True, return a raw OpenAI client for Codex providers
            instead of wrapping in CodexAuxiliaryClient.  Use this when
            the caller needs direct access to responses.stream() (e.g.,
            the main agent loop).
        explicit_base_url: Optional direct OpenAI-compatible endpoint.
        explicit_api_key: Optional API key paired with explicit_base_url.
        api_mode: API mode override.  One of "chat_completions",
            "codex_responses", or None (auto-detect).  When set to
            "codex_responses", the client is wrapped in
            CodexAuxiliaryClient to route through the Responses API.

    Returns:
        (client, resolved_model) or (None, None) if auth is unavailable.
    rB   re  zmoa://Nr  r   base_url_str	model_strr   c                     t          | t                    rdS rdS dk    rdS rdk    rdS t          |          dk    r|pd                                }d|v rdS dS )a(  Decide if a plain OpenAI client should be wrapped for Responses API.

        Returns True when api_mode is explicitly "codex_responses", or when
        auto-detection (api.openai.com + codex-family model) suggests it.
        Already-wrapped clients (CodexAuxiliaryClient) are skipped.
        Fr  Tapi.openai.comrB   r   )r$   rD  r5   r   )r  r  r  model_lowerr  r  s       r   _needs_codex_wrapz2resolve_provider_client.<locals>._needs_codex_wrap  s     j"677 	5 	5(((4 	$5555\**.>>>$?1133K+%%tur   final_model_strapi_key_strc                      | ||          r;t                               dpd||r
|dd         nd           t          | |          S t          | |||          S )a@  Wrap a plain OpenAI client in the correct transport adapter.

        Handles two cases:
        - ``CodexAuxiliaryClient`` when the endpoint needs the Responses API
          (explicit ``api_mode=codex_responses`` or api.openai.com + codex
          model name).
        - ``AnthropicAuxiliaryClient`` when the endpoint speaks Anthropic
          Messages (explicit ``api_mode=anthropic_messages``, any ``/anthropic``
          suffix, ``api.kimi.com/coding``, or ``api.anthropic.com``).

        Clients that are already specialized wrappers pass through unchanged.
        zeresolve_provider_client: wrapping client in CodexAuxiliaryClient (api_mode=%s, model=%s, base_url=%s)r  Nr  rB   )rX   rx   rD  r  )r  r  r  r  r  r  s       r   _wrap_if_neededz0resolve_provider_client.<locals>._wrap_if_needed  s     ZGG 	ELL7+O_%19SbS!!r	; ; ;
 (
ODDD %lH
 
 	
r   r  r  r  r   z\Dropping OpenRouter-format model %r for non-OpenRouter auxiliary provider (using %r instead)r  rB  )r7  z4resolve_provider_client: openrouter requested but %szmimo-v2-omnirH  zYresolve_provider_client: nous requested but Nous Portal not configured (run: hermes auth)r   nous_api_moder\   r=   r   zresolve_provider_client: openai-codex requested without a model; pass model explicitly (e.g. model.model in config.yaml or auxiliary.<task>.model for per-task aux routing).zbresolve_provider_client: openai-codex requested but no Codex OAuth token found (run: hermes model)r:  r  u   resolve_provider_client: xai-oauth requested but no xAI OAuth token found (run: hermes model -> xAI Grok OAuth — SuperGrok / Premium+)r   r  r  zQresolve_provider_client: explicit custom endpoint requested but base_url is emptyr   r  r  rv  rY  r  r3  r  r  Tr  rU  r  r_   zPresolve_provider_client: custom/main requested but no endpoint credentials foundry  key_envapi_key_envu   resolve_provider_client: named custom provider %r has no resolvable api_key — request will be sent with placeholder no-key-required and will 401 on auth-required endpointsr   r  r}  zCresolve_provider_client: named custom provider %r (%s, api_mode=%s)r  r  u   Named custom provider %r declares api_mode=anthropic_messages but the anthropic SDK is not installed — falling back to OpenAI-wire.Fr  r  zAresolve_provider_client: named custom provider %r has no base_urlr  r  zsresolve_provider_client: azure-foundry requested but runtime resolution failed (run: hermes doctor for diagnostics))r  r  -resolve_external_process_provider_credentialsz-hermes_cli.auth not available for provider %sz,resolve_provider_client: unknown provider %rr   zOresolve_provider_client: anthropic requested but no Anthropic credentials foundr   zgh auth tokenzJresolve_provider_client: provider %s has no API key configured (tried: %s)r6  r   r  z resolve_provider_client: %s (%s)r   r  )!_should_use_copilot_responses_apiud   resolve_provider_client: copilot model %s needs Responses API — wrapping with CodexAuxiliaryClientexternal_processr   commandr    zVresolve_provider_client: copilot-acp requested but no model was provided or configuredz^resolve_provider_client: copilot-acp requested but external process credentials are incompleter  )r\   r=   r  r    zLresolve_provider_client: external-process provider %s not directly supportedr  )r  has_vertex_credentialszGresolve_provider_client: vertex requested but google-auth not installedzFresolve_provider_client: vertex requested but no GCP credentials foundzTresolve_provider_client: vertex requested but could not mint token / resolve projectzgoogle/gemini-3-flash-previewr   z8resolve_provider_client: cannot create Vertex client: %sz$resolve_provider_client: vertex (%s)aws_sdk)has_aws_credentialsis_anthropic_bedrock_modelresolve_bedrock_region)build_anthropic_bedrock_clientzSresolve_provider_client: bedrock requested but boto3 or anthropic SDK not installedzGresolve_provider_client: bedrock requested but no AWS credentials foundz(anthropic.claude-haiku-4-5-20251001-v1:0r  r  z9resolve_provider_client: cannot create Bedrock client: %sr  z3resolve_provider_client: bedrock anthropic (%s, %s)z2resolve_provider_client: bedrock converse (%s, %s)>   oauth_externaloauth_device_codezMresolve_provider_client: OAuth provider %s not directly supported, try 'auto'z6resolve_provider_client: unhandled auth_type %s for %srB   rB   r   )br  r   r   r   rl  rI   r   r  rn  rn   r  rX   rx   r  r@  rY   rB  r  r!  r  rN  hermes_cli.providersr  ro   r  r  ra   r  rr  r  r  r{  r  rs  rJ   rx  r   r4   r  r  rW  r  r  r3  r5  rK   r>  r
  r'  ry   r$   r  rz  rh  r  rU   r  r  rD  r  r  r  r  r  r9   r5  r  r  r  api_key_env_varsr  r  r  r  r  r  r6  r  r  r  r  r  r  r;   r  r  r  r   r   r  r  r  r  r  r  rL  r<   r:   )\r   r   rO   r  r  r7  r  r  r  r  original_providerrN  rO  _nous_portal_visionr  rZ   r  r  r  
_is_visionr  portal_moder  r  r  
raw_clientr  r  
_main_base	_main_keyr   r  r  r  _gpf_custom
_ph_custom_merged_customr=  _cbase	_raw_ckey_ckeyrz  custom_entrycustom_key_enventry_api_moder  raw_base_for_wrap_clean_base2_dq2_extra2	_headers2r  r  _fallback_base	_fb_clean_fb_dq	_fb_extra_fb_headerssync_anthropicdefault_modelr  r  r  r  r   r\   tried_sourcesr  r=   r  r  r.  r  	_gpf_main_ph_main_merged_mainr  r  r    r  r  r  r  r   r   r  r  r  r  r  _auth_dedup_keyr  s\      `  `                                                                                    @r   rL  rL    s   T  "R..006688&x00H 5$;E$B$B!z 	(Z 	( - 3 3 5 5 ; ; = =.}==HE ! (S):%;%;%A%A%C%C%N%Nx%X%X ($(!#' b #f,: ]X''0C'+H55\9Q9S9S\W\C C D       , OQ+-
 
S 
 
%(
 
 
 
 
 
 
8 6(lNNN>:
  	SE\\h\3h3F3FLL89>J J J E'xNX + 	JJJJk*	, <);KLLL>NNF022   :/0@(KKNX + 	JJJJk*	, 6  ?/66888?""$$**,,> 	
 $:666>NN O P P P:/0@(KK 	766666#mK00'&)R88>B??76:r::@bAA&KlK
 
 OY + 	JJJJk*	, >!! 	NNG  
 : 	- 344K "  T U U U!z3E8DDK.#, 9+ F F  J
 ,,-e44>NN P Q Q Q:/0@(KKNX + 	JJJJk*	, ;5e<<>NNc   :/0@(KKNX + 	JJJJk*	, 8
 	'-.?@@FFHHK!'R..00 %"#344%2;??% %	   ",   "z"  	' \--j99?R@@FFHHOOPSTTJL,,Y77=2>>DDFFI 'i '(&
 "	0: "	03_|M,**7333_R_ K E8EEK -),o&$[.AA ,8:M+N'((&{4GHH KKKKKK+B+B"&), , ,'(( '{4NOO +CK+P+P'((MMMMMM!,X!6!6J! Tj&@ T37
8R3S3S/0    D8CT9U9UVVN :+9'(*]:]]W\]]F$_V[+zRRFR\ /$V[INNNN +.0 ,-FG 	4 	4F$fhhOFG!78H(SSWVZ<<BCC $FIr::	'	22p:iQT;U;Up\_`i`omo\p\p(feLLV` 3(	RRRR$k24 4 4 " 	 ; 	< 	< 	<zkJJJJJJ  	I!2h!>!>556GHHL55h??L [	'++J77=2DDFFK&**955;BBDDJ*..y99b\=M=Mm=\=\b`biikkN =. =,^<<
#8'8J...> !$$V,,8	   'L,*:*::*F*FL"SSUUN F47 %#''00%5AK((111t% 011% %  "%999"-K(3%%"5k"B"BK(3%%>{%K%K"d59A?D11r7DU8V8VWW	 ;1:G-.Yk>+O=OQ Q Q "%999<RRRRRR&<&<Z&U&U& < < <I %	   *=[)I)I,En,U,U)	6AG$O_f$=$=R	&A)--PaBbBb&c&c& G;FI&78!6!kzT]!k!kaj!k!k^h !; 0PY Z Z Z Z&,k%:< < <!<$ &>#[*kTY& & &N " Z<^LLkYY);66.dzLdd\cdd
 "%666z0@ @6 2&+FFFF,_V[BSU_``FV` 3(	RRRR$k24NNS   :w[	x    & ?"" 2-/	!
 !
 !
 >NN  
 :/0FQQNX + 	JJJJk*	,	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	

    DhOOOzz  ##H--G 888)--h777LLGRRRzI%%{""$2DT$U$U$U!FM~pqqq!z3E4J]HUUKR\w$V[INNNNcikvbwx44X>>eii	2..//5577
  	:&,,..9'G 	 !9::M9$$$$_555LL 6!499]#;#;= = = :599Z4455;;==DDSIIgWMg&|44  	R*+<+B+B+D+D+K+KC+P+PQQH3H==/0FQQxaaaaaaaa((22 4++GhOOO?;WWWV` 3(	RRRR$k24  >:: 	$7GL!!"8-@AA 	GGGGGGNN22"i       #8-GHH 	NN3H==>>>>"8V44 	AAAAAANN55778888GGGGGG$9X.. = 8 =NN8#;<<<   27;; 	#"G& Mw M M;BJ-w77M M y  [  	OOOOOO44[AA GLLO#% % % 2&+FFF    !lGLL7;OOONX + 	JJJJk*	, ...==hGG/ *-9C  )))t*'))	
 
 }$$%))Ir223399;;G599Z4455;;==H%))Ir223399;;CtG		&))/R00D "1   "z "( "9   "zAAAAAA%%!	  F LL;X{SSSR\ /$V[INNNN +.0;;;,00:::LL ./79 9 9z		h	&	&
	VVVVVVVVV 	 	 	NN 7 8 8 8::	
 &%'' 	LL 4 5 5 5:++--x 	H 	NN D E E E:7/0FQQ	%%%%%%VEH===FF 	 	 	NN (),. . .:::::	 	;[IIINX + 	JJJJk*	, 
	i	'	'
	         
 ONNNNNN 	 	 	NN B C C C::	
 #"$$ 	LL 4 5 5 5:''))B/0FQQDfDDD%%k22 	."<<VDD " " "  ,-02 2 2!zzzzz" .[)!  F LLN$f. . . . ,FK@@FLLM$f. . . OY + 	JJJJk*	, 
	E	E	Ev*65*EEE~%%*>5*MMM{""*;zJJJ999*..x888LL :;CE E Ez
 ((3O==='++O<<<M&	2 	2 	2:s  "1Y 
Y! Y!!Hl *f= <l =Bil i)l l A l -l 
ll 
n %n43n4;4|0 0
|=<|=3<~0 0
~=<~=G0AG9 G9$AH!H AH!JAJ  J 
AKJ*AKKAKLAL$ L$$AMMAMN%AN1 N1
AO!N;AOOAO!c                Z    t          | pd          \  }}}}}t          ||||||          S )aR  Return (client, default_model_slug) for text-only auxiliary tasks.

    Args:
        task: Optional task name ("compression", "web_extract") to check
              for a task-specific provider override.

    Callers may override the returned model via config.yaml
    (e.g. auxiliary.compression.model, auxiliary.web_extract.model).
    N)r   r  r7  r  r  _resolve_task_provider_modelrL  r  r  r   r   r=   r\   r  s          r   get_text_auxiliary_clientr  3  sM     4PPTP\X\3]3]0HeXw"" !   r   c          	      \    t          | pd          \  }}}}}t          ||d||||          S )a  Return (async_client, model_slug) for async consumers.

    For standard providers returns (AsyncOpenAI, model). For Codex returns
    (AsyncCodexAuxiliaryClient, model) which wraps the Responses API.
    Returns (None, None) when no provider is available.
    NTr   rO   r  r7  r  r  r  r  s          r   get_async_text_auxiliary_clientr  L  sP     4PPTP\X\3]3]0HeXw"" !   r   )rB  r  	deepinfrac                     	 ddl m} ddlm} n# t          $ r Y dS w xY w	  || | |                      }n# t
          $ r Y dS w xY w|dS t          |          S )u  Return True when ``provider``/``model`` is known to accept image input.

    Used by the vision auto-detect chain to skip the user's main provider
    when it's known to be text-only (e.g. DeepSeek, gpt-oss without vision).
    Without this guard, ``resolve_vision_provider_client(provider="auto")``
    would happily return the main-provider client and any subsequent image
    payload would surface as a cryptic provider-side error
    (``unknown variant `image_url`, expected `text```, #31179).

    Returns True when capability lookup is unknown — preserves the historical
    behaviour of attempting the call, so providers we haven't catalogued yet
    don't silently regress to text-only.
    r   )_lookup_supports_visionrA  T)agent.image_routingr  rH   rA   rU   rK   rn   )r   r   r  rA   supportss        r   _main_model_supports_visionr  f  s    ??????:::::::   tt**8U<P<P<R<RSS   tt t>>s    
7 
AAc                      t          |           S r   )r   r   s    r   _normalize_vision_providerr    s    "8,,,r   c                    t          |           } | dk    rt          d|d          S | dk    rt          |          S | dk    rt          d|d          S | dk    rt          d|d          S | dk    rt                      S | d	k    rA|pt	          d	          }|st
                              d
           dS t          d	|d          S | dk    rt                      S dS )Nr   Tr  rB  r*  r  r   r   r  ub   Vision auto-detect: deepinfra catalog unreachable or returned no vision-tagged models — skippingr  r   )r  rL  r@  r  r&  rX   rx   r
  )r   r   vision_models      r   _resolve_strict_vision_backendr    s$    *(33H9&y%4HHHH<U++++6 'vuEEEE>!! '~uMMMM;; M @ M M 	LL@   :&{LDQQQQ8#%%%:r   c                 0    t          |           d         d uS rR  )r  r  s    r    _strict_vision_backend_availabler    s    )(33A6dBBr   c                  ^   g } t                      }|rh|dvrd|t          v r%t          |          r|                     |           n6t	          |t                                \  }}||                     |           t          D ]*}|| vr$t          |          r|                     |           +| S )u   Return the currently available vision backends in auto-selection order.

    Order: active provider → OpenRouter → Nous → stop.  This is the single
    source of truth for setup, tool gating, and runtime auto-routing of
    vision tasks.
    >   rB   r   )r   _VISION_AUTO_PROVIDER_ORDERr  r  rL  rX  )	availabler9  rZ   r%  r4  s        r   get_available_vision_backendsr    s     I'))M 0l::777/>> 0  ////?O?Q?QRRIFA!  ///(    I"B1"E"EQr   )r=   r\   rO   r  c                  # t          |          }t          d| |||          \  }#}}	}
t          |          }dt          dt          dt
          t                   f#fd}|r/|r|dvr|nd}t          |#||	|
|          \  }}||d	d	fS |||fS |d
k    rt          |                    d          pt                                }t          |                    d          pt                                }|
                                                                dk    r8t          |          \  }}|r$|r"||}}t          |          }d|d<   d|d<   d|d<   |r|dvrt          |          }|p|}|dk    rFt          |#p|          \  }}|-t                               d||p#p|            ||||          S n"|t$          v rt                               d|           nt)          ||          st                               d|           nd	}d	}|
}|dk    s|                    d          rh|                    d          }|r3|}|                    d          pd	}|
p|                    d          pd	}nt-                      \  }}}|r
|}|}|
p|pd	}t          ||||||d          \  }}|-t                               d||p|            ||||p|          S t.          D ],} | |k    r	t          |           \  }}| || ||          c S -t                               d           dS |t.          v r t          |#          \  }} ||||          S |dk    r\|sZddg}!|!D ]/}"t1          |#|"|	pd	d|d           \  }}| ||||          c S 0t1          |#|
|d!          \  }}||d	d	fS |||fS t1          |#|
|d!          \  }}||d	d	fS |||fS )"ar  Resolve the client actually used for vision tasks.

    Direct endpoint overrides take precedence over provider selection. Explicit
    provider overrides still use the generic provider router for non-standard
    backends, so users can intentionally force experimental providers. Auto mode
    stays conservative and only tries vision backends known to work today.
    rC  r  r  r  c                 \    || d d fS p|}rt          ||d          \  }}| ||fS | ||fS )NTr  )r  )r  r  r  r  async_clientasync_modelrO   r  s         r   	_finalizez1resolve_vision_provider_client.<locals>._finalize  s]    $dD00$5 	@(8k]a(b(b(b%L+$lK?? +{::r   >   rB   r   r   r  Nr   r   r   re  rB   r=   r\   r  >   rB   re  r   r  z/Vision auto-detect: using main provider %s (%s)ui   Vision auto-detect: skipping main provider %s (no vision support) — falling through to aggregator chainut   Vision auto-detect: skipping main provider %s (reports no vision capability) — falling through to aggregator chainr   T)r  r  r7  r  r  z'Auxiliary vision client: none availabler  r   z$https://open.bigmodel.cn/api/paas/v4zhttps://api.z.ai/api/paas/v4r  r=   r\   r  r  r  )r  r  r  )r  r  r  rI   r   r
   rL  rJ   r   rX  r   r   rl  r5  r&  r  rX   r?  r'  rx   r  r   r  r  r  )$r   r   r=   r\   rO   r  rL  r  r  r  r  r  provider_for_base_overriderZ   r  r9  rM  rN  rO  provider_vision_defaultr  r  r  rpc_base_urlrpc_api_keyrpc_api_moder  r  r  r  
rpc_client	rpc_modelri  zai_openai_urls_zai_urlr  s$       `                              @r   r  r    s     &l33GXt(E8WY YUI~02BDU +955I;S ;s ;8TW= ; ; ; ; ; ; ;  ?"Ry'D'DII( 	# 6& !/-& 
 
 
 >-tT99)6;>>F$ GKK
33L7J7L7LMMW--C1A1C1CDD
  &&((E11 )@
(K(K%M: ) ),9:z w--&(
#%'	"&(
# c	N]2EEE 'G}&U&U#2@jL&& .L!>#L5L. .*] *KKI%}'T'T*   %9]KOOO + ";;; N!   
 1MM <N ' "	     $"0 H,,0H0H0S0S,'.{{:'>'>$' T'7&-kk)&<&<&D- $&{{:66$# % @W?X?X<Z& T+6L*4K+<+S+StL(?!<)&2%0!(")$ )$ )$%
I )KKI%y'@L   %9%z93LN N N
 5 	H 	HIM)))G	)R)R&K& yKGGGGG ' 	>???///%C~&
 &
"] yK??? E"32*
 ( 
	A 
	AH"4>:!(0D+$# # #FK ! yFK@@@@@ " 1NJ:K>E;?A A A >dD((&+--,Y
6G:A7;= = =FK ~$$$fk))r   c                  0    t           rt                      ni S )zReturn extra_body kwargs for auxiliary API calls.
    
    Includes Nous Portal product tags when the auxiliary client is backed
    by Nous Portal. Returns empty dict otherwise.
    )r_  r^  r   r   r   get_auxiliary_extra_bodyr    s     "3::r   r*  r=  c                    t                      }t          d          }t          |          pd}|s3t                      %|dk    s|dk    s|                    d          rd| iS t          |          rd| iS d| iS )	u  Return the correct max tokens kwarg for the auxiliary client's provider.

    OpenRouter and local models use 'max_tokens'. Direct OpenAI with newer
    models (gpt-4o, gpt-4.1, gpt-5+, o-series) requires 'max_completion_tokens'.
    The Codex adapter translates max_tokens internally, so we use max_tokens
    for it as well. Pass ``model`` so third-party OpenAI-compatible endpoints
    fronting the newer families are also recognised — URL-only detection
    misses the case where a custom base URL serves e.g. ``gpt-5.4``.
    r;  rB   Nr  r  z.githubcopilot.comrr  rq  )r  r  r5   r  ry  r7   )r=  r   r  r?  _custom_hosts        r   auxiliary_max_tokens_paramr    s     +,,K122F %[117RL 0!!) 000#:::(()=>> ; (//)%00 0'//%  r   r  @   c                   N    e Zd ZdZdZdeddfdZdefdZde	de
fd	Zdefd
ZdS )_CallableCacheDiscriminatorzBHash a credential callback by identity without exposing its state.	_callbackr   r   Nc                     || _         d S r   r  )r   r   s     r   rg   z$_CallableCacheDiscriminator.__init__  s    !r   c                 *    t          | j                  S r   )r  r  r(   s    r   __hash__z$_CallableCacheDiscriminator.__hash__  s    $.!!!r   otherc                 H    t          |t                    o| j        |j        u S r   )r$   r  r  )r   r  s     r   __eq__z"_CallableCacheDiscriminator.__eq__
  s&    u9:: 2%/1	
r   c                     dS )Nz<callable-api-key>r   r(   s    r   r)   z$_CallableCacheDiscriminator.__repr__  s    ##r   )r*   r+   r,   r-   r.   r   rg   rL  r  objectrn   r  rI   r)   r   r   r   r  r    s        LLI" " " " " ""# " " " "
F 
t 
 
 
 
$# $ $ $ $ $ $r   r  c                    | dk    rt          |          rt          |          S | dk    rVt          |t                    rA|r?t	          j        |                    d          d                                          }d|fS |S )z;Return a hashable, secret-safe runtime cache-key component.r\   r     )digest_sizezapi-key-digest)ry   r  r$   rI   hashlibblake2bencodedigest)r  r=  r  s      r   _runtime_cache_discriminatorr    s    	huoo*5111	j44g!6!6BGGGNNPP &))Lr   )r=   r\   r  r  r  r  r   c          
          t          |          | dk    r t          fdt          D                       nd}	| dk    r|pdnd}
t          | |          }|p                    dd          }t          d|pd          }| ||pd||pd|	||
||f
S )Nr   c              3   `   K   | ](}t          |                    |d                     V  )dS rB   N)r  rJ   r  s     r   r  z$_client_cache_key.<locals>.<genexpr>+  sO         	%UGKKr,B,BCC     r   r   rB   r  r   r\   )r  r  r  r  rJ   r  )r   rO   r=   r\   r  r  r  r  r   runtime_keytask_key	pool_hint	model_keyapi_key_keyrL  s                 @r   _client_cache_keyr&    s     &l33G 
V		     )      "$   (611
rH EEEI 1Wb11I.y'-RHHKj(.b+x~2{\egoqz  }F  G  Gr   
bound_loop	cache_keyr  r(  c                    t           5  t                              |           }||d         |urt          |d                    |||ft          | <   d d d            d S # 1 swxY w Y   d S rR  )r  r  rJ   r  )r)  rZ   r  r(  	old_entrys        r   _store_cached_clientr,  B  s    	 G G!%%i00	 Yq\%?%? 1...$*M:#Fi 	G G G G G G G G G G G G G G G G G Gs   A	AA"%A"r  cache_providerc           
      J   t          d          }|d|fS |\  }	}
t          |	|
          }|}d}|rB	 ddl}|                                }n# t          $ r Y nw xY wt          ||pd|          \  }}n|}t          | |||||||          }t          ||||	           ||fS )
zLRefresh Nous runtime creds, rebuild the client, and replace the cache entry.Tr  Nr_   r   rB   r  )rO   r=   r\   r  r  r  r   r'  )r  ra   rT  get_event_loopr  r  r&  r,  )r-  r   rO   r=   r\   r  r  r  rL  	fresh_keyfresh_base_urlr  r  current_loop_aiorZ   r)  s                    r   _refresh_nous_auxiliary_clientr4  J  s    (d;;;GU{ 'I~'	NSSSKKL 	""""..00LL 	 	 	D	.{K<M2Ybccc!!	 	 	I FKLQQQQ;s   A 
AAc                  T    	 ddl m}  d | _        dS # t          t          f$ r Y dS w xY w)a  Monkey-patch ``AsyncHttpxClientWrapper.__del__`` to be a no-op.

    The OpenAI SDK's ``AsyncHttpxClientWrapper.__del__`` schedules
    ``self.aclose()`` via ``asyncio.get_running_loop().create_task()``.
    When an ``AsyncOpenAI`` client is garbage-collected while
    prompt_toolkit's event loop is running (the common CLI idle state),
    the ``aclose()`` task runs on prompt_toolkit's loop but the
    underlying TCP transport is bound to a *different* loop (the worker
    thread's loop that the client was originally created on).  If that
    loop is closed or its thread is dead, the transport's
    ``self._loop.call_soon()`` raises ``RuntimeError("Event loop is
    closed")``, which prompt_toolkit surfaces as "Unhandled exception
    in event loop ... Press ENTER to continue...".

    Neutering ``__del__`` is safe because:
    - Cached clients are explicitly cleaned via ``_force_close_async_httpx``
      on stale-loop detection and ``shutdown_cached_clients`` on exit.
    - Uncached clients' TCP connections are cleaned up by the OS when the
      process exits.
    - The OpenAI SDK itself marks this as a TODO (``# TODO(someday):
      support non asyncio runtimes here``).

    Call this once at CLI startup, before any ``AsyncOpenAI`` clients are
    created.
    r   AsyncHttpxClientWrapperc                     d S r   r   r(   s    r   r{  z(neuter_async_httpx_del.<locals>.<lambda>  s    t r   N)openai._base_clientr7  __del__rU   rV   r6  s    r   neuter_async_httpx_delr;  w  sR    4??????*;*;'''(   s    ''c                     	 ddl m} t          | dd          }|t          |dd          s|j        |_        dS dS dS # t
          $ r Y dS w xY w)u  Mark the httpx AsyncClient inside an AsyncOpenAI client as closed.

    This prevents ``AsyncHttpxClientWrapper.__del__`` from scheduling
    ``aclose()`` on a (potentially closed) event loop, which causes
    ``RuntimeError: Event loop is closed`` → prompt_toolkit's
    "Press ENTER to continue..." handler.

    We intentionally do NOT run the full async close path — the
    connections will be dropped by the OS when the process exits.
    r   )ClientStater  N	is_closedT)httpx._clientr=  ro   CLOSED_staterK   )rZ   r=  inners      r   _force_close_async_httpxrC    s    ------	400WUK%F%F&-ELLL    s   6> 
AAc                     | dS t          |            	 t          | dd          }t          |          r t          j        |          s |             dS dS dS # t
          $ r Y dS w xY w)zBApply the canonical best-effort close policy to one cached client.Nr  )rC  ro   ry   inspectiscoroutinefunctionrK   )rZ   r3  s     r   r  r    s    ~V$$$67D11H 	g&A(&K&K 	HJJJJJ	 	 	 	   s   >A 
A'&A'c                     t           5  t          t                                                    D ]\  } }|d         }|t	          |            t                                           ddd           dS # 1 swxY w Y   dS )zClose all cached clients (sync and async) to prevent event-loop errors.

    Call this during CLI shutdown, *before* the event loop is closed, to
    avoid ``AsyncHttpxClientWrapper.__del__`` raising on a dead loop.
    r   N)r  r  r  r   r  r  )r<  r  rZ   s      r   shutdown_cached_clientsrH    s     
  }224455 	) 	)JC1XF~ ((((                 s   A A55A9<A9c                  $   t           5  g } t                                          D ]E\  }}|\  }}}|8|                                r$t	          |           |                     |           F| D ]
}t          |= 	 ddd           dS # 1 swxY w Y   dS )uK  Force-close cached async clients whose event loop is closed.

    Call this after each agent turn to proactively clean up stale clients
    before GC can trigger ``AsyncHttpxClientWrapper.__del__`` on them.
    This is defense-in-depth — the primary fix is ``neuter_async_httpx_del``
    which disables ``__del__`` entirely.
    N)r  r  r   r>  rC  r  )r  r<  r  rZ   _defaultcached_loops         r   cleanup_stale_async_clientsrL    s     
 # #
'--// 	' 	'JC,1)FHk&;+@+@+B+B&(000!!#&&& 	# 	#Cc""	## # # # # # # # # # # # # # # # # #s   A/BB	B	c           
          | t          | dd           t          | dd           fD ]5}|r1t          t          t          |dd          pd          d          r dS 6dS )Nr  rZ   r=   rB   r  TF)ro   r4   rI   )rZ   r%   s     r   _is_openrouter_clientrN    sr    	488'&(TX:Y:YZ   	(WS*b-I-I-OR)P)PRabb 	445r   cached_defaultc                 J    t          |           rdS t          |od|v           S )zFBest-effort check for cached clients that accept ``vendor/model`` IDs.Tr   )rN  rn   )rZ   rO  s     r   #_cached_client_accepts_slash_modelsrQ    s/    V$$ t83.#8999r   c                 :    |rd|v rt          | |          s|S |p|S )zKeep slash-bearing model IDs only for cached clients that support them.

    Mirrors the guard in resolve_provider_client() which is skipped on cache hits.
    r   )rQ  )rZ   r   rO  s      r   _compat_modelrS    s5    
  &I&R`&a&a"N"r   c	                 >   d}	|r*	 ddl }
|
                                }	n# t          $ r Y nw xY wt          |          }t	          | ||||||||	  	        }t
          5  |t          v rt          |         \  }}}|rX|duo||	u o|                                 }|r!t          |||          }||fcddd           S t          |           t          |= n!t          |||          }||fcddd           S ddd           n# 1 swxY w Y   |}|s1t          t          |                     }|t          |          }|r|}t          | ||||||||	  	        \  }}||	}t
          5  |t          vrqt          t                    t          k    rFt!          t#          t                              }t          |= t          t                    t          k    F|||ft          |<   n"|}t          |         \  }}}t%          |           ddd           n# 1 swxY w Y   ||p|fS )a  Get or create a cached client for the given provider.

    Async clients (AsyncOpenAI) use httpx.AsyncClient internally, which
    binds to the event loop that was current when the client was created.
    Using such a client on a *different* loop causes deadlocks or
    RuntimeError.  To prevent cross-loop issues, the cache validates on
    every async hit that the cached loop is the *current, open* loop.
    If the loop changed (e.g. a new gateway worker-thread loop), the stale
    entry is replaced in-place rather than creating an additional entry.

    This keeps cache size bounded to one entry per unique provider config,
    preventing the fd-exhaustion that previously occurred in long-running
    gateways where recycled worker threads created unbounded entries (#10200).
    Nr   )rO   r=   r\   r  r  r  r  r   )r  r7  r  r  r  r  )rT  r/  r  r  r&  r  r  r>  rS  rC  r  r   r  rL  rj  _CLIENT_CACHE_MAX_SIZEnextiterr  )r   r   rO   r=   r\   r  r  r  r  r2  r3  rL  r)  cached_clientrO  rK  loop_ok	effectiveeffective_api_key_pe_pkrZ   r  r(  	evict_keybuilt_clientr%  s                              r   r  r    sr   > L 	""""..00LL 	 	 	D	%l33G!!
 
 
I 
 0 0%%9Fy9Q6M>; 0
  t+ 4#|34'11333 
  4 -mUN S SI()30 0 0 0 0 0 0 0  )777!),,)-OO	$i/)0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 06   (6x@@AA?',,C ($'!3"*
 
 
FM  "
 	3 	3-- -((,BBB $T-%8%8 9 9I%i0 -((,BBB -3M:+Ni((%+8+C(q %\222#	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3$ 5)M))s8    
,,AC?:,C??DD%BHHHr   zhttps://api.openai.com/v1_AUX_DIRECT_API_BASE_URLSc           	         d}d}d}d}d}	| rt          |           }
t          |
                    dd                                                    pd}t          |
                    dd                                                    pd}t          |
                    dd                                                    pd}t          |
                    dd                                                    pd}|s^t          |
                    d          p|
                    d          pd                                          }|rt	          |          pd}t          |
                    d	d                                                    pd}	|r|                                d
k    rd}|r|                                d
k    rd}|p|}|	}dt          dt          t                   dt          t          t          t                   f         fd}|ret          |                                                                          dk    r. |||          \  }}|r|                                dk    rd}d}nh|rft          |                                                                          dk    r/ |||          \  }}|r|                                dk    r|}d}d}dt          t                   dt          t                   dt          t          t                   t          t                   f         fd}dt          t                   dt          fd}|r |||          \  }}|r |||          \  }}|r|d
k    r|s|r|d|fv r|}|s|}|r ||          r|||||fS |rd||||fS |r|||||fS | r2|r	|rd||||fS |r|r|d
k    r|||d|fS |r|d
k    r|||||fS d
|dd|fS d
|dd|fS )ad  Determine provider + model for a call.

    Priority:
      1. Explicit provider/model/base_url/api_key args (always win)
      2. Config file (auxiliary.{task}.provider/model/base_url)
      3. "auto" (full auto-detection chain)

    Returns (provider, model, base_url, api_key, api_mode) where model may
    be None (use provider default). A bare base_url is treated as custom, but
    a first-class provider plus base_url keeps the provider identity so its
    auth, transport, and request-shaping behavior still apply. api_mode is one
    of "chat_completions", "codex_responses", or None (auto-detect).
    Nr   rB   r   r=   r\   r  r  r  r   r  mdlr   c                     |                                                                  dk    r| |fS t          |          \  }}|r|r||fS | |fS )Nre  )r   r   rl  )r  rb  rj  rk  s       r   _unwrap_moa_providerz:_resolve_task_provider_model.<locals>._unwrap_moa_provider  sa    ::<<5((9"9#">">i 	+I 	+**Syr   re  existing_basec                     | s| |fS t                               |                                                                           }|| |fS d|p|fS )Nr   )r`  rJ   r   r   )r  re  target_bases      r   _expand_direct_api_aliasz>_resolve_task_provider_model.<locals>._expand_direct_api_alias  s]     	'&&/33DJJLL4F4F4H4HII&&5+55r   c                     t          | pd                                                                          }|dv s|                    d          rdS 	 ddlm}  ||          d uS # t          $ r |dv cY S w xY w)NrB   >   rB   r   r   r   Fr   )get_provider>   
qwen-oauthr  r   r   r  r   r   minimax-oauth)rI   r   r   r   r  rj  rK   )r  r   rj  s      r    _preserve_provider_with_base_urlzF_resolve_task_provider_model.<locals>._preserve_provider_with_base_url  s    __**,,2244
///:3H3H3S3S/5	999999<
++477 	 	 	  	" 	 	 	 		s   A% %A65A6r   )	r  rI   rJ   r   r  r   r
   r   rn   )r  r   r   r=   r\   r$  r=  r%  cfg_api_keycfg_api_moder_  cfg_key_envr  r  rd  rh  rm  s                    r   r  r  |  s   ( LILKL L066;??:r::;;AACCKt4455;;==E	;??:r::;;AACCKt+//)R8899??AAIT 	C	**Rkoom.L.LRPR egg   C-k::Bd;??:r::;;AACCKt   &(( Y__&&&00	'iN$3 Xc] uS(SV-EW?X      CMM''))//11U::#7#7.#Q#Q .
  	((E11HG	 #l++113399;;uDD"6"6|^"T"Ti 	L..00E99&NLK6x} 6Xc] 6W\]efi]jltuxly]yWz 6 6 6 6x}     ,  J55hII( Z%=%=lL%Y%Y"l  "H&&x&L&\^bdl]mMmMm 	"!G N44X>> N7<MMM N7<MMM N7<MMM E 	ZK 	Z^\;HYYY 	WL 	W\V-C-C  tEVVV 	^LF22{L]]]~tT3DDD>4/@@@r         >@g     r@c                 `   | si S 	 ddl m}  |            }n# t          $ r i cY S w xY wt          |t                    r|                    di           ni }t          |t                    r|                    | i           ni }t          |t                    si }	 ddlm}  |            D ]q}|                    d          | k    rV|                    d          pi }t          |t                    r(t	          |          }|                    |           |c S  nrn# t          $ r Y nw xY w|S )u  Return the config dict for auxiliary.<task>, or {} when unavailable.

    For plugin-registered auxiliary tasks (see
    :meth:`hermes_cli.plugins.PluginContext.register_auxiliary_task`) the
    plugin's declared *defaults* are layered underneath the user's config
    so an unconfigured plugin task still works:

        plugin defaults  ←  config.yaml auxiliary.<task>  (user wins)

    Built-in tasks ignore this path (their defaults live in DEFAULT_CONFIG).
    r   rA  r-  )get_plugin_auxiliary_tasksr<  defaults)
rH   rA   rU   r$   r5  rJ   hermes_cli.pluginsrs  r6  rK   )	r  rA   rC   auxr_  rs  _entry	_defaultsr;  s	            r   r  r  ;  s     	::::::%%''   			)3FD)A)A
I&**["
%
%
%rC'1#t'<'<D#''$###"Kk4(( 
AAAAAA0022 	 	Fzz%  D(("JJz228b	i.. "!)__FMM+...!MMM )     s%    &&A>D D 
D+*D+r  c                     | s|S t          |           }|                    d          }|'	 t          |          S # t          t          f$ r Y nw xY w|S )zPRead timeout from auxiliary.{task}.timeout in config, falling back to *default*.r  )r  rJ   rM  r  r   )r  r  r_  r  s       r   _get_task_timeoutrz  g  sm     ,T22K
//)
$
$C
	::I& 	 	 	D	Ns   ; AAr  c                 f    ||nt          |           }|| dk    rt          |t                    }|S )uV  Resolve the effective timeout for an auxiliary LLM call.

    Uses the caller-provided ``timeout`` when given; otherwise reads
    ``auxiliary.{task}.timeout`` from config via :func:`_get_task_timeout`.
    For the ``compression`` task only, applies a bounded floor so a reasoning
    model summarising a large context is not cut off by the default timeout
    (#54915).  The floor is intentionally skipped when the caller passes an
    explicit ``timeout=`` — explicit per-call deadlines are always honoured —
    and it is a minimum (``max``), so a config value already above it is kept.
    NrS  )rz  r  "_COMPRESSION_TIMEOUT_FLOOR_SECONDS)r  r  rZ  s      r   _effective_aux_timeoutr}  u  s@     #.4Ed4K4KI4=00	#EFF	r   c                    t          |           }|                    d          }t          |t                    rt          |          ni }d|vrs|                    d          }|\|dk    rV| dv rt                              d|            |S dd	lm}  ||          }|||d<   nt                              d
| |           |S )u  Read auxiliary.<task>.extra_body and return a shallow copy when valid.

    Also folds in ``auxiliary.<task>.reasoning_effort`` as an
    ``extra_body.reasoning`` config dict ({"enabled": ..., "effort": ...})
    when set. An explicit ``extra_body.reasoning`` in config wins over the
    ``reasoning_effort`` shorthand (it is the more specific wire control).
    Downstream, each wire already translates ``extra_body.reasoning``:
    chat.completions passes it through, the Codex Responses adapter maps it
    to top-level ``reasoning``/``include``, and the Anthropic auxiliary
    client maps it to ``build_anthropic_kwargs(reasoning_config=...)``.

    MoA tasks are excluded by design: reasoning depth for MoA is a per-slot
    setting in the MoA preset (``moa.presets.<name>.reference_models[].
    reasoning_effort`` / ``aggregator.reasoning_effort``), not an
    auxiliary-task knob — an ensemble-wide value would override the
    per-slot ones.
    r  r  reasoning_effortNrB   )moa_referencemoa_aggregatoru   auxiliary.%s.reasoning_effort is not supported — MoA reasoning depth is per-slot: set reasoning_effort on the preset's reference_models entries / aggregator instead (moa.presets.<name>...). Ignoring.r   )parse_reasoning_effortux   auxiliary.%s.reasoning_effort %r is not a valid level (none, minimal, low, medium, high, xhigh, max, ultra) — ignoring)r  rJ   r$   r5  rX   rY   hermes_constantsr  )r  r_  r  r   r  r  r   s          r   _get_task_extra_bodyr    s    $ -T22K
//,
'
'C$S$//7T#YYYRF&  !344&B,,:::9    ??????++F33F!&,{##Y&  
 Mr   _aux_sync_semaphores_aux_async_semaphoresc                     | r| dk    rdS t          |                               d          }|dS 	 t          |          }n# t          t          f$ r Y dS w xY w|dk    r|ndS )zGReturn ``auxiliary.<task>.max_concurrency`` as a positive int, or None.rC  Nmax_concurrencyr   )r  rJ   rL  r   r  )r  r  r=  s      r   _get_task_max_concurrencyr    s     48## t
$T
*
*
.
./@
A
AC
{tCz"   ttAII554's   A AAc                 &   t          |           }|dS t          5  t                              |           }||d         |k    r.t	          j        |          }||ft          | <   |cddd           S |d         cddd           S # 1 swxY w Y   dS )zCGet a per-task sync semaphore, rebuilding it after a config change.Nr   r   )r  _aux_sem_lockr  rJ   r   BoundedSemaphore)r  limitr  	semaphores       r   _acquire_sync_aux_semaphorer    s    %d++E}t	  $((..=E!H--!2599I*/); &        Qx                 s   A
B2BB
B
c                    t          |           }|dS ddl}	 |                                }n# t          $ r Y dS w xY w| t	          |          f}t
          5  t                              |          }||d         |k    r/|                    |          }||ft          |<   |cddd           S |d         cddd           S # 1 swxY w Y   dS )zCGet a per-task, per-event-loop async semaphore after config lookup.Nr   r   )	r  rT  get_running_loopr  r  r  r  rJ   	Semaphore)r  r  rT  loopr<  r  r  s          r   _acquire_async_aux_semaphorer    sS   %d++E}tNNN''))   ttD
C	  %))#..=E!H--))%00I*/);!#&        Qx                 s%   . 
<<AC/CC
Cc                      t           5  t                                           t                                           ddd           dS # 1 swxY w Y   dS )z%Drop cached semaphores (test helper).N)r  r  r  r  r   r   r   _reset_aux_semaphoresr    s    	 & &""$$$##%%%& & & & & & & & & & & & & & & & & &s   3AAA>   minimaxr   rl  c                 L    | t           v rdS |pd                                }d|v S )zDetect if an endpoint expects Anthropic-format content blocks.

    Returns True for known Anthropic-compatible providers (MiniMax) and
    any endpoint whose URL contains ``/anthropic`` in the path.
    TrB   rt  )_ANTHROPIC_COMPAT_PROVIDERSr   )r   r=   	url_lowers      r   r  r    s5     ...tR&&((I9$$r   c           	         g }| D ]]}|                     d          }t          |t                    s|                    |           Cg }d}|D ]}|                     d          dk    r|                     d          pi                      dd          }|                    d          rv|                    d          \  }}	}
d	}d
|v r:d|v r6|                    d
d          d                             dd          d         }|                    dd||
dd           n|                    dd|dd           d}|                     d          dk    r|                     d          pi                      dd          }|                    d          rv|                    d          \  }}	}
d}d
|v r:d|v r6|                    d
d          d                             dd          d         }|                    dd||
dd           n|                    dd|dd           d}|                    |           |                    |ri |d|in|           _|S )as  Convert OpenAI ``image_url``/``video_url`` blocks to Anthropic format.

    Converts:
    - ``image_url`` blocks to Anthropic ``image`` blocks
    - ``video_url`` blocks to Anthropic ``video`` blocks (MiniMax M3 compat)

    Only touches messages that have list-type content with ``image_url`` or
    ``video_url`` blocks; plain text messages pass through unchanged.
    r  Fr  	image_urlr   rB   zdata:,z	image/pngr   ;r   r   imageri  )r  
media_typer  )r  r  )r  r   T	video_urlz	video/mp4video)rJ   r$   r  r  r   	partitionr   )r  r&  r  r  new_contentchangedblockimage_url_valheaderr%  b64datar  video_url_vals                r   r  r    s    I EN EN'')$$'4(( 	S!!! =	* =	*Eyy  K//!&;!7!7!=2 B B5" M M ++G44 )6)@)@)E)E&FAw!,Jf}}%+\\#q%9%9!%<%B%B3%J%J1%M
&& '$,*4$+# #( (      && '$)#0# #( (    6""k11 "';!7!7!=2 B B5" M M ++G44 )6)@)@)E)E&FAw!,Jf}}%+\\#q%9%9!%<%B%B3%J%J1%M
&& '$,*4$+# #( (      && '$)#0# #( (    ""5))))GL8C8K888MMMMr   >
   thinkthinkingr  	verbositythinkingbudgetthinkingconfigenable_thinkingthinking_budgetthinking_configr  c                 
   t          | t                    sdS |                                 D ]V\  }}t          |                                                                          }|t          v r dS t          |          r dS WdS )zCReturn whether a profile payload contains a reasoning wire control.FT)r$   r5  r   rI   r   r   _PROFILE_REASONING_KEYS"_contains_profile_reasoning_fields)r=  r<  nestedr   s       r   r  r  r  s    eT"" u{{}}  VXX^^%%++--
00044-f55 	44	5r   r  c                 	   |||d}t          ||	          }|t          u rd}n||}|ddlm}  ||          rd}|||d<   ||	p| dk    rt	                      nd}t          | pd                                                                          }|dv pt          |d	          }t          |
          ot          |
          d
k    }|dv }|s%|r#	 ddl
m}  ||          }n# t          $ r Y nw xY wd}|dv rddlm}  ||          dk    }t          | |          s|s|s|s|r$|                    t#          ||                     |rt%                      }g }|D ]}}|                    d          pi                     dd          }|r"||v rt(                              d|| |           Q|r|                    |           |                    |           ~||d<   |	p| dk    rt	                      nd}i }i }i }d}	 ddlm} ddlm}   |t          | pd                                                                                    }!|!|!                    |||          pi }|!                    ||du||          \  }}|pi }|pi }t=          |!          j        | j        up,t?          |          pt?          |          pt?          |          }n3# t          $ r&}"t(                               d| |"           Y d}"~"nd}"~"ww xY w|                    |           tC          |pi           }#|#                    |           |#                    |           |rUtE          |tB                    r@|s>|                    d          du rddi|#d<   n|                    d          pd}$d|$d |#d<   t          | pd                                                                          }%|%dv rDd!|#vrtG                      |#d!<   d"|#vr+	 dd#l$m%}&  |&            }'n# t          $ r d}'Y nw xY w|'r|'|#d"<   |#r|#|d$<   |rtE          |tB                    rt          | pd                                                                          }(|	pd}d}|(dv rddlm}  ||          dk    }|(d%k    s!|stM          |          st          |(|          rtC          |          |d&<   |S )'zLBuild kwargs for .chat.completions.create() with model/provider adjustments.)r   r  r  Nr   rw  rs  r   rB   >   
nvidia-nimbuild-nvidianimnvidianemotronrU  r  >   r   r   r   r   )r  F>   nous-portalr  nousresearchr  r}  r*  r  r   zK_build_call_kwargs: duplicate tool name '%s' removed (provider=%s model=%s)r  r  )ProviderProfile)r   r=   rv  )rv  supports_reasoningr   r=   zA_build_call_kwargs: provider profile projection failed for %s: %sr  r  r  r  T)r  r  r\  
session_id)get_conversation_contextr  r   ro  )'r  r   rh  rx  r  rI   r   r   r4   rn   r  r  rK   r  r  r  r6  r  r   rJ   rX   rY   r5  r  r  r  providers.baser  build_extra_bodybuild_api_kwargs_extrasr  r  rx   r5  r$   r]  agent.portal_tagsr  r  ))r   r   r  rs  rq  r  r  r  rv  r=   r  r!   fixed_temperaturerx  _effective_base_provider_norm_is_nvidia_nim_is_moa_is_gemini_nativer  _nous_on_messagesr  _seen_deduped_t_tnameeffective_baseprofile_bodyprofile_reasoning_extraprofile_top_levelprofile_handles_reasoningr  r  r%  r   merged_extrar  _provider_for_portalr  
sticky_keyprovider_norms)                                            r   r  r    s/     F 5UHEE,,,		&' DDDDDD##E** 	K +}( # 
*2h*>*>$&&&B 	 X^,,2244::<<YY R$_6PQQ 	 t**=To!= + /
 
 ! 	_ 	QQQQQQ$=$=o$N$N!!   !DDD:::::: -e 4 48L L)(ODD
	O 
	O 
	O 	
	O
 !
	O MM4ZuMMMNNN # UU 	  	 BffZ((.B33FB??F &E//-He  
  "		&!!!OOB"w  &.(&:&: """  $&L.0(* %!
222222222222&&s8>r':':'@'@'B'B'H'H'J'JKK"33'!1 4    	  //%5'7t'C+	 0   7#%6 '>&C# 1 7RW5&>? I5lCCI 66MNNI 66GHH &  
 
 
O	
 	
 	
 	
 	
 	
 	
 	

 MM#$$$
(b))L%%%/000	L'..	L *	L
 	**e33)2E(:L%%%))(33?xF48F(K(KL% x~2..4466<<>>FFF%%#4#6#6L |++"FFFFFF5577

 " " "!


" 8-7\* ,+|  AJ'7>> AHN++113399;;!R!CCC:::::: -e 4 48L L[((  )2>BB ) -]NKK )
 +//?*@*@F&'Ms=   C$ $
C10C1CK 
L"LLP P%$P%r  c           
         | t          d|pd d          ddlm}  || |||           	 | j        }|rt	          |d         d          st          d	          n# t
          t          t          f$ rr}t          |           }|t                       |cY d}~S t          |           j        }t          |           dd
         }	t          d|pd d| d|	d          |d}~ww xY wt                       | S )u<  Validate that an LLM response has the expected .choices[0].message shape.

    Fails fast with a clear error instead of letting malformed payloads
    propagate to downstream consumers where they crash with misleading
    AttributeError (e.g. "'str' object has no attribute 'choices'").

    See #7264.

    Also the single accounting chokepoint for auxiliary usage: every
    successful non-streaming aux response passes through here exactly once,
    so token usage is recorded against the ambient session context published
    by the agent loop (``agent.aux_accounting``, issue #23270). Recording is
    best-effort and never affects validation. *provider*/*base_url* are
    optional accounting hints — fallback-path calls omit them and the row
    keeps the model (read from the response itself) with an empty route.
    Nr  r>  z: LLM returned None responser   )record_aux_usager   r=   r  zmissing choices[0].messagex   z&: LLM returned invalid response (type=z): ug   . Expected object with .choices[0].message — check provider adapter or custom endpoint compatibility.)r  agent.aux_accountingr  r  r  rV   r   
IndexError_recover_aux_response_message_complete_relay_auxiliary_callr  r*   rI   )
r  r  r   r=   r  r  r   	recoveredresponse_typeresponse_previews
             r   r  r  d  su   , EEEE
 
 	
 655555XthJJJJ" 	?ggaj)<< 	? !=>>>	?Iz2   1(;;	 *,,,X/x==#.9 9 9"9 9'79 9 9
 

 	 #$$$Os$   .A C&4 C!C&AC!!C&successr   r   c                     t                                           }|dS ddlm} |                    t          |                    d          pd          |            dS )zFClose one auxiliary logical call after acceptance or terminal failure.Nr   r  r  rB   r  )r}  rJ   r  r  complete_logical_callrI   )r   r  r  s      r   r  r    su    %))++G##GKK%%+,, $     r   c                      	 t          d           dS # t          $ r  t                              dd           Y dS w xY w)zDClose a terminally failed call without replacing its original error.failedr  z+Relay auxiliary failure finalization failedTrt   N)r  rK   rX   rY   r   r   r   r  r    si    
&x888888 
 
 
9 	 	
 	
 	
 	
 	
 	

s    &>>c                 `   t          |           }|sdS t          t          |          t          | dd          pd          }	 |g| _        | S # t          $ rT t          t          | dd          t          | dd          t          | d	d
          |gt          | dd                    cY S w xY w)a,  Synthesize chat-completions shape from Responses-style text fields.

    Auxiliary callers consume ``choices[0].message``.  Some compatible
    endpoints return text outside ``choices`` (for example ``output_text`` or
    ``output`` items).  Preserve that response before declaring it malformed.
    N)r  r	  r  )r  r	  r  rB   r   r  chat.completionr  r  r   r  r  r  )_extract_aux_response_textr   ro   r  rK   )r  r  r:  s      r   r  r    s     &h//D t---h>>H&  F

"8 
 
 
xr**(GR008X/@AAH(GT22
 
 
 	
 	
 	

s   	A AB-,B-c                    t          | d          }t          |t                    r(|                                r|                                S t          | d          }t          |t                    sdS g }|D ]}t          |d          }|r|dk    rt          |d          pg D ]v}t          |d          }|dv r`t          |d          }t          |t                    r;|                                r'|                    |                                           wd	                    |                                          S )
Nr  r  rB   r  r  r  >   Nr  r  r  
)_obj_getr$   rI   r   r  r  r  )	r  r  r  rn  r5  r6  r7  	part_typer  s	            r   r  r    sO   8]33K+s## #(9(9(;(; #  """h))Ffd## rE 	/ 	/T6**	 	i//dI..4" 	/ 	/D v..I999f--dC(( /TZZ\\ /LL...	/ 99U!!###r   r<  c                     t          | ||          }||u r+t          | t                    r|                     ||          }|S r   r  )r%   r<  r  r=  s       r   r  r    sE    Cg&&EJsD11W%%Lr   g     @g      @c                     	 | t          |           nd}n# t          t          f$ r d}Y nw xY wt          t          t
          |z            S )u   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.
    Nr=  )rM  r   r  r  !_AUX_STREAM_CEILING_FLOOR_SECONDS_AUX_STREAM_CEILING_MULTIPLIER)r  r  s     r   _aux_stream_total_ceilingr    sh    .?.K%)***QTz"   0-79 9 9s    ,,c                 F    t          | t          t          t          f          S )a  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.)r$   rD  r  r  )rZ   s    r   _client_streams_internallyr  
   s&    
 f    r   c                 x    t          |                                           }d|v rdS d|v od|v pd|v pd|v pd|v S )z@Provider explicitly refused a streamed chat.completions request.stream_optionsTr  r  unsupportedznot alloweddisabled)rI   r   )r   errs     r   _is_streaming_rejected_errorr      si    
c((..

C3ts? 3 	C	C	 	r   c                     t          |pd                                          }|sdS t          |d          rdS 	 ddlm}  |            pi                     di           }|                    d          pg }t          |t          t          f          rY|D ]V}t          |t                     r?|	                                r+|	                                                                |v r dS Wn# t          $ r Y nw xY wdS )	uR  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).
    rB   Fzcopilot.tencent.comTr   r[  r-  stream_only_base_urls)rI   r   r4   rH   r2  rJ   r$   r  r  r   rK   )r   r=   _urlr2  aux_cfgmarkersr  s          r   _provider_requires_streamr  #   s)     x~2$$&&D uT#899 t
111111;==&B++K<<++566<"ge}-- 	 !    fc**  v||~~  &,,..BVBVBXBX\`B`B`44    5s   B/C. ,C. .
C;:C;force_streamr  c                   t                       t                      s|rt          |           r | j        j        j        di |S t          |                    d                    }t          |          }d|d<   ddi|d<   	  | j        j        j        di |}n# t          $ r~}|s<t          |          s-t          |          st          |          st          |          r t                              d|pd|            | j        j        j        di |cY d}~S d}~ww xY wt!          |d	          rt                       |S t#          |t%          |                    d
          pd          |          S )u  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.
    r  Tr  include_usager  zBAuxiliary %s: streamed request failed (%s); retrying non-streamingr>  Nr  r   rB   r   total_ceilingr   )r   r   r  rG  r@  r  r  rJ   r5  rK   r  r  r_  rm  rX   rx   r  _aggregate_chat_streamrI   )rZ   r!   r  r  r  r1  chunksr   s           r   _create_with_progressr  G   s   .  "" 8< 8<VW]<^<^ 8-v{&-77777-fjj.C.CDDMLLM"M('6&=M"#8/(/@@-@@ 8 8 8 	,S11	 c""	 !%%		
 $C((	 
 	!^VS	
 	
 	
 .v{&-7777777777+82 vy!! !c&**W--344M   s   B 
D#%A3DD#D#r  r  r  c                   t          ||          }	 | D ]}|                    |           	 t          | dd          }t          |          r	  |             nR# t          $ r Y nFw xY wnA# t          | dd          }t          |          r	  |             w # t          $ r Y w w xY ww xY w|                                S )u  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`.
    r  r  N)_ChatStreamAccumulatorfeedro   ry   rK   finish)r  r   r  accchunkr3  s         r   r  r     s    !uM
J
J
JC	 	 	EHHUOOOO	 67D11H 	



   	 67D11H 	



   	
 ::<<sA   A+ 
A 
A'&A'+!B)
BB)
B%"B)$B%%B)c                   L    e Zd ZdZddedee         fdZdeddfd	Z	defd
Z
dS )r  a"  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).
    rB   Nr   r  c                     t          j                    | _        || _        g | _        g | _        i | _        d | _        d | _        d| _	        |pd| _
        d S r  )r  r  _started_total_ceilingcontent_partsreasoning_partstool_calls_accr	  r  resp_id
resp_model)r   r   r  s      r   rg   z_ChatStreamAccumulator.__init__   sV    ((+(**,9;!
+2r   r  r   c                 x   t                       | j        =t          j                    | j        z
  | j        k    rt          d| j        dd          t          |dd           p| j        | _        t          |dd           p| j        | _        t          |dd           }|r|| _	        t          |dd           pg }|sd S |d         }t          |d	d           p| j
        | _
        t          |d
d           }|d S t          |dd           }|r| j                            |           t          |dd           pt          |dd           }|r/t          |t                    r| j                            |           t          |dd           pg D ]}t          |dd          pd}	| j                            |	ddg d          }
t          |dd           r
|j        |
d<   t          |dd           }|Lt          |dd           r
|j        |
d<   t          |dd           r |
d                             |j                   d S )Nz(Auxiliary streamed call timed out after z.0fz3s total ceiling (stream still open but over budget)r  r   r  r  r   r	  deltar  r  reasoning_contentr  r  rB   )r  r   r  r  r   r  )r   r  r  r  r  r  ro   r  r  r  r	  r  r  r$   rI   r  r  r`   r  r   r  )r   r  chunk_usager  r:  r   piecereasoning_piecetcidxr  r(  s               r   r  z_ChatStreamAccumulator.feed   s   +!!DM1d6IIID4;NV D D D   udD11AT\!%$77J4?eWd33 	%$DJ%D117R 	F$V_dCCYtGY..=Fy$// 	-%%e,,,E;-- 9u1488 	  	9z/3?? 	9 ''8885,55; 	: 	:B"gq)).QC%00B<< C r4&& "ED	Z..B~2vt,, *"$'CK2{D11 :$++BL999	: 	:r   c                 x   d }| j         r0d t          | j                                                   D             }t          dd                    | j                  |d                    | j                  pd           }t          d|| j        pd          }t          | j        | j	        d|g| j
        	          S )
Nc                     g | ]K\  }}t          |d          dt          |d         d                    |d                                       LS )r  r  r   rB   r  r  r  )r   r  )r   _idxr  s      r   r  z1_ChatStreamAccumulator.finish.<locals>.<listcomp>   st     
 
 
 D#  4y#, ["$''#k*:";";    
 
 
r   r  rB   )r  r  r  r  r   r  r  r  r  )r  sortedr   r   r  r  r  r	  r  r  r  )r   r  r  r:  s       r   r  z_ChatStreamAccumulator.finish   s    
 	
 
 "((;(A(A(C(C!D!D
 
 
J "GGD.//!ggd233;t	
 
 
 !,6
 
 

 |/$H*
 
 
 	
r   r   )r*   r+   r,   r-   rI   r
   rM  rg   r   r  r  r   r   r   r  r     s         	& 	&c 	&x 	& 	& 	& 	&,:# ,:$ ,: ,: ,: ,:\
 
 
 
 
 
 
r   r  c                F  K   t          ||          }	 | 2 3 d{V }|                    |           6 	 t          | dd          pt          | dd          }t          |          r8	  |            }t	          j        |          r| d{V  n# t          $ r Y ntw xY wno# t          | dd          pt          | dd          }t          |          r9	  |            }t	          j        |          r	| d{V  w w # t          $ r Y w w xY ww xY w|                                S )u
  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`.
    r  Nr  aclose)r  r  ro   ry   rE  isawaitablerK   r  )r  r   r  r  r  r3  r   s          r   _aggregate_chat_stream_asyncr.  	!  s      !uM
J
J
JC! 	 	 	 	 	 	 	%HHUOOOO "6 67D11TWVXt5T5TH 	!&v.. ! LLLLLLL   	 67D11TWVXt5T5TH 	!&v.. ! LLLLLLLL!   	 ::<<sJ   B  4B  (&B 
BB 2D&C;9D;
DDDDc                 R  K   t          |                    d                    }t          |          }d|d<   ddi|d<    | j        j        j        di | d{V }t          |d          r|S t          |t          |                    d          pd	          |
           d{V S )u  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).
    r  Tr  r
  r  Nr  r   rB   r  r   )	r  rJ   r5  rG  r@  r  r  r.  rI   )rZ   r!   r  r  r1  r  s         r   _acreate_with_streamr0  %!  s       .fjj.C.CDDMLLM"M('6&=M"#16;*1BBMBBBBBBBBFvy!! -c&**W--344M         r   )r   r   r=   r\   r  rs  rq  r  r  r  rv  r4  r  r  r  r  r  c                   t          |           }||                                 	 t          di d| d|d|d|d|d|d|d	|d
|d|	d|
d|d|d|d|d|d|}|r-|+|}d}t          ||          ||                                 S S |||                                 S S # ||                                 w w xY w)zARun an auxiliary LLM request, applying the configured task limit.Nr  r   r   r=   r\   r  r  rs  rq  r  r  r  rv  r4  r  r  r  r   )r  acquire_call_llm_impl$_release_sync_semaphore_after_streamrelease)r  r   r   r=   r\   r  r  rs  rq  r  r  r  rv  r4  r  r  r  r  r  stream_semaphores                       r   call_llmr7  =!  s   , ,D11I ! 
 
 

X
 %
 X	

 G
 &
 X
 $
 "z
 %
 G
 "z
 .-
 (-
 X
  6!
" *>#
&  	Ti+(I7BRSS   !   !9  !s   AB, B, ,Cr  c              #     K   	 | E d{V  	 t          | dd          }t          |          r
 |             |                                 dS # |                                 w xY w# 	 t          | dd          }t          |          r
 |             |                                 w # |                                 w xY wxY w)zGRelease a permit only after a streaming response is consumed or closed.Nr  )ro   ry   r5  )r  r  r  s      r   r4  r4  t!  s       	 FGT22E I	 FGT22E Is.   A& *A A#&C (*B'C 'B==C c                   :;<= t          |          }t           ||||          \  =}<}}|r|}t                     }|                    |pi             dk    rt	          =dk    r=n||p|<p||p|d|          \  };};:=dk    r4<s2t
                              d=           t	          d|d|          \  };};t          d  d	= d
          |p==nt          =|<|||          \  ;};=pd	                                
                                }|rL|dvrHt           |          \  }}}|
||c;}|p==n(t          d| d|                                 d          ;5<s3t
                              d pd=           t          d|           \  ;};t          d  d	= d
          t           |
          }t          =||           t!          t#          ;d<          pd          : r-t
                              d =pd|pd:r	d:vrd: nd           t%          =|||||	|||:p<           }|rt'          |          |d<   t!          t#          ;dd          pd          }t)          =|          rt+          |d                   |d<   |rQd|d<   |r||d<    dk    r,t-          ;t.                    r ;j        j        j        d\i |S t7          ;|=|           S 	 	 t9          t;          ;|=|:;<= fd!"           =:#          S # t<          $ r}t?          |          s  d$k    r+tA          |          rt
                              d%|            tC                      }|} tE          d&|d&z             D ]}!tG          tH          d'|!d&z
  z  z  d(          }"t
                              d) pd|!||"|            tK          j&        |"           	 t9          t;          ;|=|:;<= fd*"                     c cY d}~S # t<          $ r}#t?          |#          s |#} Y d}#~#d}#~#ww xY w| d}~ww xY w# t<          $ 	r{}$d+|v rtO          |$          rt'          |          }%|%(                    d+d           t
                              d, pd           	 t9          t;          ;|%=|                      cY d}$~$S # t<          $ rS}&t!          |&          }'tS          |&          s'tU          |&          stW          |&          s	d-|'v sd.|'v s |&}$|%}Y d}&~&nd}&~&ww xY wt!          |$          }(d/|(v od0t!          t#          ;dd                    v })|d-|(v sd.|(v stY          |$d-          s|)r|(                    d-d           |(                    d1d           	 t9          t;          ;|=|                      cY d}$~$S # t<          $ r:}&tS          |&          stU          |&          st[          |&          s |&}$Y d}&~&nd}&~&ww xY w=d2k    pt]          :d3          }*t_          |$          r|*rta           dk    |1                    d4          5          }+|+r|+|1                    d4          k    rwt
                              d6 pd|1                    d4          |+           |+|d4<   	 t9          t;          ;|=|                      cY d}$~$S # t<          $ r}&|&}$Y d}&~&nd}&~&ww xY w=d2k    pt]          :d3          },tS          |$          r|,rte                      rtg          =pd2|d<||| dk    7          \  }-}.|-t
                              d8 pd           |.r|.|1                    d4          k    r|.|d4<   	 t9          t;          |-|=|                      cY d}$~$S # t<          $ rI}&tW          |&          s.tS          |&          stU          |&          st[          |&          s |&}$Y d}&~&nd}&~&ww xY wtW          |$          r|,rtg          =pd2|d<||| dk    7          \  }-}.|-ct
                              d9 pd           |.r|.|1                    d4          k    r|.|d4<   t9          t;          |-|=|                      cY d}$~$S ti          =:          }/tW          |$          r|/d:vr|,stk          |/          r|/tm          =          k    rto          =           t
                              d; pd|/           tq          d\i d< d=|/d>|p|d?<d@|dA|dB|dC|d|d+|d-|dD|	dE|dF|dG|d|cY d}$~$S ts          =;|H          }0t!          t#          ;dId          pd          }1|0rtW          |$          stS          |$          st[          |$          ri|$}2t[          |$          r}tS          |$          sn	 t9          t;          ;|=|                      cY d}$~$S # t<          $ r:}&tW          |&          stS          |&          st[          |&          s |&}2Y d}&~&nd}&~&ww xY wtu          |0|2|1J          rt
                              dK pd|0tw          |2          j<                   	 tq          d\i d< d==d>|d?<d@|dA|dB|dC|d|d+|d-|dD|	dE|dF|dG|d|cY d}$~$S # t<          $ rK}3tS          |3          stW          |3          st[          |3          rtu          |0|3           |3}$n Y d}3~3nd}3~3ww xY wtW          |$          pJtS          |$          p;tU          |$          p,t[          |$          pt{          |$          pt}          |$          }4=d:v }5tS          |$          p;tU          |$          p,t[          |$          pt{          |$          pt}          |$          }6|4r|5s|6rtW          |$          rdL}7nktS          |$          r$dM}7t          ts          =;|H          p=           n8t[          |$          rdN}7n&t{          |$          rdO}7nt}          |$          rdP}7ndQ}7t
                              dR pd|7=|$           |7dSv rdn|}8dT\  }}}|5rLt           =pd|7|8U          \  }}}|t           =pd|7V          \  }}}|t          = |7V          \  }}}n2t           =pd|7|8U          \  }}}|t          = |7|8U          \  }}}|^t          ||| ||||	|||W          }9|9|9cY d}$~$S t          = dXV          \  }}}|#t          ||| ||||	|||W          }9|9|9cY d}$~$S t
                              dY pd|7=           tU          |$          r=	 t          ;           n,# t<          $ r t
          F                    dZd[           Y nw xY w d}$~$ww xY w)]u  Centralized synchronous LLM call.

    Resolves provider + model (from task config, explicit args, or auto-detect),
    handles auth, request formatting, and model-specific arg adjustments.

    Args:
        task: Auxiliary task name ("compression", "vision", "web_extract",
              "session_search", "skills_hub", "mcp", "title_generation").
              Reads provider:model from config/env. Ignored if provider is set.
        provider: Explicit provider override.
        model: Explicit model override.
        api_mode: Explicit API mode override (e.g. "codex_responses",
              "anthropic_messages"). Takes precedence over task config.
        messages: Chat messages list.
        temperature: Sampling temperature (None = provider default).
        max_tokens: Max output tokens (handles max_tokens vs max_completion_tokens).
        tools: Tool definitions (for function calling).
        timeout: Request timeout in seconds (None = read from auxiliary.{task}.timeout config).
        extra_body: Additional request body fields.
        reasoning_config: Optional Hermes reasoning config for direct model calls
              such as MoA reference/aggregator slots.
        extra_headers: Additional per-request HTTP headers. These override
            client-level defaults for providers that gate capabilities on
            request attribution (for example Copilot's ``x-initiator``).
        stream: When True, return the raw SDK streaming iterator instead of a
            validated complete response. The caller is responsible for consuming
            chunks (and for any fallback). Used by the MoA aggregator so its
            output can stream to the user.
        stream_options: Passed through to the request when stream is True
            (e.g. {"include_usage": True}).

    Returns:
        Response object with .choices[0].message.content, OR — when stream=True —
        the raw streaming iterator from client.chat.completions.create().

    Raises:
        RuntimeError: If no provider is configured.
    rC  r   Fr   r   r=   r\   rO   r  NDVision provider %s unavailable, falling back to auto vision backendsr   r   rO   r  $No LLM provider configured for task=
 provider=. Run: hermes setupr  rB   >   r   r   rB  
Provider ':' is set in config.yaml but no API key was found. Set the U_API_KEY environment variable, or switch to a different provider with `hermes model`.BAuxiliary %s: provider %s unavailable, trying auto-detection chainr>  r  r=   zAuxiliary %s: using %s (%s)%sr  rB  z at r  r4  r  Tr  r  r  r  c           	      J    t          | t          p                    S Nr  r  r  r  
_base_inforZ   r  r  r  s    r   r{  z _call_llm_impl.<locals>.<lambda>d"  s8    +@%>-z/N=N& &	, , , r   r  r  rS  zfAuxiliary compression: timeout on the critical path; skipping same-provider retry and falling back: %sr   g       @g       @zoAuxiliary %s: transient transport error (attempt %d/%d); retrying same provider after %.1fs before fallback: %sc           	      J    t          | t          p                    S rE  rF  rG  s    r   r{  z _call_llm_impl.<locals>.<lambda>"  s9    3H & ' $-F$5$.$C2C." ."	4 4 4 r   rs  zEAuxiliary %s: provider rejected temperature; retrying once without itrq  r  1210ru  rr  r  r  r   rC  rO  z[Auxiliary %s: model %r no longer in Nous catalog; retrying with refreshed recommendation %r)r-  r   rO   r=   r\   r  r  r  zSAuxiliary %s: refreshed Nous runtime credentials after paid account check, retryingzDAuxiliary %s: refreshed Nous runtime credentials after 401, retrying>   NrB   r   zAAuxiliary %s: refreshed %s credentials after auth error, retryingr  r  r  r  r  r  r  r  r  r  r  rv  r  r\   r  z@Auxiliary %s: recovered %s via credential-pool rotation after %s
auth errorr-  rj  model incompatible with routeinvalid provider responseconnection errorz,Auxiliary %s: %s on %s (%s), trying fallbackrL  r-  r7  r/  r@  rh  r  r  rs  rq  r  r  r  rv  stale fallback credentialzoAuxiliary %s: %s on %s and all fallbacks exhausted (fallback_chain + main agent model). Raising original error.z7Auxiliary: cache eviction after connection error failedrt   r   )Gr  r  r  r6  r  rX   rY   r  r  r   r   rj  upperr?  r}  r  rI   ro   r  r5  r  r  r$   rD  rG  r@  r  r  r  r  rK   r  rr  r  ranger  _TRANSIENT_RETRY_BACKOFF_BASEr  sleepr  r  r_  r}  r  r  rm  r4   r  rS  rJ   rf  r4  r  r  r   r  r  r  r  r  r*   r  r  r<  rf  ru  r>  rQ  r*  r  rx   )>r  r   r   r=   r\   r  r  rs  rq  r  r  r  rv  r4  r  r  r  r  r  r  r  effective_providerr  	_explicitr  r  r  r  r!   _client_basetransient_err_max_transient_retries_last_transient_attempt_backoffretry_transient	first_errr  r)  retry_err_strerr_str_is_zai_param_error_heal_is_noushealed_modelclient_is_nousrefreshed_clientrefreshed_modelauth_refresh_providerpool_provider_client_api_keyrecovery_err
retry2_errshould_fallbackis_autois_capacity_errorr/  _chain_failed_modelfb_resprH  rZ   r  r  s>   `                                                         @@@@r   r3  r3  !  sn   | +<88L`|hxa2 a2]~'8:JL] %$/55
 0b111x2P*;v*E*E&&8 )E&2($/%3
 3
 3
/FK >/699BS9NNV!   7U$ )	7 7 73 >%t % %GX % % %   /C2C0&$&%
 
 
 > +0b7799??AAI Y.NNN0_)1 1-	8X (*3X'FK(0(E4E%%&\Y \ \.7oo.?.?\ \ \   ~&7~` NF,=? ? ?&8lae&f&f&f#>%t % %GX % % %& & & /tW==   WVZ1BCCIrJJJ c3,68Py,6a<z;Y;Y(J(((_a	c 	c 	c  ;J.;O)00t= = =F  6"&}"5"5 wvz266<"==L$%6EE U@
ASTTz  
x 	6'5F#$###
6;O(P(P# 26;*1;;F;;;!&&	
 
 
 	
z"F	")&..          *Z!A A A A"  4	" 4	" 4	"0??  }$$):=)I)I$H!  
 %;%=%="+O!!%;a%?@@ 6 6<ST@UVX[\\MNFH.Dh#	   
8$$$61.""%6%6$ $ $ $ $ $ $ $   !         " ! 6 6 68II &5OOOOOO6
 "!i4	"j  b b bF""'H'S'S"<<L]D111KKW  &-*$!2!2	  
          & & & #I &i00+I66 &i00 $}44.-??%	%&" i.. g Cc'&*b"A"ABBB 	 !G##&'11.y,GG 2" 2 JJ|T***JJ.555&-*!2!2	  
          & & & *)44 8LY8W8W [opy[z[z %						& ' S$Z1QRR 	 %Y// 	*M 	*:(vzz'7J7JL L LL *

70C0C C C@NFFJJw$7$7  
 #/w	*1.""%6%6	  
  ! ! ! ! ! ! ! ! ! * * * )IIIIII*
 ' S$Z1QRR 	
 i((&	*&	* ;<<&	*
 1O0:F! *(*)8+	1 	1 	1-o  +iNF   # 6&**W:M:M'M'M&5F7O*1.,"%6%6	  
  ! ! ! ! ! ! ! ! ! * * *&y11,Y77 0	:: 0	::	  )IIIIII* )$$ 	 	0N0:F! *(*)8+	1 	1 	1-o  +b NF, , ," 6&**W:M:M'M'M&5F7O-*(!2!2	  
         !Az!+ !+9%% 	)1CCC& D,-BCC (,CDU,V,VVV **;<<<WNF$9   1   &;&; $2#@[ '8&7	
 &6%5 '8&7 ". !, &X !,  *z  % '8&7 *>)= &6%5  #0-!      ( 33Df[ghhh
 gfi<<BCC 4	nY77 4	;LY;W;W 4	[opy[z[z 4	$L $I.. -7H7S7S --1.""%6%6	  
  ! ! ! ! ! ! ! ! ! - - -*955 9J99U9U YmnwYxYx #,LLLLLL- &m\Rabbb #VNFM43E3E3N  4   !T*;*; (6~ +<*;	
 *:)9 +<*; &2\ %0K "* %0K $.: $e +<*; .B-A *:)9  '4m!      $ !    **55 
9S9S 3J??.}jIII$.		 "				N 9%% 9 ++9#I..9 $I..9 ,I66	9
 .i88 	 $'99 i(( 9#I..9#I..9 ,I669 .i88 	  Y	 Y	+< Y	i(( ,%"9-- ,(
 )./@&Wcdddyhy    &i00 ,%-i88 ,8/	:: ,4+KKF0A9N N N "AAA{   -=)Ix :0N+5vf!416 16 16-	8X $4L/96&5J 5J 5J1Ix$4I)45@ 5@ 5@1Ix 1O+5vf!416 16 16-	8X $4R)4%85: 5: 5:1Ix $7x +
3D)=%57 7 7 &"NNNNNN 1F%t4O1Q 1Q 1Q-	8X(;!8X!H$/J#7H-A)9; ; ;G *& NNO(9    	** 	,,-f5555 , , ,V&*  , , , , ,, 	Ebs  :+L& &Q1B9Q+(PQQQ 
Q%P<7Q<QQQQ wAw/ Sw
T2A	T-(w-T22A>w1 Ww
X!0XwXB$w  [& w&
[<0[72w7[<<Bw ^:4w:
`?`w`Bw w&B/wwBw h?w
i	0i?wi		Aw9k	w
l$Alwl$$G>w"w(5ww#.wv"!w"&ww
wwwc                    ddl }| j        d         j        }|j        pd                                }|r7 |j        dd||j        |j        z                                            }|r|S g }dD ]i}t          ||d          }|rTt          |t                    r?|                                r+||vr'|                    |                                           jt          |dd          }|rt          |t                    r|D ]}	t          |	t                    r|	                    d          p)|	                    d	          p|	                    d
          }
|
rO|
|vrK|                    t          |
t                    r|
                                nt          |
                     |rd                    |          S dS )u  Extract content from an LLM response, falling back to reasoning fields.

    Mirrors the main agent loop's behavior when a reasoning model (DeepSeek-R1,
    Qwen-QwQ, etc.) returns ``content=None`` with reasoning in structured fields.

    Resolution order:
      1. ``message.content`` — strip inline think/reasoning blocks, check for
         remaining non-whitespace text.
      2. ``message.reasoning`` / ``message.reasoning_content`` — direct
         structured reasoning fields (DeepSeek, Moonshot, NovitaAI, etc.).
      3. ``message.reasoning_details`` — OpenRouter unified array format.

    Returns the best available text, or ``""`` if nothing found.
    r   NrB   zz<(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)>.*?</(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)>)flags)r  r!  reasoning_detailsr  r  r  z

)r  r  r  r  r   subDOTALL
IGNORECASEro   r$   rI   r  r  r5  rJ   r  )r  r  r  r  cleanedr  r  r  detailsdetailr  s              r   extract_content_or_reasoningr}  I$  s    III

1

%C{ b''))G 	"&L ry2=8	
 
 

 %'' 	  	N "$O3 0 0c5$'' 	0:c3'' 	0CIIKK 	0C<V<V""399;;///c.55G 	j:gt,, 	j 	j 	jF&$'' jJJy)) *zz),,*zz&)) 
  jwo==#**jRU>V>V+h7==???\_`g\h\hiii ,{{?+++2r   )r   r   r=   r\   r  rs  rq  r  r  r  rv  c                
  K   t          |           }||                                 d{V  	 t          | |||||||||	|
||           d{V 	 ||                                 S S # ||                                 w w xY w)zERun an asynchronous auxiliary LLM request under the configured limit.N)r  r   r   r=   r\   r  r  rs  rq  r  r  r  rv  )r  r2  _async_call_llm_implr5  )r  r   r   r=   r\   r  r  rs  rq  r  r  r  rv  r  s                 r   async_call_llmr  $  s      $ -T22I!!!!!!!!! )%#!!-
 
 
 
 
 
 
 
 
 	
    !9  !s   !A) )Bc                ~   67K   t          |          }t           ||||          \  }}}}}t                     }|                    |pi             dk    rt	          |dk    r|n||p||p||p|d|          \  }7}7:|dk    r4|s2t
                              d|           t	          d|d|          \  }7}7t          d  d	| d
          |p|}nt          ||d||||          \  7}7|pd	                                
                                }|rb|dvr^t           |          \  }}}| t          ||pd dk              \  7}|p|}n(t          d| d|                                 d          76|s4t
                              d pd|           t          dd|           \  7}7t          d  d	| d
          t           |
          }t!          |||           t#          t%          7dd          pd          }t'          ||||||	||||p|           }t)          ||          rt+          |d                   |d<   	 t-          ||p|          o"t/          7t0          t2          t4          f           6dt6          t"          t8          f         dt8          f67 fd}	 t;          t=          7||||           d{V  ||          S # t>          $ r}tA          |          s  dk    r+tC          |          rt
                              d|            t
                              d pd|           t;          t=          7||||           d{V            cY d}~S d}~ww xY w# t>          $ 	r}d |v rtE          |          rtG          |          }|$                    d d           t
                              d! pd           	 t;          t=          7|||"           d{V            cY d}~S # t>          $ rS} t#          |           }!tK          |           s'tM          |           stO          |           s	d#|!v sd$|!v s | }|}Y d} ~ nd} ~ ww xY wt#          |          }"d%|"v od&t#          t%          7dd                    v }#|d#|"v sd$|"v stQ          |d#          s|#r|$                    d#d           |$                    d'd           	 t;          t=          7|||"           d{V            cY d}~S # t>          $ r:} tK          |           stM          |           stS          |           s | }Y d} ~ nd} ~ ww xY w|d(k    ptU          |d)          }$tW          |          r|$rtY           dk    |-                    d*          +          }%|%r|%|-                    d*          k    r}t
                              d, pd|-                    d*          |%           |%|d*<   	 t;          t=          7|||"           d{V            cY d}~S # t>          $ r} | }Y d} ~ nd} ~ ww xY w|d(k    ptU          |d)          }&tK          |          r|&rt]                      rt_          |pd(|d||| dk    -          \  }'}(|'t
                              d. pd           |(r|(|-                    d*          k    r|(|d*<   	 t;          t=          |'|||"           d{V            cY d}~S # t>          $ rI} tO          |           s.tK          |           stM          |           stS          |           s | }Y d} ~ nd} ~ ww xY wtO          |          r|&rt_          |pd(|d||| dk    -          \  }'}(|'it
                              d/ pd           |(r|(|-                    d*          k    r|(|d*<   t;          t=          |'|||"           d{V            cY d}~S ta          ||          })tO          |          r|)d0vr{|&sytc          |)          rj|)te          |          k    rtg          |           t
                              d1 pd|)           ti           |)|p|||||||||	|||2           d{V cY d}~S tk          |7|3          }*t#          t%          7d4d          pd          }+|*rtO          |          stK          |          stS          |          rX|},tS          |          rtK          |          st	 t;          t=          7|||"           d{V            cY d}~S # t>          $ r:} tO          |           stK          |           stS          |           s | },Y d} ~ nd} ~ ww xY wtm          |*|,|+5          rt
                              d6 pd|*to          |,          j8                   	 ti           ||||||||||	|||2           d{V cY d}~S # t>          $ rK}-tK          |-          stO          |-          stS          |-          rtm          |*|-           |-}n Y d}-~-nd}-~-ww xY wtO          |          pJtK          |          p;tM          |          p,tS          |          pts          |          ptu          |          }.|d0v }/tK          |          p;tM          |          p,tS          |          pts          |          ptu          |          }0|.r|/s|0rtO          |          rd7}1nitK          |          r"d8}1tw          tk          |7          p|           n8tS          |          rd9}1n&ts          |          rd:}1ntu          |          rd;}1nd<}1t
                              d= pd|1||           |1d>v rdn|}2d?\  }}}|/rLty           |pd|1|2@          \  }}}|t{           |pd|1A          \  }}}|t}          | |1A          \  }}}n2ty           |pd|1|2@          \  }}}|t          | |1|2@          \  }}}|t          ||pd dk              \  }3}4t          |3|4p|| ||||	|||B           d{V }5|5|5cY d}~S t}          | dCA          \  }}}|Ft          ||pd dk              \  }3}4t          |3|4p|| ||||	|||B           d{V }5|5|5cY d}~S t
                              dD pd|1|           tM          |          r=	 t          7           n,# t>          $ r t
          B                    dEdF           Y nw xY w d}~ww xY w)GzqCentralized asynchronous LLM call.

    Same as call_llm() but async. See call_llm() for full documentation.
    rC  r   Tr:  Nr;  r<  r=  r>  r?  )rO   r=   r\   r  r  rB   >   r   r   rB  r  r@  rA  rB  rC  r>  )rO   r  r  r=   r  r  _kwargsr   c                 t   K   rt          |            d {V S  j        j        j        di |  d {V S r  )r0  rG  r@  r  )r  _force_stream_asyncrZ   r  s    r   _acreatez&_async_call_llm_impl.<locals>._acreate*%  sd      " I1&'4HHHHHHHHH707BB'BBBBBBBBBr   r  r  rS  znAuxiliary compression (async): timeout on the critical path; skipping same-provider retry and falling back: %szgAuxiliary %s (async): transient transport error; retrying once on the same provider before fallback: %srs  zMAuxiliary %s (async): provider rejected temperature; retrying once without itr  rq  r  rJ  ru  rr  r  r  r   rK  zcAuxiliary %s (async): model %r no longer in Nous catalog; retrying with refreshed recommendation %r)r-  r   rO   r=   r\   r  r  z[Auxiliary %s (async): refreshed Nous runtime credentials after paid account check, retryingzLAuxiliary %s (async): refreshed Nous runtime credentials after 401, retrying>   NrB   r   zIAuxiliary %s (async): refreshed %s credentials after auth error, retrying)r  r  r  r  r  r  r  r  rs  rq  r  r  r  rv  r  r\   r  zHAuxiliary %s (async): recovered %s via credential-pool rotation after %srL  r-  rj  rM  rN  rO  z4Auxiliary %s (async): %s on %s (%s), trying fallbackrP  r7  rQ  rh  rR  rS  zwAuxiliary %s (async): %s on %s and all fallbacks exhausted (fallback_chain + main agent model). Raising original error.z?Auxiliary (async): cache eviction after connection error failedrt   )Cr  r  r  r6  r  rX   rY   r  r  r   r   rj  r  rT  r?  r}  r  rI   ro   r  r  r  r  r$   r\  r  r  r   r   r  r  rK   r  rr  r  r5  r  r_  r}  r  r  rm  r4   r  rS  rJ   rf  r4  r  r  r   r  r  r  r  r  r*   r  r  r<  rf  ru  r>  rQ  r,  r  rx   )8r  r   r   r=   r\   r  r  rs  rq  r  r  r  rv  r  r  r  r  r  r  rX  r  rY  r  r  r  r  rZ  r!   r  r[  ra  r  r)  rb  rc  rd  re  rf  rg  rh  ri  rj  rk  rl  rm  rn  ro  rp  rq  r/  rr  async_fbasync_fb_modelrs  r  rZ   s8   `                                                     @@r   r  r  $  sh     , +<88L`|hxa2 a2]~'8:JL]/55
 0b111x2P*;v*E*E&&8 )E&2($/%3
 3
 3
/FK >/699BS9NNV!   7U$)	7 7 73 >%t % %GX % % %   /C2C0&$&%
 
 
 >*0b7799??AAI Y.NNN0_)1 1-	8X (*:!8>rdh>N+ + +'FK )1(E4E%%&\Y \ \.7oo.?.?\ \ \  
 ~&7~` NF,=? ? ?&8D_krv&w&w&w#>%t % %GX % % %& & & /tW==   wvz266<"==L;J.;O)2!2? ? ?F %%6EE U@
ASTTzi
 &!<#D3D   v)-+(   	 		CDcN 	Cs 	C 	C 	C 	C 	C 	C 	C 	C
%	)-..#         *\	C 	C 	C 	C  	 	 	0??  }$$):=)I)I$N!  
 KK@  
 *-..#                %	6  o o oF""'H'S'S"<<L]D111KK_  &-1$!2!2	        
          & & & #I%i00+I66 &i00 $}44.-??%	%& i.. g Cc'&*b"A"ABBB 	 !G##&'11.y,GG 2" 2 JJ|T***JJ.555&-1!2!2	        
          & & & *)44 8LY8W8W [opy[z[z %						& ' U$\3STT 	 %Y// 	*M 	*:(vzz'7J7JL L LL *

70C0C C C@NFFJJw$7$7  
 #/w	*15""%6%6	        
  ! ! ! ! ! ! ! ! ! * * * )IIIIII*
 ' U$\3STT 	
 i((%	*%	* ;<<%	*
 1O0:F!*(*8+1 1 1-o  +qNF   # 6&**W:M:M'M'M&5F7O*15,"%6%6	        
  ! ! ! ! ! ! ! ! ! * * *&y11,Y77 0	:: 0	::	  )IIIIII* )$$ 	 	0N0:F!*(*8+1 1 1-o  +j NF, , ," 6&**W:M:M'M'M&5F7O-1(!2!2	        
         !A|!- !-9%% 	)1CCC& D,-BCC (,CDU,V,VVV **;<<<_NF$9   8&;#1#@[&7%5&7 +% +)&7)=%5              $ 33Df[ghhhgfi<<BCC -	nY77 -	;LY;W;W -	[opy[z[z -	$L $I.. -7H7S7S --15""%6%6	        
  ! ! ! ! ! ! ! ! ! - - -*955 9J99U9U YmnwYxYx #,LLLLLL- &m\Rabbb ^NFM43E3E3N  !;!*;'5*;)9*;$/!)$/#-#*;-A)9" " "              !   )*55 
9S9S 3J??.}jIII$.		 "					 9%% 9 ++9#I..9 $I..9 ,I66	9
 .i88 	 $'99i(( 9#I..9#I..9 ,I669 .i88 	  Y	 Y	+< Y	i(( ,%"9-- ,((./@&II^M^    &i00 ,%-i88 ,8/	:: ,4+KKN0A9N N N "AAA{   -=)Ix :0N+5vf!416 16 16-	8X $4L/96&5J 5J 5J1Ix$4I)45@ 5@ 5@1Ix 1O+5vf!416 16 16-	8X $4R)4%85: 5: 5:1Ix $+;x~2$(:J, , ,(. !?n8( +
3D)=%5!7 !7 !7 7 7 7 7 7 7 &"NNNNNN 1F%t4O1Q 1Q 1Q-	8X(/?!8>rdh>N0 0 0,Hn %C ."<Hh!H$/J#7H-A)9%; %; %; ; ; ; ; ; ;G *&NNO(9    	** 	,,-f5555 , , ,^&*  , , , , ,, 	_os  AM> 5*K   
M;*BM60M;1M> 6M;;M> >t<	At7&Pt<
Q(A	Q#t7#Q((A>t7'&Tt<
U0Ut7UB$t7<&X("t<(
X>2X94t79X>>Bt7&\;t<
]?]
t7]Bt7,t<2Bt7
t<Bt7&e :t< 
f
0e?:t7?fAt7"g3-t<3
i=Ai>t7iHt7't<-At7t<.t7:t
	t7
&t30t72t33t77t<)TNNri   r   )rB   r  r  )Nr-  )Nr?  Nr  )r?  N)rB   r?  r  )	NFFNNNNFN)NFNNNNFN)NNNNN)NNNrq  NNNN(e  r-   
contextlibr   r  r  r  rE  rk  loggingrH  r  r   r  r  pathlibr   typesr   typingr   r   r   r   r	   r
   r   r   r  r   r   r   r   r   r   r  r  r   r   agent.credential_poolr/   r  r0   r1   rH   r2   r  r3   r  r4   r5   r6   r7   r8   	getLoggerr*   rX   r   r9   r:   r;   r<   rI   rM   rW   rn   r[   ra   localrp   r   rc   rq   r|   contextmanagerr   r   r   r   r   r   r   r   r5  r   r   r   r{  r   r   r  r   r  r  r  r  r	  r  r  rM  r  r  r  r  r!  r&  	frozensetr'  rG  rJ  r>  rR  rV  rW  
hermes_clirX  _HERMES_VERSION_AI_GATEWAY_HEADERSr  rZ  r]  r^  NOUS_EXTRA_BODYr_  r1  rJ  r  r#  r  r  rr  r{  r  r  r  r  r  r  rL  r  r  r  r<  rD  rJ  rY  r\  rb  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r'  r(  r+  r3  r6  r@  rB  rN  rS  rX  r   r]  ra  rl  rn  rs  rt  ru  rv  rw  rx  ry  
ContextVarr{  r}  r  r  r  r  r  r  r  r  r   r  r  rU  Tokenr  r  r  r  r  r  r  r  r
  r  r  r  r  _AUTO_PROVIDER_LABELSr  r*  r  r.  r7  r0  r1  r3  r5  r<  r  rB  rD  rK   r_  rf  rm  rr  r}  r  r  rV  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r*  r,  r>  rQ  rT  rW  rf  rj  r^  r]  ru  rw  r  r  r  rL  r  r  r  r  r  r  r  r  r  r  r  r  r  rU  r  r  r&  r,  r4  r;  rC  r  rH  rL  rN  rQ  rS  r  r`  r  _DEFAULT_AUX_TIMEOUTr|  r  rz  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r.  r0  r7  r4  r3  r}  r  r  r   r   r   <module>r     sq<  , , ,\                  				 				             ! ! ! ! ! ! X X X X X X X X X X X X X X X X X X X X 7 7 7 7 7 7 7 7 7 7  $( 8D> ( ( ($    , , , , , , , ,& 
 + + + + + + Q Q Q Q Q Q Q Q - - - - - - 0 0 0 0 0 0 D  D  D  D  D  D  D  D  D  D  D  D  D  D		8	$	$ &)SUU s * * *'*suu  , , , ),  # - - -&)cee  + + +(3- C    8 !&  $# $# $#sm$# $# 
#s(^	$# $# $# $#L@c @S @C @C @ @ @ @4 ,IO-- K K K K KM K K K E$ E E E E    & C CC C C C:8HRW,=#>    "c'1B t    0 0 0 0 0 0 0 0R  	!!@ @ @ @<d < < < < " " "B%S#X',-B%cNB% 	B% B% B% B%J# 3 4    3      hX  E	
 E E 
5 E E U M   #   !" \#$ '&!"'%=   D9hsm 9 9 9 9 92 "688 & # # #6(3- 6D 6 6 6 6,hsm , , , , ,$ +/ ' %) ! HSM Xc] VZ    :) )8C= )HSM )T ) ) ) )" # C=sm     0 ## )-	# # #C=#sm# "&	#
 e_# # # #LFS FS F F F F( !*-1,)$))%9 9 %tCH~   , 0U d38n T T T + + c3h   s x}    H (1y2 ( ( 9    <7   Y999:: & & & & & &R1 1t 1t 1 1 1 1n } 
sTz d     6 5 5 5 5 5 <222   D C C C C C)$ ) ) ) ) #"$$   4    . 'D 9 !/##k1 > $C $DcN $ $ $ $N# #    < tXc]/B)C     s x}    ." " " " " ". .# . .c . . . .6 (i)   
	s 	t 	 	 	 	3    +# +# + + + +:`
 `
 `
 `
 `
 `
 `
 `
F# # # # # # # #" " " " " " " "$D D D D D D D D# # # # # # # #
6 6 6 6 6 6 6 6&e
 e
 e
 e
 e
 e
 e
 e
P# # # # # # # #
       $D D D D D D D D# # # # # # # #
	6 	6 	6 	6 	6 	6 	6 	6,
 ,
 ,
 ,
 ,
 ,
 ,
 ,
^# # # # # # # #
       D D D D D D D D# # # # # # # #
. . . . . . . .# $    D #Q QQQ Q 	Q
 smQ 	Q Q Q Qh#$ # # # #LD S    (H H H H H
 =B 0 0 0T 0huUXZ]U]F_ 0 0 0 0f 8=    %PSUXPX/AZ    <4HU38_$= 4 4 4 4n((3- ( ( ( (Vo5&)98C=)H#I o o o oj  3   @(3- @D @ @ @ @
(%c	"2 ( ( ( ($     #A #Ac #A #AhW]N^`hil`mNmHn #A #A #A #AL
4# 
4 
4 
4 
4Q Qd QuXf-=x}-L'M Q Q Q Qh&&"*3-&c]& & & &R#    <S    2C    :S    *## #5#PXY\P]A];^ # # # #L#    $ #  #        . !        S            s           !  ! ! !K3TBBB {-htCH~.FG   
 K14@@@ /c3h0HI   
  2  2
>Dj
>:
> Dj
> 
	
> 
> 
> 
>    Dj Dj 3T#s(^#$t+	   2  59  cN Dj	
 Dj d38n%s*+d2 	   @  59  cN Dj	
 Dj d38n%s*+d2 	   :    cN Dj	
 Dj 	   , 2J uS#X I I I*IN,, 3htCH~6 3 3 3 3.	s 	s 	 	 	 	  !. . ... 	.
 . . . . . . . .b	k/ 	D 	 	 	 	 +htCH~&> + + + +A A A A /8x}hsmXc]'R!S /8 /8 /8 /8d#    
   :     $0#eHSM8C=$@A 0# 0# 0# 0#f;s ;uXc]HSM5Q/R ; ; ; ;@&;s &;uXc]HSM-I'J &; &; &; &;V  &*'+"o o oC=o smo  }	o
 smo 8C=(3-'(o o o od<c <cS <cE(3-RU:V4W <c <c <c <c@ $*!*	   ] 36MM  (4S>*B  tCQTH~        FT%[    R ! )+ d3:& + + +-/ $sEz* / / / ""    	2S 	2S 	2 	2 	2 	2 s % D    &# $     
 
s 
(3- 
4 
 
 
 
 % % % %'9 ' ' ' ' 'T	D 	 	 	 	"i "D " " " "J+9 + + + + +*#i #D # # # #LNy NT N N N N&   !$ * * * * *,	 d    $ 3 4    D?9 ? ? ? ? ?%9 % % % % %P3i 3D 3 3 3 3l	 d    &)C )D ) ) ) ) #  $        L .2& & && 4S>*& 		& & & &*Y 4S>     .2( ((( 4S>*( c]	( ( ( (V TV . . .S .y .S .Z^ . . . .D /3#F F F
3-F F SM	F
  }F smF  }F 4S>*F #F F %F F D>F F F  tn!F" DcN+#F$ 	%F F F Fr /3!D D D
3-D D SM	D
  }D smD  }D #D D %D D D>D D D tnD  DcN+!D" 	#D D D DNXC XD X X X Xv} 	   26 6 6$sTWx.AY 6 6 6 6*(3- 3 8E?    .I I I I I I    :   EEE smE C=	E
 E E E E0OS>OO smO 	O O O O O
3-OO smO 	O
 O O O O.D> &	
 4:   &zzsmz z
 3-z z %z z D>z z z tnz c]z z z zzddsmd d
 3-d d %d d D>d d d tnd c]d d d dR !0 00
0 0 8C=(3-,-	0 0 0 0j "&	S7 S7S7
S7 S7 3-	S7
 8C=(3-,-S7 S7 S7 S7Rx} #    0 	' ''' ' 	'
 c]' ' ' 'Z "&	t t
tt t 3-	t
 8C=(3-,-t t t tn
3- 8C=(3-,-   ,	(4S> 	(hsm 	( 	( 	( 	("4S> "eHSM8TW=<X6Y " " " "8 P P
3-PP P 8C=(3-,-	P P P Pj  "!	 C= sm c]	
 c]   ( .2r r4S>*r
3-r 8FXc]*+r r r r@K. K. K. K. K. K. K.\	(3- 	3 	8TW= 	 	 	 	 ! -1V VVV V 	V
 V V V 4S>*V V 3-V 8C=(3-'(V V V Vx  .2  
 4S>* 8FXc]*+	   2`d   # XdSVX[S[nE]    & # hsm     >-# -3 - - - -  & &&C=& 8C=(3-'(& & & &RCs Ct C C C CtCy    4 #o* #!-1o* o* o*smo*C=o* sm	o*
 c]o* o* 4S>*o* 8C=(3-#67o* o* o* o*d;$ ; ; ; ; FJ ! ! !c !Xc] !d ! ! ! !^ %'tE5L! & & &#Y^%%  $ $ $ $ $ $ $ $, C C     #!"-1!G !G !G!G !G sm	!G
 c]!G sm!G 4S>*!G !G 3-!G C=!G !G !G !G !GH lp G G GE G3 GxPS} Geh Gtx G G G G #!"-1* * ** C=* 	*
 sm* c]* sm* 4S>** * 8C=(3-'(* * * *Z   BS T    (
 
 
 
 
 
   # # # #&# $    : :Xc] :W[ : : : :## #hsm #Xc] #W_`cWd # # # # -1u* u*u*u* u* 	u*
 u* u* 4S>*u* u* 3-u* 8C=(3-'(u* u* u* u*J )- 4S>    "!nA nA
nAnA nA sm	nA
 c]nA 3x}hsmXc]JKnA nA nA nAb   &+ ")S )T#s(^ ) ) ) )X 3G  C % 5     x 5    "+s +tCH~ + + + +n KM d3c9+E&E FFG L L L@B tE#s(OU38_<= B B B	  (HSM (hsm ( ( ( ( hsm A[8\    x}    (& & & & (i(R(R(RSS 	%C 	%3 	%4 	% 	% 	% 	%Q$ Q4 Q Q Q Qh   
c 
d 
 
 
 
" $( $ !%'+"b bbb b %	b
 b D>b b b tnb smb 3-b 
b b b bN ""	0 00
3-0 sm0 sm	0
 	0 0 0 0f 6? 
 
 
s 
4 
 
 
 

 
 
 

C 
HSM 
 
 
 
8$ $ $ $ $ $. # C #     , %* !!$ 9% 9U 9 9 9 9	s 	t 	 	 	 	
i 
D 
 
 
 
! !x} ! ! ! ! !N ?
 ? ? ??cN? 3-?
 ? 	? ? ? ?J %)	    E?	
 	   :`
 `
 `
 `
 `
 `
 `
 `
L %)	    E?	
 	   >  cN 3- 		   0 3  -1#''+.2%3  3  3 
3  3  	3 
 3  3  4S>*3  3  %3  3  3  3  3  tn3  DcN+3   !3 " #3 $ %3 & 	'3  3  3  3 l  %6         C -1#''+.2%C C C
C C 	C
 C C 4S>*C C %C C C C C tnC DcN+C  !C" #C$ %C& 	'C C C CL5c 5 5 5 5p &  -1#''+&  &  & 
&  &  	& 
 &  &  4S>*&  &  %&  &  &  &  &  tn&  	&  &  &  & T Y -1#''+Y Y Y
Y Y 	Y
 Y Y 4S>*Y Y %Y Y Y Y Y tnY 	Y Y Y Y Y Yr   