Ë
    âß²jž<  ã                  ó„  — d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZe
j                  dk(  ZdadZdZdd„Zdd	„Z	 d	 dd
„Zdd„Z G d„ dej*                  j,                  ej*                  j.                  «      Zdd„Zdd„Zdd„Zddd„Zdd„Zdd„Z e«         e«         e«         e«         e«        y)u†  Process bootstrap for Hermes entry points: Windows UTF-8 stdio, import-path
hardening, durable lazy-install target, and dual-stack (Happy Eyeballs) connects.

Windows binds stdio to the console code page (cp1252), so ``print("cafÃ©")`` raises
``UnicodeEncodeError``, and Python children inherit the same default unless
``PYTHONUTF8``/``PYTHONIOENCODING`` are set. Import this module first in every entry
point (``hermes``, ``hermes-agent``, ``hermes-acp``, ``gateway.run``, ``batch_runner``,
``cron/scheduler``). It does NOT re-exec with ``-X utf8``: ``open()`` in the current
process still needs an explicit ``encoding="utf-8"`` (ruff ``PLW1514``). POSIX is left
alone deliberately â€” users' ``LANG``/``LC_*`` choices are respected.

Stdlib only: entry points import this before ``harden_import_path()`` runs, so nothing
here may pull in a Hermes package that a project-local directory could shadow.
é    )ÚannotationsNÚwin32Fg      Ð?zurllib3.util.connectionc                óp  — i }t        «       }| D ]I  }|\  }}}}}||||f|vsŒ|j                  ||||f«       |j                  |g «      j                  |«       ŒK g }	t	        |j                  «       «      r@|	j                  d„ |j                  «       D «       «       t	        |j                  «       «      rŒ@|	S )z[Round-robin the resolved address families (deduped), preserving resolver order within each.c              3  óD   K  — | ]  }|sŒ|j                  d «      –— Œ y­w)r   N)Úpop)Ú.0Úqueues     ú5/home/ubuntu/.hermes/hermes-agent/hermes_bootstrap.pyú	<genexpr>z(_interleave_addrinfos.<locals>.<genexpr>,   s   è ø€ ÒN¨EÊ˜5Ÿ9™9 QŸ<ÑNùs   ‚ Š )ÚsetÚaddÚ
setdefaultÚappendÚanyÚvaluesÚextend)
Ú	addrinfosÚqueuesÚseenÚaddrinfoÚfamilyÚsocktypeÚprotoÚ
_canonnameÚsockaddrÚinterleaveds
             r
   Ú_interleave_addrinfosr   !   s³   € à%'€FÜ“u€DØò ;ˆØ8@Ñ5ˆ�˜% ¨XØ�H˜e XÐ.°dÒ:Ø�H‰H�f˜h¨¨xÐ8Ô9Ø×Ñ˜f bÓ)×0Ñ0°Õ:ð	;ð
  "€KÜ
ˆf�m‰m‹oÔ
Ø×ÑÑN°V·]±]³_ÔNÔNô ˆf�m‰m‹oÕ
àÐó    c                óF   — 	 | j                  |«       y # t        $ r Y y w xY w©N)Ú
unregisterÚ	Exception)ÚselectorÚsocks     r
   Ú_quiet_unregisterr%   0   s'   € ðØ×Ñ˜DÕ!øÜò Ùðús   ‚ ”	 Ÿ c           
     ó  ‡‡‡‡— | \  }}t        t        j                  ||t        j                  ¬«      «      }|st	        d|› �«      ‚t        j                  «       Št        «       Šd}d}|€dn t        j                  «       t        |d«      z   }	t        j                  «       }
t        |«      }dt        j                  t        j                  t        j                  t        j                   t#        t        dd«      hŠˆˆˆˆfd„}	 |s‰�r`t        j                  «       }|	�||	k\  rt        j$                  d	«      ‚|r*||
k\  r%	  ||j'                  d«      «      }|��n|t(        z   }
|	€dnt        d|	|z
  «      }|rt        d|
