
    i                    b    d Z ddlmZ ddlZddlmZ ddlmZ dZdd	Z	ddZ
ddZdddddZdS )zFHelpers for loading Hermes .env files consistently across entrypoints.    )annotationsN)Path)load_dotenv)_API_KEY_TOKEN_SECRET_KEYreturnNonec                 f   t          t          j                                                  D ]\  } t	          fdt
          D                       s&	 |                     d           =# t          $ r: |                     dd                              d          t          j        <   Y w xY wdS )a  Strip non-ASCII characters from credential env vars in os.environ.

    Called after dotenv loads so the rest of the codebase never sees
    non-ASCII API keys.  Only touches env vars whose names end with
    known credential suffixes (``_API_KEY``, ``_TOKEN``, etc.).
    c              3  B   K   | ]}                     |          V  d S )N)endswith).0suffixkeys     =/home/agentuser/.hermes/hermes-agent/hermes_cli/env_loader.py	<genexpr>z/_sanitize_loaded_credentials.<locals>.<genexpr>   s/      KKF3<<''KKKKKK    asciiignore)errorsN)	listosenvironitemsany_CREDENTIAL_SUFFIXESencodeUnicodeEncodeErrordecode)valuer   s    @r   _sanitize_loaded_credentialsr"      s     2:++--.. U U
UKKKK6JKKKKK 		ULL!!!!! 	U 	U 	U#ll78lDDKKGTTBJsOOO	UU Us   A**AB.-B.pathr   overrideboolc                   	 t          | |d           n"# t          $ r t          | |d           Y nw xY wt                       d S )Nutf-8)dotenv_pathr$   encodingzlatin-1)r   UnicodeDecodeErrorr"   )r#   r$   s     r   _load_dotenv_with_fallbackr+   "   sn    Mx'JJJJJ M M Mx)LLLLLLM !"""""s    44c                   |                                  sdS 	 ddlm} n# t          $ r Y dS w xY wddd}	 t	          | fi |5 }|                                }ddd           n# 1 swxY w Y    ||          }||k    rddl}|                    t          | j	                  dd	          \  }}	 t          j        |d
d          5 }|                    |           |                                 t          j        |                                           ddd           n# 1 swxY w Y   t          j        ||            dS # t"          $ r( 	 t          j        |           n# t&          $ r Y nw xY w w xY wdS # t(          $ r Y dS w xY w)u  Pre-sanitize a .env file before python-dotenv reads it.

    python-dotenv does not handle corrupted lines where multiple
    KEY=VALUE pairs are concatenated on a single line (missing newline).
    This produces mangled values — e.g. a bot token duplicated 8×
    (see #8908).

    We delegate to ``hermes_cli.config._sanitize_env_lines`` which
    already knows all valid Hermes env-var names and can split
    concatenated lines correctly.
    Nr   )_sanitize_env_linesr'   replace)r)   r   z.tmpz.env_)dirr   prefixw)r)   )existshermes_cli.configr-   ImportErroropen	readlinestempfilemkstempstrparentr   fdopen
writelinesflushfsyncfilenor.   BaseExceptionunlinkOSError	Exception)	r#   r-   read_kwforiginal	sanitizedr7   fdtmps	            r   _sanitize_env_file_if_neededrJ   /   sn    ;;== 9999999    #i88G$""'"" 	%a{{}}H	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%''11	  OOO&&$$VG '  GBYr3999 )QLL+++GGIIIHQXXZZ((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) 
3%%%%%    IcNNNN   D ! "    s    
--E> A$E> $A((E> +A(,AE> 2E 	AD%E %D))E ,D)-E 
E9E'&E9'
E41E93E44E99E> >
FF)hermes_homeproject_envrK   str | os.PathLike | NonerL   
list[Path]c                   g }t          | p(t          j        dt          j                    dz                      }|dz  }|rt          |          nd}|                                rt          |           |                                r&t          |d           |                    |           |r;|                                r't          ||            |                    |           |S )a[  Load Hermes environment files with user config taking precedence.

    Behavior:
    - `~/.hermes/.env` overrides stale shell-exported values when present.
    - project `.env` acts as a dev fallback and only fills missing values when
      the user env exists.
    - if no user env exists, the project `.env` also overrides stale shell vars.
    HERMES_HOMEz.hermesz.envNT)r$   )r   r   getenvhomer2   rJ   r+   append)rK   rL   loaded	home_pathuser_envproject_env_paths         r   load_hermes_dotenvrX   \   s     F[UBImTY[[9=T$U$UVVI6!H,7AtK(((T  /$X...  "8d;;;;h (,3355 ("#3&jIIII&'''Mr   )r
   r   )r#   r   r$   r%   r
   r   )r#   r   r
   r   )rK   rM   rL   rM   r
   rN   )__doc__
__future__r   r   pathlibr   dotenvr   r   r"   r+   rJ   rX    r   r   <module>r^      s    L L " " " " " " 				             A U U U U 
# 
# 
# 
#* * * *^ -1,0       r   