
    .cj                      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l0m1Z1 ddl2m3Z3m4Z4  ej5        d          Z6d Z7ddZ8ddZ9dd!Z:dd$Z;d%d&dd,Z<dd.Z=dd/Z>	 ddd4Z?dd5dd>Z@d? ZAdd@ZBddAZCddBZDddCZEddFZFddJZGddKZH	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dddZIdgZJd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)parse_qsurlparse
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normalize_route_base_url)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    2/home/ice/.hermes/hermes-agent/agent/agent_init.py_rar&   ?   s    
     agentr   returnboolc                X    t          | dd          dk    ot          | dd          dk     S )zEKeep MoA display events off only the machine-readable ``-Q`` surface.platformNclitool_progress_modealloff)getattr)r(   s    r%   _moa_reference_output_allowedr2   H   s=     	z4((E1 	AE/775@ r'   eventstrkwargsNonec           
        t          |           sdS t          | dd          }|dS 	 |dk    r} |dt          |                    d          pd          t          |                    d          p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)zERelay MoA display events while preserving the ``-Q`` stdout contract.Ntool_progress_callbackzmoa.referencelabel textindexcount)	moa_index	moa_countzmoa.aggregating
aggregator	ref_count)moa_ref_count)r2   r1   r4   get	Exception)r(   r3   r5   cbs       r%   _relay_moa_reference_eventrF   P   sS   (// 	0$	7	7B	zO##BFJJw''-2..FJJv&&,"-- **W-- **W--      '''B!FJJ|,,233$jj55      ('    s   BC: +AC: :
DDbase_urlc                     t          |           S )zBCanonicalize an endpoint URL for model-route identity comparisons.r   rG   s    r%   _normalize_route_base_urlrJ   m   s    #H---r'   providerset[str]c                \   t                      }	 ddlm}m} |                    |           } ||           }t          |dd          t          |dd          fD ](}t          |          }|r|                    |           )n# t          $ r Y nw xY w	 ddl	m
}  ||           }	t          t          |	dd                    }|r|                    |           n# t          $ r Y nw xY w	 ddlm}
 ddlm} ddlm} |
                                D ]U\  }} | ||                    }|| k    r t          t          |d	d                    }|r|                    |           Vn# t          $ r Y nw xY w| d
k    r,|                    d t#          |          D                        |S )z>Return known exact default routes for a canonical provider id.r   )HERMES_OVERLAYSget_providerbase_url_overrider:   rG   get_provider_profilePROVIDER_REGISTRYnormalize_providerinference_base_urlgeminic              3  F   K   | ]}|                     d            dV  dS )/z/openaiN)rstrip).0routes     r%   	<genexpr>z+_provider_default_routes.<locals>.<genexpr>   sK       
 
 ||C  )))
 
 
 
 
 
r'   )sethermes_cli.providersrN   rO   rC   r1   rJ   addrD   	providersrR   hermes_cli.authrT   hermes_cli.modelsrV   itemsupdatelist)rK   routesrN   rO   overlayprovider_defvaluer]   rR   profilerT   normalize_model_providernormalize_registry_providerprovider_idconfigcanonical_ids                   r%   _provider_default_routesrr   r   s   uuFFFFFFFFF!%%h//#|H--G0"55L*b11
 	" 	"E .e44E "

5!!!	"    
222222&&x00)GZ,,
 
  	JJu   555555TTTTTTZZZZZZ#4#:#:#<#< 
	" 
	"K66((55 L x''- 4b99 E  "

5!!!
	"     8 
 
f
 
 
 	
 	
 	
 Ms8   A3B 
BBAC 
C)(C)-A<E* *
E76E7Falready_normalizedconfigured_base_urlactive_base_urlconfigured_provideractive_providerrt   c                  |r#t          | pd          }t          |pd          }nt          |           }t          |          }|r||k    S t          |pd                                          }t          |pd                                          }|sdS 	 ddlm}  ||          } ||          }n8# t
          $ r+ |                                }|                                }Y nw xY w	 ddlm}  ||          } ||          }n# t
          $ r Y nw xY w|rt          |          }	|	 p||	vS t          |o|o||k              S )zEReturn whether a context pin's configured route differs from runtime.r:   Fr   rU   )