|z
  «      }|€|nt+        ||«      }‰j-                  |«      D ]™  \  }}|j.                  }|j1                  t        j2                  t        j4                  «      }‰j7                  |«       ‰j9                  |«       |dk(  r|} n1|j;                  «        t	        |t=        j>                  |«      «      }Œ› |�n ‰s|rt        j                  «       }
|r�Œ\‰r�Œ`|€|�|‚t	        d
|› d|› �«      ‚tA        ‰|«       ‰j9                  |«       |jC                  |«       |xs dD ]  } |jD                  |Ž  Œ |jE                  t        jF                  t        jH                  d«       |‰D ]  }tA        ‰|«       |j;                  «        Œ  ‰j;                  «        S # t        $ r}|}‰s|}
Y d}~�Œ=d}~ww xY w# ‰D ]  }tA        ‰|«       |j;                  «        Œ  ‰j;                  «        w xY w)zäRFC 8305-style connect: staggered non-blocking attempts across families.

    ``socket.create_connection`` tries addresses serially, so broken-but-
    advertised IPv6 can burn the whole timeout per AAAA record before IPv4.
    )Útypez&getaddrinfo returned no addresses for Ng        r   ÚWSAEWOULDBLOCKi3'  c                ó6  •— | \  }}}}}t        j                   |||«      }	 ‰�Lt        j                  ‰d   ‰d   ||¬«      }|st        d|› d‰d   › �«      ‚|j                  |d   d   «       |j	                  d«       |j                  |«      }|dt        j                  fv r|S |‰
vrt        |t        j                  |«      «      ‚‰j                  |t        j                  «       ‰	j                  |«       y # t        $ r |j                  «        ‚ w xY w)Nr   é   )r   r'   zgetaddrinfo returned no local z address for é   F)ÚsocketÚgetaddrinfoÚOSErrorÚbindÚsetblockingÚ
connect_exÚerrnoÚEISCONNÚosÚstrerrorÚregisterÚ	selectorsÚEVENT_WRITEr   r"   Úclose)r   r   r   r   r   r   Ú	candidateÚlocal_infosÚresultÚactiveÚin_progressr#   Úsource_addresss            €€€€r
   Ústart_attemptz8_happy_eyeballs_create_connection.<locals>.start_attemptL   s   ø€ Ø8@Ñ5ˆ�˜% ¨XÜ—M‘M &¨(°EÓ:ˆ	ð	ØÐ)Ü$×0Ñ0°ÀÑ1BÀNÐSTÑDUÐ^dÐksÔt�Ù"Ü!Ð$BÀ6À(È-ÐXfÐghÑXiÐWjÐ"kÓlÐlØ—‘˜{¨1™~¨aÑ0Ô1Ø×!Ñ! %Ô(Ø×)Ñ)¨(Ó3ˆFØ˜!œUŸ]™]Ð+Ñ+Ø Ð Ø˜[Ñ(Ü˜f¤b§k¡k°&Ó&9Ó:Ð:Ø×Ñ˜i¬×)>Ñ)>Ô?Ø�J‰J�yÔ!ØøÜò 	Ø�O‰OÔØð	ús   ¢BC= Â(AC= Ã=Dz	timed outzCould not connect to ú:© r*   )%r   r,   r-   ÚSOCK_STREAMr.   r7   ÚDefaultSelectorr   ÚtimeÚ	monotonicÚmaxÚlistr2   ÚEINPROGRESSÚEWOULDBLOCKÚEALREADYÚEINTRÚgetattrÚtimeoutr   Ú_HAPPY_EYEBALLS_DELAY_SECONDSÚminÚselectÚfileobjÚ
getsockoptÚ
SOL_SOCKETÚSO_ERRORr!   Údiscardr9   r4   r5   r%   Ú
settimeoutÚ
setsockoptÚIPPROTO_TCPÚTCP_NODELAY)ÚaddressrN   r?   Úsocket_optionsÚhostÚportr   ÚwinnerÚ
last_errorÚdeadlineÚnext_launchÚpendingr@   ÚnowÚexcÚwait_timeoutÚuntil_launchÚkeyÚ_maskr:   Ú
error_codeÚoptionr=   r>   r#   s     `                   @@@r
   Ú!_happy_eyeballs_create_connectionrl   7   sH  û€ ð �J€Dˆ$Ü%¤f×&8Ñ&8¸¸tÌ&×J\ÑJ\Ô&]Ó^€IÙÜÐ>¸t¸fÐEÓFÐFä×(Ñ(Ó*€HÜ!$£€FØ€FØ!%€JØ�‰t¬D¯N©NÓ,<¼sÀ7ÈCÓ?PÑ,P€HÜ—.‘.Ó"€KÜ�9‹o€GØ”e×'Ñ'¬×):Ñ):¼E¿N¹NÌEÏKÉKÔY`ÔafÐhxÐzó  ZAð  B€K÷ð,0ÙšÜ—.‘.Ó"ˆCØÐ#¨¨xªÜ—n‘n [Ó1Ð1Ù˜3 +Ò-ðÙ*¨7¯;©;°q«>Ó:�Fð Ð%ÙØ!Ô$AÑA�Ø#+Ð#3™4¼¸SÀ(ÈSÁ.Ó9QˆLÙÜ" 3¨°cÑ(9Ó:�Ø/;Ð/C™|ÌÈ\Ð[gÓIh�Ø&Ÿo™o¨lÓ;ò 	J‘
��UØŸK™K�	Ø&×1Ñ1´&×2CÑ2CÄVÇ_Á_ÓU�
Ø×#Ñ# IÔ.Ø—‘˜yÔ)Ø ’?Ø&�FÙØ—‘Ô!Ü$ Z´·±¸ZÓ1HÓI‘
ð	Jð Ð!ØÙ™gÜ"Ÿn™nÓ.�óA ›ðD ˆ>Ø *Ð 6�*Ðj¼GÐF[Ð\`Ð[aÐabÐcgÐbhÐDiÓ<jÐjÜ˜( FÔ+Ø�‰�vÔØ×Ñ˜'Ô"Ø$Ò*¨ò 	'ˆFØˆF×Ñ˜vÒ&ð	'à×Ñœ&×,Ñ,¬f×.@Ñ.@À!ÔDØàò 	ˆIÜ˜h¨	Ô2Ø�O‰OÕð	ð 	�‰ÕøôQ ò Ø!$�JÙ!Ø&)˜Ýûð	ûðJ  ò 	ˆIÜ˜h¨	Ô2Ø�O‰OÕð	ð 	�‰ÕúsD   Ä<M ÅL/ ÅDM É(M É,BM Ì/	M	Ì8MÌ>M ÍM	Í	M Í5Nc                ó|   ‡— t        | j                  dd«      ry| j                  Š‰ddfˆfd„	}d|_        || _        y)zYPoint ``urllib3.util.connection.create_connection`` (its own serial walker) at the racer.Ú_hermes_happy_eyeballsFNc           	     óp   •— |‰u rt        j                  «       n|}t        | ||t        |xs d«      ¬«      S )NrB   )r?   r\   )r,   Úgetdefaulttimeoutrl   Útuple)r[   rN   r?   r\   Ú	effectiveÚurllib3_sentinels        €r
   Ú_urllib3_racerz8_patch_urllib3_create_connection.<locals>._urllib3_racer›   sB   ø€ Ø29Ð=MÑ2M”F×,Ñ,Ô.ÐSZˆ	ô 1Ø�Y¨~ÌeÐTbÒThÐfhÓNiôkð 	kr   T)rM   Úcreate_connectionÚ_DEFAULT_TIMEOUTrn   )Úmodulert   rs   s     @r
   Ú _patch_urllib3_create_connectionrx   •   sE   ø€ äˆv×'Ñ'Ð)AÀ5ÔIØØ×.Ñ.Ðà(8ÈÐ^bõ kð -1€NÔ)Ø-€FÕr   c                  ó$   — e Zd ZdZdd„Zd„ Zd„ Zy)Ú_Urllib3ConnectionPatcherz÷One-shot import hook: patch urllib3's connect walker the moment the module loads.

    Importing urllib3 eagerly costs ~50 ms on every CLI start, and ``hermes`` / the TUI
    gateway never load it unless something actually calls ``requests``.
    Nc                ó  — |t         k7  ry | t        j                  v rt        j                  j                  | «       t        j
                  j                  |«      }|�|j                  €y |j                  | _        | |_        |S r    )	Ú_URLLIB3_CONNECTION_MODULEÚsysÚ	meta_pathÚremoveÚ	importlibÚutilÚ	find_specÚloaderÚ_inner)ÚselfÚfullnameÚpathÚtargetÚspecs        r
   r‚   z#_Urllib3ConnectionPatcher.find_spec­   sh   € ØÔ1Ò1ØØ”3—=‘=Ñ Ü�M‰M× Ñ  Ô&Ü�~‰~×'Ñ'¨Ó1ˆØˆ<˜4Ÿ;™;Ð.ØØ—k‘kˆŒØˆŒØˆr   c                ó8   — | j                   j                  |«      S r    )r„   Úcreate_module)r…   r‰   s     r
   r‹   z'_Urllib3ConnectionPatcher.create_module¹   s   € Ø�{‰{×(Ñ(¨Ó.Ð.r   c                óP   — | j                   j                  |«       t        |«       y r    )r„   Úexec_modulerx   )r…   rw   s     r
   r�   z%_Urllib3ConnectionPatcher.exec_module¼   s   € Ø�‰×Ñ Ô'Ü(¨Õ0r   r    )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r‚   r‹   r�   rB   r   r
   rz   rz   ¦   s   „ ñó
