Ë
    áß²jX-  ã                  óŽ  — U d Z ddlm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m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
ZdZdZded<    e
dd¬«      Z d,d„Z!d-d„Z"d.d„Z#d/d„Z$ G d„ de%e«      Z&eee&ee%   f      Z'd0d„Z(d1d„Z)e G d„ d«      «       Z*e&jV                  de&jX                  de&jZ                  de&j\                  de&j^                  de&j`                  d iZ1 G d!„ d"e«      Z2 ejf                  d#«      Z4 ejf                  d$«      Z5d2d%„Z6d3d&„Z7ejp                  d'œ	 	 	 	 	 d4d(„Z9d)ded*œ	 	 	 d5d+„Z:y)6a7  Secret-source contract: the ABC every secret backend implements.

A *secret source* resolves credentials from an external secret manager into
env-var-shaped values at process startup, AFTER ``~/.hermes/.env`` has loaded
and BEFORE the rest of Hermes reads ``os.environ``. The contract is deliberately
narrow: read-only; startup-time and synchronous (one ``fetch()`` per process per
HERMES_HOME, under a registry-enforced wall-clock timeout, no background
refreshers); never raises, never prompts (errors go in ``FetchResult.error``
with an :class:`ErrorKind`; interactive auth belongs in the CLI ``setup`` flow);
sources fetch, the orchestrator (``registry.apply_all``) applies.

``SECRET_SOURCE_API_VERSION`` gates plugin compatibility: additive optional
hooks with defaults do NOT bump it; required-signature changes do.
é    )ÚannotationsN)ÚABCÚabstractmethod)Ú
ContextVarÚToken)Ú	dataclassÚfield)ÚEnum)ÚPath)ÚAnyÚDictÚ	FrozenSetÚListÚMutableMappingÚOptionalÚSequenceÚTupleé   g      ^@g      >@z.ContextVar[Optional[MutableMapping[str, str]]]Ú_SOURCE_ENVIRONMENTÚ hermes_secret_source_environment)Údefaultc                ó,   — t         j                  | «      S )zEInstall a per-fetch environment view without changing ``os.environ``.)r   Úset©Úenvirons    ú>/home/ubuntu/.hermes/hermes-agent/agent/secret_sources/base.pyÚset_source_environmentr   &   s   € ä×"Ñ" 7Ó+Ð+ó    c                ó.   — t         j                  | «       y ©N)r   Úreset)Útokens    r   Úreset_source_environmentr#   +   s   € Ü×Ñ˜eÕ$r   c                 óR   — t         j                  «       } | �| S t        j                  S )zDReturn the active per-fetch environment, or the process environment.)r   ÚgetÚosr   r   s    r   Úget_source_environmentr'   /   s$   € ä!×%Ñ%Ó'€GØÐ)ˆ7Ð9¬r¯z©zÐ9r   c                 óp   — t        «       } | t        j                  u rddlm}  |dd¬«      S t        | «      S )zêEnvironment for a helper child that legitimately needs the caller's env:
    full process env (minus the terminal blocklist) in single-profile startup;
    ONLY the per-fetch view under multiplex, so no sibling profile's secrets leak.r   )Úbuild_subprocess_envF)Úscrub_secretsÚinherit_profile_home)r'   r&   r   Útools.environments.localr)   Údict)Ú
