
    NQj                   H   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
m
Z
 ddlmZmZmZmZmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddl m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2  ej3        d          Z4d Z5ddZ6dddd$Z7d% Z8dd&Z9dd'Z:dd)Z;dd,Z<dd/Z=dd5Z>dd6Z?	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dddZ@dgZAdS )uQ  Implementation of :meth:`AIAgent.__init__` — extracted as a module function.

``AIAgent.__init__`` is one of the longest methods in the codebase (60+
parameters, ~1,400 lines of attribute initialization, provider
auto-detection, credential resolution, context-engine bootstrap, etc.).
Keeping it in ``run_agent.py`` bloats that file with code that's mostly
"setup state, then forget".

After this extraction the body lives here as ``init_agent(agent, ...)``
and :meth:`AIAgent.__init__` is a thin wrapper that calls
``init_agent(self, ...)``.  All imports the body needs at module-load
time are listed below; the body also performs many lazy imports inside
its own scope that come along unchanged.

Symbols that tests patch on ``run_agent.*`` (``OpenAI``, ``cleanup_vm``,
etc.) are resolved through :func:`_ra` so the patch contract is
preserved.
    )annotationsN)datetime)AnyCallableDictListOptional)urlparseparse_qs
urlunparse)ContextCompressor)IterationBudget)StreamingContextScrubber)MINIMUM_CONTEXT_LENGTHfetch_model_metadatais_local_endpointquery_ollama_num_ctx)_install_safe_stdio)SubdirectoryHintTracker)StreamingThinkScrubber)ToolCallGuardrailConfigToolCallGuardrailControllerToolGuardrailDecision)cfg_get)get_provider_request_timeoutget_hermes_home)base_url_host_matchesis_truthy_value	run_agentc                     ddl } | S )zLazy reference to ``run_agent`` so callers can patch
    ``run_agent.OpenAI`` / ``run_agent.cleanup_vm`` / ... and have those
    patches reach this code path.
    r   Nr    r"   s    4/home/alina/.hermes/hermes-agent/agent/agent_init.py_rar$   >   s    
     	autoraiseDict[str, Any]returnstrc           	        t          |                     d          pd                                                                                              dd          d         }|                    d          rdnd}t          t          | d	         d
z                      }t          t          | d         d
z                      }d| d| d| d| d	S )aZ  Build the one-time notice shown when Codex gpt-5.x raises compaction.

    ``autoraise`` is ``{"model": <slug>, "from": <old_ratio>, "to": <new_ratio>}``.
    The same text is printed inline for CLI users and replayed via
    ``status_callback`` for gateway users, so it must be self-contained and
    include the exact opt-back-out command.
    modelzgpt-5.4/5.5/   zgpt-5.3-codex-spark128K272Kfromd   tou
   ℹ Codex z caps context at z#, so auto-compaction was raised to z% (from zz%) to use more of the window before summarizing.
  Opt back out: hermes config set compression.codex_gpt55_autoraise false)r)   getstriplowerrsplit
startswithintround)r&   r+   capfrom_pctto_pcts        r#   "_build_codex_gpt5_autoraise_noticer>   G   s     	g&&7-88>>@@FFHHOOPSUVWWXZ[E $$%:;;
G&&C56*S01122Hy,--..F	UU 	U 	US 	U 	U	U 	U&	U 	U 	Ur%   )r+   global_thresholdfloatmodel_cthreshOptional[float]r+   Optional[str]is_codex_autoraisebool&tuple[float, Optional[Dict[str, Any]]]c               D    || dfS |r|| dz   k    r| dfS ||| |dfS |dfS )a  Combine the user's global compaction threshold with a per-model override.

    Returns ``(effective_threshold, autoraise_notice)``. ``autoraise_notice`` is
    ``{"model": <slug>, "from": <old>, "to": <new>}`` only when a Codex
    autoraise (gpt-5.4/5.5 272K family or gpt-5.3-codex-spark) actually raises
    the threshold, otherwise ``None``.

    The Codex overrides are *autoraises*: they must never LOWER a higher
    user-configured threshold. A user who already set ``compression.threshold``
    above the raised value deliberately keeps more raw context, and silently
    dropping them would both waste usable window and contradict the feature's
    purpose (use more of the window). Other overrides (e.g. Arcee Trinity)
    keep their existing unconditional behaviour.
    Ng&.>)r+   r1   r3    )r?   rA   r+   rD   s       r#   _resolve_compression_thresholdrI   ]   sf    * %% 
,t333#T))$
 
 
 	

 $r%   c                 $    t                      dz  S )u6  Path to the per-profile marker recording that the autoraise notice ran.

    Lives under ``$HERMES_HOME`` (which is profile-scoped) alongside the other
    internal markers like ``.container-mode`` — so it is not a user-facing config
    key, and every profile tracks its own notice state independently.
    z.codex_gpt55_autoraise_noticer   rH   r%   r#   $_codex_gpt55_autoraise_notice_markerrK      s     >>>r%   c                   t          |                     d          pd                                                                                              dd          d         }t          t          t          | d                   dz                      }t          t          t          | d                   dz                      }| d	| d	| S )
uf  Stable identity for one autoraise notice, keyed on what it displays.

    Uses the model slug plus the same from→to percentages the notice text
    shows, so an unchanged threshold stays silent across restarts while a
    later change (the user edits their global ``threshold``, or switches to a
    different autoraised Codex model) re-notifies once.
    r+    r,   r-   r.   r1   r2   r3   :)r)   r4   r5   r6   r7   r9   r:   r@   )r&   r+   r<   r=   s       r#   #_codex_gpt55_autoraise_notice_staterO      s     	g&&,"--3355;;==DDS!LLRPE5y011C78899HuYt_--34455F))h)))))r%   c                    	 t          |           }t                                          d                                          |k    S # t          t
          t          t          f$ r Y dS w xY w)zTrue if this exact autoraise notice was already shown for this profile.

    A missing/unreadable marker (or one recording a different threshold) reads
    as unseen, so the notice shows.
    utf-8encodingF)rO   rK   	read_textr5   OSErrorKeyError	TypeError
ValueError)r&   currents     r#   "_codex_gpt55_autoraise_notice_seenrZ      sx    5i@@355?? @ 
 

%''W 	 Xy*5   uus   AA	 	A*)A*Nonec                    	 t                      }|j                            dd           |                    t	          |           d           dS # t
          t          t          t          f$ r Y dS w xY w)zPersist that the autoraise notice was shown for this profile/config state.

    Best-effort: a read-only or missing ``$HERMES_HOME`` just means the notice
    may show again next init, which is preferable to breaking agent init.
    Tparentsexist_okrQ   rR   N)	rK   parentmkdir
write_textrO   rU   rV   rW   rX   )r&   markers     r#   $_record_codex_gpt55_autoraise_noticerd      s    577D4888/	::W 	 	
 	
 	
 	
 	
 Xy*5   s   AA A32A3valuer   c                ~    t          | t                    sdS |                                                     d          S )NrM   r,   )
isinstancer)   r5   rstrip)re   s    r#   _normalized_custom_base_urlri      s5    eS!! r;;==$$$r%   agent_modelentryc                   t          |                    dd          pd                                                                          }|sdS |t          | pd                                                                          k    S )Nr+   rM   T)r)   r4   r5   r6   )rj   rk   provider_models      r#   _custom_provider_model_matchesrn      sw    7B//5266<<>>DDFFN tS!23399;;AACCCCr%   providerbase_urlcustom_providersList[Dict[str, Any]]Optional[Dict[str, Any]]c                   | pd                                                                 }|dk    rd}nF|                    d          r/|                    dd          d                                          }nd S t	          |          }|sd S d }|pg D ]t}t          |t                    s|rt          |                    dd          pd                                                                           t          |                    dd          pd                                                                           h}	||	vrt	          |                    d                    |k    r|                    d	          }
t          |
t                    r|
st          |                    d
d          pd                                           }|r#t          ||          rt          |
          c S c|t          |
          }v|S )NrM   customzcustom:rN   r-   provider_keynamerp   