ò/ó1r   rz   c                 ó‚  — t        t        j                  dd«      ryt        j                  dfddœd„} d| _        | t        _        t
        j                  j                  t        «      }|�t        |«       yt        d„ t
        j                  D «       «      s)t
        j                  j                  dt        «       «       yy)	u  Race IPv6/IPv4 for every sync TCP connect in the process (RFC 8305, #114265).

    The startup path does not build its HTTP clients in one place: the model catalog
    fetch goes through ``requests``/``urllib3``, sync LLM and OAuth clients through
    httpcore, plugins through ``urllib``/``http.client``. All of them funnel their TCP
    connect into ``socket.create_connection`` (``http.client`` re-reads it per connection;
    httpcore looks it up at call time) or into urllib3's own serial copy in
    ``urllib3.util.connection``. The stock implementations walk the ``getaddrinfo``
    results serially â€” on a network whose advertised IPv6 route is blackholed, each AAAA
    record burns the full connect timeout before IPv4 answers. Idempotent, best-effort.
    rn   FN)Ú
all_errorsc               ón   — |t         j                  u rt        j                  «       n|}t        | ||¬«      S )N)r?   )r,   Ú_GLOBAL_DEFAULT_TIMEOUTrp   rl   )r[   rN   r?   r“   rr   s        r
   Ú_socket_racerz<install_happy_eyeballs_socket_connect.<locals>._socket_racerÐ   s4   € ð 3:¼V×=[Ñ=[Ñ2[”F×,Ñ,Ô.Ðahˆ	ô 1°¸)ÐTbÔcÐcr   Tc              3  ó<   K  — | ]  }t        |t        «      –— Œ y ­wr    )Ú
