Ë
    âß²jñt  ã                  ó²  — U 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m	Z	m
Z
 g d¢ZdZ eh d£«      Zh d£Zd/d	„Zej"                  d
k(  ZdZd0d„Zd1d„ZdZdZdZd2d„Zd2d„Zd2d„Zd3d„Zd4d„ZdZddddej>                  ddddddœ
Z d5d„Z!i Z"de#d<   d6d „Z$d7d8d!„Z%d9d"„Z&d:d#„Z'd;d$„Z(dd%œd<d&„Z)d=d'„Z*d=d(„Z+d)ddd*d+œ	 	 	 	 	 	 	 	 	 	 	 	 	 d>d,„Z,d3d-„Z-d?d.„Z.y)@uŸ  Windows subprocess compatibility helpers.

* ``["npm", ...]`` â€” on Windows ``npm`` is ``npm.cmd``, a batch shim; ``Popen`` fails with
  WinError 193 because CreateProcessW can't run a ``.cmd`` without ``shell=True``/PATHEXT.
* ``start_new_session=True`` â€” POSIX ``os.setsid()`` detach; silently ignored on Windows, whose
  equivalent is the ``CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW`` creationflags bundle.
é    )ÚannotationsN)ÚMappingÚSequence)Ú
IS_WINDOWSÚresolve_node_commandÚsplit_command_lineÚsuppress_platform_ver_consoleÚwindows_detach_flagsÚ&windows_detach_flags_without_breakawayÚwindows_hide_flagsÚwindows_detach_popen_kwargsÚbounded_git_probeÚbounded_probe_runÚnoninteractive_git_envÚNO_DRIVER_DIFF_FLAGSÚpid_is_hermes)z--no-ext-diffz--no-textconv>   ÚlogÚdiffÚshowÚblame>   ú-Cú-cú	--git-dirú--exec-pathú--namespaceú--work-treec                óæ   — t        | «      }d}|t        |«      k  rU||   }|t        v r|dz  }Œ!|j                  d«      r|dz  }Œ8|t        v r!|d|dz    t        t
        «      z   ||dz   d z   S |S |S )aŠ  Copy of subcommand-first git *args* (no leading ``"git"``) with :data:`NO_DRIVER_DIFF_FLAGS`
    inserted right after a diff-rendering subcommand; other subcommands are returned unchanged.

    Pair with :func:`noninteractive_git_env`: the env layer disables fsmonitor/hooks/pager/editor/
    credential sinks, this closes the one class (attacker-named attribute drivers) env cannot reach.
    r   é   ú-é   N)ÚlistÚlenÚ_GIT_VALUE_OPTSÚ
