
    sj                        d 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ddl	m
Z
 ddlmZmZ ddlmZ ddlZ ej        e          Z eh d          ZdXded	ed
efdZdYded	ed
efdZde
d
dfdZde
d
dfdZde
ddd
dfdZde
ddd
dfdZej        dk    Z eh d          Z dZ!dZ"dZ#de$d
efdZ%ded ed
dfd!Z&ded ed
dfd"Z'd#eee
f         d$eee
f         d
efd%Z(d&d'ddd(deee
f         d)ed*ed+ed,ed-dd
dfd.Z)d/dd0deee
f         d1ed2e*de*dz  d3ed
dfd4Z+ddd5deee
f         d6ed7ej,        dz  d
efd8Z- G d9 d:ej.                  Z/ddddd;deee
f         d1ed<ed=ed>edz  d-dd
dfd?Z0deee
f         d@eded
dfdAZ1deee
f         dBe2d
dfdCZ3dZdDed	ed
efdEZ4da5dF Z6dGed
efdHZ7d[dIed	e*d
e*fdJZ8d\dIed	e9d
e9fdLZ:dXdIed	ed
efdMZ;dNZ<dOedz  d
edz  fdPZ=d]dQZ>dRed
efdSZ?dTed
efdUZ@dRedVed
efdWZAdS )^z*Shared utility functions for hermes-agent.    N)Path)AnyUnion)urlparse>   1onyestrueFvaluedefaultreturnc                     | |S t          | t                    r| S t          | t                    r-|                                                                 t
          v S t          |           S )zDCoerce bool-ish values using the project's shared truthy string set.)