isinstancerz   )r   Úfinders     r
   r   z8install_happy_eyeballs_socket_connect.<locals>.<genexpr>ß   s   è ø€ Ò[À6”˜FÔ$=×>Ñ[ùs   ‚r   )rM   r,   ru   r•   rn   r}   ÚmodulesÚgetr|   rx   r   r~   Úinsertrz   )r–   Úurllib3_connections     r
   Ú%install_happy_eyeballs_socket_connectrž   Á   sš   € ô Œv×'Ñ'Ð)AÀ5ÔIØä'-×'EÑ'EÐVZð dÐjoô dð ,0€MÔ(Ø,„FÔäŸ™Ÿ™Ô)CÓDÐØÐ%Ü(Ð);Õ<ÜÑ[ÌSÏ]É]Ô[Ô[Ü�‰×Ñ˜QÔ 9Ó ;Õ<ð \r   c                 ó.  — t         rt        ryt        j                  j	                  dd«       t        j                  j	                  dd«       dD ],  } t        t        t        | d«      dd«      }|€Œ"	  |dd	¬
«       Œ. day# t        t        f$ r Y ŒCw xY w)zPApply the Windows UTF-8 bootstrap once; True only when it was applied this call.FÚ
PYTHONUTF8Ú1ÚPYTHONIOENCODINGzutf-8)ÚstdoutÚstderrÚstdinNÚreconfigureÚreplace)ÚencodingÚerrorsT)	Ú_IS_WINDOWSÚ_bootstrap_appliedr4   Úenvironr   rM   r}   r.   Ú
ValueError)Ústream_namer¦   s     r
   Úapply_windows_utf8_bootstrapr¯   ã   sœ   € õ Õ,Øô ‡J�J×Ñ˜,¨Ô,Ü‡J�J×ÑÐ,¨gÔ6ð 5ò ˆÜœg¤c¨;¸Ó=¸}ÈdÓSˆØÐØð	Ù °Ö;ðð ÐØøô	 œÐ$ò 	Ùð	ús   Á3