startswithÚ_DIFF_RENDERING_SUBCOMMANDSr   )ÚargsÚoutÚiÚtoks       úB/home/ubuntu/.hermes/hermes-agent/hermes_cli/_subprocess_compat.pyÚharden_git_argvr+   4   s�   € ô ˆt‹*€CØ	€AØ
Œc�#‹hŠ,Ø�!‰fˆØ”/Ñ!Ø�‰FˆAØØ�>‰>˜#ÔØ�‰FˆAØØÔ-Ñ-Ø�w˜˜Q™�<¤$Ô';Ó"<Ñ<¸sÀ1ÀqÁ5À7¸|ÑKÐKØˆ
Ø€Jó    Úwin32Ú_HERMES_GATEWAY_BREAKAWAYc                óÜ   — ddl }t        s|j                  | «      S g }|j                  | d¬«      D ]8  }t        |«      dk\  r|d   |d   k(  r|d   dv r|dd }|j	                  |«       Œ: |S )	u®  Split a user-supplied command line into tokens, Windows-safely.

    ``shlex.split`` (posix=True) treats every backslash as an escape, mangling Windows paths. On
    Windows use ``posix=False`` and strip one layer of matching quotes per token; on POSIX this is
    exactly ``shlex.split``. Raises ValueError on unbalanced quotes.

    ``shlex.split(line)`` (posix=True) treats every backslash as an escape character, so Windows paths are
    silently mangled: ``C:\Users\me\out.txt`` becomes ``C:Usersmeout.txt`` â€” no error, just a wrong path
    that then "succeeds" against a mangled relative filename (#83934) or makes a valid hook script report
    "not executable" (#78293).
    r   NF)Úposixr   éÿÿÿÿ)ú'ú"r    )Úshlexr   Úsplitr"   Úappend)Úliner4   r'   r)   s       r*   r   r   Q   s|   € ó åØ�{‰{˜4Ó Ð Ø€CØ�{‰{˜4 uˆ{Ó-ò ˆÜˆs‹8�qŠ=˜S ™V s¨2¡wÒ.°3°q±6¸ZÑ3GØ�a˜�)ˆCØ�
‰
�3�ðð €Jr,   c                ó>   — t        j                  | «      }|xs | g|¢S )uA  Resolve a Node-ecosystem command name (``npm``, ``npx``, ``yarn``â€¦) to an absolute-path argv.

    On Windows these ship as ``.cmd`` batch shims that CreateProcessW won't execute by bare name;
    ``shutil.which`` resolves via PATHEXT to a fully-qualified path whose extension routes it
    through ``cmd.exe /c``.
    )ÚshutilÚwhich)ÚnameÚargvÚresolveds      r*   r   r   i   s%   € ô �|‰|˜DÓ!€HØÒ˜Ð$˜tÐ$Ð$r,   i   i   i   c                 ó8   — t         syt        t        z  t        z  S )u´  Win32 creationflags detaching a child from the parent console/group; 0 elsewhere.

    Pair with the default ``start_new_session=False`` (POSIX uses ``start_new_session=True``).
    CREATE_NEW_PROCESS_GROUP stops Ctrl+C propagating; CREATE_NO_WINDOW gives the child a hidden
    console descendants (git, gh, cmd, node, â€¦) inherit so they don't flash â€” deliberately replacing
    the old DETACHED_PROCESS approach, which re-created the per-descendant console-flash bug
    (#54220/#56747) at every spawn; CREATE_BREAKAWAY_FROM_JOB escapes Electron/Tauri job objects. A
    job that forbids breakaway yields PermissionError from Popen â€” callers catch OSError and fall
    back to :func:`windows_detach_flags_without_breakaway`.

    Rationale: This both detaches it from the parent's console lifetime (closing the launching terminal
    doesn't CTRL_CLOSE it) AND gives every console-subsystem descendant (git, gh, cmd, node, â€¦) a console to
    inherit, so they don't allocate visible flashing ones. This deliberately replaces the old
    ``DETACHED_PROCESS`` approach: MSDN specifies CREATE_NO_WINDOW is *ignored* when combined with
    DETACHED_PROCESS, and a truly console-less daemon re-creates the per-descendant console-flash bug
    (#54220/#56747) at every spawn â€” see the note on ``_DETACHED_PROCESS`` above. Electron (Desktop app) and
    Tauri (bootstrap installer) wrap their children in job objects; without breakaway, those children die
    when the parent process exits even though they have their own console. This was the missing flag that
    made the post-update gateway respawn watcher silently die alongside the Tauri updater after the Electron
    Desktop's update flow finished.
    r   )r   Ú_CREATE_NEW_PROCESS_GROUPÚ_CREATE_NO_WINDOWÚ_CREATE_BREAKAWAY_FROM_JOB© r,   r*   r
   r
   ˆ   s   € õ, ØÜ$Ô'8Ñ8Ô;UÑUÐUr,   c                 ó*   — t         syt        t        z  S )zS:func:`windows_detach_flags` minus ``CREATE_BREAKAWAY_FROM_JOB``; 0 on non-Windows.r   )r   r?   r@   rB   r,   r*   r   r   £   s   € åØÜ$Ô'8Ñ8Ð8r,   c                 ó   — t         rt        S dS )aX  Win32 creationflags hiding the child's console without detaching it; 0 elsewhere.

    For short-lived synchronous helpers (``taskkill``, ``where``, version probes): no flash, but the
    child stays in the parent's process group and job so Ctrl+C and job teardown still propagate.
    Stdio is inherited, so ``capture_output=True`` works.
    r   )r   r@   rB   r,   r*   r   r   ª   s   € õ !+ÔÐ1°Ð1r,   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 so it never flashes a console. No-op elsewhere.

    ``platform.win32_ver()`` shells out ``cmd /c ver`` without CREATE_NO_WINDOW, so a windowless
    parent (pythonw gateway, kanban workers) flashes a cmd window whenever a dependency touches
    ``platform.uname()`` at import. With the stub, ``win32_ver()`` takes its documented fallback to
    ``sys.getwindowsversion()`` â€” same data, in-process. Call before heavy imports.
    Nr   Ú_syscmd_verc                ó   — | ||fS ©NrB   )ÚsystemÚreleaseÚversionÚsupported_platformss       r*   Ú_quiet_syscmd_verz8suppress_platform_ver_console.<locals>._quiet_syscmd_verÂ   s   € à˜w¨Ð/Ð/r,   )Ú rN   rN   )r-   Úwin16Údos)r   ÚplatformÚhasattrrF   Ú	Exception)rQ   rM   s     r*   r	   r	   ´   sJ   € õ Øð
