
    ۘj                    Z    d Z ddlmZ ddlZddlZddlmZ ddZddd
ZddZ	ddddZ
dS )z0Shared helpers for direct xAI HTTP integrations.    )annotationsN)Dictreturnboolc                    t           j                            dd                                          rdS 	 ddlm}   |             dz  }|                                sdS t          j        |	                                          }t          |t                    r|                    d          nd	}t          |t                    r|                    d
          nd	}t          |t                    r|                    d          nd	}t          |t                    r|                    d          nd	}t          t          |pd                                                    S # t          $ r Y dS w xY w)u  Cheap probe — return True when xAI credentials are *likely* usable.

    Deliberately avoids :func:`resolve_xai_http_credentials` so callers in
    hot-paint paths (``hermes tools`` repaint, tool-registration scans,
    ``WebSearchProvider.is_available()``) don't incur disk locks or — in
    the OAuth path — a network token refresh. The ABC contract on
    :meth:`agent.web_search_provider.WebSearchProvider.is_available`
    explicitly forbids network calls for exactly this reason.

    Resolution order, fast-to-slow:

    1. ``XAI_API_KEY`` env var (cheapest; covers explicit-key users).
    2. ``~/.hermes/auth.json`` has a non-empty ``providers.xai-oauth.tokens.access_token``
       (single file read, no expiry check, no refresh).

    Returns False on any exception so a corrupted auth store can't block
    other availability scans. Truthful refresh + expiry handling happens
    in ``search()`` (or whichever caller actually makes the request).
    XAI_API_KEY Tr   )get_hermes_homez	auth.jsonF	providersN	xai-oauthtokensaccess_token)osenvirongetstriphermes_constantsr
   existsjsonloads	read_text
isinstancedictr   str	Exception)r
   	auth_pathstorer   	xai_stater   r   s          3/home/ubuntu/.hermes/hermes-agent/tools/xai_http.pyhas_xai_credentialsr    
   si   ( 
z~~mR((..00 t444444#O%%3	!! 	5
9..0011.8.E.EOEIIk***4	2<Y2M2MWIMM+...SW	,6y$,G,GQx(((T5?5M5MWvzz.111SWC*++1133444   uus   'E% DE% %
E32E3namer   c                    	 ddl m}  ||           }||S n# t          $ r Y nw xY wt          j                            | |          S )zRead ``name`` from ``~/.hermes/.env`` first, then ``os.environ``.

    Wraps :func:`hermes_cli.config.get_env_value` so tests can patch
    ``tools.xai_http.get_env_value`` to inject dotenv-only secrets into the
    xAI credential resolver.
    r   )get_env_value)hermes_cli.configr#   r   r   r   r   )r!   default_hermes_get_env_valuevalues       r   r#   r#   0   so    LLLLLL%%d++L    :>>$(((s    
%%c                 @    	 ddl m}  n# t          $ r d} Y nw xY wd|  S )z>Return a stable Hermes-specific User-Agent for xAI HTTP calls.r   __version__unknownzHermes-Agent/)
hermes_clir*   r   r)   s    r   hermes_xai_user_agentr-   B   sN     *******       (;(((s   	 Fforce_refreshr/   Dict[str, str]c                   | s	 ddl m}  |d          }t          |                    d          pd                                          }t          |                    d          pd                                                              d          }|rd||pd	d
S n# t          $ r Y nw xY w	 ddlm}  ||           }t          |                    d          pd                                          }t          |                    d          pd                                                              d          }|rd||pd	d
S n# t          $ r Y nw xY wt          t          d          pd                                          }t          t          d          pd	                                                              d          }d||d
S )u  Resolve bearer credentials for direct xAI HTTP endpoints.

    Prefers Hermes-managed xAI OAuth credentials when available, then falls back
    to ``XAI_API_KEY`` resolved via ``hermes_cli.config.get_env_value`` so keys
    stored in ``~/.hermes/.env`` (the standard Hermes location) are honored —
    not just ones already exported into ``os.environ``. This keeps direct xAI
    endpoints (images, TTS, STT, etc.) aligned with the main runtime auth model
    and preserves the regression contract from PR #17140 / #17163.

    Set ``force_refresh=True`` to bypass the resolver's JWT-exp shortcut and
    perform an unconditional OAuth refresh. Callers should use this only as a
    reactive remediation after a server 401 (mid-window revocation, opaque
    tokens where the proactive JWT check is a no-op, etc.), not as a default —
    the auth-store lock is held for the duration of the refresh.
    r   )resolve_runtime_providerr   )	requestedapi_keyr	   base_url/zhttps://api.x.ai/v1)providerr4   r5   )%resolve_xai_oauth_runtime_credentialsr.   r   XAI_BASE_URLxai)
hermes_cli.runtime_providerr2   r   r   r   rstripr   hermes_cli.authr8   r#   )r/   r2   runtimer   r5   r8   credsr4   s           r   resolve_xai_http_credentialsr@   K   s4      	LLLLLL..EEEGw{{955;<<BBDDL7;;z228b99??AAHHMMH  ++ ( A,A    	 	 	D	IIIIII55MRRR599Y//5266<<>>uyy,,23399;;BB3GG 	''$=(=  	     -..4"55;;==G=00I4IJJPPRRYYZ]^^H  s%   BB   
B-,B-1BE 
EE)r   r   )N)r!   r   )r   r   )r/   r   r   r0   )__doc__
__future__r   r   r   typingr   r    r#   r-   r@        r   <module>rF      s    6 6 " " " " " "  				      # # # #L) ) ) ) )$) ) ) ) ;@ 5 5 5 5 5 5 5 5rE   