BÂBÂBc                 ón   — t         sy	 ddl} t        | d«      r	 	 dd„}|| _        yy# t        $ r Y yw xY w)u  Stub ``platform._syscmd_ver`` on Windows â€” decode-crash + console-flash guard.

    ``platform.win32_ver()`` (reached via ``platform.platform()``, which the OpenAI SDK
    calls) shells out ``cmd /c ver`` with ``shell=True`` and no ``CREATE_NO_WINDOW``: a
    windowless parent (pythonw gateway, slash/kanban workers) flashes a console per call,
    and Python 3.11.0/3.11.1 (no ``encoding="locale"`` fix) strict-utf-8-decodes the OEM
    code page output under PEP 540 mode and raises (#69413). Returning the inputs makes
    ``win32_ver()`` fall back to ``sys.getwindowsversion()`` â€” same data, no subprocess.
    Mirrors ``hermes_cli._subprocess_compat.suppress_platform_ver_console`` for callers
    that never import ``hermes_cli.main``; double application is harmless.
    Nr   Ú_syscmd_verc                ó   — | ||fS r    rB   )ÚsystemÚreleaseÚversionÚsupported_platformss       r
   Ú_quiet_syscmd_verz8suppress_platform_ver_console.<locals>._quiet_syscmd_ver  s   € à˜w¨Ð/Ð/r   )Ú r¸   r¸   )r   Úwin16Údos)rª   ÚplatformÚhasattrr±   r"   )r»   r·   s     r
   Úsuppress_platform_ver_consoler½      sJ   € õ Øð
Ûä�8˜]Ô+ØACØ6Oó0ð $5ˆHÕ ð ,øô ò Ùðús   ‰( ¨	4³4c                ól  — | xsa t         j                  j                  d«      xs@ t         j                  j	                  t         j                  j                  t        «      «      }t        j                  D �cg c]	  }|dvsŒ|‘Œ c}t        j                  dd t         j                  j                  |«      }t        j                  D �cg c]'  }t         j                  j                  |«      |k7  sŒ&|‘Œ) c}t        j                  dd t        j                  j                  d|«       yc c}w c c}w )a‘  Stop a package in the current directory from shadowing Hermes modules.

    Hermes ships top-level modules with common names (``utils``, ``proxy``, ``ui``); a
    project with its own ``utils/`` launched from its directory would win the import.
    The cwd reaches ``sys.path`` as ``""``/``"."`` (script/``-m`` launches) AND as an
    absolute path (venv activation, PYTHONPATH), so both are handled: relative forms are
    dropped and the Hermes root is *relocated* to the front, not merely inserted when
    absent. ``src_root`` defaults to this module's directory (the repo root for every
    shipped entry point), so no spawner env var is required.
    ÚHERMES_PYTHON_SRC_ROOT)r¸   ú.Nr   )	r4   r¬   r›   r‡   ÚdirnameÚabspathÚ__file__r}   rœ   )Úsrc_rootÚrootÚpÚroot_abss       r
   Úharden_import_pathrÈ     sÇ   € ð ò ”r—z‘z—~‘~Ð&>Ó?ò Ä2Ç7Á7Ç?Á?Ü