r4   rJ   striprd   rV   rD   lowerr`   rr   r*   )
ru   rv   rw   rx   rt   configured_routeactive_routerm   rn   configured_routess
             r%   _context_route_mismatchr      s     B28b99?0b1145HII0AA 0<//17R88>>@@//R006688O u2TTTTTT667JKK22?CC 2 2 217799)//112ZZZZZZ99:MNN55oFF     N45HII$$M<M(MM 	3	3?2  s$   B4 42C)(C)-D
 

DDrk   c                    t          | pd                                                                                              dd          S )zFMirror runtime normalization for a requested custom-provider identity.r:    -)r4   rz   r{   replacerk   s    r%   _normalize_custom_provider_namer      s<    u{!!##))++33C===r'   c                N    t          |           }|st                      S |d| hS )zFReturn raw/menu identities that runtime accepts for a configured name.custom:)r   r_   )rk   
normalizeds     r%   _custom_provider_runtime_idsr      s4    077J uu.*..//r'   	autoraiseDict[str, Any]context_lengthOptional[int]c           	        t          |                     d          pd                                                                                              dd          d         }t          |t                    r|dk    rt          |dz             d}n|                    d	          rd
nd}t          t          | d         dz                      }t          t          | d         dz                      }d| d| d| d| d	S )u  Build the one-time notice shown when Codex gpt-5.x raises compaction.

    ``autoraise`` is ``{"model": <slug>, "from": <old_ratio>, "to": <new_ratio>}``.
    ``context_length`` is the live-resolved window from the context compressor
    (Codex's /models catalog is authoritative and can change server-side, e.g.
    the gpt-5.6 family's 272K → 372K → 272K shifts in July 2026), so the banner
    reports what this session actually got rather than a hardcoded cap. 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.5rZ      r     Kz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)	r4   rC   rz   r{   rsplit
isinstanceintround
startswith)r   r   r   capfrom_pctto_pcts         r%   "_build_codex_gpt5_autoraise_noticer      s3    	g&&7-88>>@@FFHHOOPSUVWWXZ[E.#&& L>A+=+=~,--000
 (()>??KffV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&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   r   r    )r   r   r   r   s       r%   _resolve_compression_thresholdr     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   r   r'   r%   $_codex_gpt55_autoraise_notice_markerr   +  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:   rZ   r   r   r   r   r   :)r4   rC   rz   r{   r   r   r   r   )r   r   r   r   s       r%   #_codex_gpt55_autoraise_notice_stater   5  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)r   r   	read_textrz   OSErrorKeyError	TypeError
ValueError)r   currents     r%   "_codex_gpt55_autoraise_notice_seenr   C  sx    5i@@355?? @ 
 

%''W 	 Xy*5   uus   AA	 	A*)A*c                    	 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_okr   r   N)	r   parentmkdir
write_textr   r   r   r   r   )r   markers     r%   $_record_codex_gpt55_autoraise_noticer   R  s    577D4888/	::W 	 	
 	
 	
 	
 	
 Xy*5   s   AA A32A3c                ~    t          | t                    sdS |                                                     d          S )Nr:   rZ   )r   r4   rz   r[   r   s    r%   _normalized_custom_base_urlr   b  s5    eS!! r;;==$$$r'   agent_modelentryc                   t          | pd                                                                          }|                    d          }g }t	          |t
                    rd |                                D             }n(t	          |t          t          f          rd |D             }|r||v rdS t          |                    dd          pd                                                                          }|s|sdS ||k    S )Nr:   modelsc                t    g | ]5}t          |                                                                          6S r   r4   rz   r{   )r\   ks     r%   
<listcomp>z2_custom_provider_model_matches.<locals>.<listcomp>t  s2    AAAa3q66<<>>''))AAAr'   c                t    g | ]5}t          |                                                                          6S r   r   )r\   ms     r%   r   z2_custom_provider_model_matches.<locals>.<listcomp>v  s2    :::a3q66<<>>'')):::r'   Tr   )	r4   rz   r{   rC   r   dictkeysrg   tuple)r   r   agent_model_normr   catalogprovider_models         r%   _custom_provider_model_matchesr   h  s   ;,"--3355;;== YYx  FG&$ ;AA6;;==AAA	FT5M	*	* ;::6::: #w..t7B//5266<<>>DDFFN ' t---r'   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 )Nr:   customr   r   r   provider_keynamerG   
extra_bodyr   )
rz   r{   r   splitr   r   r   r4   rC   r   )rK   r   rG   r   provider_normprovider_key_filter
target_urlfallbackr   
entry_keysr   r   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)rK   r   rG   r   request_overridesr   )
r   rK   r   rG   r   r1   rC   r   rf   r   )r(   r   r   	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'   r:   Z         ?r/   r        
   api_keyapi_modeacp_commandacp_argslist[str] | Nonecommandargsmax_iterationsr   
tool_delayenabled_toolsets	List[str]disabled_toolsetssave_trajectoriesverbose_logging
quiet_moder.   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_idr8   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]]reaction_callbackOptional[Callable[[str], None]]
max_tokensreasoning_configservice_tierr   prefill_messagesr,   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_idrequested_providercI                ~}   t                       |	| _        |
| _        |@pt          |
          | _        || _        || _        || _        || _        || _	        || _
        |2| _        |3| _        |4| _        |5| _        |6| _        |7| _        |8| _        |9| _        |:| _        d| _        d| _        d| _        |;| _        |<| _        |G| _        || _        |r| dnd| _        |pd| _        t;          |t<                    r:|                                r&|                                                                 nd}I|Ipd| _!        t;          |Ht<                    r:|H                                r&|H                                                                 n| j!        | _"        |B| _#        |p|| _$        tK          |p|pg           | _&        |dv r	|| _'        n
| j!        dk    rd| _'        n| j!        dv rd| _'        n|I#| j(        d	k    rd
| j)        v rd| _'        d| _!        n|I| j(        dk    rd| _'        d| _!        n| j!        dk    s|I| j(        dk    rd| _'        d| _!        n~| j)        *                    d          +                    d          rd| _'        nI| j!        dk    s/| j(        ,                    d          rt[          | j)        d          rd| _'        nd| _'        |B>	 ddl.m/}J  |J|B| j!        | j                  sd| _#        n# t`          $ r
 d| _#        Y nw xY w	 | 1                                 n# t`          $ r Y nw xY w	 ddl2m3}Km4}L | j!        |Kvr |L| 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| 5                                se| 6                                s!| 7                    | j        | j!                  r0d| _'        tq          | d          r| j9        :                                 | j!        d k    s| ;                                rxty                      j=        >                                sSty                      j=        ?                                 t          jA        t          d!d"#          C                                 || _D        || _E        || _F        d$| _G        | | _H        |!| _I        |"| _J        |#| _K        |$| _L        |%| _M        |&| _N        |(| _O        |)| _P        |*| _Q        |+| _R        |,| _S        |'| _T        d$| _U        t                      | _W        d| _X        d$| _Y        d| _Z        d| _[        d$| _\        t          j]                    | _^        t          j_                    | _`        d!| _a        d| _b        t          jc                    | _d        d| _e        t          jc                    | _f        t                      | _g        t          jc                    | _h        d| _i        g | _j        t          jc                    | _k        || _l        || _m        || _n        || _o        || _p        || _q        || _r        || _s        || _t        |-| _u        |.| _v        |/| _w        t          |0pi           | _y        |1pg | _z        d$| _{        | |                                \  | _}        | _~        d%| _        	 dd&lm}M  |M                                d'i           pi }N|N                    d(d%          }O|Od)v r|O| _        n# t`          $ r Y nw xY wd$| _        d$| _        t          j                    | _        d*| _        d| _        d| _        d$| _        d| _        d| _        d| _        d| _        t                      d$dd+| _        d| _        dd,lm}Pm}Q  |Pty                      j        -           | j        r1 |Q             ty                      j                            d.           n| j        r	 d| _        d$| _        t3                      | _        t7                      | _        d| _        t                      | _        t          jc                    | _        d| _        t          j                    | _        d| _        d| _        d| _        d| _        d| _        i | _        d| _        d$| _        tW          | j!        | j                  }R| j'        dk    rHdd/lm}Sm}T | j!        dk    }U|Urdd0lm}V ta          j        d1|pd          }W|Wr|W                    d2          nd3}X|X| _         |V|X          | _        d4| _        || _        d$| _        d4| _        d| _        i | _        | j        sts          d5| j         d6|X d7           n`| j!        dk    }Y|Yr|p |T            pdn|pd}Z| j!        d8k    rst;          |Zt<                    r^|Zr\	 dd9lm}[  |[            }ZnJ# t`          $ r=}\ddl}]|]                    t|                                        d:|\           Y d}\~\nd}\~\ww xY w|Z| _        |Z| _        || _        dd;lm}^ |Yr t;          |Zt<                    r |^|Z          nd$| _         |S|Z||R<          | _        d| _        i | _        | j        sts          d5| j         d=           dd>lm}_  |_|Z          rts          d?           