source_envr)   s     r   Úsource_child_envr/   5   s3   € ô (Ó)€JØ”R—Z‘ZÑÝAá#°%ÈeÔTÐTÜ�
ÓÐr   c                  ó4   — e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
Zy)Ú	ErrorKindz©Failure taxonomy for :class:`FetchResult.error`; lets the orchestrator apply
    kind-dependent policy once (stale-cache fallback on NETWORK/TIMEOUT, never AUTH_FAILED).Únot_configuredÚbinary_missingÚauth_failedÚauth_expiredÚref_invalidÚnetworkÚempty_valueÚtimeoutÚinternalN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚNOT_CONFIGUREDÚBINARY_MISSINGÚAUTH_FAILEDÚAUTH_EXPIREDÚREF_INVALIDÚNETWORKÚEMPTY_VALUEÚTIMEOUTÚINTERNAL© r   r   r1   r1   A   s7   „ ñ`ð &€NØ%€NØ€KØ!€LØ€KØ€GØ€KØ€GØ�Hr   r1   c                óˆ   ‡— | j                  «       Š|D ]  \  }}t        ˆfd„|D «       «      sŒ|c S  t        j                  S )zABest-effort mapping of helper-CLI failure text onto the taxonomy.c              3  ó&   •K  — | ]  }|‰v –— Œ
 y ­wr    rH   )Ú.0ÚtokÚlowereds     €r   ú	<genexpr>z%classify_cli_error.<locals>.<genexpr>Y   s   øè ø€ Ò0 #ˆs�gŒ~Ñ0ùs   ƒ)ÚlowerÚanyr1   rG   )ÚmessageÚrulesÚkindÚtokensrM   s       @r   Úclassify_cli_errorrU   U   sB   ø€ à�m‰m‹o€GØò ‰ˆˆfÜÓ0¨Ô0Õ0ØŠKðô ×ÑÐr   c                óH   — 	 t        | «      S # t        t        f$ r |cY S w xY w)z>``float(value)`` with ``default`` for malformed config values.)ÚfloatÚ	TypeErrorÚ
ValueError)Úvaluer   s     r   Úcoerce_floatr[   ^   s*   € ðÜ�U‹|ÐøÜ”zÐ"ò ØŠðús   ‚
 �! !c                  óÆ   — e Zd ZU dZ ee¬«      Zded<    ee¬«      Z	ded<    ee¬«      Z
ded<    ee¬«      Zded<   d	Zd
ed<   d	Zded<   d	Zded<   edd„«       Zdd„Zy	)ÚFetchResultz¾Outcome of one source's fetch. ``secrets`` is what the source *would*
    contribute; ``applied``/``skipped`` serve the legacy fetch-and-apply entry
    points and stay empty in ``fetch()``.)Údefault_factoryúDict[str, str]Úsecretsz	List[str]ÚappliedÚskippedÚwarningsNúOptional[str]ÚerrorzOptional[ErrorKind]Ú
error_kindzOptional[Path]Úbinary_pathc                ó   — | j                   d u S r    )re   ©Úselfs    r   ÚokzFetchResult.oku   s   € à�z‰z˜TÐ!Ð!r   c                ó$   — ||c| _         | _        | S r    )re   rf   )rj   re   rS   s      r   ÚfailzFetchResult.faily   s   € Ø&+¨TÐ#ˆŒ
�D”OØˆr   )ÚreturnÚbool)re   ÚstrrS   r1   rn   z'FetchResult')r;   r<   r=   r>   r	   r-   r`   Ú__annotations__Úlistra   rb   rc   re   rf   rg   Úpropertyrk   rm   rH   r   r   r]   r]   f   s{   … ñ-ñ $°DÔ9€Gˆ^Ó9Ù¨tÔ4€GˆYÓ4Ù¨tÔ4€GˆYÓ4Ù°Ô5€HˆiÓ5Ø€Eˆ=ÓØ&*€JÐ#Ó*à"&€K�Ó&àò"ó ð"ôr   r]   z:Run `hermes secrets {name} setup` to finish configuration.z<Run `hermes secrets {name} setup` to install the helper CLI.uN   Credentials rejected â€” run `hermes secrets {name} setup` to re-authenticate.uM   Credentials expired â€” run `hermes secrets {name} setup` to re-authenticate.uN   Network problem reaching the secrets backend â€” check connectivity and retry.uI   Backend was slow â€” raise secrets.{name}.timeout_seconds if this recurs.c                  óÚ   — e Zd ZU dZeZded<   dZded<   dZded<   dZ	ded	<   d
Z
ded<   d
Zded<   dZded<   dZded<   i Zded<   edd„«       Zdd„Zdd„Zdd„Zdd„Zd d„Zd!d„Zd"d„Zy
)#ÚSecretSourcea
  One external secret backend. Subclasses set attributes + ``fetch``.

    ``name``: config-section key under ``secrets:`` (``[a-z0-9_]+``) and the
    provenance label. ``shape``: ``"mapped"`` (user binds env-var names to refs)
    or ``"bulk"`` (backend injects whole projects); mapped beats bulk because an
    explicit binding is stronger intent. ``scheme``: URI scheme this source owns
    for refs, unique across sources. ``token_env_key`` / ``default_token_env``:
    config key naming the bootstrap-auth env var and its default; drives
    :meth:`protected_env_vars` so a vault holding its own access token can't
    clobber the credential used to reach it. ``remediation_hints``: per-kind
    overrides of the generic remediation text (``{name}`` / ``{token_env}``).
    ÚintÚapi_versionÚ rp   ÚnameÚlabelÚmappedÚshapeNrd   ÚschemeÚtoken_env_keyÚdefault_token_envFro   Úoverride_existing_defaultzDict[ErrorKind, str]Úremediation_hintsc                 ó   — y)z„Resolve this source's secrets. MUST NOT raise or prompt; ``cfg`` is the
        raw ``secrets.<name>`` section and may be malformed.NrH   )rj   ÚcfgÚ	home_paths      r   ÚfetchzSecretSource.fetch    s   � r   c                óZ   — t        t        |t        «      xr |j                  d«      «      S )NÚenabled)ro   Ú