Ûä�8˜]Ô+ØACØ6Oó0ð $5ˆHÕ ð ,øô ò Ùðús   ‰( ¨	4³4c                 ó.   — t         rdt        «       iS ddiS )zòPopen kwargs detaching a child on Windows, or ``start_new_session=True`` on POSIX.

    Bare ``start_new_session=True`` is accepted but has no effect on Windows: the child stays
    attached to the parent console and dies when it closes.
    ÚcreationflagsÚstart_new_sessionT)r   r
   rB   r,   r*   r   r   Ë   s!   € õ ØÔ!5Ó!7Ð8Ð8Ø Ð&Ð&r,   )ÚGIT_CONFIG_KEY_ÚGIT_CONFIG_VALUE_rN   ÚfalseÚcatÚtruezssh -o BatchMode=yes)
zcredential.helperzcore.askPasszcore.fsmonitorzcore.untrackedCachezcore.hooksPathz
core.pagerzcore.editorzsequence.editorzdiff.externalzcore.sshCommandc                ó¸  — | j                  dd«      }| j                  d«      xs  t        j                  j                  |d«      }| j                  d«      xs d| j                  d«      xs  t        j                  j                  |d«      t        j                  j                  |d	d
«      f}g }|D ]1  }	 |j	                  t        j
                  |«      j                  «       Œ3 | j                  d«      | j                  d«      | j                  d«      || j                  d«      | j                  d«      g|¢­S # t        $ r |j	                  d«       Y Œ¦w xY w)z±Everything that decides which files ``git config --system/--global`` reads, plus the
    global candidates' mtimes so an edit to ``~/.gitconfig`` is picked up without a restart.ÚHOMErN   ÚXDG_CONFIG_HOMEz.configÚGIT_CONFIG_SYSTEMz/etc/gitconfigÚGIT_CONFIG_GLOBALz
.gitconfigÚgitÚconfigNÚGIT_CONFIG_NOSYSTEMÚPATH)ÚgetÚosÚpathÚjoinr6   ÚstatÚst_mtime_nsÚOSError)ÚenvÚhomeÚxdgÚ
candidatesÚstampsrg   s         r*   Ú_safe_directory_cache_keyrq   ë   s*  € ð �7‰7�6˜2Ó€DØ
�'‰'Ð#Ó
$Ò
E¬¯©¯©°T¸9Ó(E€Cà�‰Ð#Ó$Ò8Ð(8Ø�‰Ð#Ó$ÒH¬¯©¯©°T¸<Ó(HÜ
�‰�‰�S˜% Ó*ð€Jð
 €FØò  ˆð	 Ø�M‰Mœ"Ÿ'™' $›-×3Ñ3Õ4ð ð 	�‰Ð#Ó$ c§g¡gÐ.AÓ&BÀCÇGÁGÐLaÓDbØˆc�g‰gÐ'Ó(¨#¯'©'°&«/ðà<Bñð øô ò 	 Ø�M‰M˜$Öð	 ús   Â6.D<Ä<EÅEzdict[tuple, list[str]]Ú_safe_directory_cachec                ó¤  — t        | «      }t        j                  |«      }|�t        |«      S t	        | «      }t        |«      D ]/  }|dk(  s|j                  t        «      sŒ|j                  |d«       Œ1 |j                  dd«       d|d<   g }dD ]‹  }	 t        j                  dd|d	d
dgdddddt        j                  |d¬«	      }|j                  dk7  rŒF|j                  j                  d«      }|r|d   dk(  r|j                  «        |j!                  |«       Œ� t        |«      t        |<   |S # t        t        j                  f$ r Y Œ½w xY w)am  The user's configured ``safe.directory`` values, in git's own effective order.

    Read with ``git config -z --get-all`` under *base_env* (the caller's untouched environment) so
    an explicit ``GIT_CONFIG_GLOBAL``/``GIT_CONFIG_SYSTEM`` still points at the file the user means.
    Best-effort: any failure (git missing, malformed config, timeout) yields no entries and leaves
    the caller exactly as it behaved before. Memoised per process on the inputs that select the
    config files (and the global file's mtime): ``noninteractive_git_env()`` runs on every internal
    git call, including the startup banner probe, and two ``git config`` children per call is
    ~10 ms against ~0.2 ms for the rest of the function.

    ``safe.directory`` is an *ordered* multi-valued setting and an empty value resets every entry
    seen so far, so a user can revoke a system-wide ``safe.directory=*`` and then name only the
    repositories they actually trust. Order and empty resets are therefore policy, not formatting:
    scopes are read lowest-precedence first (system, then global) and every value is preserved
    verbatim -- no de-duplication (it is a sequence, not a set) and no dropping of the reset
    marker, either of which would resurrect a revoked wildcard and widen trust. ``-z`` keeps a
    value containing whitespace or a newline as the single entry git reads it as.
    NÚGIT_CONFIG_PARAMETERSÚGIT_CONFIG_COUNTÚ0ÚGIT_TERMINAL_PROMPT)z--systemz--globalra   rb   z-zz	--get-allúsafe.directoryTúutf-8Úreplaceé   F)Úcapture_outputÚtextÚencodingÚerrorsÚtimeoutÚstdinrl   Úcheckr   ú r1   rN   )rq   rr   re   r!   Údictr$   Ú_GIT_CONFIG_INJECT_PREFIXESÚpopÚ
