
    `gjd$              
          U d Z ddlZddlZddlZddlmZmZ ddlmZ	m
Z
 	 ddlmZ  edd       	 ddlZddlZdd	lmZ  ej*                  e      Zd
Zi Zeed<   defdZddee   defdZdee   fdZdee   dee   fdZ ddZ!ddee   deee   ee   f   fdZ"efdededefdZ#	 	 ddee   dee   deee   ee   f   fdZ$de%fdZ&y# e$ r Y w xY w# e$ r dZY w xY w)u  Vertex AI (Google Cloud) adapter for Hermes Agent.

Provides authentication and configuration for Vertex AI's OpenAI-compatible
endpoint. This allows Hermes to use Gemini models via Google Cloud with
enterprise-grade rate limits and quotas.

Requires: pip install google-auth

Environment variables honored (all optional):
  GOOGLE_APPLICATION_CREDENTIALS — path to a service account JSON file (secret).
  VERTEX_CREDENTIALS_PATH        — alias, takes precedence if set (secret).
  VERTEX_PROJECT_ID              — override the project_id embedded in creds.
  VERTEX_REGION                  — override default region ("global" unless set).

Non-secret routing settings (project_id, region) also live in config.yaml
under the ``vertex:`` section; env vars take precedence over config.yaml.
    N)OptionalTuple)
get_secretis_multiplex_active)ensurezprovider.vertexF)prompt)service_accountglobal_creds_cachereturnc                      	 ddl m}   |        j                  d      }t        |t              r|S i S # t
        $ r i cY S w xY w)u0  Return the ``vertex:`` section of config.yaml, or {} on any failure.

    Non-secret routing settings (project_id, region) live in config.yaml per
    the .env-secrets-only rule. Env vars still take precedence — they are read
    directly at the call sites below, with config.yaml as the fallback.
    r   )load_configvertex)hermes_cli.configr   get
isinstancedict	Exception)r   sections     G/root/.hermes/venv/lib/python3.12/site-packages/agent/vertex_adapter.py_vertex_configr   2   sD    1-##H-$Wd3w;; 	s   -2 2 A A explicitc                     | r| S t        d      xs dj                         }|r|S t        t               j	                  d      xs d      j                         }|xs t
        S )zLRegion precedence: explicit arg > VERTEX_REGION env > config.yaml > default.VERTEX_REGION region)_get_secretstripstrr   r   DEFAULT_REGION)r   
env_region
cfg_regions      r   _resolve_regionr#   B   s\    o.4";;=J^%))(39r:@@BJ''    c                      t        d      xs dj                         } | r| S t        t               j	                  d      xs d      j                         }|xs dS )zProject-ID override precedence: VERTEX_PROJECT_ID env > config.yaml.

    Returns None when neither is set (the credentials' embedded project_id
    is used in that case).
    VERTEX_PROJECT_IDr   
project_idN)r   r   r   r   r   )env_projectcfg_projects     r   _resolve_project_overrider*   M   sW     239r@@BKn&**<8>B?EEGK$r$   c                     | r!t         j                  j                  |       r| S dD ]3  }t        |      }|st         j                  j                  |      s1|c S  y )N)VERTEX_CREDENTIALS_PATHGOOGLE_APPLICATION_CREDENTIALS)ospathexistsr   )r   env_varr/   s      r   _resolve_credentials_pathr2   Z   sQ    BGGNN8, Q 7#BGGNN4(K r$   c                     t         j                  j                  j                  j	                         }| j                  |       y N)googleauth	transportrequestsRequestrefresh)credsauth_reqs     r   _refresh_credentialsr=   j   s,    {{$$--557H	MM(r$   credentials_pathc                    t         t        j                  d       yt        |       }|xs d}	 t        j                  |      }||r/t        j                  j                  |dg      }|j                  }nct               r5t        j                  j                  d      rt        j                  d       yt         j                  j                  dg      \  }}||ft        |<   n|\  }}t        |d	d       xsR t        |d
d      xsC t        |dd      duxr2 |j                   j#                         t%        j$                         z
  dk  }|rt'        |       t)               }|r|}|j*                  |fS # t,        $ rp}t        j/                  d|        t        j1                  |d       |dk(  r3t        |       }	|	r&t        j3                  d|	       t5        |	      cY d}~S Y d}~yd}~ww xY w)zReturn a (fresh access_token, project_id) pair or (None, None) on failure.

    Caches the underlying Credentials object and refreshes it when within
    5 minutes of expiry, so repeated calls don't thrash the token endpoint.
    Nz8google-auth package not installed. Cannot use Vertex AI.NN__adc__z.https://www.googleapis.com/auth/cloud-platform)scopesr-   zVertex ADC skipped for this profile: GOOGLE_APPLICATION_CREDENTIALS is set in the process environment (from another profile's .env) but not in this profile's own config. Set VERTEX_CREDENTIALS_PATH in this profile's .env instead of relying on ADC.tokenexpiredFexpiryi,  z)Failed to resolve Vertex AI credentials: z-ADC failed, retrying with service account: %s)r5   loggerwarningr2   r   r   r	   Credentialsfrom_service_account_filer'   r   r.   environr6   defaultgetattrrE   	timestamptimer=   r*   rC   r   errorpopinfoget_vertex_credentials)
r>   resolved_path	cache_keycachedr;   r'   needs_refreshoverride_projectesa_paths
             r   rR   rR   o   s    ~QR-.>?M*I?!!),>'33MM!LM N  #--
 '(RZZ^^<\-]NNL &$*KK$7$7LM %8 %!z (-j&9L# &E: w-- ui/ x.d: C\\++-		;sB 	  '46)J{{J&& @DED) 	!/0@AGKWU-g66s&   BE6 6B?E6 6	G/?A G*G/*G/r'   r   c                 2    |dk(  rdn| d}d| d|  d| dS )a.  Build the OpenAI-compatible base URL for Vertex AI.

    The `global` location uses a bare `aiplatform.googleapis.com` hostname,
    while regional locations use `{region}-aiplatform.googleapis.com`.
    Gemini 3.x preview models are only served via the global endpoint at
    the time of writing.
    r
   zaiplatform.googleapis.comz-aiplatform.googleapis.comzhttps://z/v1beta1/projects/z/locations/z/endpoints/openapi )r'   r   hosts      r   build_vertex_base_urlr]      s8     +1H*<&VHLfBgDdV-j\VHL^__r$   c                 ^    t        |       \  }}|r|syt        |      }t        ||      }||fS )zKResolve (access_token, base_url) for Vertex AI, or (None, None) on failure.r@   )rR   r#   r]   )r>   r   rC   r'   effective_regionbase_urls         r   get_vertex_configra      s>    
 //?@E:
&v.$Z1ABH(?r$   c                  2    t        d      ryt               ryy)uP  Fast check for whether Vertex credentials appear configured.

    No network calls and no google-auth import — safe for provider
    auto-detection and setup-status display. True when either a service
    account JSON path is resolvable, or an explicit project ID is configured
    (env or config.yaml, implying ADC is intended).
    NTF)r2   r*   r[   r$   r   has_vertex_credentialsrc      s     !& "r$   r4   )r   Nr@   )'__doc__loggingr.   rN   typingr   r   agent.secret_scoper   r   r   tools.lazy_depsr   _lazy_ensurer   google.authr5   google.auth.transport.requestsgoogle.oauth2r	   ImportError	getLogger__name__rF   r    r   r   __annotations__r   r   r#   r*   r2   r=   rR   r]   ra   boolrc   r[   r$   r   <module>rr      s~  $  	  " M	6"51)- 
		8	$d   (hsm (s (
8C= 
 (3-  
LXc] LeHUXM[cdg[hLhFi L^ :H 	`c 	`3 	`C 	` '+ smSM 8C=(3-'( o  		  Fs"   C C CCC%$C%