isinstancer-   r%   ©rj   rƒ   s     r   Ú
is_enabledzSecretSource.is_enabled¥   s"   € Ü”J˜s¤DÓ)Ò@¨c¯g©g°iÓ.@ÓAÐAr   c                óp   — t        t        |t        «      xr |j                  d| j                  «      «      S )z£May this source overwrite vars .env / the shell already set? Never extends
        to vars claimed by another source (a config error the orchestrator warns about).Úoverride_existing)ro   rˆ   r-   r%   r€   r‰   s     r   rŒ   zSecretSource.override_existing¨   s7   € ô ”J˜s¤DÓ)ò UØŸ™Ð 3°T×5SÑ5SÓTóVð 	Vr   c                ó¶   — t        |t        «      r>| j                  r2t        |j	                  | j                  «      xs | j
                  «      S | j
                  S )z?Name of the env var holding this source's bootstrap credential.)rˆ   r-   r~   rp   r%   r   r‰   s     r   Ú	token_envzSecretSource.token_env®   sE   € ä�cœ4Ô  T×%7Ò%7Ü�s—w‘w˜t×1Ñ1Ó2ÒL°d×6LÑ6LÓMÐMØ×%Ñ%Ð%r   c                ód   — | j                   rt        | j                  |«      h«      S t        «       S )z>Env vars the orchestrator must never let ANY source overwrite.)r~   Ú	frozensetrŽ   r‰   s     r   Úprotected_env_varszSecretSource.protected_env_vars´   s(   € à37×3EÒ3EŒy˜$Ÿ.™.¨Ó-Ð.Ó/ÐVÌ9Ë;ÐVr   c                ól   — t        |xs i j                  dt        «      t        «      }|dkD  r|S t        S )z;Wall-clock budget the orchestrator enforces around fetch().Útimeout_secondsr   )r[   r%   ÚDEFAULT_FETCH_TIMEOUT_SECONDS)rj   rƒ   Úvals      r   Úfetch_timeout_secondsz"SecretSource.fetch_timeout_seconds¸   s4   € ä˜CšI 2Ÿ?™?Ð+<Ô>[Ó\Ü8ó:ˆà˜A’gˆsÐ@Ô#@Ð@r   c                ó   — i S )zLInformational ``{key: {"description": str, "default": Any}}`` for setup UIs.rH   ri   s    r   Úconfig_schemazSecretSource.config_schema¾   s   € àˆ	r   c                óÆ   — |€y| j                   j                  |«      xs t        j                  |d«      }|j                  | j                  | j                  |«      ¬«      S )zPOne-line actionable next step for a failed fetch (pure); "" suppresses the hint.rx   )ry   rŽ   )r�   r%   Ú_GENERIC_REMEDIATIONÚformatry   rŽ   )rj   rS   rƒ   Útemplates       r   ÚremediationzSecretSource.remediationÂ   sU   € àˆ<ØØ×)Ñ)×-Ñ-¨dÓ3ÒYÔ7K×7OÑ7OÐPTÐVXÓ7YˆØ�‰ D§I¡I¸¿¹ÈÓ9LˆÓMÐMr   )rƒ   r-   r„   r   rn   r]   )rƒ   r-   rn   ro   )rƒ   r-   rn   rp   )rƒ   r-   rn   zFrozenSet[str])rƒ   r-   rn   rW   )rn   r-   )rS   zOptional['ErrorKind']rƒ   r-   rn   rp   )r;   r<   r=   r>   ÚSECRET_SOURCE_API_VERSIONrw   rq   ry   rz   r|   r}   r~   r   r€   r�   r   r…   rŠ   rŒ   rŽ   r‘   r–   r˜   r�   rH   r   r   ru   ru   ˆ   s¡   … ñð 1€K�Ó0Ø€Dˆ#ƒNØ€Eˆ3ƒOØ€Eˆ3ÓØ €FˆMÓ Ø#'€M�=Ó'ØÐ�sÓØ&+Ð˜tÓ+Ø.0ÐÐ+Ó0àò@ó ð@óBóVó&óWóAóôNr   ru   z^[A-Za-z_][A-Za-z0-9_]*$z<\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?)c                óX   — t        | «      xr t        t        j                  | «      «      S )z8True when ``name`` is a legal environment-variable name.)ro   Ú_ENV_NAME_REÚmatch)ry   s    r   Úis_valid_env_namer¢   Ô   s!   € ä�‹:Ò8œ$œ|×1Ñ1°$Ó7Ó8Ð8r   c                ó6   — t         j                  d| xs d«      S )zDStrip ANSI escape sequences (whole CSI/OSC sequences, not just ESC).rx   )Ú_ANSI_REÚsub)Útexts    r   Ú