subprocessÚrunÚDEVNULLrk   ÚSubprocessErrorÚ
returncodeÚstdoutr5   Úextend)	Úbase_envÚ	cache_keyÚcachedrl   ÚkeyÚvaluesÚscopeÚprocÚrecordss	            r*   Ú_user_safe_directoriesr–     sX  € ô& *¨(Ó3€IÜ"×&Ñ& yÓ1€FØÐÜ�F‹|ÐÜ
ˆx‹.€Cä�C‹yò ˆØÐ)Ò)¨S¯^©^Ô<WÕ-XØ�G‰G�C˜Õðð ‡G�GÐ Ô%Ø!$€CÐÑØ€FØ)ò ˆð	Ü—>‘>Ø˜ %¨¨{Ð<LÐMØ#¨$¸ÈØ¤×!3Ñ!3¸ÀEôˆDð �?‰?˜aÒØð —+‘+×#Ñ# DÓ)ˆÙ�w˜r‘{ bÒ(Ø�K‰KŒMØ�‰�gÕð!ô" (,¨F£|Ô˜)Ñ$Ø€Møô œ×3Ñ3Ð4ò 	Ùð	ús   Â2D3Ä3EÅEc                ó„  — t        | �| nt        j                  «      }t        | �| nt        j                  «      }d|d<   d|d<   t	        |«      D ]/  }|dk(  s|j                  t        «      sŒ|j                  |d«       Œ1 |j                  dd«       t        j                  |d<   t        j                  |d	<   d
|d<   d|d<   d|d<   d|d<   t	        t        j                  «       «      }|j                  d„ |D «       «       t        t        |«      «      |d<   t        |«      D ]  \  }\  }}||d|› �<   ||d|› �<   Œ |S )uu  Environment for *internal* git invocations that must never prompt.

    Copy of ``base`` (default ``os.environ``) with ``GIT_TERMINAL_PROMPT=0`` (fail instead of
    prompting), ``GCM_INTERACTIVE=Never`` (no Git Credential Manager dialog), and isolated git
    config: inherited ``GIT_CONFIG_*`` injection, global/system config, pagers, editors, fsmonitor,
    external diff and hooks are all disabled so a user's repo/global config cannot hang or mutate
    Hermes's plumbing calls. ``core.sshCommand`` is pinned to ``ssh -o BatchMode=yes`` so the ssh
    child of a fetch/ls-remote fails instead of prompting â€” ssh bypasses ``stdin=DEVNULL`` and
    opens ``/dev/tty`` directly (#104591); an agent-authenticated ssh still succeeds, and an
    explicit user ``GIT_SSH_COMMAND`` env var still takes precedence over this config-layer pin.
    ``GIT_ASKPASS``/``SSH_ASKPASS`` env vars are left alone, but OpenSSH BatchMode disables
    passphrase/password prompts, including SSH askpass. Usable keys and ssh-agent authentication
    still work; Git's own working askpass helper is unaffected. Pair with
    ``stdin=subprocess.DEVNULL``. Internal plumbing only â€” the agent-facing terminal tool has its
    own policy layer and visible PTY.

    Hermes shells out to git from many non-interactive contexts â€” MCP catalog installs, plugin
    install/update, profile distribution staging, worktree base fetches, desktop review-pane fetch/push.
    When the remote is private, misconfigured, or requires auth, git's default behavior is to prompt on the
    inherited terminal (or via an askpass helper), which silently hangs the operation until its timeout â€” or
    forever at call sites without one. Ported from openai/codex#34540 / #34612 ("detach non-interactive
    subprocesses from stdin"): a background tool invocation must fail fast with a readable error, not wait
    for input nobody can type.
    Nrv   rw   ÚNeverÚGCM_INTERACTIVErt   ru   r`   r_   Ú1rc   rZ   Ú	GIT_PAGERÚPAGERr[   Ú
GIT_EDITORc              3  ó$   K  — | ]  }d |f–— Œ
 y­w)rx   NrB   )Ú.0Úvalues     r*   ú	<genexpr>z)noninteractive_git_env.<locals>.<genexpr>o  s   è ø€ ÒM°5Ð&¨Ô.ÑMùs   ‚rW   rX   )r„   rf   Úenvironr–   r!   r$   r…   r†   ÚdevnullÚ_GIT_CONFIG_OVERRIDESÚitemsr�   Ústrr"   Ú	enumerate)Úbaserl   Úsafe_directoriesr‘   Ú	overridesÚidxr    s          r*   r   r   8  s\  € ô2 �tÐ'‰t¬R¯Z©ZÓ
8€Cô .°dÐ6F©dÌBÏJÉJÓWÐØ!$€CÐÑØ$€CÐÑô �C‹yò ˆØÐ)Ò)¨S¯^©^Ô<WÕ-XØ�G‰G�C˜Õðð ‡G�GÐ Ô%Ü!Ÿz™z€CÐÑÜ!Ÿz™z€CÐÑØ!$€CÐÑØ€CˆÑØ€Cˆ�LØ€CˆÑÜÔ*×0Ñ0Ó2Ó3€Ið ×ÑÑMÐ<LÔMÔMÜ!¤# i£.Ó1€CÐÑÜ& yÓ1ò /Ñˆ‰\ˆc�5Ø'*ˆˆo˜c˜UÐ#Ñ$Ø).ˆÐ ˜uÐ%Ò&ð/ð €Jr,   c                ó>   — 	 ddl m}  || «      S # t        $ r Y yw xY w)z@The repository's stable process-start fingerprint, if available.r   )Úget_process_start_timeN)Úgateway.statusr­   rS   )Úpidr­   s     r*   Ú_process_start_timer°   w  s'   € ðÝ9á% cÓ*Ð*øÜò Ùðús   ‚ �	›c                ój   — t        d„ t        j                  d| j                  «       «      D «       «      S )u	  True when *text* names Hermes at a path-segment / token boundary.

    A bare ``"hermes" in text`` substring test would also match unrelated processes whose paths
    merely contain the letters (``...\shermesa\...``) â€” the false-positive class this prevents.
    c              3  ó>   K  — | ]  }|j                  d «      –— Œ y­w))Úhermesz.hermesN)r$   )rŸ   Útokens     r*   r¡   z%_text_names_hermes.<locals>.<genexpr>‡  s&   è ø€ ò GØð ×ÑÐ 5×6ñ Gùs   ‚z[\\/\s=,;\"']+)ÚanyÚrer5   Úlower)r}   s    r*   Ú_text_names_hermesr¸   �  s4   € ô ñ GÜŸH™HÐ%6¸¿
¹
»ÓEôGó Gð Gr,   c                óÚ   — 	 ddl }|j                  | «      }dj                  |j                  «       xs g «      }|j	                  «       xs d}t        |› d|› �«      S # t        $ r Y yw xY w)z8Best-effort check that *pid* currently runs Hermes code.r   Nú rN   F)ÚpsutilÚProcessrh   ÚcmdlineÚexer¸   rS   )r¯   r»   ÚprocessÚcommandÚ
executables        r*   Ú_process_command_is_hermesrÂ   ‹  sj   € ðÛà—.‘. Ó%ˆØ—(‘(˜7Ÿ?™?Ó,Ò2°Ó3ˆØ—[‘[“]Ò( bˆ
Ü! W I¨Q¨z¨lÐ";Ó<Ð<øÜò Ùðús   ‚AA Á	A*Á)A*)Úexpected_start_timec               ó  — t        | t        «      rt        | t        «      s| dk  ryt        s|€y	 t	        | «      |k(  S 	 t	        | «      }|€y|�||k7  ry	 t        | «      S # t
        $ r Y yw xY w# t
        $ r Y yw xY w# t
        $ r Y yw xY w)aA  Whether it is safe to use ``taskkill`` for *pid*.

    The PID must be valid, currently exist, and identify a Hermes process. When the caller captured
    a start-time fingerprint before the destructive action, the live process must still have the
    same ``(pid, start_time)`` identity. Any ambiguity fails closed.
    r   FT)Ú
isinstanceÚintÚboolr   r°   rS   rÂ   )r¯   rÃ   Úcurrent_start_times      r*   r   r   ˜  s¹   € ô �cœ3Ô¤:¨c´4Ô#8¸CÀ1ºHØÝØÐ&Øð	Ü& sÓ+Ð/BÑBÐBðÜ0°Ó5Ðð Ð!ØØÐ&Ð+=ÐATÒ+TØðÜ)¨#Ó.Ð.øô ò 	Ùð	ûô ò Ùðûô ò Ùðús5   ±A" Á A1 Á
B  Á"	A.Á-A.Á1	A=Á<A=Â 	BÂBc                óª   — 	 ddl m}  || j                  «       	 | j                  «        y# t        $ r t	        | «       Y yw xY w# t        $ r Y yw xY w)ue  Best-effort terminate *proc* and its descendants on both platforms; never raises.

    ``proc.kill()`` alone only terminates the direct child. This is cleanup on an already-failing
    path whose contract is to fail open, so every failure (access denied, already reaped) is
    swallowed rather than escaping the caller's ``except``.

    On Windows a suspended descendant (e.g. ``git.exe``) can survive holding duplicates of the captured pipe
    handles, which keeps the pipes from reaching EOF and leaks two reader threads + the process per fired
    timeout â€” ``taskkill /T /F`` takes the whole tree down so the bounded drain that follows can actually
    reach EOF. On POSIX the same class exists: killing the launcher leaves descendants (credential helpers,
    ``git-remote-https``, hook children) running and holding the pipe write ends. Callers spawn the child in
    its own process group (``process_group=0``, Python â‰¥3.11), so when â€” and only when â€” the child leads its
    own group (``pgid == pid``), the entire group is signalled with ``os.killpg``. The ownership check means
    a fallback spawn that shares our group can never cause us to kill unrelated processes. Ported from
    openai/codex#36793 ("Terminate timed-out Git process trees"); generalized for the shell-hook runner via
    openai/codex#37527 ("Terminate timed-out hook process trees").
    r   )Úkill_process_treeN)Úagent.deadlinerÊ   r¯   rS   Ú_legacy_kill_process_treeÚkillrk   )r”   Ú_deadline_kill_trees     r*   rÊ   rÊ   ¶  sS   € ð$ÝKá˜DŸH™HÔ%ð
Ø�	‰	�øô ò Ü! $Ô'Ùðûô ò Ùðús    ‚, ›A ¬AÁAÁ	AÁAc           
     ó  — t         sS	 ddl}t        j                  | j                  «      }|| j                  k(  r t        j
                  ||j                  «       	 | j                  «        t         rh	 t        j                  ddddt        | j                  «      gt        j                  t        j                  t        j                  ddt        «       ¬	«       yy# t        $ r Y Œ‹w xY w# t        $ r Y Œ‰w xY w# t        $ r Y yw xY w)
zULocal tree-kill fallback when agent.deadline is unavailable (partial install, cycle).r   NÚtaskkillz/Tz/Fz/PIDr   F)rŒ   Ústderrr�   r€   r‚   rU   )r   Úsignalrf   Úgetpgidr¯   ÚkillpgÚSIGKILLrS   rÍ   rk   r‡   rˆ   r¦   r‰   r   )r”   Ú_signalÚpgids      r*   rÌ   rÌ   Ö  sÙ   € åð	Û$ä—:‘:˜dŸh™hÓ'ˆDØ�t—x‘xÒÜ—	‘	˜$ §¡Ô0ðØ�	‰	Œõ ð	Ü�N‰N˜J¨¨d°F¼CÀÇÁ»MÐJÜ",×"4Ñ"4¼Z×=OÑ=OÜ!+×!3Ñ!3¸QÀeÜ);Ó)=ö?ð	 øô ò 	Ùð	ûô ò Ùðûô ò 	Ùð	ús7   ˆAC ÁC) Á2A&C8 Ã	C&Ã%C&Ã)	C5Ã4C5Ã8	DÄDrz   F)r   rl   ÚcwdÚraise_on_spawn_failurec               ó6  — t         rdt        «       inddi}d}	 ddlm}  |t	        | «      ft
        j                  t
        j                  t
        j                  dd||�t        |«      nd|dœ|¤Ž\  }	}	 |	j                  |¬	«      \  }
}t        |«       t        j                  t	        | «      |	j                  |
|«      S # t        $ r |r‚ Y yw xY w# t        $ r< t        |«       t        |	«       	 |	j                  d
¬	«       Y y# t        $ r Y Y yw xY ww xY w)u
  Deadlock-safe ``subprocess.run(argv, capture_output=True, timeout=â€¦)`` for fail-open probes.

    Returns a ``CompletedProcess`` when the child finished within *timeout* (any exit code), or
    ``None`` on spawn failure or timeout. With ``raise_on_spawn_failure=True`` the ``Popen``
    exception propagates instead, so callers that treat a *timeout* as a verdict can still tell
    "our own probe never started" apart from "the child hung".

    Why not ``subprocess.run``: on Windows, ``run()``'s post-timeout cleanup calls an *unbounded*
    ``communicate()`` after killing the direct child. Killing it can leave a descendant (``git.exe`` under a
    launcher shim, ``conhost.exe`` under wmic/powershell) holding duplicates of the captured stdout/stderr
    handles, so the pipes never reach EOF and the reader-thread join blocks forever. The wmic /
    ``Get-CimInstance Win32_Process`` gateway scan hit exactly this during ``hermes update`` on slow-WMI
    machines (#87134); the git probes hit it first (#68609 / #66037).
    rU   Úprocess_groupr   N)Úspawn_serverTry   )rŒ   rÑ   r�   r}   r~   r   rl   rØ   )r€   r    )r   r   Ú"hermes_cli.local_runtime.processesrÜ   r!   r‡   ÚPIPEr‰   r„   rS   ÚcommunicateÚ
_close_jobrÊ   ÚCompletedProcessr‹   )r<   r€   r   rl   rØ   rÙ   Ú_popen_kwargsÚjobrÜ   r”   rŒ   rÑ   s               r*   r   r   ò  s4  € õ& FP˜?Ô,>Ó,@ÑAÐVeÐghÐUi€MØ
€Cðõ
 	Dá Ü�‹JðRÜ)Ÿ™´z·±Ìj×N`ÑN`Ø °Ø ˜_”�S”	°$¸CñRð DQñR‰	ˆˆcðØ×)Ñ)°'Ð)Ó:‰ˆ�ô ˆs„OÜ×&Ñ&¤t¨D£z°4·?±?ÀFÈFÓSÐSøô% ò Ù!ØÙðûô ò 	ô 	�3ŒÜ˜$Ôð	Ø×Ñ QÐÔ'ñ øô ò 	ØÙð	úð	ús<   šAC Á6C ÃCÃCÃDÃ3DÄ	DÄDÄDÄDc                óJ   — | €y 	 | j                  «        y # t        $ r Y y w xY wrH   )ÚcloserS   )rã   s    r*   rà   rà   '  s*   € Ø
€{ØðØ�	‰	�øÜò Ùðús   … –	"¡"c               óŽ   — t        | |t        «       ¬«      }|�|j                  dk7  ry|j                  xs dj	                  «       S )uÀ  Run a short ``git`` probe and return stripped stdout, or ``""`` on ANY failure.

    On Windows ``run()``'s post-timeout cleanup calls an unbounded ``communicate()``; a suspended
    descendant git.exe holding the pipe handles then blocks forever. Here: bounded ``communicate``,
    tree-kill plus a 1s drain, then abandon the pipes; on POSIX the probe gets its own process
    group so cleanup also takes down credential/remote helpers.

    Security (GHSA-7x36-8jrh-v4pw): these probes run automatically against whatever directory the
    session sits in, before any tool call or trust prompt, and an index refresh executes the
    repo-configured ``core.fsmonitor`` program. Every probe therefore runs under
    :func:`noninteractive_git_env`; diff-rendering callers additionally pass
    :data:`NO_DRIVER_DIFF_FLAGS` (attribute-scoped drivers can't be disabled via env).

    Killing the PATH-resolved launcher can leave a suspended descendant ``git.exe`` holding duplicates of
    the captured stdout/stderr handles, so the pipes never reach EOF and the reader-thread join blocks
    forever. On the Desktop agent-build path (``_start_agent_build â†’ _session_info â†’ branch() â†’ run_git``)
    that turned an optional branch label into ``agent initialization timed out`` (issues #68609 / #66037).
    The normal-path spawn contract mirrors the previous ``run`` call byte-for-byte: PIPE/PIPE/DEVNULL,
    ``text`` with UTF-8 ``errors="replace"`` decoding, and the hidden-window ``creationflags`` on Windows
    only. On POSIX the probe is additionally placed in its own process group (``process_group=0``, Python
    â‰¥3.11) so timeout cleanup can take down descendants â€” credential helpers, ``git-remote-https``, hook
    children â€” with the launcher instead of orphaning them (see :func:`kill_process_tree`; port of
    openai/codex#36793). ``process_group`` only changes which group the child belongs to; it does not detach
    the terminal or alter the fast path.
    )r€   rl   r   rN   )r   r   r‹   rŒ   Ústrip)r<   r€   Úresults      r*   r   r   0  sC   € ô4 ˜t¨WÔ:PÓ:RÔS€FØ€~˜×*Ñ*¨aÒ/ØØ�M‰MÒ˜R×&Ñ&Ó(Ð(r,   )r&   úSequence[str]Úreturnú	list[str])r7   r¦   rê   rë   )r;   r¦   r<   ré   rê   rë   )rê   rÆ   )rê   ÚNone)rê   r„   )rl   ú'Mapping[str, str]'rê   Útuple)rŽ   rí   rê   rë   rH   )r¨   ú'Mapping[str, str] | None'rê   zdict[str, str])r¯   rÆ   rê   ú
int | None)r}   r¦   rê   rÇ   )r¯   rÆ   rê   rÇ   )r¯   rÆ   rÃ   rð   rê   rÇ   )r”   z'subprocess.Popen'rê   rì   )r<   ré   r€   Úfloatr   r¦   rl   rï   rØ   z'str | os.PathLike[str] | None'rÙ   rÇ   rê   z)'subprocess.CompletedProcess[str] | None')r<   ré   r€   rñ   rê   r¦   )/Ú__doc__Ú
__future__r   rf   r¶   r9   r‡   ÚsysÚtypingr   r   Ú__all__r   Ú	frozensetr%   r#   r+   rQ   r   Ú_WINDOWS_GATEWAY_BREAKAWAY_ENVr   r   r?   r@   rA   r
   r   r   r	   r   r…   r£   r¤   rq   rr   Ú__annotations__r–   r   r°   r¸   rÂ   r   rÊ   rÌ   r   rà   r   rB   r,   r*   ú<module>rú      s}  ðòõ #ã 	Û 	Û Û Û 
ß $ò€ð. :Ð ñ (Ò(HÓIÐ ò Y€óð. �\‰\˜WÑ$€
ð "=Ð óó0%ð 'Ð ð Ð ð
 (Ð óVó69ó2óó.'ð GÐ àØØØ"Ø—j‘jØØØØð
 .ñÐ ó$ð, 13Ð Ð-Ó 2ó1ôh<ó~óGó
ð BFõ ó<ó@ð: ;DØ&*ÐSWØ#(ñ2TØ
ð2TØ%*ð2TØ47ð2Tà	#ð2Tà1Pð2Tð !ð2Tð /ó	2Tójô)r,   