extra_bodyr+   )
r5   r6   r8   splitri   rg   dictr)   r4   rn   )ro   r+   rp   rq   provider_normprovider_key_filter
target_urlfallbackrk   
entry_keysrx   rm   s               r#   %_custom_provider_extra_body_for_agentr      s    ^**,,2244M   		!	!)	,	, +11#q99!<BBDDt,X66J t)-H!'R ( (%&& 	 	EIInb117R88>>@@FFHHEIIfb))/R006688>>@@J #*44&uyy'<'<==KKYY|,,
*d++ 	: 	UYYw339r::@@BB 	(-eU;; (J'''''(J''HOr%   c                F   t          | j        | j        | j        |          }|sd S t	          t          | di           pi           }t	          |          }|                    d          }t          |t                    r|                    |           ||d<   || _	        d S )N)ro   r+   rp   rq   request_overridesrx   )
r   ro   r+   rp   rz   getattrr4   rg   updater   )agentrq   rx   	overridesmerged_extra_bodyexisting_extra_bodys         r#   !_merge_custom_provider_extra_bodyr      s    6k)	  J  WU$7<<BCCIZ((#--55%t,, 6  !4555/Il'Er%   rM   Z         ?Fallr2        
   api_keyapi_modeacp_commandacp_argslist[str] | Nonecommandargsmax_iterationsr9   
tool_delayenabled_toolsets	List[str]disabled_toolsetssave_trajectoriesverbose_logging
quiet_modetool_progress_modeephemeral_system_promptlog_prefix_chars
log_prefixproviders_allowedproviders_ignoredproviders_orderprovider_sortprovider_require_parametersprovider_data_collectionopenrouter_min_coding_score
session_idtool_progress_callbackcallabletool_start_callbacktool_complete_callbackthinking_callbackreasoning_callbackclarify_callbackread_terminal_callbackstep_callbackstream_delta_callbackinterim_assistant_callbacktool_gen_callbackstatus_callbacknotice_callbacknotice_clear_callbackevent_callback%Optional[Callable[[str, dict], None]]
max_tokensreasoning_configservice_tierr   prefill_messagesplatformuser_iduser_id_alt	user_namechat_id	chat_name	chat_type	thread_idgateway_session_keyskip_context_filesload_soul_identityskip_memoryparent_session_iditeration_budget'IterationBudget'fallback_modelcheckpoints_enabledcheckpoint_max_snapshotscheckpoint_max_total_size_mbcheckpoint_max_file_size_mbpass_session_idcG                 e    t                       |	 _        |
 _        |?pt          |
           _        | _        | _        | _        | _        | _	        | _
        |1 _        |2 _        |3 _        |4 _        |5 _        |6 _        |7 _        |8 _        |9 _        d _        d _        d _        |: _        |; _        |F _        |A _        | _        |r| dnd _        |pd _        t=          |t>                    r:|                                 r&|                                 !                                nd}G|Gpd _"        |p| _#        tI          |p|pg            _%        |dv r	| _&        n
 j"        dk    rd _&        n j"        dv rd _&        n|G# j'        d	k    rd
 j(        v rd _&        d _"        n|G j'        dk    rd _&        d _"        n j"        dk    s|G j'        dk    rd _&        d _"        n~ j(        )                    d          *                    d          rd _&        nI j"        dk    s/ j'        +                    d          rtY           j(        d          rd _&        nd _&        	  -                                 n# t\          $ r Y nw xY w	 ddl/m0}Hm1}I  j"        |Hvr |I j         j"                   _        n# t\          $ r Y nw xY w| j&        dk    r j"        dk    rt?           j        pd          !                                +                    d          st?           j        pd          !                                +                    d          sy 2                                se 3                                s! 4                     j         j"                  r0d _&        tk           d          r j6        7                                  j"        dk    s 8                                rxts                      j:        ;                                sSts                      j:        <                                 t{          j>        t~          dd !          @                                 | _A        | _B        | _C        d" _D        |  _E        |! _F        |" _G        |# _H        |$ _I        |% _J        |& _K        |( _L        |) _M        |* _N        |+ _O        |' _P        d" _Q        t                       _S        d _T        d" _U        d _V        d _W        d" _X        t{          jY                     _Z        d _[        t{          j\                     _]        ty                       _^        t{          j\                     __        d _`        g  _a        t{          j\                     _b        | _c        | _d        | _e        | _f        | _g        | _h        | _i        | _j        | _k        |, _l        |- _m        |. _n        t          |/pi            _p        |0pg  _q        d" _r         s                                \   _t         _u        d# _v        	 dd$lwmx}J  |J            y                    d%i           pi }K|Ky                    d&d#          }L|Ld'v r|L _v        n# t\          $ r Y nw xY wd" _z        d" _{        t          j|                     _}        d( _~        d _        d _        d" _        d _        d _        d _        d _        ty                      d"dd) _        d _        dd*lm}Mm}N  |Mts                      j        +            j        r1 |N             ts                      j                            d,           n j        r	 d _        d" _        t!                       _        t%                       _        d _        d _        d _        d _        i  _        d _        d" _        t7           j"         j                  }O j&        dk    rHdd-lm}Pm}Q  j"        dk    }R|Rrdd.lm}S tA          j        d/|pd          }T|Tr|T                    d0          nd1}U|U _         |S|U           _        d2 _        | _        d" _        d2 _        d _        i  _         j        stS          d3 j         d4|U d5           nj j"        dk    }V|Vr|p |Q            pdn|pd}W j"        d6k    rst=          |Wt>                    r^|Wr\	 dd7lm}X  |X            }WnJ# t\          $ r=}Yddl}Z|Z                    t\                                        d8|Y           Y d}Y~Ynd}Y~Yww xY w|W _        |W _        | _        dd9lm}[ |Vr t=          |Wt>                    r |[|W          nd" _         |P|W||O:           _        d _        i  _         j        stS          d3 j         d;           dd<lm}\  |\|W          rtS          d=           
n%t=          |Wt>                    r:tg          |W          d>k    r&tS          d?|Wdd@          dA|WdBd                     	nԉ j"        dCk    reddDlm}] d _&        dR fdK}^ |] j        pdL|^M           _        i  _        |pdN _        dO _         j        stS          dP j                    	nd j&        dk    rVtA          j        d/|pd          }T|Tr|T                    d0          nd1 _        d _        	 dd$lwmx}_  |_            y                    di           y                    dQi           }`|`y                    dR          ru|`y                    dS          r`|`dR         |`dS         dT _        |`y                    dU          r|`dU          j        dV<   |`y                    dW          r|`dW          j        dW<   n# t\          $ r Y nw xY wd _        i  _         j        s. j        rdXnd}atS          d3 j         dY j         |a d5           n|r|r	to          |          }b|bj        r\ts          |b                    dZ                    }cd[ tw          |bj                                                  D             }d||c|dd\}en||d]}e|O|O|ed^<    j"        dk    r j#        |ed_<    j%        |ed`<   |}ftY          |fda          rddblm}g  |g            |edc<   nxtY          |fdd          rddelm}h  |h|f          |edc<   nRtY          |fdf          r%ts                                                      |edc<   ntY          |fdg          rddhlm}i  |i            |edc<   ntY          |fdi          r	djdki|edc<   ntY          |fdl          r%ts                                                      |edc<   ntY          |fd	          rddmlm}j  |j|          |edc<   ndc|evrJ	 ddnlm}k  |k j"                  }l|lr|lj        rt          |lj                  |edc<   nG# t\          $ r Y n:w xY wn4ddolm}m  |m j"        pdp j        dq          \  }n}o|ns|nj        t?          |nj                  d]}e|O|O|ed^<   t          |ndrd          }p|pst          |ndcd          }p|pst          |ndsd          }p|prt          |p          |edc<   n j"        pd                                 !                                }q|qrJ|qdtvrE|q                                 du}r	 ddvlm}s |sy                    |q          }t|tr|tj        r|tj        d         }rn# t\          $ r Y nw xY wg }ut=          |@tH                    rdw |@D             }unBt=          |@t                    r-|@y                    dx          r|@y                    dy          r|@g}ud"}v|uD ]f}w|wy                    dz          pd                                 pd}x|xsj|wy                    d{          p|wy                    d|          pd                                 }y|yr*t          j        |yd                                           pd}x |m|wdx         |wdy         d|wy                    d}          |x~          \  }z}{|z|wdx          _"        |{p|wdy          _        d _        |zj        t?          |zj                  d]}e|O|O|ed^<   t          |zdrd          }|||st          |zdcd          }|||st          |zdsd          }|||rt          ||          |edc<   d}v nh|vst          d|q d|r d          t           dd"          st          d          |e _        t?          |ey                    d}d                    !                                }}tY          |}da          rgd j        pd!                                v rJ|ey                    dc          pi }~|~y                    dd          }d}||vr|r| d| |~d<   n||~d<   |~|edc<                                     	 ddlwm}m}m}mx}  |            } ||          }t?          |ey                    d}          p j        pd          } ||e||            ||e||           n-# t\          $ r  t                              dd           Y nw xY w|ey                    dzd           _        |ey                    d} j                   _        	 ddlm}  |                                  |edd           _         j        s͐tS          d3 j                    |rtS          d|            dd<lm}\ |ey                    dzd          } |\|          rtS          d=           nht=          |t>                    rC|rA|dk    r;tg          |          d>k    r'tS          d|dd@          dA|dBd                     ntS          d           n%# t\          $ r}t          d|           d}~ww xY wt=          |@tH                    rd |@D              _        nOt=          |@t                    r3|@y                    dx          r|@y                    dy          r	|@g _        ng  _        d _        t           dd"           _         j        r j        d         nd _         j        r j        stg           j                  d0k    r1 j        d         }tS          d|dy          d|dx          d5           nLtS          dtg           j                   dd                    d  j        D                       z              	 ddlm} |j         _        n# t\          $ r
 d _        Y nw xY wts                                          || j                   _        ty                       _         j        rd  j        D              _        t           j                  } j        stS          dtg           j                   dd                    |                      |r&tS          dd                    |                      |r&tS          dd                    |                      n j        stS          d           ddlm} d j        v r|nd _         j        rZ j        sSts                                                      }d |                                D             }|rtS          d|             j        r j        stS          d            j
        rM j        sFtg           j
                  dk    r j
        dd         dAz   n j
        }tS          d| d            jt        rD j        s= ju        r j"        dk    rd}n ju        rd}nd}tS          d| d jv         d           t          j                     _        |r| _        nG j                            d          }t          j                    j        dd         }| d|  _        	 ddlm}  | j                   n%# t\          $ r  j        t          j        d<   Y nw xY wt                      }|dz   _         j                            dd           d" _        	 dd$lwmx}  |            y                    d          pi }t          |y                    dd"                     _        n# t\          $ r Y nw xY wg  _        d _        d _        d _        d _        ddlm}  ||B|C|D|E           _        |= _         |> _        d _        d" _        d _        d" _         j        |-|,d _        ddlm}  |             _	        	 dd$lwmx}  |            }n# t\          $ r i }Y nw xY w	 t          t          j        |y                    di                                _S        n># t\          $ r1}ts                      j                            d|           Y d}~nd}~ww xY wd _        d _        d" _        d" _        d _        d _        d _        |<s	 |y                    di           }|y                    dd"           _        |y                    dd"           _        t'          |y                    dd                     _         j        s j        r^ddƐlm}  ||y                    ddȦ          |y                    ddʦ          ˦           _         j                                         n# t\          $ r Y nw xY wd _        |<s	 |r|y                    dxd          nd}|r/|                                 rdd̐lm} dd͐lm}  |             _         ||          }|r1|                                r j                            |            j        j        r j        |1pdt?          t                                ddМ}|d         dk    r j        |d<    j        |d<    j         r:	  j                               j                  }|r||d<   n# t\          $ r Y nw xY w j        r
 j        |d<    j        r
 j        |d<    j        r
 j        |d<    j        r
 j        |d<    j        r
 j        |d<    j        r
 j        |d<    j        r
 j        |d<    j        r
 j        |d<   	 ddݐl!m"}  |            }||d<   d|d<   n# t\          $ r Y nw xY w  j        j#        dSi | ts                      j                            d|           n/ts                      j                            d|           d _        nF# t\          $ r9}ts                      j                            d|           d _        Y d}~nd}~ww xY wddlm$}  |            d _%        	 |y                    di           }t'          |y                    dd                     _%        n# t\          $ r Y nw xY w|y                    di           }t=          |t                    si }|y                    ddp           _&        |y                    ddp           _'        t          |y                    dd                     _(        t          |y                    dd                     _)        t          |y                    dd                     _*         j*        r$	 ddl+m,}  |             n# t\          $ r Y nw xY w|y                    di           }t=          |t                    si }| _-        	 |y                    dd          }t'          |          }t]          |d0          }n# t^          t`          f$ r d}Y nw xY w| _1        |y                    di           }t=          |t                    si }te          |y                    dd                    }t?          |y                    dd                    !                                dv }t?          |y                    dd                    !                                dv }d _3        	 ddlm4}m5}m6}  | j         j"        |          }to          || j         | j         j"                  p | j         j"                            \  } _3        n# t\          $ r Y nw xY wt?          |y                    dd                    !                                dv }te          |y                    dd                    }t'          |y                    dd                    }t]          dt'          |y                    dd                              }t?          |y                    d d"                    !                                dv }tq          |y                    d          d"          }t?          |y                    dd          pd          !                                }|dvr+ts                      j                            d|           d}	 ts          |ddi           }n# t\          $ r i }Y nw xY wt=          |t                    r|y                    d          }nd}|-	 t'          |          }n# t^          t`          f$ r d}Y nw xY w| _        |y                    dyi           } jl        t=          |t                    r|y                    d	          }|	 t=          |t                    rt`          t'          |¦          }|dk    rt`          |É _l        nf# t^          t`          f$ rP ts                      j                            d
|¦           tS          d|dtt          j;                   Y nw xY w jl         j        d	<   t=          |t                    r|y                    d          }nd}|āz	 t'          |Ħ          }nh# t^          t`          f$ rR ts                      j                            d|Ħ           tS          d|ědtt          j;                   d}Y nw xY w	 ddlwm}  ||          }n=# t\          $ r0 |y                    d          }t=          |tH                    sg }Y nw xY w|ŉ _<        t{           |Ŧ           |Đ|Őr	 ddlwm>}  |Ɖ j         j        |Ő          }|rt'          |Ǧ          }n# t\          $ r d}Y nw xY w|Đ j        r j        )                    d          nd}|D ]X}t=          |t                    s|ɠy                    d}          pd)                    d          }|Ȑr||k    r|ɠy                    di           }t=          |t                    r|ˠy                     j        i           }t=          |t                    r|̠y                    d          }|́	 t'          |ͦ          }|dk    rt`          nu# t^          t`          f$ r_ ts                      j                            d j        |ͦ           tS          d j        d|͛dtt          j;                   Y nw xY w nZ|ĉ _?         @                    |Ħ           d}d"}Аd}	 t=          |t                    r|y                    di           ni }|Ҡy                    dd          pd}n# t\          $ r Y nw xY w|ѐdk    r	 ddlAmB}  ||Ѧ          }n?# t\          $ r2}ts                      j                            d|Ԧ           Y d}~nd}~ww xY w|πd}	 ddlCmD}  |֦            }n# t\          $ r d}Y nw xY w|Ձm|ՐjE        |k    raddlF}	 |אG                    |զ          }nD# t\          $ r7}d}ts                      j                            d ||ئ           d}Y d}~nd}~ww xY w|π*|s(ts                      j                            d!|Ѧ           |ρ|ω _H        d _3        dd"lImJ}  |ى j         j        t           dzd          |ĉ j"        |Ő#          }ډ jH        K                     j        |ډ j        t           dzd           j"         j&        $            j        s.ts                      j                            d%|ϐjE                   nSt           j        ||||d j         j        t           dzd          |ĉ j"         j&        | jl        &           _H        t           jH        d'd          }ېt          |ۦ          r%	  ||= j        (           n# t\          $ r Y nw xY w| _N        | _O        | _P        t           jH        dd          }|rS|ܐt          k     rGta          d) j         d*|dd+t          dd,t          d-z   d.t          d-z   d/           j        s j        pddk    r	 dd0lRmS}  |݉ j        pd          }|rvd1}tk           d2          r                     |ߦ           n%tS          d3|ߛ d3tt          j;                   ts                      j                            |ަ           n# t\          $ r Y nw xY wty                       _T        tk           d4          r jH        r j         jj        
d5 jj        v rd6  j        D             }dd7lmU}  jH        V                                D ]} ||          }|)ts                      j                            d8|           8|d9         }||v rFd:|d;} j        W                    |            j        X                    |            jT        X                    |           |X                    |           tk           d4          r jH        r	  jH        Y                     j        t?          t                                 j        pdΉ j        t           jH        dd          t           d<d          =           n?# t\          $ r2}ts                      j                            d>|           Y d}~nd}~ww xY wt          t          j        d?          pd@           _[        d _\        d" _]        d _^        d __        d _`        d _a        d _b        d _c        d _d        d _e        d _f        dA _g        dB _h        d _i        d _j        d}t=          |t                    r|y                    dC          }|Y	 t'          |           _j        nA# t^          t`          f$ r+ ts                      j                            dD|           Y nw xY w jj         j        rt           j                  r	 t=           j        t>                    r j        nd}t           j         j        |pdE          }|r|dk    r| _j        n?# t\          $ r2}ts                      j                            dF|           Y d}~nd}~ww xY w jj        rG|rE|C jj        |k    r7ts                      j                            dG jj        |Ħ           |ĉ _j         jj        r5 j        s.ts                      j                            dH jj                   t           dId          }t          |          o|o|ot          |           } j        s|rct           jH        dJ|          }tS          dK jH        jn        ddLt'          |dMz             dN jH        jo        dd5           n#tS          dK jH        jn        ddO           |rtS          t          |                     d _q        |rt          |           _q        |rt          |           d" _s         jH        } j         j"         j         j&        t           dzd          t           j                   jt         ju        t          |dy j                  t          |d} j                  t          |dzd          t          |dx j"                  |jn        |jo        dP _t         j&        dk    r2 jt        u                     j         j         j        dQ           dS dS (T  a  
    Initialize the AI Agent.

    Args:
        base_url (str): Base URL for the model API (optional)
        api_key (str): API key for authentication (optional, uses env var if not provided)
        provider (str): Provider identifier (optional; used for telemetry/routing hints)
        api_mode (str): API mode override: "chat_completions" or "codex_responses"
        model (str): Model name to use (default: "anthropic/claude-opus-4.6")
        max_iterations (int): Maximum number of tool calling iterations (default: 90)
        tool_delay (float): Delay between tool calls in seconds (default: 1.0)
        enabled_toolsets (List[str]): Only enable tools from these toolsets (optional)
        disabled_toolsets (List[str]): Disable tools from these toolsets (optional)
        save_trajectories (bool): Whether to save conversation trajectories to JSONL files (default: False)
        verbose_logging (bool): Enable verbose logging for debugging (default: False)
        quiet_mode (bool): Suppress progress output for clean CLI experience (default: False)
        ephemeral_system_prompt (str): System prompt used during agent execution but NOT saved to trajectories (optional)
        log_prefix_chars (int): Number of characters to show in log previews for tool calls/responses (default: 100)
        log_prefix (str): Prefix to add to all log messages for identification in parallel processing (default: "")
        providers_allowed (List[str]): OpenRouter providers to allow (optional)
        providers_ignored (List[str]): OpenRouter providers to ignore (optional)
        providers_order (List[str]): OpenRouter providers to try in order (optional)
        provider_sort (str): Sort providers by price/throughput/latency (optional)
        openrouter_min_coding_score (float): Coding-score floor (0.0-1.0) for the
            openrouter/pareto-code router. Only applied when model == "openrouter/pareto-code".
            None or empty = let OpenRouter pick the strongest available coder.
        session_id (str): Pre-generated session ID for logging (optional, auto-generated if not provided)
        tool_progress_callback (callable): Callback function(tool_name, args_preview) for progress notifications
        clarify_callback (callable): Callback function(question, choices) -> str for interactive user questions.
            Provided by the platform layer (CLI or gateway). If None, the clarify tool returns an error.
        max_tokens (int): Maximum tokens for model responses (optional, uses model default if not set)
        reasoning_config (Dict): OpenRouter reasoning configuration override (e.g. {"effort": "none"} to disable thinking).
            If None, defaults to {"enabled": True, "effort": "medium"} for OpenRouter. Set to disable/customize reasoning.
        prefill_messages (List[Dict]): Messages to prepend to conversation history as prefilled context.
            Useful for injecting a few-shot example or priming the model's response style.
            Example: [{"role": "user", "content": "Hi!"}, {"role": "assistant", "content": "Hello!"}]
            NOTE: Anthropic Sonnet 4.6+ and Opus 4.6+ reject a conversation that ends on an
            assistant-role message (400 error).  For those models use structured outputs or
            output_config.format instead of a trailing-assistant prefill.
        platform (str): The interface platform the user is on (e.g. "cli", "telegram", "discord", "whatsapp").
            Used to inject platform-specific formatting hints into the system prompt.
        skip_context_files (bool): If True, skip auto-injection of project context files
            (SOUL.md, .hermes.md, AGENTS.md, CLAUDE.md, .cursorrules) from the cwd / HERMES_HOME
            into the system prompt. Use this for batch processing and data generation to avoid
            polluting trajectories with user-specific persona or project instructions.
        load_soul_identity (bool): If True, still use ~/.hermes/SOUL.md as the primary
            identity even when skip_context_files=True. Project context files from the cwd
            remain skipped.
    Non rM   >   codex_responsesbedrock_conversechat_completionscodex_app_serveranthropic_messageszopenai-codexr   >   	xai-oauthxaizchatgpt.comz/backend-api/codexzapi.x.air   	anthropiczapi.anthropic.comr   r,   z
/anthropicbedrockzbedrock-runtime.zamazonaws.comr   r   r   )_AGGREGATOR_PROVIDERSnormalize_model_for_providerzcopilot-acpzacp://copilotz
acp+tcp://)ro   _transport_cache
openrouterTzopenrouter-prewarm)targetdaemonrw   F5m)load_configprompt_caching	cache_ttl>   1hr   initializing)activeseen_below_90
usage_band)setup_loggingsetup_verbose_logging)hermes_homez=Verbose logging enabled (third-party library logs suppressed))build_anthropic_clientresolve_anthropic_token)build_anthropic_bedrock_clientzbedrock-runtime\.([a-z0-9-]+)\.r-   z	us-east-1zaws-sdku&   🤖 AI Agent initialized with model: z& (AWS Bedrock + AnthropicBedrock SDK, )zminimax-oauth)"build_minimax_oauth_token_providerz{MiniMax OAuth: failed to install per-request token provider (%s); falling back to static bearer that will expire ~15min in.)_is_oauth_token)timeoutz (Anthropic native))is_token_provideru*   🔑 Using credentials: Microsoft Entra ID   u   🔑 Using token:    z...moa)	MoAClienteventr)   kwargsr   r(   r[   c           	        t          dd           }|d S 	 | dk    rt          |                    d          pd          }t          |                    d          pd          }|                    d          }|                    d          } |d||d ||           d S | d	k    rG |d	t          |                    d
          pd          d d |                    d                     d S d S # t          $ r Y d S w xY w)Nr   zmoa.referencelabelrM   textindexcount)	moa_index	moa_countzmoa.aggregating
aggregator	ref_count)moa_ref_count)r   r)   r4   	Exception)r   r  cbr  r  idxr  r   s          r#   _moa_reference_relayz(init_agent.<locals>._moa_reference_relay;  sS    8$??BzO++

7 3 3 9r::Evzz&117R88D **W--C"JJw//EB'"%"'      ///B)FJJ|44:;;&,jj&=&=      0/    s   B	C2 #AC2 2
D ?D default)reference_callbackzmoa-virtual-providerzmoa://localu+   🤖 AI Agent initialized with MoA preset: 	guardrailguardrail_identifierguardrail_version)guardrailIdentifierguardrailVersionstream_processing_modestreamProcessingModetracez + Guardrailsz (AWS Bedrock, )queryc                &    i | ]\  }}||d          S )r   rH   ).0kvs      r#   
<dictcomp>zinit_agent.<locals>.<dictcomp>  s/     ! ! ! $1Aqt! ! !r%   )r   rp   default_query)r   rp   r   r   r   zopenrouter.ai)build_or_headersdefault_headerszintegrate.api.nvidia.com)build_nvidia_nim_headerszapi.routermint.comzgithubcopilot.com)copilot_default_headerszapi.kimi.comz
User-Agentzclaude-code/0.1.0zportal.qwen.ai)_codex_cloudflare_headers)get_provider_profile)resolve_provider_clientauto)r+   	raw_codex_custom_headers_default_headers>   r(  ru   r   _API_KEY)PROVIDER_REGISTRYc                    g | ]C}t          |t                    |                    d           ,|                    d          A|DS ro   r+   rg   rz   r4   r  fs     r#   
<listcomp>zinit_agent.<locals>.<listcomp>  s_     ' ' '"#)!T22'78uuZ7H7H'MNUUSZ^^'' ' 'r%   ro   r+   r   key_envapi_key_envrp   )r+   r)  explicit_base_urlexplicit_api_keyz
Provider 'z:' is set in config.yaml but no API key was found. Set the zM environment variable, or switch to a different provider with `hermes model`._fallback_activatedzxNo LLM provider configured. Run `hermes model` to select a provider, or run `hermes setup` for first-time configuration.claudezx-anthropic-betaz&fine-grained-tool-streaming-2025-05-14,)4apply_custom_provider_extra_headers_to_client_kwargs*apply_custom_provider_tls_to_client_kwargsget_compatible_custom_providersr   z&custom-provider TLS resolution skipped)exc_info)verify_ca_bundle_with_fallback
agent_init)reasonsharedu   🔗 Using custom base URL: nonez	dummy-keyu   🔑 Using API key: u3   ⚠️  Warning: API key appears invalid or missingz$Failed to initialize OpenAI client: c                    g | ]C}t          |t                    |                    d           ,|                    d          A|DS r/  r0  r1  s     r#   r3  zinit_agent.<locals>.<listcomp>k  s^     !
 !
 !
!T""!
'(uuZ'8'8!
=>UU7^^!
!
 !
 !
r%   u   🔄 Fallback model:  (u   🔄 Fallback chain (z providers): u    → c              3  >   K   | ]}|d           d|d          dV  dS )r+   rE  ro   r   NrH   r1  s     r#   	<genexpr>zinit_agent.<locals>.<genexpr>}  s;      ``Q!G*@@*@@@``````r%   )registry)r   r   r   c                *    h | ]}|d          d         S functionrw   rH   )r  tools     r#   	<setcomp>zinit_agent.<locals>.<setcomp>  s"    !S!S!St$z"26":!S!S!Sr%   u   🛠️  Loaded z tools: z, u      ✅ Enabled toolsets: u      ❌ Disabled toolsets: u@   🛠️  No tools loaded (all tools filtered out or unavailable))KANBAN_GUIDANCEkanban_showc                    g | ]	\  }}||
S rH   rH   )r  rw   	availables      r#   r3  zinit_agent.<locals>.<listcomp>  s"    ZZZyPYZZZZr%   u=   ⚠️  Some tools may not work due to missing requirements: u   📝 Trajectory saving enabled<   u   🔒 Ephemeral system prompt: 'z' (not saved to trajectories)znative AnthropiczAnthropic-compatible endpointzClaude via OpenRouteru   💾 Prompt caching: ENABLED (z TTL)z%Y%m%d_%H%M%S   _)set_current_session_idHERMES_SESSION_IDsessionsr]   write_json_snapshotsassistant_tool
foreground)CheckpointManager)enabledmax_snapshotsmax_total_size_mbmax_file_size_mb)r   r   r   )	TodoStoretool_loop_guardrailsz&Tool loop guardrail config ignored: %sr   memorymemory_enableduser_profile_enablednudge_interval)MemoryStorememory_char_limiti  user_char_limiti_  )rg  rh  )MemoryManager)load_memory_providercliprimary)r   r   r   agent_contextr   warning_callbackr   session_titler   r   r   r   r   r   r   r   )get_active_profile_nameagent_identityhermesagent_workspacezMemory provider '%s' activatedz/Memory provider '%s' not found or not availablez&Memory provider plugin init failed: %s)inject_memory_provider_toolsskillscreation_nudge_intervalr   tool_use_enforcementintent_ack_continuationtask_completion_guidanceparallel_tool_call_guidanceenvironment_probe)warm_environment_probe_asyncplatform_hintsapi_max_retries   compression	thresholdg      ?codex_gpt55_autoraise>   1yestruecodex_gpt55_autoraise_notice) _compression_threshold_for_model_is_codex_gpt54_or_gpt55_is_codex_spark)allow_codex_gpt55_autoraise)r+   rD   r\  target_ratiog?protect_last_nr   protect_first_nabort_on_summary_failurein_place)r  codex_app_server_autonative>   offrr  r  zdInvalid compression.codex_app_server_auto=%r; using 'native'. Valid values are: native, hermes, off.	auxiliarycontext_lengthr   uy   Invalid model.max_tokens in config.yaml: %r — must be a positive integer (e.g. 4096). Falling back to provider default.u.   
⚠ Invalid model.max_tokens in config.yaml: zO
  Must be a positive integer (e.g. 4096).
  Falling back to provider default.
)fileu   Invalid model.context_length in config.yaml: %r — must be a plain integer (e.g. 256000, not '256K'). Falling back to auto-detection.u2   
⚠ Invalid model.context_length in config.yaml: zf
  Must be a plain integer (e.g. 256000, not '256K').
  Falling back to auto-detected context window.
)r=  rq   )"get_custom_provider_context_length)r+   rp   rq   modelsu   Invalid context_length for model %r in custom_providers: %r — must be a positive integer (e.g. 256000, not '256K'). Falling back to auto-detection.u&   
⚠ Invalid context_length for model z in custom_providers: zi
  Must be a positive integer (e.g. 256000, not '256K').
  Falling back to auto-detected context window.

compressorcontextengine)load_context_enginez4Context engine load from plugins/context_engine/: %s)get_plugin_context_engineu   Context engine '%s' could not be safely copied for this agent (%s) — falling back to built-in compressor. Plugin engines that hold uncopyable state (locks, DB connections) should implement __deepcopy__ to copy only mutable budget state.uE   Context engine '%s' not found — falling back to built-in compressor)get_model_context_length)rp   r   config_context_lengthro   rq   )r+   r  rp   r   ro   r   zUsing context engine: %s)r+   threshold_percentr  r  summary_target_ratiosummary_model_overrider   rp   r   r  ro   r   r  r   bind_session_state)
session_dbr   zModel z has a context window of z$ tokens, which is below the minimum z9 required by Hermes Agent.  Choose a model with at least i  zK context.  If your server reports a window smaller than the model's true window, set model.context_length in config.yaml to the real value (this must be at least zK).)_check_hermes_model_warningu   ⚠ Nous Research Hermes 3 & 4 models are NOT agentic — they lack reliable tool-calling for agent workflows (delegation, cron, proactive tools). Consider an agentic model instead (Claude, GPT, Gemini, Qwen-Coder, etc.)._emit_warning
context_compressorcontext_enginec                    h | ]@}t          |t                    |                    d i                               d          AS rJ  r0  )r  ts     r#   rM  zinit_agent.<locals>.<setcomp>p  sT      
  
  
!T"" 
EE*b!!%%f-- 
  
  
r%   )normalize_tool_schemazkContext engine returned a tool schema with no resolvable name; skipping to avoid poisoning the request (%r)rw   rK  )typerK  _gateway_session_key)r   r   r+   r  conversation_idz#Context engine on_session_start: %sTERMINAL_CWD)working_dirg        unknownollama_num_ctxz'Invalid ollama_num_ctx config value: %r)r   z#Ollama num_ctx detection failed: %sz?Ollama num_ctx capped: %d -> %d (model.context_length override)zAOllama num_ctx: will request %d tokens (model max from /api/show)!_compression_threshold_autoraisedr  u   📊 Context limit: z tokens (compress at r2   z% = z# tokens (auto-compression disabled))r+   ro   rp   r   r   client_kwargsuse_prompt_cachinguse_native_cache_layoutcompressor_modelcompressor_base_urlcompressor_api_keycompressor_providercompressor_context_lengthcompressor_threshold_tokens)anthropic_api_keyanthropic_base_urlis_anthropic_oauth)r   r)   r  r   r(   r[   rH   (v  r   r+   r   r   r   r   r   r   r   r   r   r   _user_id_user_id_alt
_user_name_chat_id
_chat_name
_chat_type
_thread_idr  	_print_fnbackground_review_callbackmemory_notificationsr   r   r   _credential_poolr   r   rp   rg   r)   r5   r6   ro   r   listr   r   _base_url_hostname_base_url_lowerrh   endswithr8   r   _get_transportr  hermes_cli.model_normalizer   r   _is_azure_openai_url_is_direct_openai_url&_provider_model_requires_responses_apihasattrr   clear_is_openrouter_urlr$   _openrouter_prewarm_doneis_setset	threadingThreadr   startr   r   r   suppress_status_outputr   r   r   r   r   r   r   r   r   r   r   r   _executing_toolsr   _tool_guardrails_tool_guardrail_halt_decision_interrupt_requested_interrupt_message_execution_thread_id _interrupt_thread_signal_pendingRLock_client_lock_pending_steerLock_pending_steer_lock_tool_worker_threads_tool_worker_threads_lock_delegate_depth_active_children_active_children_lockr   r   r   r   r   r   r   r   r   r   r   r   rz   r   r   _force_ascii_payload_anthropic_prompt_cache_policy_use_prompt_caching_use_native_cache_layout
_cache_ttlhermes_cli.configr   r4   _budget_exhausted_injected_budget_grace_calltime_last_activity_ts_last_activity_desc_current_tool_api_call_count_skip_mcp_refresh_tool_snapshot_generation_rate_limit_state_credits_state_credits_session_start_micros_credits_latch_or_cache_hitshermes_loggingr   r   _hermes_homeloggerinfo_stream_callback_stream_needs_breakr   _stream_context_scrubberr   _stream_think_scrubber _current_streamed_assistant_text_persist_user_message_idx_persist_user_message_override_persist_user_message_timestamp_anthropic_image_fallback_cache_anthropic_client_is_anthropic_oauthr   agent.anthropic_adapterr   r   r   researchgroup_bedrock_region_anthropic_api_key_anthropic_base_urlr   client_client_kwargsprinthermes_cli.authr   logging	getLogger__name__warningr   agent.azure_identity_adapterr   lenagent.moa_loopr   _bedrock_guardrail_configr
   r  r   _replacer   itemsagent.auxiliary_clientr!  r#  _routermint_headershermes_cli.modelsr$  _qwen_portal_headersr%  	providersr&  r"  r'  r   upperr-  api_key_env_varsosgetenvr8  RuntimeError_apply_user_default_headersr;  r<  r=  debugagent.ssl_guardr?  _create_openai_client_fallback_chain_fallback_index_fallback_modeljointools.registryrH  _generationget_tool_definitionstoolsvalid_tool_namessortedagent.prompt_builderrN  _kanban_worker_guidancecheck_toolset_requirementsr   nowsession_startr   strftimeuuiduuid4hexgateway.session_contextrU  environr   logs_dirra   _session_json_enabledrE   _session_messages_codex_reasoning_replay_enabled_memory_write_origin_memory_write_context_cached_system_prompttools.checkpoint_managerr[  _checkpoint_mgr_session_db_parent_session_id_last_flushed_db_idx_session_db_created_end_session_on_close_persist_disabled_session_init_model_configtools.todo_toolr`  _todo_storer   from_mapping&_aux_compression_context_length_config_memory_store_memory_enabled_user_profile_enabled_memory_nudge_interval_turns_since_memory_iters_since_skillr9   tools.memory_toolrf  load_from_disk_memory_manageragent.memory_managerri  plugins.memoryrj  is_availableadd_providerr  _emit_statusget_session_titlehermes_cli.profilesrp  initialize_allrt  _skill_nudge_interval_tool_use_enforcement_intent_ack_continuation_task_completion_guidance_parallel_tool_call_guidance_environment_probetools.env_prober|  _platform_hint_overridesmaxrW   rX   _api_max_retriesr@   r  r  r  r  rI   r   r   sysstderr_custom_providersr   r  _config_context_length_ensure_lmstudio_runtime_loadedplugins.context_enginer  hermes_cli.pluginsr  rw   copydeepcopyr  agent.model_metadatar  update_modelr   r   compression_enabledcompression_in_place codex_app_server_auto_compactionr   hermes_cli.model_switchr  _context_engine_tool_namesr  get_tool_schemasappendaddon_session_startr   _subdirectory_hints_user_turn_count_is_user_initiated_turnsession_prompt_tokenssession_completion_tokenssession_total_tokenssession_api_callssession_input_tokenssession_output_tokenssession_cache_read_tokenssession_cache_write_tokenssession_reasoning_tokenssession_estimated_cost_usdsession_cost_statussession_cost_source_ollama_num_ctxr   r   rZ   r  threshold_tokensr>   _compression_warningrd    _compression_feasibility_checked_primary_runtimer   )r   rp   r   ro   r   r   r   r   r   r+   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   credential_poolr   r   r   r   r   provider_namer   r   _load_pc_cfg_pc_cfg_ttlr   r   _provider_timeoutr   r   _is_bedrock_anthropicr   _region_match
_br_region_is_native_anthropiceffective_keyr   _mm_exc_logging_is_oatr   r   r  _load_br_cfg_gr	_gr_label_parsed_url
_clean_url_query_paramsr  effective_baser!  r#  r$  r%  _gpf_phr'  _routed_clientrT  _routed_headers	_explicit	_env_hintr-  _pcfg_fb_entries_fb_resolved_fb_fb_explicit_key_fb_key_env
_fb_client	_fb_model_fb_headers_effective_baseheadersexisting_beta_FINE_GRAINEDr;  r<  r=  r   
_cp_config_cp_entries_cp_base_urlr?  key_usedefb_snapshot_registry
tool_namesrN  requirementsmissing_reqsprompt_previewsourcetimestamp_str
short_uuidrU  r   _load_sess_cfg	_sess_cfgr[  r`  _load_agent_config
_agent_cfg_tlg_err
mem_configrf  _mem_provider_name_MemoryManager	_load_mem_mp_init_kwargs_strp  _profile_mpe_inject_memory_provider_toolsskills_config_agent_sectionr|  _platform_hints_cfg_raw_api_retries_api_retries_compression_cfgcompression_threshold_codex_gpt55_autoraise_codex_gpt55_autoraise_notice_cthresh_fn_is_codex_gpt54_or_gpt55_fn_is_codex_spark_fn_model_cthreshr  compression_target_ratiocompression_protect_lastcompression_protect_first$compression_abort_on_summary_failurer  r  _aux_cfg_aux_context_config
_model_cfg_config_max_tokens_parsed_max_tokensr|  r{  r  _cp_ctx_resolved_target	_cp_entry_cp_url
_cp_models_cp_model_cfg_cp_ctx_parsed_selected_engine_copy_failed_engine_name_ctx_cfgr  _ce_load_err
_candidater  r  	_copy_errr  _plugin_ctx_len_bind_session_state_ctxr  _hermes_warn	_user_msg_existing_tool_names_normalize_tool_schema_raw_schema_schema_tname_wrapped_ce_err_ollama_num_ctx_override_key_for_ollama	_detectedexc
_autoraise_show_autoraise_notice_active_threshold_pct_ccs   `                                                                                                                                                                                                                                              r#   
init_agentr    s>>   t EK)E .P1P1PE!E/E+E!E1E$;E!ENEN$E EEN E E E!4E
 EO'+E$!%E1E1E+E,E-E+5=*''''2E^EN0:8S0I0IhhnnN^N^hHNN$$**,,,dhM"(bEN#.wE(0d0b11ENxxx!	>	)	)*	/	/	/*

 M11 E$999*'

U%=%K%K*	;	&	&=+@UE]atEtEt-$			%	%c	*	*	3	3L	A	A , .	9	$	$ ++,>?? 
%!%"7II 
% ,+   		
 	
 	
 	
 	
 	
 	
 	

 >!66666u{ENSSEK     	N000Nm++EN(b))//11<<_MM ,EN(b))//11<<\JJ , **,, ,
 '')) , ;; <   , + 5,-- 	+"((*** 	,&&%*B*B*D*D&.5577 	'&**,,,'%	
 	
 	
 %'''#9E  3E#9E #(E /E1E-E#9E 'E"7E'AE$+E+E"7E)E/E
 #E8::EHLE' "'E#E-1E-2E*"**E +/E ) 0 0E ,/55E&/n&6&6E# EE"+."2"2E 0E/E+E'E(CE%%=E"(CE% .E/E "E-E%E"#4#:;;E-3E!&E 	,,.. >Eu= EAAAAAA,..$$%5r::@b{{;--<#E    (-E$$E &*Y[[E%3E&*E!"E $E '(E# ;?E  E*.E'&)eeeSWXXE !"E
 DCCCCCCCMcee01111 YZZZZ		  	 "E !&E &>%?%?E" $:#;#;E 
 .0E*
 '+E#+/E(,0E)
 =?E) #E %E 5U^U[QQ~---[[[[[[[[ !&) ;  I	[NNNNNNI&H(.VXYYM3@Q,,Q///kJ$.E!&D&DZ&P&PE#'0E$(0E%(-E%%EMEL#%E # Au{r|  A  A  A
 $)>[#@ L`uWG(?(?(A(AGRgngtrtM ~00Zs5S5S0Xe0	RRRRRR$F$F$H$HMM    ....&&x0088Z        *EM'4E$(0E% KJJJJJCW  )G\fgtvy\z\z  )G(>(>(>  BGE%&<&<]H^o&p&p&pE#EL#%E # [_u{___``` KJJJJJ$$]33 [FGGGGs33 [M8J8JR8O8OY}RaR/@YY]SUSVSVEWYYZZZ	5	 	 ,,,,,,+	 	 	 	 	 	: !yK$93
 
 
  "9#9& 	OMMMNNN	-	-	- 	"DhnRTUU:G X 3 3A 6 6 6[*.'	EEEEEE,..$$Y3377RHHCww-.. L377;N3O3O L+./E+F(+,?(@3 3/ 77344 lNQRjNkE34JK777## L?B7|E3G< 	 	 	D	! 	|+0+JRPRIz5;zzW\Wlznwzzz{{{ U	x U	 #8,,K  K'(<(<2(<(F(FGG
! !(01B(C(C(I(I(K(K! ! !  ' *%2! ! -4 J J ,+<i(~..+0+<i((-f%%N$^_EE CCCCCC3C3C3E3E/00&~7QRR KKKKKK3K3KN3[3[/00&~7KLL 36553L3L3N3N/00&~7JKK EEEEEE3J3J3L3L/00&~~FF  "54/00 '~7GHH 36553M3M3O3O/00&~}EE LLLLLL3L3LW3U3U/00"-77FFFFFF$u~..C Us2 U;?@S;T;T&78    D 8 GFFFFF 7 7(&t!M !M !MNA)-5 #N$; < <! ! %0/@M),
 #*.:KT"R"R& W&-n>OQU&V&VO& X&-n>PRV&W&WO" M7;O7L7LM"34
 #^1r88::@@BB	 92R!R!R $-??#4#4 > > >IEEEEEE 1 5 5i @ @  BU%; B(-(>q(AI$    #%K!.$77 7' ''5' ' ' $ND99 7n>P>PQ[>\>\ 7aoasast{a|a| 7'5&6#(L* " ",/GGI,>,>,D"+K+K+M+M+UQU(/ ^+.779+=+=+]AWAW+][]*d*d*f*fK* ^359["3M3M3S3S3U3U3]Y] 00G0G
O3w<4.1ggj.A.A-=1 1 1-
I
 &1-0_EN*3*Cs7|EK8<E5+5+=,/
0C,D,D- -M  1<;Li 8*1*>OQU*V*VK#. [.5jBSUY.Z.Z#. \.5jBTVZ.[.[* UCGCTCT.? @+/L!E% 2& ( *` ` `2;` ` `  
 u&;UCC &)    - m//
B??@@FFHH /BB 		;xTYT_TeceSlSlSnSnGnGn#''(9::@bG#KK(:B??MDMM11  @5B2T2T]2T2TG.//2?G./3:/0 	))+++	R            %J99*EEK}00<<TTRTUUL66   A@   
  	R 	R 	RLLADLQQQQQ	R &)))R88&**:u~FF	KFFFFFF**,,, 66}\bf6ggEL# QLu{LLMMM ECCCDDD
 KJJJJJ(,,Y??$$X.. QFGGGG#.. Q8 QK@W@W\_`h\i\iln\n\nQ"1"QQ(233-QQRRRROPPP 	K 	K 	KIaIIJJJ	K .$'' #!
 !
%!
 !
 !
 
ND	)	) #n.@.@.L.L #Q_QcQcdkQlQl #!/ 0 "E '/De L LE8=8MWE1!44SWE bU%5 bu$%%**&q)BJ"W+JJJJJJKKKKS#e.C*D*DSSS,,``%J_`````a b b b,AAAAAA*<*H'' , , ,*+''',%%,,)+# -  EK !UUE{ R!S!Su{!S!S!SE233
 	SVS%5%5VVtyy?T?TVVWWW QO$))<L2M2MOOPPP  SQ499=N3O3OQQRRR RPQQQ 544444(E,BBB 
!
 { b5+ buu7799ZZL4F4F4H4HZZZ 	b`R^``aaa  0u'7 0./// $ _U-= _GJ5KhGiGilnGnGn6ss;eCCty  uR]]]]^^^   R)9 R) 	-en.K.K'FF+ 	-4FF,FPvPP9IPPPQQQ #,..E ;% +44_EEZ\\%bqb)
+::j::;BBBBBBu/0000 ; ; ;*/*:
&'''; "##K :-EN	N555
 #(ECCCCCC#^%%))*55;	&*9==9OQV+W+W&X&X##    57E -1E)!1E".E 26E ;:::::--#.64	  E #E0E!"E %E #'E
 $E., ( (E$ *)))))!	EGGGGGG''))

   


Q!<#05r:: "
 "

  Q Q QExPPPPPPPPQ
 48E0 E!E"'E#%E  !E E 	#"55J$.NN3CU$K$KE!*4..9OQV*W*WE'+.z~~>NPR/S/S+T+TE($ 5(C 5999999&1k&0nn5H$&O&O$.NN3Dd$K$K' ' '# #22444 	 	 	D	 !E ?)>	)CM!U
B!?!?!?SU! 81&8&>&>&@&@ 81PPPPPPLLLLLL(6(8(8%i 233 <3++-- <)66s;;;(2 11&+&6$,$5'*?+<+<'='=)2	$ $L $J/588;@;N%78:?:L%67 ( !!"'"3"E"EeFV"W"WC" D@C_ =( ! ! ! D! ~ A27.Y/) I6;6H]3' E494D[1~ A27.Y/' E494D[1' E494D[1' E494D[11 Y>C>X%:;OOOOOO#:#:#<#<9A%56:B%677$   8E)8HH<HHHEEL%%&FHZ[[[[EEL&&'XZlmmm,0E) 	) 	) 	)EEL  !I4PPP$(E!!!!!!	) cbbbbb!!%((( #%E"x44&)-*;*;<UWY*Z*Z&[&[##   
  ^^GR00Nnd++ "0"4"45KV"T"TE &4%7%78QSY%Z%ZE" '+>+=+=>XZ^+_+_&`&`E# *.n.@.@A^`d.e.e)f)fE&  $N$6$67JD$Q$QRRE  	DDDDDD((**** 	 	 	D	 %..)92>>)400 ! %8E")--.?CC+,,<++z"   )E
 "~~mR88&-- !"2"6"6{D"I"IJJ !4d;; egg%& %(;TBB% %egg%%&! /3E+	
 	
 	
 	
 	
 	
 	
 	
 	
 	

 %KN(>
 
 
 +%k//U^LL G))%+u~FF   	GuFF    .229dCCDDJJLLPdd$%5%9%9.$%O%OPP"#3#7#78H"#M#MNN !$	3##$5q99::! ! ,/7??, ,egg%,&( +Z((%   (+4h??K8( (egg % (/JJJ5,	
 	
 	

 ,4(
:{M2NNN   (D!! #&ll+;<<"&	'"%&9":"::& 	' 	' 	'"&	'3FE0 ,,JJz4$@$@'^^L99)0$77 %$$%();%<%<"%**$$#5  z*   $$8 '	   =FX = = = 	      6;5EE$\2 *d## &!+0@!A!A!%)	*%()?%@%@"":& 	* 	* 	*EEL  2 '	   EF\ E E E Z	    &*"""	*"#EEEEEE;;JGG # # #&NN+=>>+T22 	# "# 0E%e->??? %*;%
	$LLLLLLAAk!2     
   ?),-=)>)>& 	$ 	$ 	$#	$
 ")49NJen++C000G.  	!)T22 $==44:BB3GG w'11!*x!<!<J!*d33 &(2u{B(G(G%mT:: &&3&7&78H&I&IG&2!&.1'llG'.!||.8(8 (4(1:'> !& !& !&$'EEL$8$8)J ).W%& %& %& %*)]RWR] )] )]w~ )] )] )] .1Z	%& %& %& %& %& %&!& E $:E 	))*@AAA LL4>z44P4PX:>>)R000VX||Hl;;K|    |##	eBBBBBB22<@@ 	e 	e 	eEELUWcdddddddd	e #J"HHHHHH6688

 " " "!


"%*/\*I*I ,'+}}Z'@'@$$  
, 
, 
,#'LEEL((!
 %i   (,$$$$$$
, #L#EEL  W   ##3  37/AAAAAA22K^E9b11"8^.
 
 
 	 --+*^E9b11^^ 	. 	
 	
 	
  	QEEL8:J:OPPP#4+353!9#''^E9b11"8^^%I'$
 $
 $
   "%":<PRVWW#$$ 	:%BRSSSSS 	 	 	D	 3E!5E-ME* 5+-=qAAD 	
---JU[ J J4L J J*@NJ J &-J J '=&DJ J J
 
 	
"  !85U B B	KKKKKK66u{7HbIIL 3?  5/22 ?''	2222,y,,,3:>>>>$$\222 	 	 	D	" -0EEE$+,,"-$"- K#"*5#999 
  
[ 
  
  

 	YXXXXX 3DDFF 	- 	-K,,[99G $$I  
 V_F--- *@@HKx((("&&v...,00888 $$V,,,, u*++ O0H O
	O$55  1 12205k&u'?AQSTUU '/Et L L 6      	O 	O 	OEELDgNNNNNNNN	O !8In--5! ! !E E$)E! #$E&'E#!"EE!"E"#E&'E#'(E$%&E"'*E$ )E &E )-E#*d## D#->>2B#C#C +	d$'(@$A$AE!!:& 	d 	d 	dEELHJbccccc	d$$<Men<]<]$
	K
 0:%-/M/MUemmSUO,U[%.RaRgeghhhI 2Y]](1% 	K 	K 	KEELDcJJJJJJJJ	K 	
7"
7 %,!$:::M!#9	
 	
 	
 !7 
U%5 
O!	
 	
 	
  CTJJJZ 	?	?)	? 3:>>>	   B 		y %,(*=?T% %!   |)A)P  |  |  |il  nC  DG  nG  jH  jH  |  |  NS  Nf  Nw  |  |  |  |  }  }  }  }w)A)Pwwwwxxx " 	B4Z@@AAA
 "&E  T%G
%S%S"
  9,Z888 .3E* 
"CNNN5)R00e233#7#(#A $C%+>>&sJGG%c9b99&sJGG%(%7'*';# E& ~---%%!&!9"'";"'";'
 '
 	 	 	 	 	 .-s  ?J 
J! J!%,K 
KKAZ! !
Z.-Z.d% %
e,/3e''e,"Co% %
o21o2>6x6 6
yy.1}   
}-,}-IA&AJ, J,'AKKAKLDAP P
AP9P!AP4P4AP9VAV# V#AV7V6AV7a9Ab bAb2b1Ab2c2AAe e
AeeAeg(Ag9 g9AhhAhh<Ai	 i	
Aji'Ai?i?AjkC&An) n)
An6n5An6oC0Ax r6(As sAx s
As,s)Ax s+As,s,BAx u8Av vAx v
Av"vAx v!Av"v"A/Ax x
Ayx/AyyAyy4A Az5 z5
A{{A{~1A 
AA@
7BA ABAABAD-A1BF F
BF,F+BF,L+BM MBMMBMNBN NBN.N-BN.PABQ QA BR+R*BR+S0BT TA"BU&U%BU&U*BU= U=7BV7V6BV7W3BX XBXXBX\
B\)\)A/B^^B^_A	B` `
B``B``+Ba  a 
Ba<a
(Ba7a7Ba<bBb bBb'b&Bb'b>Bc c
Bdc-BddBdjBj j
Bj,j+Bj,m
BBo o
Bo+o*Bo+t;A6Bv2 v2
Bw.v<(Bw)w)Bw.{	B{  { ;B||B|}AB~ ~
B~$(BBr  )r&   r'   r(   r)   )
r?   r@   rA   rB   r+   rC   rD   rE   r(   rF   )r&   r'   r(   rE   )r&   r'   r(   r[   )re   r   r(   r)   )rj   r)   rk   r'   r(   rE   )
ro   r)   r+   r)   rp   r)   rq   rr   r(   rs   )rq   rr   r(   r[   )FNNNNNNNNrM   r   r   NNFFFr   Nr2   rM   NNNNFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFFNNNNNFr   r   r   F)rp   r)   r   r)   ro   r)   r   r)   r   r)   r   r   r   r)   r   r   r+   r)   r   r9   r   r@   r   r   r   r   r   rE   r   rE   r   rE   r   r)   r   r)   r   r9   r   r)   r   r   r   r   r   r   r   r)   r   rE   r   r)   r   rB   r   r)   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r9   r   r'   r   r)   r   r'   r   rr   r   r)   r   r)   r   r)   r   r)   r   r)   r   r)   r   r)   r   r)   r   r)   r   rE   r   rE   r   rE   r   r)   r   r   r   r'   r   rE   r   r9   r   r9   r   r9   r   rE   )B__doc__
__future__r   r  r.  r  ry  r  r  rE  r   typingr   r   r   r   r	   urllib.parser
   r   r   agent.context_compressorr   agent.iteration_budgetr   rg  r   r  r   r   r   r   agent.process_bootstrapr   agent.subdirectory_hintsr   agent.think_scrubberr   agent.tool_guardrailsr   r   r   r  r   hermes_cli.timeoutsr   hermes_constantsr   utilsr   r   r  r  r$   r>   rI   rK   rO   rZ   rd   ri   rn   r   r   r  __all__rH   r%   r#   <module>r.     s   & # " " " " "  				 				 



             6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 2 2 2 2 2 2 9 9 9 9 9 9            8 7 7 7 7 7 < < < < < < 7 7 7 7 7 7         
 & % % % % % < < < < < < , , , , , , 8 8 8 8 8 8 8 8 
	;	'	'     4  	           F? ? ?* * * *       % % % %D D D D* * * *Z( ( ( (* !%!"&#'#!##'#'#'!%(-$(37'+$('+"&#'!%'+"&*+/"& $ $&*<@'+(,-1#$$!*.%) %$&(+')!Oo o o o of9 .r%   