scrub_ansir§   Ù   s   € ä�<‰<˜˜DšJ BÓ'Ð'r   )Ústdinc          
     óÚ   — 	 t        j                  t        | «      |dddd||¬«      S # t         j                  $ r}t	        |«      |‚d}~wt
        $ r}t	        d|› d|› �«      |‚d}~ww xY w)z¤``subprocess.run`` an argv list (never a shell), capturing utf-8 text; timeout
    and spawn failure become ``RuntimeError``. Callers own returncode interpretation.Tzutf-8Úreplace)ÚenvÚcapture_outputr¦   ÚencodingÚerrorsr9   r¨   Nzfailed to invoke z: )Ú
subprocessÚrunrr   ÚTimeoutExpiredÚRuntimeErrorÚOSError)Úargvr«   r9   rz   Útimeout_messager¨   Úexcs          r   Úrun_clir·   Þ   s{   € ðHÜ�~‰~Ü�‹J˜C°¸4È'ÐZcØ 5ô
ð 	
øô ×$Ñ$ò 5Ü˜?Ó+°Ð4ûÜò HÜÐ.¨u¨g°R¸°uÐ=Ó>ÀCÐGûðHús    ‚%( ¨A*»AÁA*ÁA%Á%A*rH   )Ú	allow_envÚ	extra_envr9   c          
     ó¦  — d}g |¢|¢­D �ci c])  }|t         j                  v sŒ|t         j                  |   “Œ+ }}|r|j                  |«       |j                  dd«       t	        t        | d   «      «      j                  }t        | ||||› d|d›d�¬«      }|j                  xs d	|_        t        |j                  xs d	«      |_
        |S c c}w )