�‰�‰œÓ!óD€Dô "Ÿh™hÖ=˜¨!°9Ò*<’1Ò=„C‡H�H‰Q€Kä�w‰w�‰˜tÓ$€HÜ!Ÿh™hÖI˜¬"¯'©'¯/©/¸!Ó*<ÀÓ*H’1ÒI„C‡H�H‰Q€KÜ‡H�H‡O�O�A�tÕùò	 >ùò Js   Á8	D,ÂD,Ã'D1Ã3D1c                 ó®   — t         j                  j                  dd«      j                  «       sy	 ddlm}  | j                  «        y# t        $ r Y yw xY w)a±  Put the durable lazy-install dir (``HERMES_LAZY_INSTALL_TARGET``) on ``sys.path``.

    Immutable Docker images seal the venv and redirect lazy installs to the data volume;
    packages installed there on a previous run must be importable before any backend
    imports its SDK. Appends to the END of ``sys.path`` so the core venv always wins name
    collisions (see ``tools.lazy_deps``). Never raises; unset target is a no-op.
    ÚHERMES_LAZY_INSTALL_TARGETr¸   Nr   ©Ú	lazy_deps)r4   r¬   r›   ÚstripÚtoolsrÌ   Úactivate_durable_lazy_targetr"   rË   s    r
   rÏ   rÏ   1  sI   € ô �:‰:�>‰>Ð6¸Ó;×AÑAÔCØðÝ#Ø×.Ñ.Õ0øÜò Ùðús   ±A Á	AÁAc                 ó>   — 	 ddl m}   | «        y# t        $ r Y yw xY w)a¼  Point ``TMPDIR``/``TMP``/``TEMP`` at ``HERMES_HOME/cache/scratch`` unless the user set them.

    System temp is tmpfs on most Linux hosts and containers; Hermes' browser profiles, PTY
    probes and every ``tempfile`` default a child script makes would eat RAM there. Runs at
    import so every entry point and every child they spawn inherits it; ``hermes_cli.main``
    re-runs it after ``--profile`` re-homes the process. Never raises.
    r   )Úexport_scratch_tmp_envN)Úhermes_constantsrÑ   r"   )Ú_exports    r
   rÑ   rÑ   B  s!   € ðÝFÙ�	øÜò Ùðús   ‚ �	›)r   úlist[tuple]ÚreturnrÔ   )rÕ   ÚNone)NrB   )r[   ztuple[str, int]rN   zfloat | Noner?   ztuple[str, int] | None)rÕ   Úboolr    )rÄ   z
str | NonerÕ   rÖ   )r‘   Ú
__future__r   r2   Úimportlib.abcr€   Úimportlib.utilr4   r7   r,   r}   rE   r»   rª   r«   rO   r|   r   r%   rl   rx   ÚabcÚMetaPathFinderÚLoaderrz   rž   r¯   r½   rÈ   rÏ   rÑ   rB   r   r
   ú<module>rÞ      sÎ   ðñõ #ã Û Û Û 	Û Û Û 
Û à�l‰l˜gÑ%€ØÐ Ø $Ð Ø6Ð óóð egð[Ø6Ló[ó|.ô"1 	§¡× <Ñ <¸i¿m¹m×>RÑ>Rô 1ó6=óDó:ô6ó,ó"ñ  Ô Ù Ô Ù Ô Ù %Ô 'Ù Õ r   