nt;          |Zt<                    r:t          |Z          d@k    r&ts          dA|ZddB          dC|ZdDd                     	n| j!        dEk    r[ddFlm}` d| _'         |`| | j                  | _        i | _        |pdG| _        dH| _        | j        sts          dI| j                    	nd| j'        dk    rVta          j        d1|pd          }W|Wr|W                    d2          nd3| _        d| _        	 dd&lm}a  |a                                di                               dJi           }b|b                    dK          ru|b                    dL          r`|bdK         |bdL         dM| _        |b                    dN          r|bdN         | j        dO<   |b                    dP          r|bdP         | j        dP<   n# t`          $ r Y nw xY wd| _        i | _        | j        s.| j        rdQnd}cts          d5| j         dR| j         |c d7           n|r|r	t          |          }d|dj        r\t          |d                    dS                    }edT t          |dj                                                  D             }f||e|fdU}gn||dV}g|R|R|gdW<   | j!        dk    r| j$        |gdX<   | j&        |gdY<   |}ht[          |hdZ          rdd[lm}i  |i            |gd\<   nxt[          |hd]          rdd^lm}j  |j|h          |gd\<   nRt[          |hd_          r%ty                                                      |gd\<   nt[          |hd`          rddalm}k  |k            |gd\<   nt[          |hdb          r	dcddi|gd\<   nt[          |hde          r%ty                                                      |gd\<   nt[          |hd	          rddflm}l  |l|          |gd\<   nd\|gvrJ	 ddglm}m  |m| j!                  }n|nr|nj        rt          |nj                  |gd\<   nG# t`          $ r Y n:w xY wn4ddhlm}o  |o| j!        pdi| j        d!j          \  }p}q|ps|pj        t=          |pj                  dV}g|R|R|gdW<   t          |pdkd          }r|rst          |pd\d          }r|rst          |pdld          }r|rrt          |r          |gd\<   n| j!        pd                                                                 }s|srJ|sdmvrE|s                                 dn}t	 ddolm}u |u                    |s          }v|vr|vj        r|vj        d         }tn# t`          $ r Y nw xY wg }wt;          |AtJ                    rdp |AD             }wnBt;          |At                    r-|A                    dq          r|A                    dr          r|Ag}wd$}x|wD ]f}y|y                    ds          pd                                pd}z|zsj|y                    dt          p|y                    du          pd                                }{|{r*t          j        |{d                                          pd}z |o|ydq         |ydr         d!|y                    dv          |zw          \  }|}}|||ydq         | _!        |}p|ydr         | _        d!| _        ||j        t=          ||j                  dV}g|R|R|gdW<   t          ||dkd          }~|~st          ||d\d          }~|~st          ||dld          }~|~rt          |~          |gd\<   d!}x nh|xst          dx|s dy|t dz          t          | d{d$          st          d|          |g| _        t=          |g                    dvd                                                     }t[          |dZ          rgd}| j        pd                                 v rJ|g                    d\          pi }|                    d~d          }d}||vr|r| d| |d~<   n||d~<   ||gd\<   |                                  	 ddlm}m}m}m}  |            } ||          }t=          |g                    dv          p| j        pd          } ||g||            ||g||           n-# t`          $ r  t*                              dd!           Y nw xY w|g                    dsd          | _        |g                    dv| j                  | _        	 ddlm}  |             |                     |gdd!          | _        | j        s͐ts          d5| j                    |rts          d|            dd>lm}_ |g                    dsd          } |_|          rts          d?           nht;          |t<                    rC|rA|dk    r;t          |          d@k    r'ts          d|ddB          dC|dDd                     nts          d           n%# t`          $ r}t          d|           d}~ww xY wt;          |AtJ                    rd |AD             | _        nOt;          |At                    r3|A                    dq          r|A                    dr          r	|Ag| _        ng | _        d| _        t          | d{d$          | _        | j        r| j        d         nd| _        | j        r| j        st          | j                  d2k    r1| j        d         }ts          d|dr          d|dq          d7           nLts          dt          | j                   dd                    d | j        D                       z              	 ddlm} |j        | _        n# t`          $ r
 d| _        Y nw xY wty                                          ||| j                  | _        t                      | _        | j        rd | j        D             | _        t          | j                  }| j        sts          dt          | j                   dd                    |                      |r&ts          dd                    |                      |r&ts          dd                    |                      n| j        sts          d           ddlm} d| j        v r|nd| _        | j        rZ| j        sSty                                                      }d |                                D             }|rts          d|            | j        r| j        sts          d           | j
        rM| j        sFt          | j
                  dk    r| j
        dd         dCz   n| j
        }ts          d| d           | j}        rD| j        s=| j~        r| j!        dk    rd}n| j~        rd}nd}ts          d| d| j         d           t          j                    | _        |r|| _        nG| j                            d          }t          j                    j        dd         }| d| | _        	 ddl m}  || j                   n&# t`          $ r | j        t          j        d<   Y nw xY wt                      }|dz  | _        | j                            d!d!           d$| _        	 dd&lm}  |                                d          pi }t          |                    dd$                    | _        n# t`          $ r Y nw xY wg | _        d!| _	        d| _
        d| _        d| _        ddlm}  ||C|D|E|F          | _        |>| _        |?| _        t          j]                    | _        d| _        d| _        d$| _        d!| _        d$| _        | j        |.|-d| _        ddlm}  |            | _        	 dd&lm}  |            }n# t`          $ r i }Y nw xY wd!| _        	 |                    di           }t;          |t                    r*t          |                    dd!                    | _        n# t`          $ r d!| _        Y nw xY wd| _        	 |                    dri           }t;          |t                    rt=          |                    dd          pd                                                                           }|dv r	|| _        n/t*                              d|                    d                     n# t`          $ r d| _        Y nw xY w	 t          t=          j        |                    di                               | _W        n># t`          $ r1}ty                      j                            d|           Y d}~nd}~ww xY wd| _         d| _!        d$| _"        d$| _#        d| _$        d| _%        d| _&        d| js        pg v }|=r|r	 |                    di           }|                    dd$          | _"        |                    dd$          | _#        tO          |                    dd                    | _$        | j"        s| j#        r^ddŐl(m)}  ||                    ddǦ          |                    ddɦ          ʦ          | _!        | j!        *                                 n# t`          $ r Y nw xY wd| _+        |=s	 |r|                    dqd          nd}|r/|                                rddːl,m-} dd̐l.m/}  |            | _+         ||          }|r1|0                                r| j+        1                    |           | j+        j        r| j        |2pdt=          t                                ddϜ}|d         dk    r| j2        |d<   | j3        |d<   | j        r:	 | j        4                    | 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ܐl5m6}  |            }||d<   d|d<   n# t`          $ r Y nw xY w | j+        j7        dui | ty                      j                            d|           n/ty                      j                            d|           d| _+        nF# t`          $ r9}ty                      j                            d|           d| _+        Y d}~nd}~ww xY wddl,m8}  ||            d| _9        	 |                    di           }tO          |                    dd                    | _9        n# t`          $ r Y nw xY w|                    di           }t;          |t                    si }|                    ddi          | _:        |                    ddi          | _;        t          |                    dd!                    | _<        t          |                    dd!                    | _=        t          |                    dd!                    | _>        | j>        r$	 ddl?m@}  |             n# t`          $ r Y nw xY w|                    di           }t;          |t                    si }|| _A        	 |                    dd          }tO          |          }t          |d2          }n# t          t          f$ r d}Y nw xY w|| _E        |                    di           }t;          |t                    si }t          |                    dd                    }t=          |                    dd!                                                     dv }t=          |                    dd!                                                     dv }d| _G        	 ddl͐mH}mI}mJ}  || j        | j!        |          }t          ||| j         || j        | j!                  p || j        | j!                            \  }| _G        n# t`          $ r Y nw xY wt=          |                    dd!                                                     dv }t          |                    dd                    }tO          |                    dd                    }|                    dd2          }t;          |t                    rd2}nt;          |tN                    r|}nt;          |t                    r(|L                                rtO          |          nd2}nL	 tO          t=          |                                                    }n# t          t          f$ r d2}Y nw xY w|d2k     rd2}|                    dd          }t;          |Ðt                    rd}nt;          |ÐtN                    r|}nt;          |Ðt                    r(|ÐL                                rtO          |æ          nd}nL	 tO          t=          |æ                                                    }n# t          t          f$ r d}Y nw xY w|d2k     rd}Đt          |d          }Đd  }Őt          d ||                    dd          d                    } ||                    dd          d          }ǐt          d ||                    dd          d                    }Ȑt          dtO          |                    dd                              }t=          |                    dd$                                                     dv }|                    di           }t;          |t                    r d	 |ˠ                                D             }ni }|                    d
          }|́5	 tO          |ͦ          }|dk    rd}n# t          t          f$ r d}Y nw xY wt          |                    d          d$          }t=          |                    dd          pd                                           }|ϐdvr+ty                      j                            d|Ϧ           d}ϐt          dtO          |                    dd                              }	 t          |ddi           }n# t`          $ r i }Y nw xY wt;          |t                    r|Ѡ                    d          }nd}|ҁ-	 tO          |Ҧ          }n# t          t          f$ r d}Y nw xY w|| _         |                    dri           }| ju        t;          |t                    r|Ӡ                    d          }|ԁ	 t;          |Ԑt                    rt          tO          |Ԧ          }|dk    rt          || _u        nf# t          t          f$ rP ty                      j                            d|Ԧ           ts          d|ԛdt          jQ                   Y nw xY w| ju        | j        d<   t;          |t                    r|Ӡ                    d          }nd}|ցz	 tO          |֦          }nh# t          t          f$ rR ty                      j                            d|֦           ts          d|֛dt          jQ                   d}Y nw xY w	 ddlm}  ||          }n=# t`          $ r0 |                    d          }t;          |tJ                    sg }Y nw xY w|֐Nt;          |t                    r8t=          |Ӡ                    d          pd                                          }|}| j        }|r@	 ddl2m4}L  |L|| j!                  } |L| j        | j!                  }n# t`          $ r Y nw xY wt=          |Ӡ                    dq          pd                                          }ېt          |Ӡ                    dv                    }ܐt          |ۦ          }ݐt          |ݦ          }h d }||v rd$}n}|r{|ݐd!k    rt|ݠ,                    d"          s^	 dd#lmT}  ||ݦ          }t=          |pd                                                                           |k    }n# t`          $ r Y nw xY w|ܐsb|ސr_t          |ۦ          }|                    d$          }t                      }t;          |t                    rdd%lmU} |                                D ]\  }}t;          |t                    st=          |砂                    d&          pd                                          }t          |          t          |          z  } ||          s"|W                    d' |D                        ||vrt          |砂                    d(          p*|砂                    d)          p|砂                    dv                    }|r n|s|D ]}t;          |t                    st=          |砂                    d&          pd                                          }t=          |砂                    d*          pd                                                                           }t          |          t          |          z  }|rt          |          |z  r||vrԐt          |砂                    dv                    }|r nt=          | j        pd          }t=          |pd          }d+|X                    d,d2          d         v rs	 t          |          }t          |                    dS                    }t          |          t          |          k    r|}n# t          t          f$ r Y nw xY wt          |          }t          |||| j!        d!-          }t          |o||k              }|s|rOty                      j                            d.|| j        |p| j!        ||p|Ӡ                    dq                     d}|| _Z        t          | |צ           |֐|אr	 dd/lm\}  || j        | j        |א0          }|rtO          |          }n# t`          $ r d}Y nw xY w|֐jt          | j                  }|D ]Q}t;          |t                    st          |                    dv                    }|r||k    r|                    d1i           }t;          |t                    r|                    | j        i           }t;          |t                    r|                    d          }|	 tO          |          }|dk    rt          nu# t          t          f$ r_ ty                      j                            d2| j        |           ts          d3| j        d4|d5t          jQ                   Y nw xY w nS|| _]        | ^                    |֦           d}d$}d6}	 t;          |t                    r|                    d7i           ni }|                    d8d6          pd6}n# t`          $ r Y nw xY w|d6k    r1	 dd9l_m`}  ||          }nE# t`          $ r8} ty                      j                            d:|            Y d} ~ n