a<  Run a secret-manager helper CLI with a minimal, allowlisted env (never the
    full post-dotenv ``os.environ``): PATH/HOME/locale basics plus ``allow_env``
    and ``extra_env``. ``NO_COLOR=1`` + ANSI-scrubbed stderr; stdin is /dev/null so
    a prompting helper fails fast. Pass user refs AFTER a ``--`` terminator.)
ÚPATHÚHOMEÚUSERPROFILEÚ
SYSTEMROOTÚTMPDIRÚTEMPÚLANGÚLC_ALLÚXDG_CONFIG_HOMEÚXDG_DATA_HOMEÚNO_COLORÚ1r   z timed out after z.0fÚs)r«   r9   rz   rµ   rx   )r&   r   ÚupdateÚ
setdefaultr   rp   ry   r·   Ústdoutr§   Ústderr)	r´   r¸   r¹   r9   Ú	base_keepÚkr«   ry   Úprocs	            r   Úrun_secret_clirÏ   í   sÉ   € ðG€Ià%= yÐ%=°9Ñ%=Ö
Q ÀÄbÇjÁjÂˆ1Œb�j‰j˜‰mÑÐ
Q€CÐ
QÙØ�
‰
�9ÔØ‡N�N�:˜sÔ#ä”�D˜‘G“Ó×"Ñ"€DÜ�4˜S¨'¸Ø&* VÐ+<¸WÀS¸MÈÐ#KôM€Dà—+‘+Ò# €D„KÜ˜TŸ[™[Ò.¨BÓ/€D„KØ€Kùò Rs
   ŒC¤C)r   úMutableMapping[str, str]rn   r   )r"   r   rn   ÚNone)rn   rÐ   )rn   r_   )rQ   rp   rR   Ú
ErrorRulesrn   r1   )rZ   r   r   rW   rn   rW   )ry   rp   rn   ro   )r¦   rp   rn   rp   )r´   úSequence[str]r«   r_   r9   rW   rz   rp   rµ   rp   r¨   r   rn   úsubprocess.CompletedProcess)
r´   rÓ   r¸   rÓ   r¹   zOptional[Dict[str, str]]r9   rW   rn   rÔ   );r>   Ú
__future__r   r&   Úrer¯   Úabcr   r   Úcontextvarsr   r   Údataclassesr   r	   Úenumr
   Úpathlibr   Útypingr   r   r   r   r   r   r   r   rž   r”   ÚDEFAULT_CLI_TIMEOUT_SECONDSrq   r   r   r#   r'   r/   rp   r1   rÒ   rU   r[   r]   r?   r@   rA   rB   rD   rF   rš   ru   Úcompiler    r¤   r¢   r§   ÚDEVNULLr·   rÏ   rH   r   r   ú<module>rà      s–  ðòõ #ã 	Û 	Û ß #ß )ß (Ý Ý ß X× XÓ XàÐ ð !&Ð Ø"Ð àCÓ CÙ Ð!CÈTÔRÐ ó,ó
%ó:ó	ô��Tô ð" �e˜I x°¡}Ð4Ñ5Ñ6€
óóð ÷ð ó ðð0 ×ÑÐZØ×ÑÐ\Ø×ÑÐkØ×ÑÐkØ×ÑÐgØ×ÑÐbðÐ ô?N�3ô ?NðH ˆr�z‰zÐ5Ó6€ð
 ˆ2�:‰:ÐUÓV€ó9ó
(ð 0:×/AÑ/AñHØ ðHØ),ðHØFaóHð GIÐptØ$?ñØ!ðØD_ôr   