isinstanceboolstrstriplowerTRUTHY_STRINGS)r   r   s     )/home/agent/.hermes/hermes-agent/utils.pyis_truthy_valuer      s`    }% % 7{{}}""$$66;;     namec                 J    t          t          j        | |          d          S )zBReturn True when an environment variable is set to a truthy value.Fr   r   osgetenv)r   r   s     r   env_var_enabledr   "   s!    29T733UCCCCr   pathz
int | Nonec                     	 |                                  r+t          j        |                                 j                  ndS # t          $ r Y dS w xY w)zBCapture the permission bits of *path* if it exists, else ``None``.N)existsstatS_IMODEst_modeOSError)r    s    r   _preserve_file_moder'   '   sV    48KKMMKt|DIIKK/000tK   tts   A A 
AAztuple[int, int] | Nonec                     t           j        dk    rdS 	 |                                 }n# t          $ r Y dS w xY w|j        |j        fS )zACapture the owning uid/gid of *path* if the platform supports it.posixN)r   r   r#   r&   st_uidst_gid)r    sts     r   _preserve_file_ownerr-   /   sY    	w'tYY[[   tt9bis   ) 
77ownerc                     |t          t          d          sdS 	 t          j        | |d         |d                    dS # t          $ r Y dS w xY w)a  Re-apply uid/gid after an atomic replace when permitted.

    Docker and NAS-backed installs often run some commands as root while the
    persistent volume is owned by the runtime user. ``os.replace`` swaps in the
    temp file's owner, so a root-run config write can leave ``config.yaml`` owned
    by root. Best-effort chown preserves the existing owner for privileged
    callers and is harmless for unprivileged callers that cannot chown.
    Nchownr      )hasattrr   r0   r&   )r    r.   s     r   _restore_file_ownerr3   :   se     }GB00}
uQxq*****   s   "? 
AAmodec                 \    |dS 	 t          j        | |           dS # t          $ r Y dS w xY w)a  Re-apply *mode* to *path* after an atomic replace.

    ``tempfile.mkstemp`` creates files with 0o600 (owner-only).  After
    ``os.replace`` swaps the temp file into place the target inherits
    those restrictive permissions, breaking Docker / NAS volume mounts
    that rely on broader permissions set by the user.  Calling this
    right after ``os.replace`` restores the original permissions.
    N)r   chmodr&   )r    r4   s     r   _restore_file_moder7   K   sM     |
t   s    
++nt>          !      g{Gz?g?excc                 @    t           ot          | dd          t          v S )uH  Return True for Windows rename failures a retry might clear.

    Only a *candidate* classification: ``ERROR_ACCESS_DENIED`` covers both a
    concurrent handle and a real ACL denial, and the two are not reliably
    distinguishable up front.  Probing the target with ``os.access`` does not
    work — ``os.replace`` needs delete-child rights on the *parent directory*,
    so a directory-level denial reports the target as writable.  Instead of
    guessing, both cases enter the same bounded retry and a genuine denial
    falls through to the caller with its original error.
    winerrorN)_IS_WINDOWSgetattr!_WINDOWS_CONTENDED_REPLACE_ERRORS)r=   s    r   #_is_contended_windows_replace_errorrC      s'      73
D99) r   tmp_str	real_pathc                    t          | d          5 }|                                }ddd           n# 1 swxY w Y   t          j        t	          t          dd          z  }t          j         ||          }	 t          j        |dt          j                   d}|t          |          k     r3|t          j        |||d                   z  }|t          |          k     3t          j	        |t          |                     	 t          j
        |           n# t          $ r Y nw xY wt          j        |           n# t          j        |           w xY wt          j        |            dS )u  Overwrite *real_path* with the contents of *tmp_str*, in place.

    Last-resort path for a target whose handle is still held after the retry
    budget: writing through the existing file works where renaming onto it
    does not.  Unlike ``shutil.copyfile`` this never truncates the target to
    zero first — a concurrent reader would otherwise be able to observe an
    empty ``auth.json`` / ``gateway_state.json`` mid-write (measured: a
    4-thread poller sees a 0-byte read during a plain copyfile).  A single
    ``os.write`` of the full payload followed by ``ftruncate`` keeps the
    visible content going straight from old to new.

    This is still not atomic — it is a strictly smaller window than a copy,
    not the absence of one — so it runs only after the rename has genuinely
    failed.  Writing through the target also preserves its ACL, which
    ``os.replace`` does not (the temp file's inherited ACL wins there).
    rbNO_BINARYr   )openreadr   O_WRONLYrA   lseekSEEK_SETlenwrite	ftruncatefsyncr&   closeunlink)rD   rE   srcdataflagsfdwrittens          r   _rewrite_in_placerY      s   " 
gt		 xxzz              K'"j!444E	E	"	"B
Q$$$D		!!rxDN333G D		!!
RT###	HRLLLL 	 	 	D	 	Igs=   2666B
D; D D; 
D# D; "D##D; ;Ec                 f   t          j        | |           	 t          j        | |           n# t          $ r Y nw xY w	 t	          |d          5 }t          j        |                                           ddd           n# 1 swxY w Y   n# t          $ r Y nw xY wt          j        |            dS )zCCopy/fsync/unlink fallback for cross-device and bind-mount renames.rG   N)	shutilcopyfilecopystatr&   rI   r   rQ   filenorS   )rD   rE   fs      r   _copy_fallbackr`      s   
OGY'''++++   )T"" 	!aHQXXZZ   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!   IgsA   - 
::B 'B5B BB B	B 
BBtmp_pathtargetc                    t          |          }t          j                            |          rt          j                            |          n|}t          |           }	 t          j        ||           |S # t          $ rx}t          |          }|j        t          j	        t          j
        fvr|s |rddlm} t          dt          dz             D ]}t          j         ||t"          t$                               	 t          j        ||           |c cY d}~S # t          $ rE}	|	j        t          j	        t          j
        fv r
|	}d}Y d}	~	 nt          |	          s |	}Y d}	~	d}	~	ww xY wt&                              d||t+          |dd          p+t          j                            |j        pd|j                  |rd	nd
           |rt1          ||           nt3          ||           Y d}~nd}~ww xY w|S )u  Atomically move *tmp_path* onto *target*, preserving symlinks.

    ``os.replace(tmp, target)`` atomically swaps ``tmp`` into place at
    ``target``.  When ``target`` is a symlink, the symlink itself is
    replaced with a regular file — silently detaching managed deployments
    that symlink ``config.yaml`` / ``SOUL.md`` / ``auth.json`` etc. from
    ``~/.hermes/`` to a git-tracked profile package or dotfiles repo
    (GitHub #16743).

    This helper resolves the symlink first so ``os.replace`` writes to
    the real file in-place while the symlink survives.  For non-symlink
    and non-existent paths the behavior is identical to a plain
    ``os.replace`` call unless the rename fails with:

    * ``EXDEV`` / ``EBUSY`` (any platform) — cross-device, bind-mount, and
      busy-file deployments fall back to copy/fsync/unlink immediately.
      These never clear on retry.
    * A Windows rename contended by another open handle (winerror 5/32/33).
      CPython opens files without ``FILE_SHARE_DELETE``, so *any* concurrent
      reader of the target blocks the rename.  The rename is retried with
      jittered backoff first — a retry that wins keeps the write atomic —
      and only a target whose handle outlives the budget is rewritten in
      place, so the update lands instead of being silently dropped.

    A genuine Windows permission failure produces the same winerror as a
    contended one, so it is not classified up front: it exhausts the retry
    budget, fails the in-place rewrite too, and is re-raised unchanged.

    Returns the resolved real path used for the replace, so callers that
    need to re-apply permissions can target it instead of the symlink.
    r   )jittered_backoffr1   )
base_delay	max_delayNFz;atomic_replace: %s -> %s failed with %s; falling back to %sr?   zin-place rewritecopy)r   r   r    islinkrealpathreplacer&   rC   errnoEXDEVEBUSYagent.retry_utilsrd   range_REPLACE_RETRY_ATTEMPTStimesleep_REPLACE_RETRY_BASE_DELAY_S_REPLACE_RETRY_MAX_DELAY_SloggerdebugrA   	errorcodegetrY   r`   )
ra   rb   
target_strrE   rD   r=   	contendedrd   attempt	retry_excs
             r   atomic_replacer}      s[   @ VJ02z0J0JZ  ,,,PZI(mmG./

7I&&& +/ +/ +/7<<	9U[%+666y6 	$ ;::::: $;a$?@@ $ $
$$#>"<    $Jw	222$$$$$$$$$ $ $ $ 5;*DDD'$)	>yII #CCCCCC$ 	ICT** >""39>39=="+7	
 	
 	
  	/ gy11117I...W+/X sV    A7 7G:A=G5 DG5G:
E-(#E(G5E(#G5(E--BG55G:utf-8z.tmp_)encoding
tmp_prefixpreserve_modecreate_modecontentr   r   r   r   c                   t          |           } | j                            dd           |rt          |           nd}|rt	          |           nd}|}|||                                 s|}t          j        t          | j                  |d          \  }	}
	 t          j
        |	d|          5 }|<t          t          d          r't          j        |                                |           |                    |           |                                 t          j        |                                           ddd           n# 1 swxY w Y   t#          |
|           }|rt%          t          |          |           |4t          t          d          s!t'          t          |          |           dS dS dS # t(          $ r( 	 t          j        |
           n# t,          $ r Y nw xY w w xY w)	a  Write *content* to *path* via temp file + fsync + atomic rename.

    Ensures the target file is never left in a partially-written state if
    the process crashes or is interrupted.  ``atomic_replace`` preserves
    symlinks and handles cross-device / busy-file fallbacks.

    Used by the memory store, skill manager, and agent importer so that
    every destructive file rewrite in the codebase shares one implementation.

    Args:
        preserve_mode: When True, carry an existing target's permission bits
            and (POSIX, best-effort) owner across the replace, like
            ``atomic_yaml_write`` does unconditionally.  ``os.replace`` swaps
            in mkstemp's 0600 temp file owned by the writing user, so without
            this a root-run rewrite of a user-owned file flips its owner and
            tightens its mode.  The mode is applied to the temp fd *before*
            the replace, so the file never transits through 0600.  Off by
            default: the historical callers (memory store, skill manager,
            cron) own their 0600-is-fine files.
        create_mode: Permission bits to apply when the target does not yet
            exist (otherwise the new file keeps mkstemp's 0600).  Never
            applied to an existing file.
    Tparentsexist_okN.tmpdirprefixsuffixwr   fchmod)r   parentmkdirr'   r-   r"   tempfilemkstempr   r   fdopenr2   r   r^   rO   flushrQ   r}   r3   r7   BaseExceptionrS   r&   )r    r   r   r   r   r   original_modeoriginal_ownereffective_moderW   ra   handlerE   s                r   atomic_write_textr     sD   @ ::DKdT2221>H'---DM3@J)$///dN"N+"9$++--"9$#Z  LBYr3222 	&f)gb(.C.C) 	&--//>:::LL!!!LLNNNHV]]__%%%	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& #8T22	 	AY@@@%gb(.C.C%tI????? &%%%   	Ih 	 	 	D	sV   G  2BE G  EG  EA&G   
G2G G2 
G-*G2,G--G2   )indentr4   rU   r   dump_kwargsc                   t          |           } | j                            dd           |dnt          |           }t	          |           }t          j        t          | j                  d| j         dd          \  }}	 |*t          t          d          rt          j        ||           t          j        |d	d
          5 }	t          j        ||	f|dd| |	                                 t          j        |	                                           ddd           n# 1 swxY w Y   t%          ||           }
t          |
          }t'          ||           |)	 t          j        ||           dS # t*          $ r Y dS w xY wt-          ||           dS # t.          $ r( 	 t          j        |           n# t*          $ r Y nw xY w w xY w)a  Write JSON data to a file atomically.

    Uses temp file + fsync + os.replace to ensure the target file is never
    left in a partially-written state. If the process crashes mid-write,
    the previous version of the file remains intact.

    Args:
        path: Target file path (will be created or overwritten).
        data: JSON-serializable data to write.
        indent: JSON indentation (default 2).
        mode: Optional final permission mode. When set, the temp file is
            created and replaced with this mode, avoiding chmod-after-write
            TOCTOU exposure for secret-bearing files.
        **dump_kwargs: Additional keyword args forwarded to json.dump(), such
            as default=str for non-native types.
    Tr   N._r   r   r   r   r~   r   F)r   ensure_ascii)r   r   r   r'   r-   r   r   r   stemr2   r   r   r   jsondumpr   rQ   r^   r}   r3   r6   r&   r7   r   rS   )r    rU   r   r4   r   r   r   rW   ra   r_   rE   real_path_objs               r   atomic_json_writer   Z  s\   0 ::DKdT222 ,DD2Ed2K2KM)$//N#49  LB
"H 5 5 Ib$Yr3111 		!QI "	 
    GGIIIHQXXZZ   		! 		! 		! 		! 		! 		! 		! 		! 		! 		! 		! 		! 		! 		! 		! #8T22	YM>:::-----    }m<<<<<   	Ih 	 	 	D	st   AF AD$F $D((F +D(,4F !E8 8
FF FF 
G&F;:G;
GGGG)labellogr   r   c                \   t          |           }|pt          }	 |                                j        }n# t          $ r Y dS w xY wt
          j        dk    rdS |t          j        t          j        z  z  sdS |	                    d|r| dnd|j        t          j
        |          |           dS )aj  Warn (once per call) when a credential file is group/world-readable.

    Secret-bearing files that users create by hand (or that older Hermes
    versions wrote without an explicit mode) commonly end up 0o644 under the
    default umask. This helper is the shared read-time check for that class:
    call it before loading any token/credential file so the owner gets a
    remediation hint in the logs.

    Returns True when a warning was emitted. No-ops (returns False) on
    platforms without POSIX permission bits semantics (best effort), when the
    file is missing, or when permissions are already tight.
    Fr)   zO%s%s is group/world-readable (mode 0%o) and contains secrets. Run: chmod 600 %s r   T)r   ru   r#   r%   r&   r   r   S_IRGRPS_IROTHwarningr$   )r    r   r   p_log	file_modes         r   (warn_if_credential_file_broadly_readabler     s    $ 	T

A=&DFFHH$		   uu	w' u45 uLL	$5"	Y	   4s   4 
AAc                   $     e Zd ZdZd fd	Z xZS )IndentDumperuD  PyYAML dumper that indents list items under mapping keys (2-space).

    Default PyYAML emits "indentless" sequences — list items start at the
    same column as their parent mapping key.  ``ruamel.yaml`` (used by
    :func:`atomic_roundtrip_yaml_update`) emits 2-space-indented sequences.
    Mixing both styles in the same ``config.yaml`` produces a file that
    stricter parsers like ``js-yaml`` reject with ``bad indentation of a
    mapping entry``.  Forcing ``indentless=False`` aligns the two
    serializers so all write paths emit byte-identical layouts (#31999).
    Fc                 H    t                                          |d          S )NF)superincrease_indent)selfflow
indentless	__class__s      r   r   zIndentDumper.increase_indent  s    ww&&tU333r   )FF)__name__
__module____qualname____doc__r   __classcell__)r   s   @r   r   r     sG        	 	4 4 4 4 4 4 4 4 4 4r   r   )default_flow_style	sort_keysextra_contentr   r   r   r   c          	         t          |           } | j                            dd           t          |           }t	          |           }|||                                 s|}t          j        t          | j                  d| j	         dd          \  }}		 t          j        |dd	
          5 }
|<t          t          d          r't          j        |
                                |           t          j        ||
t"          ||d           |r|
                    |           |
                                 t          j        |
                                           ddd           n# 1 swxY w Y   t+          |	|           }t          |          }t-          ||           t/          ||           dS # t0          $ r( 	 t          j        |	           n# t4          $ r Y nw xY w w xY w)aL  Write YAML data to a file atomically.

    Uses temp file + fsync + os.replace to ensure the target file is never
    left in a partially-written state.  If the process crashes mid-write,
    the previous version of the file remains intact.

    Args:
        path: Target file path (will be created or overwritten).
        data: YAML-serializable data to write.
        default_flow_style: YAML flow style (default False).
        sort_keys: Whether to sort dict keys (default False).
        extra_content: Optional string to append after the YAML dump
            (e.g. commented-out sections for user reference).
        create_mode: Permission bits to apply when the target does not yet
            exist (a created file otherwise keeps mkstemp's 0600).  Never
            applied to an existing file, whose mode is always preserved.
    Tr   Nr   r   r   r   r   r~   r   r   )Dumperr   r   allow_unicode)r   r   r   r'   r-   r"   r   r   r   r   r   r   r2   r   r^   yamlr   r   rO   r   rQ   r}   r3   r7   r   rS   r&   )r    rU   r   r   r   r   r   r   rW   ra   r_   rE   r   s                r   atomic_yaml_writer     sA   4 ::DKdT222'--M)$//N!8!8##49  LB
'Yr3111 	!Q(WR-B-B(
 	!((**m444 I##5#"     '&&&GGIIIHQXXZZ   3	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!6 #8T22	YM>:::=-88888   	Ih 	 	 	D	sV   F8 1B/E, F8 ,E00F8 3E04AF8 8
G*GG*
G%"G*$G%%G*key_pathc                 N   ddl m} ddlm} t	          |           } | j                            dd            |d          }d|_        d|_        d|_	        |
                    d	d
d	           |                                 rO|                     dd          5 }|                    |          p	 |            }ddd           n# 1 swxY w Y   n
 |            }t          ||          s ||          }|}|                    d          }	|	dd         D ]8}
|                    |
          }t          ||          s |            }|||
<   |}9|||	d         <   t#          |           }t%          |           }t'          j        t+          | j                  d| j         dd          \  }}	 t/          j        |dd          5 }|                    ||           |                                 t/          j        |                                           ddd           n# 1 swxY w Y   t;          ||           }t	          |          }t=          ||           t?          ||           dS # t@          $ r( 	 t/          j!        |           n# tD          $ r Y nw xY w w xY w)a_  Update one dotted YAML key while preserving comments and readable text.

    This is intentionally narrower than :func:`atomic_yaml_write`: it is for
    user-edited config files where comments, ordering, quoting, and Unicode
    should survive a single setting mutation.  Writes still use the same temp
    file + fsync + atomic replace pattern.
    r   YAMLCommentedMapTr   rttypFr   r<   mappingsequenceoffsetrr~   r   Nr   r   r   r   r   )#ruamel.yamlr   ruamel.yaml.commentsr   r   r   r   preserve_quotesr   r   r   r"   rI   loadr   splitrx   r'   r-   r   r   r   r   r   r   r   r   rQ   r^   r}   r3   r7   r   rS   r&   )r    r   r   r   r   yaml_rtr_   configcurrentkeyskey
next_valuer   r   rW   ra   rE   r   s                     r   atomic_roundtrip_yaml_updater   ,  s[    !     111111::DKdT222dtnnnG"G G!&GNN1qN333{{}}  YYsWY-- 	7\\!__6F	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 fl++ &f%%G>>#DCRCy  [[%%
*l33 	&%J%GCLGDH'--M)$//N#49  LB
Yr3111 	!QLL###GGIIIHQXXZZ   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! #8T22	YM>:::=-88888   	Ih 	 	 	D	sh    CCC2I2 	AH&I2 &H**I2 -H*.AI2 2
J$=JJ$
JJ$JJ$	new_statec                    ddl m} ddlm ddlm ddlm} t          |           } | j	        
                    dd            ||             |d	          }d|_        d|_        d
|_        |                    ddd           |                                 rb|                     dd          5 }|                    |          }ddd           n# 1 swxY w Y   t%          |          s |pi           }n
             }h dfdddt&          ddffd ||           t)          |           }t+          |           }t-          j        t1          | j	                  d| j         dd          \  }	}
	 t5          j        |	dd          5 }|                    ||           |                                 t5          j        |                                           ddd           n# 1 swxY w Y   tA          |
|           }t          |          }tC          ||           tE          ||           dS # tF          $ r( 	 t5          j$        |
           n# tJ          $ r Y nw xY w w xY w)u  Persist a full config-state dict while preserving comments and ordering.

    Behaves like ``atomic_yaml_write`` (writes the whole file in one shot from
    ``new_state``), but routes through ruamel.yaml round-trip mode so existing
    comments, key order, quotes, and readable Unicode survive.

    Reconciliation rules against the on-disk YAML:

    * Keys present in both are updated in-place via assignment, which keeps
      ruamel's CommentedMap anchors (and their attached comments) attached to
      their original positions.
    * Keys missing from ``new_state`` are deleted.
    * Keys added in ``new_state`` are appended at the end of their parent map.
    * Nested ``dict`` values recurse with the same rules.
    * Non-dict values (lists, scalars) are overwritten wholesale — list
      element comments are not individually preserved, matching ruamel's
      semantics.

    This is the comment-safe replacement for ``yaml.safe_dump(cfg, f)`` in
    callers that mutate a deep-loaded config dict and want to persist the
    whole thing.

    Shares the fail-closed contract ``hermes_cli.config.atomic_config_write``
    enforces for plain (non-comment-preserving) full-document writes: an
    existing-but-unreadable ``config.yaml`` (permission error, broken mount,
    transient I/O) raises rather than being silently replaced with only
    ``new_state``. Imported lazily to avoid a module-level circular import —
    ``hermes_cli.config`` itself imports from this module.
    r   r   r   )DoubleQuotedScalarString)$require_readable_config_before_writeTr   r   r   Fr   r<   r   r   r~   r   N>
   ny~nor   offr	   nullr
   falsec                 t    t          | t                    r!|                                 v r |           S | S N)r   r   r   )r   r   _YAML11_AMBIGUOUS_WORDSs    r   _quote_if_yaml11_ambiguousz>atomic_roundtrip_yaml_save.<locals>._quote_if_yaml11_ambiguous  s>    eS!! 	3ekkmm7N&N&N++E222r   dstrT   r   c                 R                                    D ]i\  }}t          |t                    rA|                     |          }t          |          s             }|| |<    ||           [ |          | |<   jfd|                                 D             D ]}| |= d S )Nc                     g | ]}|v|	S  r   ).0krT   s     r   
<listcomp>z>atomic_roundtrip_yaml_save.<locals>._merge.<locals>.<listcomp>  s    :::!Qc\\A\\\r   )itemsr   dictrx   r   )r   rT   r   r   r   r   _merger   s    `   r   r   z*atomic_roundtrip_yaml_save.<locals>._merge  s    ))++ 	= 	=JC%&& =''#,,!'<88 '*lnnG&CHw&&&&55e<<C ;:::sxxzz::: 	 	CC	 	r   r   r   r   r   r   )&r   r   r   r   ruamel.yaml.scalarstringr   hermes_cli.configr   r   r   r   r   r   r   r   r"   rI   r   r   r   r'   r-   r   r   r   r   r   r   r   r   rQ   r^   r}   r3   r7   r   rS   r&   )r    r   r   r   r   r_   existingr   r   rW   ra   rE   r   r   r   r   r   r   s                @@@@@r   atomic_roundtrip_yaml_saver   o  s   B !     111111AAAAAAFFFFFF::DKdT222((...dtnnnG"G G!&GNN1qN333{{}} "YYsWY-- 	'||AH	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	'(L11 	4#|HN33H<>>       
L t         " F8Y'--M)$//N#49  LB
Yr3111 	!QLL1%%%GGIIIHQXXZZ   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! #8T22	YM>:::=-88888   	Ih 	 	 	D	sh   8CC!C
I
 !AG>2I
 >HI
 HAI
 

I<I*)I<*
I74I<6I77I<textc                 t    	 t          j        |           S # t           j        t          t          f$ r |cY S w xY w)zParse JSON, returning *default* on any parse error.

    Replaces the ``try: json.loads(x) except (JSONDecodeError, TypeError)``
    pattern duplicated across display.py, anthropic_adapter.py,
    auxiliary_client.py, and others.
    )r   loadsJSONDecodeError	TypeError
ValueError)r  r   s     r   safe_json_loadsr    sE    z$ )Z8   s    77c                  b    t           "t          t          dd           pt          j        a t           S )NCSafeLoader)_fast_yaml_loaderrA   r   
SafeLoaderr   r   r   _get_fast_yaml_loaderr    s'     #D->>Q$/r   streamc                 F    t          j        | t                                S )uy  ``yaml.safe_load`` using the libyaml C loader when available.

    Accepts the same inputs as ``yaml.safe_load`` (a ``str``/``bytes`` document
    or a readable file object) and returns the same parsed structure. Falls
    back to PyYAML's pure-Python ``SafeLoader`` when ``CSafeLoader`` isn't
    available, so behavior is identical everywhere — only the speed differs.
    )Loader)r   r   r  )r  s    r   fast_safe_loadr    s      9V$9$;$;<<<<r   r   c                     t          j        | d                                          }|s|S 	 t          |          S # t          t
          f$ r |cY S w xY w)z:Read an environment variable as an integer, with fallback.r   )r   r   r   intr  r  r   r   raws      r   env_intr    se    
)C


"
"
$
$C 3xx	"      < AA        c                     t          j        | d                                          }|s|S 	 t          |          S # t          t
          f$ r |cY S w xY w)z7Read an environment variable as a float, with fallback.r   )r   r   r   floatr  r  r  s      r   	env_floatr    sf    
)C


"
"
$
$C Szz	"   r  c                 J    t          t          j        | d          |          S )z*Read an environment variable as a boolean.r   r   r   )r   r   s     r   env_boolr  *  s!    29S"--w????r   )HTTPS_PROXY
HTTP_PROXY	ALL_PROXYhttps_proxy
http_proxy	all_proxy	proxy_urlc                     t          | pd                                          }|sdS |                                                    d          rd|t	          d          d          S |S )zNormalize proxy URLs for httpx/aiohttp compatibility.

    WSL/Clash-style environments often export SOCKS proxies as
    ``socks://127.0.0.1:PORT``. httpx rejects that alias and expects the
    explicit ``socks5://`` scheme instead.
    r   Nzsocks://z	socks5://)r   r   r   
startswithrN   )r#  	candidates     r   normalize_proxy_urlr'  8  ss     IO$$**,,I t##J// 989S__%5%56888r   c                      t           D ]=} t          j        | d          }t          |          }|r||k    r|t          j        | <   >dS )zARewrite supported proxy env vars to canonical URL forms in-place.r   N)_PROXY_ENV_KEYSr   r   r'  environ)r   r   
normalizeds      r   normalize_proxy_env_varsr,  G  sW     ) )	#r""(//
 	)*--(BJsO	) )r   base_urlc                     | pd                                 }|sdS t          d|v r|nd|           }|j        pd                                                    d          S )a  Return the lowercased hostname for a base URL, or ``""`` if absent.

    Use exact-hostname comparisons against known provider hosts
    (``api.openai.com``, ``api.x.ai``, ``api.anthropic.com``) instead of
    substring matches on the raw URL. Substring checks treat attacker- or
    proxy-controlled paths/hosts like ``https://api.openai.com.example/v1``
    or ``https://proxy.test/api.openai.com/v1`` as native endpoints, which
    leads to wrong api_mode / auth routing.
    r   z://z//r   )r   r   hostnamer   rstrip)r-  r  parseds      r   base_url_hostnamer2  S  sl     >r
 
 
"
"C rUc\\cczCzz::FO!r((**11#666r   modelc                    | pd                                                                 }|sdS d|v r|                    dd          d         }|                    d          ph|                    d          pS|                    d          p>|                    d	          p)|                    d
          p|                    d          S )uA  Return True for model families that require ``max_completion_tokens``.

    OpenAI's newer families reject ``max_tokens`` on /v1/chat/completions with
    HTTP 400 ``unsupported_parameter`` — the caller must send
    ``max_completion_tokens`` instead. This covers:

    - ``gpt-4o`` / ``gpt-4o-mini`` / ``gpt-4o-*``
    - ``gpt-4.1`` / ``gpt-4.1-*``
    - ``gpt-5`` / ``gpt-5.x`` / ``gpt-5-*``
    - ``o1`` / ``o1-*``
    - ``o3`` / ``o3-*``
    - ``o4`` / ``o4-*``

    Handles vendor prefixes like ``openai/gpt-5.4`` by stripping to the tail.
    The URL-based check (``base_url_hostname == "api.openai.com"``) misses
    third-party OpenAI-compatible endpoints (custom OpenAI gateways,
    OpenRouter) that front these models and enforce the same parameter
    constraint, so name-based detection is required as a fallback.
    r   F/r1   r   zgpt-4ozgpt-4.1zgpt-5o1o3o4)r   r   rsplitr%  )r3  ms     r   "model_forces_max_completion_tokensr;  g  s    ( 
"##%%A u
axxHHS!R 	X 	<<	""	<<  	 <<	 <<		
 <<r   domainc                     t          |           }|sdS |pd                                                                                    d          }|sdS ||k    p|                    d|z             S )ac  Return True when the base URL's hostname is ``domain`` or a subdomain.

    Safer counterpart to ``domain in base_url``, which is the substring
    false-positive class documented on ``base_url_hostname``. Accepts bare
    hosts, full URLs, and URLs with paths.

        base_url_host_matches("https://api.moonshot.ai/v1", "moonshot.ai") == True
        base_url_host_matches("https://moonshot.ai", "moonshot.ai")        == True
        base_url_host_matches("https://evil.com/moonshot.ai/v1", "moonshot.ai") == False
        base_url_host_matches("https://moonshot.ai.evil/v1", "moonshot.ai")     == False
    Fr   r   )r2  r   r   r0  endswith)r-  r<  r/  s      r   base_url_host_matchesr?    s|     !**H ul!!##))++22377F uv@!2!23<!@!@@r   )F)r   r   )r   )r  )r   N)Br   rk   r   loggingr   r[   r#   r   rq   pathlibr   typingr   r   urllib.parser   r   	getLoggerr   ru   	frozensetr   r   r   r   r   r'   r-   r3   r7   r   r@   rB   rp   rs   rt   r&   rC   rY   r`   r}   r   r  r   Loggerr   
SafeDumperr   r   r   r   r   r  r
  r  r  r  r  r  r  r)  r'  r,  r2  r;  r?  r   r   r   <module>rH     s   0 0    				                   ! ! ! ! ! ! 		8	$	$ 55566 3  $    D D# D DT D D D D
d |     t  (@        d +C     "T  $    " go" %.Ikkk$:$: !  "   W      !s !s !t ! ! ! !HC C D    RU39- RuS$Y7G RC R R R Rr  $@ @ @
T	
@@ 	@
 @ @ @ 
@ @ @ @N E E E
T	
E
E 	E
 *E E 
E E E EV !%	& & &
T	
& & 
$		&
 
& & & &R4 4 4 4 44? 4 4 4(  % $ $N N N
T	
N
N 	N
 N :N N 
N N N Nb@
T	
@@ @ 
	@ @ @ @Fs
T	
ss 
s s s sr
 
# 
 
s 
 
 
 
(    =3 =3 = = = =  s 3     3      @ @# @ @ @ @ @ @3: #*    ) ) ) )7 7 7 7 7 7( c  d        FAC A A A A A A A Ar   