d} ~ ww xY w|d}	 dd;lamb}  |            }n# t`          $ r d}Y nw xY w|w|jc        |k    rjddld}	 |e                    |          }nJ# t`          $ r=}d!}ty                      j                            d<||           d}Y d}~n
d}~ww xY w|*|s(ty                      j                            d=|           ||| _f        d| _G        dd>lgmh}  || j        | j        t          | dsd          || j!        |א?          }|r|| jf        _i        | jf        j                    | j        || j        t          | dsd          | j!        | j'        @           | j        s.ty                      j                            dA|jc                   nt          dui dr| j        dB|d|ɓd|dC|dDddE| j        dv| j        dst          | dsd          dF|֓dq| j!        dG| j'        d|ʓd| ju        d|̓dH|͓d|Ɠd|Ǔd|ȓd|| _f        t          | jf        dId          }t          |          r&	  ||>| j        J           n# t`          $ r Y nw xY w|| _m        || _n        || _o        || _p        || _q        t          | jf        dd          }|rU|t          k     rHt          dK| j         dL|ddMt          ddNt          dOz   dPt          dOz   dQ          | j        s| j        pddk    r	 ddRlsmt}	  |	| j        pd          }
|
rzdS}tq          | dT          r| 2                    |           n&ts          dU| dUt          jQ                   ty                      j                            |
           n# t`          $ r Y nw xY wt                      | _u        tq          | dV          r!| jf        r| j        | js        
