
    nSjd$              
       &   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           n# e$ r Y nw xY w	 ddlZddlZdd	lmZ n# e$ r dZY nw xY w 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&dS )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}   |                                 d          }t          |t                    r|n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     6/home/ice/.hermes/hermes-agent/agent/vertex_adapter.py_vertex_configr   2   so    111111+--##H--$Wd33;ww;   			s   ;> AAexplicitc                     | r| S t          d          pd                                }|r|S t          t                                          d          pd                                          }|p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   sx     o..4";;==J ^%%))(339r::@@BBJ''    c                      t          d          pd                                } | r| S t          t                                          d          pd                                          }|p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   sn     2339r@@BBK n&&**<88>B??EEGGK$r$   c                     | r!t           j                            |           r| S dD ]6}t          |          }|r#t           j                            |          r|c S 7d S )N)VERTEX_CREDENTIALS_PATHGOOGLE_APPLICATION_CREDENTIALS)ospathexistsr   )r   env_varr/   s      r   _resolve_credentials_pathr2   Z   so     BGNN8,,  Q  7## 	BGNN4(( 	KKK4r$   c                     t           j        j        j                                        }|                     |           d S N)googleauth	transportrequestsRequestrefresh)credsauth_reqs     r   _refresh_credentialsr=   j   s3    {$-5577H	MM(r$   credentials_pathc                 P   t           t                              d           dS t          |           }|pd}	 t                              |          }||r*t          j                            |dg          }|j	        }nmt                      r;t          j                            d          rt                              d           dS t           j                            dg          \  }}||ft          |<   n|\  }}t          |d	d           pTt          |d
d          pCt          |dd          duo0|j                                        t%          j                    z
  dk     }|rt'          |           t)                      }|r|}|j        |fS # t,          $ r}t                              d|            t                              |d           |dk    r@t          |           }	|	r/t                              d|	           t5          |	          cY d}~S Y d}~dS 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RRz-.>??M*I?!!),,> '3MM!LM N   #-

 '(( &RZ^^<\-]-] &NNL   &:$*K$7$7LM %8 % %!z (-j&9L## &E: w--- ui// x..d: C\++--	;sB 	  	( '''466 	*)J{J&&   DDDEEED))) 	!!/0@AAG 7KWUUU-g66666666zzzzzs&   BF 	CF 
H%A8H H% H%r'   r   c                 4    |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]      sC     +1H*<*<&&VBgBgBgD_d__j__V____r$   c                 x    t          |           \  }}|r|sdS 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      sS    
 //?@@E: 
 z&v..$Z1ABBH(?r$   c                  H    t          d          rdS t                      rdS dS )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      s1     !&& t "" t5r$   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 M M M M M M M	666666L"511111 	 	 	D	))))-------   FFF 
	8	$	$d        ( (hsm (s ( ( ( (
8C= 
 
 
 
 (3-        
L LXc] LeHUXM[cdg[hLhFi L L L L^ :H 	` 	`c 	`3 	`C 	` 	` 	` 	` '+  smSM 8C=(3-'(         s   5 ==A AA