dW| js        v rdX | j        D             }ddYl,mv} | jf        w                                D ]Ɛ} ||          }|*ty                      j                            dZ|           >|d&         }||v rPd[|d\}| j        x                    |           | j        y                    |           | ju        y                    |           |y                    |           tq          | dV          r| jf        r	 | jf        z                    | j        t=          t                                | j        pd| j        t          | jf        dd          t          | d]d          ^           nE# t`          $ r8}ty                      j                            d_|           Y d}~n
d}~ww xY wt          t          j        d`          pda          | _|        d| _}        d$| _~        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        db| _        dc| _        d| _        d| _        d}t;          |t                    r|Ӡ                    dd          }|[	 tO          |          | _        nB# t          t          f$ r, ty                      j                            de|           Y nw xY w| j        | j        rt          | j                  r	 t;          | j        t<                    r| j        nd}t          | j        | j        |pdf          }|r|dk    r	|| _        nE# t`          $ r8}ty                      j                            dg|           Y d}~n
d}~ww xY w| j        rH|rF|C| j        |k    r7ty                      j                            dh| j        |֦           || _        | j        r5| j        s.ty                      j                            di| j                   t          | djd          pi }t          |          o|o|ot          |           }| j        s|rt          | jf        dB|          }d}t          | jf        dHd          }|r|dk    rdk|ddl}ts          dm| jf        j        ddntO          |doz             dp| jf        j        d| d7           n#ts          dm| jf        j        ddq           |r9ts          t#          |t          | jf        dd          r                     d| _        |r1t#          |t          | jf        dd          r          | _        |rt'          |           d$| _        | jf        }| j        | j!        | j"        | j        | j'        t          | dsd          t          | j                  | j}        | j~        t          |dr| j                  t          |dv| j                  t          |dsd          t          |dq| j!                  |j        |j        ds| _        | j'        dk    r2| j        W                    | j        | j        | j        dt           dS dS (v  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)
        requested_provider (str): Original provider identity before runtime canonicalization
        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onr   r:   >   codex_responsesbedrock_conversechat_completionscodex_app_serveranthropic_messageszopenai-codexr9  >   	xai-oauthxaizchatgpt.comz/backend-api/codexzapi.x.air?  	anthropiczapi.anthropic.comr=  rZ   z
/anthropicbedrockzbedrock-runtime.zamazonaws.comr:  r;  r   ) credential_pool_matches_providerrI   )_AGGREGATOR_PROVIDERSnormalize_model_for_providerzcopilot-acpzacp://copilotz
acp+tcp://)rK   _transport_cache
openrouterTzopenrouter-prewarm)targetdaemonr   F5m)load_configprompt_caching	cache_ttl>   1hrI  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)build_moa_facadez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   r   r\   r   vs      r%   
<dictcomp>zinit_agent.<locals>.<dictcomp>`  s/     ! ! ! $1Aqt! ! !r'   )r   rG   default_query)r   rG   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_headersrQ   )resolve_provider_clientauto)r   	raw_codex_custom_headers_default_headers>   rv  r   rF  _API_KEYrS   c                    g | ]C}t          |t                    |                    d           ,|                    d          A|DS rK   r   r   r   rC   r\   fs     r%   r   zinit_agent.<locals>.<listcomp>  s_     ' ' '"#)!T22'78uuZ7H7H'MNUUSZ^^'' ' 'r'   rK   r   r   key_envapi_key_envrG   )r   rw  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_providersrJ  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|  r}  r~  s     r%   r   zinit_agent.<locals>.<listcomp>F  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   r  rK   rX  Nr   r~  s     r%   r^   zinit_agent.<locals>.<genexpr>X  s;      ``Q!G*@@*@@@``````r'   )registry)r   r   r   c                *    h | ]}|d          d         S functionr   r   )r\   tools     r%   	<setcomp>zinit_agent.<locals>.<setcomp>k  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 r   r   )r\   r   	availables      r%   r   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displayshow_commentaryexplicitlmstudio_load_mode>   jitr  zRInvalid model.lmstudio_load_mode=%r; expected 'explicit' or 'jit'. Using explicit.tool_loop_guardrailsz&Tool loop guardrail config ignored: %sr   memorymemory_enableduser_profile_enablednudge_interval)MemoryStorememory_char_limiti  user_char_limiti_  )r  r  )MemoryManager)load_memory_providerr-   primary)r  r,   rT  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   r   r  target_ratiog?protect_last_nr   min_tail_user_messagesmax_attemptsc                b   t          | t                    r|S t          | t                    r| S t          | t                    r%|                                 rt          |           n|S 	 t          t          |                                                     S # t          t          f$ r |cY S w xY wN)	r   r*   r   r   
is_integerr4   rz   r   r   )rawdefaults     r%   _parse_prune_intz$init_agent.<locals>._parse_prune_intP  s     c4   	Nc3 	Jc5!! 	="~~//<3s888W<	s3xx~~''(((:& 	 	 	NNN	s   *-B B.-B.proactive_prune_tokens proactive_prune_min_result_charsi@  "proactive_prune_min_reclaim_tokensi   protect_first_nabort_on_summary_failuremodel_thresholdsc                    i | ]S\  }}t          |t          t          f          !t          |t                    6t	          |          t          |          TS r   )r   r   r   r*   r4   rl  s      r%   rn  zinit_agent.<locals>.<dictcomp>  s`     (
 (
 (
!%A!c5\**(
3=a3F3F(
FFE!HH(
 (
 (
r'   threshold_tokensin_place)r  codex_app_server_autonative>   r0   r  r  zdInvalid compression.codex_app_server_auto=%r; using 'native'. Valid values are: native, hermes, off.idle_compact_after_seconds	auxiliaryr   r  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  r   r  )rD  >   	vertex-ai
gcp-vertexgoogle-vertexr`  rv  vertexvertexair   r   )resolve_providerrb   )is_provider_enabledr   c              3     K   | ]}||V  	d S r  r   )r\   ro   s     r%   r^   zinit_agent.<locals>.<genexpr>J  s<       = = +*='= = = = = =r'   apiurlr   ?#rs   z^Ignoring model.context_length=%s for startup runtime %s at %s (configured default is %s at %s))"get_custom_provider_context_length)r   rG   r   r   u   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)rG   r   config_context_lengthrK   r   )r   r   rG   r   rK   r   zUsing context engine: %sthreshold_percentsummary_target_ratiosummary_model_overrider   r  r   threshold_tokens_cap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 r   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 r  r}  )r\   ts     r%   r  zinit_agent.<locals>.<setcomp>	  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)r  )typer  _gateway_session_key)rT  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_autoraisedz (capped at z tokens)u   📊 Context limit: z tokens (compress at r   z% = z# tokens (auto-compression disabled))r   )r   rK   r6  rG   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_oauthr   (  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+  r5  r  r  rG   r   r4   rz   r{   rK   r6  _credential_poolr   rg   r   r   _base_url_hostname_base_url_lowerr[   endswithr   r    agent.credential_poolrB  rD   _get_transporthermes_cli.model_normalizerC  rD  _is_azure_openai_url_is_direct_openai_url&_provider_model_requires_responses_apihasattrrE  clear_is_openrouter_urlr&   _openrouter_prewarm_doneis_setr_   	threadingThreadr   startr8   r  r  suppress_status_outputr  r  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Event_model_request_active_supports_active_turn_redirect_pending_steerLock_pending_steer_lock_pending_redirect_pending_redirect_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   r   r   r!  _force_ascii_payload_anthropic_prompt_cache_policy_use_prompt_caching_use_native_cache_layout
_cache_ttlhermes_cli.configrJ  rC   _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_loggingrR  rS  _hermes_homeloggerinfo_stream_callback_stream_needs_breakr   _stream_context_scrubberr   _stream_think_scrubber _current_streamed_assistant_text_delivered_interim_texts_stream_writer_lock_stream_writer_tokenlocal_stream_writer_tls_stream_writer_dropped _current_streamed_reasoning_text_persist_user_message_idx_persist_user_message_override_persist_user_message_timestamp_anthropic_image_fallback_cache_anthropic_client_is_anthropic_oauthr   agent.anthropic_adapterrU  rV  rW  researchgroup_bedrock_region_anthropic_api_key_anthropic_base_urlr   client_client_kwargsprintrc   rY  logging	getLogger__name__warningrZ  agent.azure_identity_adapterr\  lenagent.moa_loopra  _bedrock_guardrail_configr   rj  r   _replacer
   re   agent.auxiliary_clientrp  rr  _routermint_headersrd   rs  _qwen_portal_headersrt  rb   rR   rq  ru  r1   upperrT   api_key_env_varsosgetenvr  RuntimeError_apply_user_default_headersr  r  r  debugagent.ssl_guardr  _create_openai_client_fallback_chain_fallback_index_fallback_modeljointools.registryr  _generationget_tool_definitionstoolsvalid_tool_namessortedagent.prompt_builderr  _kanban_worker_guidancecheck_toolset_requirementsr   nowsession_startr  strftimeuuiduuid4hexgateway.session_contextr  environr   logs_dirr   _session_json_enabledr*   _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_session_persist_lock_pending_cli_user_message_last_flushed_db_idx_session_db_created_end_session_on_close_persist_disabled_session_init_model_configtools.todo_toolr  _todo_storer  r  r   from_mapping&_aux_compression_context_length_config_memory_store_memory_enabled_user_profile_enabled_memory_nudge_interval_turns_since_memory_iters_since_skillr   tools.memory_toolr  load_from_disk_memory_manageragent.memory_managerr  plugins.memoryr  is_availableadd_providerr  _emit_statusget_session_titlehermes_cli.profilesr  initialize_allr  _skill_nudge_interval_tool_use_enforcement_intent_ack_continuation_task_completion_guidance_parallel_tool_call_guidance_environment_probetools.env_prober  _platform_hint_overridesmaxr   r   _api_max_retriesr   r  r  r  r  r   r  minr!   r   sysstderrrJ   r   r  r  r   rf   r   r   _custom_providersr   r  _config_context_length_ensure_lmstudio_runtime_loadedplugins.context_enginer  hermes_cli.pluginsr  r   copydeepcopyr  agent.model_metadatar  r  update_modelr   r  compression_enabledcompression_in_place codex_app_server_auto_compactionmax_compression_attempts&compression_idle_compact_after_secondsr   hermes_cli.model_switchr  _context_engine_tool_namesr  get_tool_schemasappendra   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   r   r   r  r   _compression_warningr    _compression_feasibility_checked_primary_runtime(  r(   rG   r   rK   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  r8   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.  r0  credential_poolr1  r2  r3  r4  r5  r6  provider_namerB  rC  rD  _load_pc_cfg_pc_cfg_ttlrR  rS  _provider_timeoutrU  rV  _is_bedrock_anthropicrW  _region_match
_br_region_is_native_anthropiceffective_keyrY  _mm_exc_logging_is_oatr\  ra  _load_br_cfg_gr	_gr_label_parsed_url
_clean_url_query_paramsr  effective_baserp  rr  rs  rt  _gpf_phru  _routed_clientr  _routed_headers	_explicit	_env_hintrT   _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  rJ  
_cp_config_cp_entries_cp_base_urlr  key_usedefb_snapshot_registry
tool_namesr  requirementsmissing_reqsprompt_previewsourcetimestamp_str
short_uuidr  rT  _load_sess_cfg	_sess_cfgr  r  _load_agent_config
_agent_cfg_display_section_model_section
_load_mode_tlg_err_memory_toolset_requested
mem_configr  _mem_provider_name_MemoryManager	_load_mem_mp_init_kwargs_str  _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_raw_min_tail_userscompression_min_tail_users_raw_max_attemptscompression_max_attemptsr  "compression_proactive_prune_tokens%compression_proactive_prune_min_chars'compression_proactive_prune_min_reclaimcompression_protect_first$compression_abort_on_summary_failure_raw_model_thresholdscompression_model_thresholdscompression_threshold_tokensr  r  r  _aux_cfg_aux_context_config
_model_cfg_config_max_tokens_parsed_max_tokensr  r  _configured_default_model!_configured_default_runtime_model_active_runtime_model_configured_provider_configured_base_url_configured_provider_norm_custom_provider_candidate_runtime_first_provider_idsresolve_auth_provider_resolved_auth_provider_configured_custom_provider_user_providers_disabled_custom_provider_idsr  _provider_key_provider_entry_entry_name_entry_provider_ids_entry_provider_key_active_route_url_requested_route_url_requested_parts_requested_without_query_active_base_url_route_mismatch_model_mismatchr  _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	_cap_note_cap_ccs                                                                                                                                                                                                                                                                                               r%   
init_agentr    sL   z 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+5=*''''2E^EN0:8S0I0IhhnnN^N^hHNN$$**,,,dhM"(bEN (#..	3E3K3K3M3M	  ""((***^ 

 -E#.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 
% ,+ "
	*NNNNNN33   .
 *.& 	* 	* 	*%)E"""	*
   		
 	
 	
 	
 	
 	
 	
 	

 >!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
 #E8::EHLE' "'E#E-1E-2E*"**E"+/"3"3E+/E( +/E ) 0 0E .2E#,>#3#3E  ,/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* 03uuE" !* 0 0E!"E(00E#$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	 	 333333+ ('u{;;!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 #,/"3"3E '+E#!"E %E #'E
 $E., ( (E$ *)))))!	EGGGGGG''))

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


 !E%%>>)R88&-- 	X$()9)=)=>OQU)V)V$W$WE! % % % $%  *E.#44nd++ 	^//0DjQQ_U_``ffhhnnppJ000+5((h"&&';<<    . . .#-   .Q!<#05r:: "
 "

  Q Q QExPPPPPPPPQ
 48E0 E!E"'E#%E  !E E !)U-C-Ir J 3 	#"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 +../GKK%t,, +%&""	'	-	- 
+%8""	'	/	/ +(;(F(F(H(HOC#$$$a 	#"	+),S1D-E-E-K-K-M-M)N)N&&:& 	+ 	+ 	+)*&&&	+!A%%%&" ),,^Q??#T** )#$  	%s	+	+ 
)#4  	%u	-	- )&7&B&B&D&DKC!"""! 	! 	)'*3/@+A+A+G+G+I+I'J'J$$:& 	) 	) 	)'($$$	)!###$ "#;R@@  ( *-	,001I1MMqQQ* *& -=,<?FF- -) /2	  !EtLLd	
 	
/ /+ !$	3##$5q99::! ! ,/7??, ,egg%,&( -001CRHH'.. *(
 (
)>)D)D)F)F(
 (
 (
$$
 (*$
 $4#7#78J#K#K #/	0+./K+L+L(+q00/3,:& 	0 	0 	0+/(((	0 +Z((%   (+4h??K8( (egg % (/JJJ5,	
 	
 	

 ,4( .1	3##$@!DDEE. .*:{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 	# "# )jT.J.J)$'
y(A(A(GR$H$H$N$N$P$P!,E) %$ 	
SSSSSS4P4P-u~5 51 )E(DK) )%%    ":>>*#=#=#CDDJJLL8NN:&& 
  
 %D %
 %
! &**C%D%D"'
 '
 '
# %(CCC).&&&	)X55-88CC 6UUUUUU*?*?-+ +' /5266<<>>DDFF01 +*    # ;	(B ;	*I$+ +' )nn[99O69ee)/400 AAAAAA6E6K6K6M6M  2M?%ot<< ! "%'++F339r# #egg   +G%+ +4[AA+B' /.?? !5<< = =/B= = =   
 !2:MMM +D'++E22 ;*..u55;*..z::, ,(
 , ' '8  O%ot<< ! "%'++F339r# #egg   +.'++N;;Ar+ +eggeegg ( +G#+ +45HII+J' ,!89LMM78!
 !2:MMM +D'++J77, ,( ,  4"55"8>r22&,,S!44Q777
#+,@#A#A +5$--B-77, ,( -, ./@AAB B )=%z*   45FGG1  N#
 
 
 - K15JJ
 
  
	*o 
	*EEL3& 2EN)$B
z(B(B   &*" 0E%e->??? %*;%
	$LLLLLLAAk!2     
   ?),-=)>)>& 	$ 	$ 	$#	$
 ")/??G.  	!)T22 3IMM*4M4MNN 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^.
 
 
  ( 	U8TE$5 --+*^E9b11^^ 	. 	
 	
 	
  	QEEL8:J:OPPP#4 $
 $
 $
++$
33$
 65$
 43	$

 ":!9$
 $(4$
 ''$
 ^^$
 E9b111$
 #9"8$
 ^^$
 ^^$
 &J%I$
 ''$
 :9$
  ">!=!$
" $F#E#$
$ .S-R%$
& 0W/V'$
( $>#=)$
 , "%":<PRVWW#$$ 	:%BRSSSSS 	 	 	D	 3E!5E-ME*%=E". 
0 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JPbJZ 	?	?)	? 3:>>>	    	y %,(*=?T% %! I535KTRRD <q;4;;;;	  G)A)P  G  G  Gil  nC  DG  nG  jH  jH  G  G  NS  Nf  Nw  G  G  {D  G  G  G  H  H  H  Hw)A)Pwwwwxxx " 	4&u'?AQSWXX      "&E  
%G"5#;=MtTT&
 &
 &
"  9,Z888 .3E* 
"CN#6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  %L LLL. .
L;:L;?,M, ,
M98M98A^   
^^i 
j$'3jj$Ct 
t t ,6}$ $
}21}2A1AB B
ABBABM3A&AO O'APPAPQDAU U
AU'UAU"U"AU'Z>A[ [A[%[$A[%f'Ag  g  Ag#g"Ag#h'AAi7 i7
AjjAjmAm mAm'm&Am'm3AAo	 o	AooAoo*B0Ar rAr0r/Ar0r4<As1 s1
At,s;'At't'At,u7C&Ay y
Ay+y*Ay+y:C0BC }+(A~ ~BC ~
A~!~BC ~ A~!~!BBC @-BA
 A	BC A

BAABC ABAAA/BC C
BD
C/BDDBD
D)A BE* E*
BE7E6BE7I&BI9 I9
BJJBJJ?7BK7 K7BLLBLO"A1BQ Q
BQ!Q BQ!U*/BV VBV2V1BV2Y/BY4 Y4BZZBZ`B` `B`5`4B`5c>Bd dBd$d#Bd$eBe) e)Bff BfgABh hA Bi>i=Bi>kBk kA"Bl9l8Bl9l=Bm m7Bn
n	Bn
o).Bp p
Bp%p$Bp%sABt t
Bt't&Bt'AC@1 @1CAACAC>3CD2 D2CEE CEHCH8H8A/CJ*J)CJ*KA	CL! L!
CL.L-CL.L:CM MCNM)CN
N
CNNCN1 N1COO COOCO4 O4CP;O?.CP4P4CP;W=CX X
CXXCX[BC]- ]-
C]:]9C]:cA6Ce eCfe )CffCfi5Cj j<CkkCkk4ACm mCnm)Cn	n	Cnr  )r(   r   r)   r*   )r(   r   r3   r4   r5   r   r)   r6   )rG   r   r)   r4   )rK   r4   r)   rL   )ru   r   rv   r   rw   r   rx   r   rt   r*   r)   r*   )rk   r   r)   r4   )rk   r   r)   rL   r  )r   r   r   r   r)   r4   )
r   r   r   r   r   r   r   r*   r)   r   )r   r   r)   r4   )r   r   r)   r*   )r   r   r)   r6   )r   r4   r   r   r)   r*   )
rK   r4   r   r4   rG   r4   r   r   r)   r   )r   r   r)   r6   )HNNNNNNNNr:   r   r   NNFFFr/   Nr   r:   NNNNFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFFNNNNNFr   r   r   FN)rG   r4   r   r4   rK   r4   r   r4   r   r4   r   r   r   r4   r   r   r   r4   r   r   r   r   r   r   r   r   r   r*   r   r*   r   r*   r.   r4   r  r4   r  r   r  r4   r  r   r  r   r  r   r  r4   r  r*   r	  r4   r
  r   r  r4   r8   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   r4   r   r   r!  r   r,   r4   r"  r4   r#  r4   r$  r4   r%  r4   r&  r4   r'  r4   r(  r4   r)  r4   r*  r*   r+  r*   r,  r*   r-  r4   r.  r/  r0  r   r1  r*   r2  r   r3  r   r4  r   r5  r*   r6  r4   )K__doc__
__future__r   r  r  r  r  rA  rc  r  r   typingr   r   r   r   r	   urllib.parser
   r   r   agent.context_compressorr   agent.iteration_budgetr   r  r   r  r   r   r   r   agent.process_bootstrapr   agent.subdirectory_hintsr   agent.think_scrubberr   agent.tool_guardrailsr   r   r   r`  r   hermes_cli.route_identityr   hermes_cli.timeoutsr   hermes_constantsr   utilsr    r!   r  rq  r&   r2   rF   rJ   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  __all__r   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 
	;	'	'        :. . . .
6 6 6 6~  %- - - - - -`> > > >
0 0 0 0 @D    H  	           F? ? ?* * * *       % % % %. . . ..* * * *Z( ( ( (* !%!"&#'#!##'#'#'!%(-$(37'+$('+"&#'!%'+"&*+/"& $ $&*<@9='+(,-1#$$!*.%) %$&(+')!"Sm" m" m" m" m"bE .r'   