
    i	                       d Z ddlZddlZddlZddlZddlZddlZddlZ ej	        e
          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ZddlmZmZmZmZ ddlmZ ddlZddlmZ ddlm Z  ddl!m"Z" dd	l#m$Z$  e"            Z% e e&          j'        d
z  Z( e$e%e(          Z)e)re)D ]Z*e+                    de*           ne+                    d           ddl,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z: ddl;m<Z< ddl!m=Z= ddl>m?Z?m@Z@ ddlAmBZB ddlCmDZDmEZE ddlFmGZGmHZHmIZImJZJmKZKmLZL ddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZW ddlXmYZY ddlZm[Z[ ddl\m]Z] ddlFm^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZf ddlgmhZhmiZi ddljmkZkmlZmmnZompZpmqZr ddlsmtZtmuZumvZw dd lxmyZymzZz  G d! d"          Z{dWd$Z| G d% d&          Z} e~d'h          Z e~h d(          Z e~h d)          Zd*Z ej        d+ej                  Z ej        d,          Zd-ed#efd.Zd#efd/Zd0ed1ed#e dz  fd2Zd3e d4e d#efd5Z ej        d6          Zd7ed#efd8Zd9ed#efd:Zd7ed#efd;Zd9ed#efd<Zd=ed#efd>Zd?ed#efd@ZdAZd#efdBZ G dC dD          Z	 	 	 	 	 	 	 	 	 	 	 	 dXdIedJedKedLedMedNedOedPedQedRedSedTefdUZe
dVk    r ej        e           dS dS )Yao  
AI Agent Runner with Tool Calling

This module provides a clean, standalone agent that can execute AI models
with tool calling capabilities. It handles the conversation loop, tool execution,
and response management.

Features:
- Automatic tool calling loop until completion
- Configurable model parameters
- Error handling and recovery
- Message history management
- Support for multiple model providers

Usage:
    from run_agent import AIAgent
    
    agent = AIAgent(base_url="http://localhost:30000/v1", model="claude-opus-4-20250514")
    response = agent.run_conversation("Tell me about the latest Python updates")
    N)SimpleNamespace)ListDictAnyOptional)OpenAI)datetime)Pathget_hermes_home)load_hermes_dotenvz.env)hermes_homeproject_envz$Loaded environment variables from %sz7No .env file found. Using system environment variables.)get_tool_definitionsget_toolset_for_toolhandle_function_callcheck_toolset_requirements)
cleanup_vmget_active_envis_persistent_env)maybe_persist_tool_resultenforce_turn_budget)set_interruptcleanup_browser)OPENROUTER_BASE_URL)build_memory_context_blocksanitize_context)jittered_backoff)classify_api_errorFailoverReason)DEFAULT_AGENT_IDENTITYPLATFORM_HINTSMEMORY_GUIDANCESESSION_SEARCH_GUIDANCESKILLS_GUIDANCEbuild_nous_subscription_prompt)
fetch_model_metadataestimate_tokens_roughestimate_messages_tokens_roughestimate_request_tokens_roughget_next_probe_tierparse_context_limit_from_error(parse_available_output_tokens_from_errorsave_context_lengthis_local_endpointquery_ollama_num_ctx)ContextCompressor)SubdirectoryHintTracker)apply_anthropic_cache_control)	build_skills_system_promptbuild_context_files_promptbuild_environment_hintsload_soul_mdTOOL_USE_ENFORCEMENT_GUIDANCETOOL_USE_ENFORCEMENT_MODELSDEVELOPER_ROLE_MODELS!GOOGLE_MODEL_OPERATIONAL_GUIDANCEOPENAI_MODEL_EXECUTION_GUIDANCE)estimate_usage_costnormalize_usage)KawaiiSpinnerbuild_tool_previewget_cute_tool_message_detect_tool_failureget_tool_emoji)convert_scratchpad_to_thinkhas_incomplete_scratchpadsave_trajectory)atomic_json_writeenv_var_enabledc                   :    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
d	S )
_SafeWriterup  Transparent stdio wrapper that catches OSError/ValueError from broken pipes.

    When hermes-agent runs as a systemd service, Docker container, or headless
    daemon, the stdout/stderr pipe can become unavailable (idle timeout, buffer
    exhaustion, socket reset). Any print() call then raises
    ``OSError: [Errno 5] Input/output error``, which can crash agent setup or
    run_conversation() — especially via double-fault when an except handler
    also tries to print.

    Additionally, when subagents run in ThreadPoolExecutor threads, the shared
    stdout handle can close between thread teardown and cleanup, raising
    ``ValueError: I/O operation on closed file`` instead of OSError.

    This wrapper delegates all writes to the underlying stream and silently
    catches both OSError and ValueError. It is transparent when the wrapped
    stream is healthy.
    )_innerc                 >    t                               | d|           d S )NrL   )object__setattr__)selfinners     1/home/agentuser/.hermes/hermes-agent/run_agent.py__init__z_SafeWriter.__init__   s     4511111    c                     	 | j                             |          S # t          t          f$ r) t	          |t
                    rt          |          ndcY S w xY wNr   )rL   writeOSError
ValueError
isinstancestrlen)rP   datas     rR   rW   z_SafeWriter.write   sb    	=;$$T***$ 	= 	= 	= *4 5 5<3t9991<<<	=s    7AAc                 j    	 | j                                          d S # t          t          f$ r Y d S w xY wN)rL   flushrX   rY   rP   s    rR   r`   z_SafeWriter.flush   sH    	K$ 	 	 	DD	s    22c                 4    | j                                         S r_   )rL   filenora   s    rR   rc   z_SafeWriter.fileno   s    {!!###rT   c                 f    	 | j                                         S # t          t          f$ r Y dS w xY w)NF)rL   isattyrX   rY   ra   s    rR   re   z_SafeWriter.isatty   sB    	;%%'''$ 	 	 	55	s    00c                 ,    t          | j        |          S r_   )getattrrL   )rP   names     rR   __getattr__z_SafeWriter.__getattr__   s    t{D)))rT   N)__name__
__module____qualname____doc__	__slots__rS   rW   r`   rc   re   ri    rT   rR   rK   rK   q   s         $ I2 2 2= = =  $ $ $  * * * * *rT   rK   returnc                      dD ]R} t          t          | d          }|8t          |t                    s#t	          t          | t          |                     SdS )zHWrap stdout/stderr so best-effort console output cannot crash the agent.)stdoutstderrN)rg   sysrZ   rK   setattr)stream_namestreams     rR   _install_safe_stdiorx      s\    + ; ;k400j&E&ECk&&9&9:::; ;rT   c                   j    e Zd ZdZdefdZdefdZd
dZe	defd            Z
e	defd	            ZdS )IterationBudgetua  Thread-safe iteration counter for an agent.

    Each agent (parent or subagent) gets its own ``IterationBudget``.
    The parent's budget is capped at ``max_iterations`` (default 90).
    Each subagent gets an independent budget capped at
    ``delegation.max_iterations`` (default 50) — this means total
    iterations across parent + subagents can exceed the parent's cap.
    Users control the per-subagent limit via ``delegation.max_iterations``
    in config.yaml.

    ``execute_code`` (programmatic tool calling) iterations are refunded via
    :meth:`refund` so they don't eat into the budget.
    	max_totalc                 R    || _         d| _        t          j                    | _        d S rV   )r{   _used	threadingLock_lock)rP   r{   s     rR   rS   zIterationBudget.__init__   s#    "
^%%


rT   rp   c                     | j         5  | j        | j        k    r	 ddd           dS | xj        dz  c_        	 ddd           dS # 1 swxY w Y   dS )z7Try to consume one iteration.  Returns True if allowed.NF   T)r   r}   r{   ra   s    rR   consumezIterationBudget.consume   s    Z 	 	zT^++	 	 	 	 	 	 	 	 JJ!OJJ		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   AAA	A	Nc                 |    | j         5  | j        dk    r| xj        dz  c_        ddd           dS # 1 swxY w Y   dS )z6Give back one iteration (e.g. for execute_code turns).r   r   N)r   r}   ra   s    rR   refundzIterationBudget.refund   s    Z 	  	 zA~~

a

	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 s   155c                     | j         S r_   )r}   ra   s    rR   usedzIterationBudget.used   s
    zrT   c                 ~    | j         5  t          d| j        | j        z
            cd d d            S # 1 swxY w Y   d S rV   )r   maxr{   r}   ra   s    rR   	remainingzIterationBudget.remaining   s    Z 	7 	7q$.4:566	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   266rp   N)rj   rk   rl   rm   intrS   boolr   r   propertyr   r   ro   rT   rR   rz   rz      s         &# & & & &
            c    X 73 7 7 7 X7 7 7rT   rz   clarify>   	read_file
skill_view
web_searchskills_listweb_extractha_get_statesearch_filessession_searchvision_analyzeha_list_entitiesha_list_services>   patchr   
write_file   z(?:^|\s|&&|\|\||;|`)(?:
        rm\s|rmdir\s|
        mv\s|
        sed\s+-i|
        truncate\s|
        dd\s|
        shred\s|
        git\s+(?:reset|clean|checkout)\s
    )z[^>]>[^>]|^>[^>]cmdc                 ~    | sdS t                               |           rdS t                              |           rdS dS )zJHeuristic: does this terminal command look like it modifies/deletes files?FT)_DESTRUCTIVE_PATTERNSsearch_REDIRECT_OVERWRITE)r   s    rR   _is_destructive_commandr      sJ     u##C(( t!!#&& t5rT   c           	         t          |           dk    rdS d | D             }t          d |D                       rdS g }| D ]}|j        j        }	 t	          j        |j        j                  }n:# t          $ r- t          j	        d||j        j        dd                    Y  dS w xY wt          |t                    s+t          j	        d|t          |          j                    dS |t          v rIt          ||           dS t          fd	|D                       r dS |                               |t"          vr dS 	d
S )z?Return True when a tool-call batch is safe to run concurrently.r   Fc                 &    g | ]}|j         j        S ro   functionrh   .0tcs     rR   
<listcomp>z2_should_parallelize_tool_batch.<locals>.<listcomp>  s    888r"+"888rT   c              3   (   K   | ]}|t           v V  d S r_   )_NEVER_PARALLEL_TOOLS)r   rh   s     rR   	<genexpr>z1_should_parallelize_tool_batch.<locals>.<genexpr>  s(      
@
@T4((
@
@
@
@
@
@rT   u@   Could not parse args for %s — defaulting to sequential; raw=%sN   u6   Non-dict args for %s (%s) — defaulting to sequentialc              3   8   K   | ]}t          |          V  d S r_   )_paths_overlap)r   existingscoped_paths     rR   r   z1_should_parallelize_tool_batch.<locals>.<genexpr>,  s-      XXX>+x88XXXXXXrT   T)r\   anyr   rh   jsonloads	arguments	ExceptionloggingdebugrZ   dicttyperj   _PATH_SCOPED_TOOLS_extract_parallel_scope_pathappend_PARALLEL_SAFE_TOOLS)
tool_calls
tool_namesreserved_paths	tool_call	tool_namefunction_argsr   s         @rR   _should_parallelize_tool_batchr     s   
:!u88Z888J

@
@Z
@
@
@@@ u!#N  	&+		 Jy'9'CDDMM 	 	 	MR",TcT2  
 555	 -.. 	MH]##,  
 55***6y-PPK"uuXXXXXXXXX uu!!+...00055 1 4s   A112B('B(r   r   c                    | t           vrdS |                    d          }t          |t                    r|                                sdS t          |                                          }|                                r9t          t          j	        
                    t          |                              S t          t          j	        
                    t          t          j                    |z                                S )z8Return the normalized file target for path-scoped tools.Npath)r   getrZ   r[   stripr
   
expanduseris_absoluteosr   abspathcwd)r   r   raw_pathexpandeds       rR   r   r   7  s    ***t  ((Hh$$ HNN,<,< tH~~((**H 4BGOOCMM22333 DHJJ$9 : :;;<<<rT   leftrightc                    | j         }|j         }|r|s/t          |          t          |          k    ot          |          S t          t          |          t          |                    }|d|         |d|         k    S )z9Return True when two paths may refer to the same subtree.N)partsr   minr\   )r   r   
left_partsright_parts
common_lens        rR   r   r   H  s    J+K J[ JJ4#4#44Ij9I9IIS__c+&6&677Jkzk"k+:+&>>>rT   z[\ud800-\udfff]textc                 p    t                               |           rt                               d|           S | S )zReplace lone surrogate code points with U+FFFD (replacement character).

    Surrogates are invalid in UTF-8 and will crash ``json.dumps()`` inside the
    OpenAI SDK.  This is a fast no-op when the text contains no surrogates.
       �)_SURROGATE_REr   subr   s    rR   _sanitize_surrogatesr   Y  s5     D!! 1  4000KrT   messagesc                 8   d}| D ]}t          |t                    s|                    d          }t          |t                    r;t                              |          r!t                              d|          |d<   d}nt          |t                    r~|D ]{}t          |t                    rd|                    d          }t          |t                    r:t                              |          r t                              d|          |d<   d}||                    d          }t          |t                    r:t                              |          r t                              d|          |d<   d}|                    d          }t          |t                    rs|D ]o}t          |t                    s|                    d          }	t          |	t                    r:t                              |	          r t                              d|	          |d<   d}|                    d	          }
t          |
t                    r|
                    d          }t          |t                    r:t                              |          r t                              d|          |
d<   d}|
                    d
          }t          |t                    r:t                              |          r t                              d|          |
d
<   d}q|S )a,  Sanitize surrogate characters from all string content in a messages list.

    Walks message dicts in-place. Returns True if any surrogates were found
    and replaced, False otherwise. Covers content/text, name, and tool call
    metadata/arguments so retries don't fail on a non-content field.
    Fcontentr   Tr   rh   r   idr   r   )rZ   r   r   r[   r   r   r   list)r   foundmsgr   partr   rh   r   r   tc_idfnfn_namefn_argss                rR   _sanitize_messages_surrogatesr   d  s    E $% $%#t$$ 	'')$$gs## 		%(<(<W(E(E 		%*..xAAC	NEE&& 	% % %dD)) %88F++D!$,, %1E1Ed1K1K %'4'8'84'H'HV $wwvdC   	]%9%9$%?%? 	'++Hd;;CKEWW\**
j$'' 	%  % %!"d++ teS)) !m.B.B5.I.I !,005AABtH EVVJ''b$'' % ffVnnG!'3// %M4H4H4Q4Q %%2%6%6x%I%I6
 $ ff[11G!'3// %M4H4H4Q4Q %*7*;*;Hg*N*N; $LrT   c                 V    |                      dd                              d          S )zRemove non-ASCII characters, replacing with closest ASCII equivalent or removing.

    Used as a last resort when the system encoding is ASCII and can't handle
    any non-ASCII characters (e.g. LANG=C on Chromebooks).
    asciiignoreerrors)encodedecoder   s    rR   _strip_non_asciir     s(     ;;wx;0077@@@rT   c                 R   d}| D ] }t          |t                    s|                    d          }t          |t                    rt	          |          }||k    r||d<   d}nut          |t
                    r`|D ]]}t          |t                    rF|                    d          }t          |t                    rt	          |          }||k    r||d<   d}^|                    d          }t          |t                    rt	          |          }||k    r||d<   d}|                    d          }t          |t
                    r|D ]}	t          |	t                    rq|	                    di           }
t          |
t                    rF|
                    d          }t          |t                    rt	          |          }||k    r||
d<   d}|                                D ];\  }}|d	v r
t          |t                    rt	          |          }||k    r|||<   d}<"|S )
a  Strip non-ASCII characters from all string content in a messages list.

    This is a last-resort recovery for systems with ASCII-only encoding
    (LANG=C, Chromebooks, minimal containers).  Returns True if any
    non-ASCII content was found and sanitized.
    Fr   Tr   rh   r   r   r   >   rh   roler   r   )rZ   r   r   r[   r   r   items)r   r   r   r   	sanitizedr   r   rh   r   r   r   r   keyvalues                 rR   _sanitize_messages_non_asciir     s]    E /! /!#t$$ 	'')$$gs## 	)(11IG##!*I&& 	) ) )dD)) )88F++D!$,, )$4T$:$:	$,,+4DL$(EwwvdC   	(..ID  'FWW\**
j$'' 
	-  	- 	-b$'' -
B//B!"d++ -"$&&"5"5%gs33 -(8(A(AI(G332;;(,))++ 	! 	!JC???%%% !,U33	%%(CH E	! LrT   toolsc                      t          |           S )z7Strip non-ASCII characters from tool payloads in-place.)_sanitize_structure_non_ascii)r   s    rR   _sanitize_tools_non_asciir    s    (///rT   payloadc                 0    dfd |            S )zCStrip non-ASCII characters from nested dict/list payloads in-place.Fc                 &   t          | t                    ru|                                 D ]^\  }}t          |t                    rt	          |          }||k    r|| |<   d7t          |t          t
          f          r |           _d S t          | t
                    rnt          |           D ]`\  }}t          |t                    rt	          |          }||k    r|| |<   d7t          |t          t
          f          r |           _d S d S )NT)rZ   r   r   r[   r   r   	enumerate)noder   r   r   idx_walkr   s        rR   r  z,_sanitize_structure_non_ascii.<locals>._walk  s5   dD!! 	!"jjll ! !
UeS)) ! 0 7 7I E))$-S	 $d|44 !E%LLL! ! d## 	!'oo ! !
UeS)) ! 0 7 7I E))$-S	 $d|44 !E%LLL	! 	!! !rT   ro   )r  r  r   s    @@rR   r   r     s;    E! ! ! ! ! !* 
E'NNNLrT   z0.14.1c                      ddl } dt           d|                                                                  d|                                  d}|d|dd	S )
z8Return default HTTP headers required by Qwen Portal API.r   Nz	QwenCode/ (z; )enablez
qwen-oauth)
User-AgentzX-DashScope-CacheControlzX-DashScope-UserAgentzX-DashScope-AuthType)platform_QWEN_CODE_VERSIONsystemlowermachine)_plat_uas     rR   _qwen_portal_headersr  
  sf    
X(
X
XELLNN,@,@,B,B
X
Xemmoo
X
X
XC$,!$ ,	  rT   c            m       n   e Zd ZdZedefd            Zej        deddfd            Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddedededededee         dz  dedee         dz  dede	de
dee         dee         dedededede	d ed!ee         d"ee         d#ee         d$ed%ed&ed'ed(ed)ed*ed+ed,ed-ed.ed/ed0ed1ed2ed3e	d4eeef         d5ed6eeef         d7eeeef                  d8ed9ed:ed;ed<ed=ed>d?d@eeef         dAedBe	dCedDefldEZdF ZddGZdH Zd
dIdJefdKZdefdLZdefdMZdNeddfdOZdeeef         fdPZddQZddRZddedefdSZdefdTZededefdU            ZeddVdedee         defdW            Z de	de!fdXZ"dYedefdZZ#dYedefd[Z$edYedefd\            Z%defd]Z&	 dd^ed_ee         defd`Z'daedbed_eeeef                  defdcZ(dee         fddZ)deeddfdfZ*dgZ+dhZ,diZ-	 	 ddjee         dkedleddfdmZ.d_ee         ddfdnZ/dd_ee         doee         fdpZ0dd_ee         doee         fdqZ1d_ee         dee         fdrZ2defdsZ3d_eeeef                  dteduedeeeef                  fdvZ4d_eeeef                  dteduefdwZ5edxe6defdy            Z7dzee         dee         fd{Z8d|edefd}Z9edxe6deeef         fd~            Z:dedeeeef                  fdZ;dddeeef         dedxee6         dee<         fdZ=edYedefd            Z>dd_eeeef                  fdZ?ddNeddfdZ@ddZAdeddfdZBdeddfdZCd ZDde!fdZEdd_eddfdZFdd_eddfdZGddZHdeeeef                  ddfdZIedefd            ZJddedefdZKedefd            ZL eMh d          ZNed_eeeef                  deeeef                  fd            ZOededefd            ZPededefd            ZQdededz  fdZRd ZSddeeeeef                           deeeeef                           fdZTeddedede	defd            ZUededeVee         ee         f         fd            ZW	 ddedee         defdZXd_eeeef                  deeeef                  fdZYdedeeeef                  fdZZd
ddededeeef         fdZ[dedefdZ\dedefdZ]dedeVeef         fdZ^defdZ_defdZ`deajb        fdZcededefd            Zdde!dededefdZeedede	fd            ZfdedededdfdZgdedefdZhdedefdZidefdZjdedefdÄZkdededdfdĄZldde!dedefdƄZmdde!defdǄZnddIdJedefdȄZoddIdJedefdɄZpdefdʄZqdeddfd˄Zrdd̄Zsddd͜dee	         dedeet         deeeef                  deVeef         f
d҄Zude!fdӄZvde!fdԄZwddՄZxdeddfdׄZyededefd؄            ZzdYedefdلZ{deeef         ddfdۄZ|deddfd܄Z}deddfd݄Z~deddfdބZdefd߄Zddde!defdZdefdZdefdZ eMh d          Zde6de	de	defdZedYedefd            ZededeVeee<         f         fd            ZdededefdZdYededefdZdedefdZdefdZdefdZdedefdZd_eddfdZdede!fdZdefdZde!dz  fdZd^ede!fdZede!de!fd            ZdefdZdd_ede	fdZddddd_eded e	deededeVfdZdd_edede	ddfdZ	 ddede!dedee         def
d	Zeddedededefd            Zdd_edede	ddfdZdd_edede	ddfdZd_ede	defdZ	 	 	 	 	 ddaededoeeeef                  deedee         dee         deeef         fdZddNedee         defdZdS (  AIAgentz
    AI Agent with tool calling capabilities.

    This class manages the conversation flow, tool execution, and response handling
    for AI models that support function calling.
    rp   c                     | j         S r_   )	_base_urlra   s    rR   base_urlzAIAgent.base_url  s
    ~rT   r   Nc                 N    || _         |r|                                nd| _        d S N )r  r  _base_url_lowerrP   r   s     rR   r  zAIAgent.base_url#  s(    05=u{{}}}2rT   r  Z         ?Fd   2   Tr  api_keyproviderapi_modeacp_commandacp_argscommandargsmodelmax_iterations
tool_delayenabled_toolsetsdisabled_toolsetssave_trajectoriesverbose_logging
quiet_modeephemeral_system_promptlog_prefix_chars
log_prefixproviders_allowedproviders_ignoredproviders_orderprovider_sortprovider_require_parametersprovider_data_collection
session_idtool_progress_callbacktool_start_callbacktool_complete_callbackthinking_callbackreasoning_callbackclarify_callbackstep_callbackstream_delta_callbackinterim_assistant_callbacktool_gen_callbackstatus_callback
max_tokensreasoning_configservice_tierrequest_overridesprefill_messagesr  user_idgateway_session_keyskip_context_filesskip_memoryparent_session_iditeration_budgetrz   fallback_modelcheckpoints_enabledcheckpoint_max_snapshotspass_session_idpersist_sessionc9                 @   t                       |	| _        |
| _        |2pt          |
          | _        || _        || _        || _        || _        || _	        |+| _
        |,| _        |-| _        d| _        d| _        |.| _        |7| _        |8| _        |4| _        || _        |r| dnd| _        |pd| _        t-          |t.                    r:|                                r&|                                                                nd}9|9pd| _        |p|| _        t9          |p|pg           | _        |dv r|| _        n| j        dk    rd| _        n| j        dk    rd| _        n|9d| j        v rd| _        d| _        n|9d	| j        v rd| _        d| _        n}| j        d
k    s|9d| j        v rd| _        d
| _        nX| j                             d          !                    d          rd| _        n#| j        dk    s	d| j        v rd| _        nd| _        	 ddl"m#}:m$}; | j        |:vr |;| j        | j                  | _        n# tJ          $ r Y nw xY w|| j        dk    r| j        dk    rt/          | j        pd                                          &                    d          swt/          | j        pd                                          &                    d          s<| '                                s!| (                    | j        | j                  rd| _        | j        dk    s| )                                r)tU          j+        d d          ,                                 || _-        || _.        || _/        d| _0        || _1        || _2        | | _3        |!| _4        |"| _5        |#| _6        |%| _7        |$| _8        d| _9        d| _:        d| _;        d| _<        d| _=        tU          j>                    | _?        d| _@        g | _A        tU          jB                    | _C        || _D        || _E        || _F        || _G        || _H        || _I        || _J        || _K        |&| _L        |'| _M        |(| _N        t          |)pi           | _P        |*pg | _Q        d| _R        | )                                }<d| j                                        v }=| j        dk    o
| j        d
k    }>|<r|=p|>| _S        d| _T        d| _U        d| _V        t          jW                    | _X        d | _Y        d| _Z        d| _[        d| _\        dd!l]m^}?m_}@  |?t          "           | j        r% |@             t          b                    d#           n=| j        r6d$D ]3}At          jd        |A          e                    t          jf                   4d| _g        d| _h        d| _i        d| _j        d| _k        i | _l        d| _m        d| _n        | j        dk    rydd%lomp}Bmq}C | j        dk    }D|Drdd&lomr}E ddls}F|Ft                    d'|pd          }G|Gr|Gu                    d(          nd)}H|H| _v         |E|H          | _m        d*| _w        || _x        d| _n        d*| _y        d| _z        i | _{        | j        st          d+| j         d,|H d-           n| j        d
k    }I|Ir|p |C            pdn|pd}J|J| _y        |J| _w        || _x        dd.lom}}K  |K|J          | _n         |B|J|          | _m        d| _z        i | _{        | j        sRt          d+| j         d/           |Jr8t          |J          d0k    r%t          d1|Jdd2          d3|Jd4d                     n| j        dk    rYddls}F|Ft                    d'|pd          }G|Gr|Gu                    d(          nd)| _v        d| _        	 dd5lm}L  |L                                di                               d6i           }M|M                    d7          ru|M                    d8          r`|Md7         |Md8         d9| _        |M                    d:          r|Md:         | j        d;<   |M                    d<          r|Md<         | j        d<<   n# tJ          $ r Y nw xY wd| _z        i | _{        | j        s-| j        rd=nd}Nt          d+| j         d>| jv         |N d-           n|r|r||d?}O| j        dk    r| j        |Od@<   | j        |OdA<   |}Pd|P                                v rdBdCdDdE|OdF<   ndG|P                                v rddHlm}Q  |Q            |OdF<   nndI|P                                v r	dJdKi|OdF<   nOdL|P                                v rt                      |OdF<   n%ddMlm}R  |R| j        pdN| j        dO          \  }S}T|SL|Sjy        t/          |Sj                  d?}Ot          |SdP          r|Sj        rt          |Sj                  |OdF<   n| j        pd                                                                }U|Uru|UdQvrq|U                                 dR}V	 ddSlm}W |W                    |U          }X|Xr|Xj        r|Xj        d         }Vn# tJ          $ r Y nw xY wt          dT|U dU|V dV          t          dW          |O| _{        t/          |O                    dXd                                                    }Yd|Yv rgd| j        pd                                v rJ|O                    dF          pi }Z|Z                    dYd          }[dZ}\|\|[vr|[r|[ d[|\ |ZdY<   n|\|ZdY<   |Z|OdF<   |O                    d\d          | _y        |O                    dX| j                  | _        	 |                     |Od]d^          | _z        | j        st          d+| j                    |rt          d_|            |O                    d\d`          }]|]r?|]dak    r9t          |]          d0k    r&t          db|]dd2          d3|]d4d                     nt          dc|]r
|]ddd         nd` de           n%# tJ          $ r}^t          df|^           d}^~^ww xY wt-          |3t8                    rdg |3D             | _        nOt-          |3t                    r3|3                    dh          r|3                    di          r	|3g| _        ng | _        d| _        d| _        | j        r| j        d         nd| _        | j        r| j        st          | j                  d(k    r0| j        d         }_t          dj|_di          dk|_dh          d-           nJt          dlt          | j                   dmdn                    do | j        D                       z              t+          ||| j        p          | _        t/                      | _        | j        rdq | j        D             | _        t3          | j                  }`| j        st          drt          | j                   dsdt                    |`                      |r%t          dudt                    |                      |r%t          dvdt                    |                      n| j        st          dw           | j        rH| j        sAt5                      }adx |a                                D             }b|brt          dy|b            | j        r| j        st          dz           | j	        rK| j        sDt          | j	                  d{k    r| j	        dd{         d3z   n| j	        }ct          d||c d}           | jS        r(| j        s!|>rd~nd}dt          d|d dt| jT         d           t9          j                    | _        |r|| _        nG| j                            d          }etC          j                    j        dd         }f|e d|f | _        tI                      }g|gdz  | _        | j                            dd           | j        d| j         dz  | _        g | _        d| _        ddlm}h  |h|5|6          | _        |0| _        |1| _        d| _        | j        r	 | j                            | j        | j
        p tb          j                            dd          | j        | j        |'|&dd| j                   n2# tJ          $ r%}^t                              d|^           Y d}^~^nd}^~^ww xY wddlm}i  |i            | _        	 dd5lm}j  |j            }kn# tJ          $ r i }kY nw xY wd| _        d| _        d| _        d| _        d| _        d| _        d| _        |/s	 |k                    di           }l|l                    dd          | _        |l                    dd          | _        t}          |l                    dd                    | _        t}          |l                    dd                    | _        | j        s| j        rYddlm}m  |m|l                    dd          |l                    dd                    | _        | j                                         n# tJ          $ r Y nw xY wd| _        |/sr	 |lr|l                    dhd          nd}n|ns	 ddlm}o |o                                }p|pj        r}|pjy        s|pj        rod}n	 ddlm}qm}r  |q            }sd|s                    di           dh<    |r|s           n# tJ          $ r Y nw xY w| j        st          d           t          d           n# tJ          $ r Y nw xY w|nrhddlm}t ddlm}u  |t            | _         |u|n          }v|vr.|v                                r| j                            |v           | j        j        rddlm}w | j        |+pdt/           |w                      dd}x| j        r8	 | j                            | j                  }y|yr|y|xd<   n# tJ          $ r Y nw xY w| j        r
| j        |xd<   | j        r
| j        |xd<   	 ddlm}z  |z            }{|{|xd<   d|xd<   n# tJ          $ r Y nw xY w | j        j        di |x t          b                    d|n           n"t                              d|n           d| _        n9# tJ          $ r,}|t                              d||           d| _        Y d}|~|nd}|~|ww xY w| j        r| j        d | j        D             }}| j                                        D ]o}~|~                    dd          }|r||}v rd|~d}| j                            |           |r/| j                            |           |}                    |           pd| _        	 |k                    di           }t}          |                    dd                    | _        n# tJ          $ r Y nw xY w|k                    di           }t-          |t                    si }|                    ddN          | _        |k                    di           }t-          |t                    si }t          |                    dd                    }t/          |                    dd                                                    dv }t          |                    dd                    }t}          |                    ddd                    }|k                    dii           }t-          |t                    r|                    d          }nd}|f	 t}          |          }nT# t          t          f$ r> t                              d|           ddl}t          d|dĝ|j        Ŧ           d}Y nw xY w|| _        |	 ddlm}  ||k          }n<# tJ          $ r/ |k                    dǦ          }t-          |t8                    sg }Y nw xY w|D ]J}t-          |t                    s|                    dX          pd                     d          }|r|| j                             d          k    r|                    di           }t-          |t                    r|                    | j        i           }t-          |t                    r|                    d          }|r	 t}          |          }n`# t          t          f$ rJ t                              d| j        |           ddl}t          d| j        d|dĝ|j        Ŧ           Y nw xY w nLd}d}	 t-          |kt                    r|k                    di           ni }|                    dd̦          pd}n# tJ          $ r Y nw xY w|dk    r	 ddlm}  ||          }n2# tJ          $ r%}t                              d|           Y d}~nd}~ww xY w|1	 ddlm}  |            }|r|j        |k    r|}n# tJ          $ r Y nw xY w|t                              d|           ||| _        ddlm}  || j        | j        t          | d\d          || j        Ԧ          }| j                            | j        || j        t          | d\d          | j        զ           | j        s t          b                    d|j                   nJt          | j        |d||d| j        | j        t          | d\d          || j        | j        ئ          | _        || _        ddlm} t          | j        dd          }|r-||k     r't          d| j         d|d[d|d[d|dz   dߝ	          t/                      | _        t          | d          r| j        r| j        | j                                        D ]m}~d|~d}| j                            |           |~                    dd          }|r4| j                            |           | j                            |           nt          | d          r| j        r	 | j                            | j        t/          tI                                | j
        pd| j        t          | j        dd                     n2# tJ          $ r%}t                              d|           Y d}~nd}~ww xY wt          tc          j        d          pd          | _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _         d`| _        d| _        d}t-          |t                    r|                    d          }|L	 t}          |          | _        n4# t          t          f$ r t                              d|           Y nw xY w| j        {| j        rtt          | j                  r_	 t	          | j        | j                  }|r|dk    r|| _        n2# tJ          $ r%}t                              d|           Y d}~nd}~ww xY w| j        r(| j        s!t          b                    d| j                   | j        sd|rCt          d| j        j        d[dt}          |dz             d| j        j        d[d-           nt          d| j        j        d[d           d| _        |                                  | j        }| j        | j        | j        | j        t          | d\d          t          | j{                  | jS        t          |di| j                  t          |dX| j                  t          |d\d          t          |dh| j                  |j        |j        d| _	        | j        dk    r1| j	        
                    | jw        | jx        | jn        d           dS dS )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)
            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 SOUL.md, AGENTS.md, and .cursorrules
                into the system prompt. Use this for batch processing and data generation to avoid
                polluting trajectories with user-specific persona or project instructions.
        N r  >   codex_responsesbedrock_conversechat_completionsanthropic_messagesopenai-codexrZ  xaichatgpt.com/backend-api/codexapi.x.ai	anthropiczapi.anthropic.comr]  /
/anthropicbedrockbedrock-runtimer[  r\  r   )_AGGREGATOR_PROVIDERSnormalize_model_for_providercopilot-acpacp://copilotz
acp+tcp://r%  
openrouterc                      t                      S r_   )r(   ro   rT   rR   <lambda>z"AIAgent.__init__.<locals>.<lambda>  s    355 rT   TtargetdaemonFclaude5minitializing)setup_loggingsetup_verbose_logging)r   z=Verbose logging enabled (third-party library logs suppressed))r   	run_agenttrajectory_compressorcron
hermes_cli)build_anthropic_clientresolve_anthropic_token)build_anthropic_bedrock_clientzbedrock-runtime\.([a-z0-9-]+)\.r   	us-east-1zaws-sdku&   🤖 AI Agent initialized with model: z& (AWS Bedrock + AnthropicBedrock SDK, r  _is_oauth_tokenz (Anthropic native)   u   🔑 Using token: r   ...)load_config	guardrailguardrail_identifierguardrail_version)guardrailIdentifierguardrailVersionstream_processing_modestreamProcessingModetracez + Guardrailsz (AWS Bedrock, r$  r  r)  r*  z%https://hermes-agent.nousresearch.comzHermes Agentzproductivity,cli-agent)zHTTP-RefererzX-OpenRouter-TitlezX-OpenRouter-Categoriesdefault_headersapi.githubcopilot.comcopilot_default_headersapi.kimi.comr  KimiCLI/1.30.0portal.qwen.airesolve_provider_clientauto)r+  	raw_codex_default_headers)r  rl  custom_API_KEY)PROVIDER_REGISTRYz
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`.zxNo LLM provider configured. Run `hermes model` to select a provider, or run `hermes setup` for first-time configuration.r  zx-anthropic-betaz&fine-grained-tool-streaming-2025-05-14,r$  
agent_initreasonsharedu   🔗 Using custom base URL: nonez	dummy-keyu   🔑 Using API key: u;   ⚠️  Warning: API key appears invalid or missing (got: '   z...')z$Failed to initialize OpenAI client: c                     g | ]C}t          |t                    |                    d           ,|                    d          A|DS )r%  r+  rZ   r   r   r   fs     rR   r   z$AIAgent.__init__.<locals>.<listcomp>,  s^     $ $ $a&&$+,55+<+<$ABw$$ $ $rT   r%  r+  u   🔄 Fallback model: r
  u   🔄 Fallback chain (z providers):     → c              3   >   K   | ]}|d           d|d          dV  dS )r+  r
  r%  r  Nro   r  s     rR   r   z#AIAgent.__init__.<locals>.<genexpr>>  s;      "c"caj#D#DAjM#D#D#D"c"c"c"c"c"crT   )r.  r/  r2  c                 *    h | ]}|d          d         S r   ro   )r   tools     rR   	<setcomp>z#AIAgent.__init__.<locals>.<setcomp>J  s"    $U$U$U$T*%5f%=$U$U$UrT   u   🛠️  Loaded z tools: , u      ✅ Enabled toolsets: u      ❌ Disabled toolsets: u@   🛠️  No tools loaded (all tools filtered out or unavailable)c                     g | ]	\  }}||
S ro   ro   )r   rh   	availables      rR   r   z$AIAgent.__init__.<locals>.<listcomp>Z  s"    ^^^_T9T]^D^^^rT   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Claude via OpenRouteru   💾 Prompt caching: ENABLED (z TTL)%Y%m%d_%H%M%S   _sessions)parentsexist_oksession_.json)CheckpointManager)enabledmax_snapshotsHERMES_SESSION_SOURCEcli)r,  rI  rH  )r<  sourcer+  model_configrM  rQ  zESession DB create_session failed (session_search still available): %s)	TodoStore
   memorymemory_enableduser_profile_enablednudge_intervalflush_min_turns)MemoryStorememory_char_limiti  user_char_limiti_  )r  r  )HonchoClientConfighoncho)r  save_configu5     ✓ Auto-migrated Honcho to memory provider plugin.z(    Your config and data are preserved.
)MemoryManager)load_memory_providerr   primary)r<  r  r   agent_contextsession_titlerM  rN  )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: %sc                     h | ]@}t          |t                    |                    d i                               d          AS r   r  r   ts     rR   r  z#AIAgent.__init__.<locals>.<setcomp>#  sT     $ $ $a&&$j"%%))&11$ $ $rT   rh   r   )r   r   skillscreation_nudge_intervalagenttool_use_enforcementcompression	thresholdg      ?r  )true1yestarget_ratio皙?protect_last_ncontext_lengthu   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.
)file)get_compatible_custom_providerscustom_providersmodelsu   Invalid context_length for model %r in custom_providers: %r — must be a plain integer (e.g. 256000, not '256K'). Falling back to auto-detection.u&   
⚠ Invalid context_length for model z in custom_providers: 
compressorcontextengine)load_context_enginez4Context engine load from plugins/context_engine/: %s)get_plugin_context_engineuE   Context engine '%s' not found — falling back to built-in compressorget_model_context_length)r  r$  config_context_lengthr%  r+  r  r  r$  r%  zUsing context engine: %s   )r+  threshold_percentprotect_first_nr  summary_target_ratiosummary_model_overrider2  r  r$  r  r%  r&  )MINIMUM_CONTEXT_LENGTHz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  zBK context, or set model.context_length in config.yaml to override.context_compressor)r   r  r+  r  z#Context engine on_session_start: %sTERMINAL_CWD)working_dir        unknownollama_num_ctxz'Invalid ollama_num_ctx config value: %rz#Ollama num_ctx detection failed: %szAOllama num_ctx: will request %d tokens (model max from /api/show)u   📊 Context limit: z tokens (compress at r"  z% = z# tokens (auto-compression disabled)r+  r%  r  r&  r$  client_kwargsuse_prompt_cachingcompressor_modelcompressor_base_urlcompressor_api_keycompressor_providercompressor_context_lengthcompressor_threshold_tokensanthropic_api_keyanthropic_base_urlis_anthropic_oauthro   (  rx   r+  r,  rz   rR  r-  r0  r1  r2  r3  r  _user_id_gateway_session_key	_print_fnbackground_review_callbackrO  rV  rW  _credential_poolr4  r5  r  rZ   r[   r   r  r%  r'  r   r(  r&  r  rstripendswithhermes_cli.model_normalizerg  rh  r   
startswith_is_direct_openai_url&_provider_model_requires_responses_api_is_openrouter_urlr~   Threadstartr=  r>  r?  suppress_status_outputr@  rA  rB  rC  rD  rE  rG  rF  _executing_tools_interrupt_requested_interrupt_message_execution_thread_id _interrupt_thread_signal_pendingRLock_client_lock_delegate_depth_active_childrenr   _active_children_lockr6  r7  r8  r9  r:  r;  r.  r/  rH  rI  rJ  r   rK  rL  _force_ascii_payload_use_prompt_caching
_cache_ttl_budget_exhausted_injected_budget_grace_calltime_last_activity_ts_last_activity_desc_current_tool_api_call_count_rate_limit_statehermes_loggingru  rv  _hermes_homeloggerinfor   	getLoggersetLevelERROR_stream_callback_stream_needs_break _current_streamed_assistant_text_persist_user_message_idx_persist_user_message_override_anthropic_image_fallback_cache_anthropic_client_is_anthropic_oauthagent.anthropic_adapterr{  r|  r}  rer   group_bedrock_region_anthropic_api_key_anthropic_base_urlr$  client_client_kwargsprintr  r\   _bedrock_guardrail_confighermes_cli.configr  r   hermes_cli.modelsr  r  agent.auxiliary_clientr  hasattrr  upperhermes_cli.authr  api_key_env_varsRuntimeError_create_openai_client_fallback_chain_fallback_index_fallback_activated_fallback_modeljoinr   r   setvalid_tool_namessortedr   r   r	   nowsession_startr<  strftimeuuiduuid4hexr   logs_dirmkdirsession_log_file_session_messages_cached_system_prompttools.checkpoint_managerr  _checkpoint_mgr_session_db_parent_session_id_last_flushed_db_idxcreate_sessionr   environwarningtools.todo_toolr  _todo_store_memory_store_memory_enabled_user_profile_enabled_memory_nudge_interval_memory_flush_min_turns_turns_since_memory_iters_since_skillr   tools.memory_toolr  load_from_disk_memory_managerplugins.memory.honcho.clientr  from_global_configr  r  
setdefaultagent.memory_managerr  plugins.memoryr  is_availableadd_provider	providershermes_constantsget_session_titlehermes_cli.profilesr  initialize_allr   get_all_tool_schemasr   add_skill_nudge_interval_tool_use_enforcementfloat	TypeErrorrY   rt   rs   _config_context_lengthr  plugins.context_enginer  hermes_cli.pluginsr  rh   r  agent.model_metadatar  rg   update_modelr2   compression_enabledr  _context_engine_tool_namesget_tool_schemason_session_startr3   getenv_subdirectory_hints_user_turn_count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_ctxr0   r1   r  threshold_tokens_compression_warning$_check_compression_model_feasibility_primary_runtimeupdate)rP   r  r$  r%  r&  r'  r(  r)  r*  r+  r,  r-  r.  r/  r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  r:  r;  r<  r=  r>  r?  r@  rA  rB  rC  rD  rE  rF  rG  rH  rI  rJ  rK  rL  r  rM  rN  rO  rP  
session_dbrQ  rR  rS  credential_poolrT  rU  rV  rW  provider_namerg  rh  is_openrouter	is_claudeis_native_anthropicru  rv  quiet_loggerr{  r|  _is_bedrock_anthropicr}  _re_region_match
_br_region_is_native_anthropiceffective_key_is_oat_load_br_cfg_gr	_gr_labelr   effective_baser  r  _routed_clientr  	_explicit	_env_hintr  _pcfg_effective_baseheadersexisting_beta_FINE_GRAINEDkey_usedefbr   requirementsmissing_reqsprompt_previewr  timestamp_str
short_uuidr   r  r  _load_agent_config
_agent_cfg
mem_configr  _mem_provider_name_HCC_hcfg_lc_sc_cfg_MemoryManager	_load_mem_mp_ghh_init_kwargs_str  _profile_mpe_existing_tool_names_schema_tname_wrappedskills_config_agent_section_compression_cfgcompression_thresholdr  compression_target_ratiocompression_protect_last
_model_cfgr  rt   r  _custom_providers	_cp_entry_cp_url
_cp_models_cp_model_cfg_cp_ctx_selected_engine_engine_name_ctx_cfgr  _ce_load_errr  
_candidater  _plugin_ctx_lenr  _ctx_ce_err_ollama_num_ctx_override	_detectedexc_ccs                                                                                                                                                                     rR   rS   zAIAgent.__init__(  s)   J 	
, !1 SON4S4S$!2.$'>$ $7!
 *.'"4.. / 0.8@Z****b B4>x4M4MlRZR`R`RbRbl((..000hl%+&1'X3344hhh$DMM]n,,-DMM]e##-DMM#)HDL`)`)`-DM*DMM#t7K)K)K-DM!DMM]k))m.CH[_c_sHsHs0DM'DMM!((--66|DD 		/ 1DMM]i''+<@T+T+T.DMM.DM		       
 }$99999$*dmTT
 	 	 	D	 !333..+,,2244??PP /+,,2244??MM / **,,	 /
 >>J!] ?   / .DM
 =L((D,C,C,E,E(55   eggg&<##6 &<#&+#!2"4 0*%:"*D'.!2
 !& %*!"&04!05-%O--  ! "%.^%5%5" "3!2.*+F((@% !1!2 % 0(!%&7&=2!>!> 0 6B$)!
 //11
 0 0 2 22	"m/CCdYdHd$1$?i#WDW  +0'"' )-	(6 )-$% >B
 	HGGGGGGG,//// 	L!!###KKWXXXX L
% L LL %l33<<W]KKKK !% $) 
 13-
 *.&.2+
 @B, "&#( =000________ %)MY$>!$ !_RRRRRR     #

+Mx~[] ^ ^7DU]00333+
'1$)G)G
)S)S&*3'+3(+0(("&(# D  C4:  C  Cu  C  C  C  D  D  D
 (,}'C$Pd y!K,C,C,E,E!Kkrkxvx,*7'+3(NNNNNN+27=+A+A()?)?x)X)X&"&(# _b4:bbbccc$ _]););b)@)@]=!3D]]WYWZWZI[]]^^^]000 JJ'I8>WYZZM=J#[=#6#6q#9#9#9P[D -1D*IIIIII"lnn((B77;;KLL77122 Osww?R7S7S O/23I/J,/0C,D6 6D2 ww788 oQTUmQn67MNwww'' OBEg,6w?   DK"$D? ~/3/MUOOSU	|tz||Z^Zn|py|||}}} @8 @ -4 J J=M11/3/?M),,0MM&)!)>#7#7#9#999(O.<3K8 8M"344
 -0D0D0F0FFFIIIIII7N7N7P7PM"344#~';';'='===$&68M"344 &)=)=)?)???7K7M7MM"34 KJJJJJ$;$;M+V4:%O %O %O!!-#1#9$'(?$@$@% %M
 ~/ABB a~Gf a;?@_;`;`&78
 "&!4" ; ; = = C C E EI  Y6V%V%V (1'8'8$B$B$B	!IIIIII$5$9$9)$D$DE$ F)? F,1,B1,E	( ! ! ! D!*` ` `2;` ` `   ')   #0D "-"3"3J"C"CDDJJLLO..8
@Pb?W?W?Y?Y3Y3Y'++,=>>D" ',> C C H 55$ D9F6X6X6X6X 2336C 237>M"34(,,Y;;DL)--j$-HHDMO"88|dh8ii 	JO4:OOPPP IGXGGHHH,00FCCH JH$;$;HPR@R@RUXbqb\UUhrssmUUVVVV  Imu  ]B\dehfheh\i\i  |B  I  I  I  J  J  J O O O"#M!#M#MNNNO nd++ 	&$ $)$ $ $D   -- 	&.2D2DZ2P2P 	&UcUgUghoUpUp 	&$2#3D  #%D  #( :>:NXt3A66TX 	e 	e4'((A--)!,NbkNNR
^NNNOOOOVc$2F.G.GVVVll"c"cdNb"c"c"cccd e e e *-/
 
 

 !$: 	V$U$U$*$U$U$UD! 566J? WYTZYY$))JBWBWYYZZZ $ USdii@P6Q6QSSTTT$ WUtyyAR7S7SUUVVV 	VTUUU : 	fdo 	f577L^^8J8J8L8L^^^L fdVbddeee ! 	4$/ 	42333 ' 	c 	cJMdNjJkJknpJpJpT9#2#>FFvz  wSNaNaaabbb # 	UDO 	U+>[''D[FS6SST_SSSTTT &\^^ 	>(DOO !.77HHM)"1"-J!.====DO &''#j0D4888 $0Q4?0Q0Q0Q Q 8: 59" 	?>>>>>00'2 
  
  
 &"3$%! 	 //#=ZBJNN;RTY,Z,Z**.*=,<&0" "
 !&*&= 0      	 	 	 []^       	 	.-----$9;;	KKKKKK++--JJ 	 	 	JJJ	 "$%*"&(#'($#$ "# 	'^^Hb99
'1~~6F'N'N$-7^^<RTY-Z-Z*.1*..AQSU2V2V.W.W+/2:>>BSUV3W3W/X/X,' 84+E 8======)4*4..9Ld*S*S(27H$(O(O* * *D& &55777     $ J	,I,GQ%YZ^^J%C%C%CWY" * [[[[[[ $ 7 7 9 9 = Sem Su~ S19.% d d d d d d d d'*suuLT" = =j I #D				#, % % % $%#'? S %&] ^ ^ ^ %&Q R R R$    & *4TTTTTTPPPPPP+9>+;+;D(#)$677C ?s//11 ?,99#>>>+5 #4LLLLLL*./(0(9E+.ttvv;;-6	( (  + %%&*&6&H&H&Y&Y#& !HDGL$A#, % % % $%  = D6:mL34 \BFB[L)>?!SSSSSS'>'>'@'@H=EL)9:>FL):;;( ! ! ! D!;,;KKlKKK$DFXYYYY%VXjkkk/3, , , ,GNNN'+$$$$$$,  	5DJ$:$ $$ $ $ 
  /DDFF 5 5 VR00 f(<<<$.GDD
!!(+++ 5)--f555(,,V444 &("	&NN8R88M),]->->?XZ\-]-])^)^D&& 	 	 	D	
 $44.$// 	 N%3%7%78NPV%W%W"
 &>>-<<*D11 	"! %&6&:&:;&M&M N N!"2"6"6y$"G"GHHNNPPThh#()9)=)=nd)S)S#T#T #&'7';';<Lb'Q'Q#R#R   ^^GR00
j$'' 	*%/^^4D%E%E""%)"!-.),-C)D)D&&z* . . .6 +	   


IJ` I I I 	    *.&&&." '=# ")+MMMMMM$C$CJ$O$O!! + + +$.NN3E$F$F!!"3T:: +(*%+ /  	!)T22 $==44:BB3GG w$-*>*>s*C*CCC!*x!<!<J!*d33 &(2tz2(F(F%mT:: &&3&7&78H&I&IG&2!&=@\\$:$:(1:'> !& !& !&$*NN)J )-
G%& %& %& %/JJJ$))]RVR\ )] )]v} )] )] )] .1Z	%& %& %& %& %& %&!& E  #	8B:t8T8T\z~~i444Z\H#<<,??O<LL 	 	 	D	 <''cFFFFFF#6#6|#D#D   c c cSUabbbbbbbbc  'LLLLLL!:!:!<!<J! 6jo&E&E+5(    D  '[    '&6D#EEEEEE66
i44&<  O #00j.i44 1    ? O68H8MNNN&7j"7 !7%='+?i44&<' ' 'D# $7  	@?????t.0@!DD 	D111D D DdO D D.DRD D *T1D D D   03uu'4-.. 	@43J 	@tzOe2CCEE @ @$.GDD
!!(+++ VR00 @)--f555377??? 4-.. 
	M43J 
	M	M'88O #O$5$5 6 6!]3e*#*4+BDTVW#X#X 9      M M MBGLLLLLLLLM $;	.119T$
 $
 $
  !" &'")*&$%!!"$%!%&")*&*+'()%*-'#, #)  ,0#' j$'' 	H'1~~6F'G'G$#/b'*+C'D'D$$z* b b bFH`aaaaab'DM'>OPTP]>^>^'I0T]KK	 5Q+4D( I I IBCHHHHHHHHI 	 	KKS$  
  	|" |  ~T-D-S  ~  ~  ~lo  qF  GJ  qJ  mK  mK  ~  ~  QU  Qh  Qy  ~  ~  ~  ~        zT-D-Szzzz{{{
 %)!11333 %ZtY33!$"566"&": !(Wdj A A#*3
DM#J#J")#y""="=#*3
DM#J#J),);+.+?!!
 !
$ =000!((%)%<&*&>&*&>* *      10s  ,H? ?
II/Ca2 2
a?>a?1i3 3
j ?j Cq 
q5q00q5B'AAD D
AD5DAD0D0AD5EAE EAE.E-AE.F&DAJ, J,
AJ9J8AJ9KAS? K$1AN L6AM MAN M
AMMAN MAMM(AN NAS? N
ANNAS? NANNBAS? P)&AQ QAS? Q
AQQAS? QAQQ%AS? RAR RAS? R
AR+R(AS? R*AR+R+AAS? S?
AT5T	"AT0T0AT5W(?AX( X(
AX5X4AX5^A^' ^'AA_8_7A_8`A` `6AaaAad-Ad>d>AAffAff'AAg- g-
Ag:g9Ag:hAh h
Aih Ai i AiiAi+ i+
Ai8i7Ai8r,AAt t
At;tAt6t6At;w=Ax x.AyyAyy-+Az z
A{z#A{{A{c                 $   d| _         d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        d| _        t          | d          r"| j        r| j                                         dS dS dS )a  Reset all session-scoped token counters to 0 for a fresh session.
        
        This method encapsulates the reset logic for all session-level metrics
        including:
        - Token usage counters (input, output, total, prompt, completion)
        - Cache read/write tokens
        - API call count
        - Reasoning tokens
        - Estimated cost tracking
        - Context compressor internal counters
        
        The method safely handles optional attributes (e.g., context compressor)
        using ``hasattr`` checks.
        
        This keeps the counter reset logic DRY and maintainable in one place
        rather than scattering it across multiple methods.
        r   r  r  r  r  N)r  r  r  r  r  r  r  r  r  r  r  r  r  rL  r  on_session_resetra   s    rR   reset_session_statezAIAgent.reset_session_stateW  s    & %&!$%!%&"%&")*&)*&*+'()%!"*-'#, #)  !" 4-.. 	743J 	7#4466666	7 	7 	7 	7rT   c                    ddl }ddl}ddlm} |s |||          }|dk    r2|dv r.t	          |t
                    r|r|                    dd|          }| j        }	| j        }
|| _        || _        |p| j	        | _	        || _
        |r|| _        |dk    rddlm}m}m} |d	k    }|r|p| j        p |            pdn
|p| j        pd}|| _        || _        |pt#          | d
d          | _         ||| j                  | _         ||          | _        d| _        i | _        nK|p| j        }|p| j	        }||d| _        |                     t1          | j                  dd          | _        |dk    o|d	k    }d| j	        pd                                v rd|                                v p|| _        t7          | d          r| j        r|ddlm}  || j        | j	        | j        | j        t#          | dd                    }| j                            | j        || j	        t#          | dd          | j        | j
                   d| _         t7          | d          r| j        r| j        nd}| j        | j        | j	        | j
        t#          | dd          t1          | j                  | j        |rt#          |d| j                  n| j        |rt#          |d| j	                  n| j	        |rt#          |dd          nd|rt#          |d| j                  n| j        |r|j!        nd|r|j"        ndd| _#        |dk    r-| j#        $                    | j        | j        | j        d           d| _%        d| _&         |j'        d|	|
||           dS )a]  Switch the model/provider in-place for a live agent.

        Called by the /model command handlers (CLI and gateway) after
        ``model_switch.switch_model()`` has resolved credentials and
        validated the model.  This method performs the actual runtime
        swap: rebuilding clients, updating caching flags, and refreshing
        the context compressor.

        The implementation mirrors ``_try_activate_fallback()`` for the
        client-swap logic but also updates ``_primary_runtime`` so the
        change persists across turns (unlike fallback which is
        turn-scoped).
        r   N)determine_api_moder]  )opencode-zenopencode-goz/v1/?$r  r{  r|  r  rb  rD  r  switch_modelTr  rl  rr  r  r  r  )r  r$  r%  r  r$  )r+  r  r  r$  r%  r&  r+  r  r%  r  r  Fz+Model switched in-place: %s (%s) -> %s (%s))(r   r@  hermes_cli.providersr  rZ   r[   r   r+  r%  r  r&  r$  r?  r{  r|  r  rC  rg   rD  r=  r>  rE  rF  rQ  r   r  r&  rL  r  r  r  r  rd  r  r  r  r  rT  rS  r3  )rP   	new_modelnew_providerr$  r  r&  r   r  r  	old_modelold_providerr{  r|  r  r  r  r  r  r  new_context_lengthr  s                        rR   r  zAIAgent.switch_model~  s    	;;;;;;  	B)),AAH ,,, ???8S)) @ @ wwy"h77HJ	} 
$ 1DM  	#"DL +++          $0;#> \p  VWWW8O8O8Q8QWUWw~  xU  CG  CO  xU  SUM(DL&3D#'/']74AVX\3]3]D$%;%;t7& &D" (7}'E'ED$DK"$D#3t|M%6N(*# #D 44T())% 5  DK '*>>^<S^C^dm1r88:::\x9??K\K\?\ #" 	  4-.. 	43J 	EEEEEE!9!9
&-d4Ld&S&S" " " #00j1i44 1    &*" *17K)L)LrQUQhrd%%nrZtY33!$"566"&":EH XWdj A A AdjNQ#d73
DM#J#J#JW[WdAD"L'#y""="="="NQ#d73
DM#J#J#JW[Wd?B)I););CF+M3+?+?A!
 !
 +++!((%)%<&*&>&*&>* *    $)  9|Y	
 	
 	
 	
 	
rT   c                 d    	 | j         pt          } ||i | dS # t          t          f$ r Y dS w xY w)a3  Print that silently handles broken pipes / closed stdout.

        In headless environments (systemd, Docker, nohup) stdout may become
        unavailable mid-session.  A raw ``print()`` raises ``OSError`` which
        can crash cron jobs and lose completed work.

        Internally routes through ``self._print_fn`` (default: builtin
        ``print``) so callers such as the CLI can inject a renderer that
        handles ANSI escape sequences properly (e.g. prompt_toolkit's
        ``print_formatted_text(ANSI(...))``) without touching this method.
        N)r  rG  rX   rY   )rP   r*  kwargsr   s       rR   _safe_printzAIAgent._safe_print  sU    	(5BB$ 	 	 	DD	s    //forcer  c                    t          | dd          rdS |st          | dd          rdS |s|                                 r	| j        sdS  | j        |i | dS )ue  Verbose print — suppressed when actively streaming tokens.

        Pass ``force=True`` for error/warning messages that should always be
        shown even during streaming playback (TTS or display).

        During tool execution (``_executing_tools`` is True), printing is
        allowed even with stream consumers registered because no tokens
        are being streamed at that point.

        After the main response has been delivered and the remaining tool
        calls are post-response housekeeping (``_mute_post_response``),
        all non-forced output is suppressed.

        ``suppress_status_output`` is a stricter CLI automation mode used by
        parseable single-query flows such as ``hermes chat -q``. In that mode,
        all status/diagnostic prints routed through ``_vprint`` are suppressed
        so stdout stays machine-readable.
        r  FN_mute_post_response)rg   _has_stream_consumersr  r
  )rP   r  r*  r	  s       rR   _vprintzAIAgent._vprint  s    & 41599 	F 	'<eDD 	F 	3355 	d>S 	F$)&)))))rT   c                     | j         dS t          t          dd          }|dS 	 t          |                                          S # t
          t          t          f$ r Y dS w xY w)a  Return True when quiet-mode spinner output has a safe sink.

        In headless/stdio-protocol environments, a raw spinner with no custom
        ``_print_fn`` falls back to ``sys.stdout`` and can corrupt protocol
        streams such as ACP JSON-RPC. Allow quiet spinners only when either:
        - output is explicitly rerouted via ``_print_fn``; or
        - stdout is a real TTY.
        NTrr   F)r  rg   rt   r   re   AttributeErrorrY   rX   )rP   rw   s     rR   _should_start_quiet_spinnerz#AIAgent._should_start_quiet_spinner9  sp     >%4h-->5	(((
G4 	 	 	55	s    A A! A!c                      | j         o| j         S )a  Return True when quiet-mode tool summaries should print directly.

        When the caller provides ``tool_progress_callback`` (for example the CLI
        TUI or a gateway progress renderer), that callback owns progress display.
        Emitting quiet-mode summary lines here duplicates progress and leaks tool
        previews into flows that are expected to stay silent, such as
        ``hermes chat -q``.
        )r2  r=  ra   s    rR    _should_emit_quiet_tool_messagesz(AIAgent._should_emit_quiet_tool_messagesL  s     Bt'B#BBrT   messagec                    	 |                      | j         | d           n# t          $ r Y nw xY w| j        rF	 |                     d|           dS # t          $ r  t                              dd           Y dS w xY wdS )u  Emit a lifecycle status message to both CLI and gateway channels.

        CLI users see the message via ``_vprint(force=True)`` so it is always
        visible regardless of verbose/quiet mode.  Gateway consumers receive
        it through ``status_callback("lifecycle", ...)``.

        This helper never raises — exceptions are swallowed so it cannot
        interrupt the retry/fallback logic.
        Tr  	lifecyclez%status_callback error in _emit_statusexc_infoN)r  r5  r   rG  r2  r   )rP   r  s     rR   _emit_statuszAIAgent._emit_statusW  s    	LLDO6W66dLCCCC 	 	 	D	 	UU$$['::::: U U UDtTTTTTTU	U 	Us    # 
00A &A=<A=c           	          t          | dd          pdt          | dd          pdt          | dd          pdt          | dd          pdt          | dd          pddS )zBReturn the live main runtime for session-scoped auxiliary routing.r+  r  r%  r  r$  r&  )r+  r%  r  r$  r&  )rg   ra   s    rR   _current_main_runtimezAIAgent._current_main_runtimek  sw     T7B//52j"55;j"55;tY339rj"55;
 
 	
rT   c                    | j         sdS 	 ddlm} ddlm}  |d|                                           \  }}||s:d}|| _        |                     |           t          	                    d           dS t          t          |d	d
                    }t          t          |dd
                    }| j        pi                     di                               di           }t          |t                    r|                    d          nd}	|	*	 t!          |	          }	n# t"          t$          f$ r d}	Y nw xY w |||||	          }
| j        j        }|
|k     rot!          |
| j        j        z  dz            }d| d|
dd|dd|dd|d
}|| _        |                     |           t          	                    d||
|           dS dS # t,          $ r&}t                              d|           Y d}~dS d}~ww xY w)a  Warn at session start if the auxiliary compression model's context
        window is smaller than the main model's compression threshold.

        When the auxiliary model cannot fit the content that needs summarising,
        compression will either fail outright (the LLM call errors) or produce
        a severely truncated summary.

        Called during ``__init__`` so CLI users see the warning immediately
        (via ``_vprint``).  The gateway sets ``status_callback`` *after*
        construction, so ``_replay_compression_warning()`` re-sends the
        stored warning through the callback on the first
        ``run_conversation()`` call.
        Nr   )get_text_auxiliary_clientr  r  )main_runtimeu   ⚠ No auxiliary LLM provider configured — context compression will drop middle turns without a summary. Run `hermes setup` or set OPENROUTER_API_KEY.uL   No auxiliary LLM provider for compression — summaries will be unavailable.r  r  r$  	auxiliaryr  )r  r$  r  r"  u   ⚠ Compression model (z) context is r  z7 tokens, but the main model's compression threshold is u	   tokens. Context compression will not be possible — the content to summarise will exceed the auxiliary model's context window.
  Fix options (config.yaml):
  1. Use a larger compression model:
       auxiliary:
         compression:
           model: <model-with-zt+-context>
  2. Lower the compression threshold to fit the current model:
       compression:
         threshold: 0.02du   Auxiliary compression model %s has %d token context, below the main model's compression threshold of %d tokens — compression summaries will fail or be severely truncated.z4Compression feasibility check failed (non-fatal): %s)r  rK  r  r  r  r  r  r  r2  rl  r[   rg   configr   rZ   r   r   r  rY   r  r  r  r   r   )rP   r  r  rE  	aux_modelr   aux_base_urlaux_api_key_aux_cfg_aux_context_configaux_contextr  safe_pctr  s                 rR   r  z,AIAgent._check_compression_model_feasibilityu  s    ' 	FQ	HHHHHHEEEEEE 9 9!7799! ! !FI ~Y~D 
 -0)!!#&&&5   wvz2>>??Lgfi<<==K )r..{B??CCMSUVVHDNxY]D^D^"h(,,/?"@"@"@dh"./*-.A*B*B''!:. / / /*.'''/ 32%#&9	  K /@IY&& d.E.T TX[[\\<i < <%G< <09F< < 6?N< < .6;< < " -0)!!#&&&*     / '&@  	 	 	LLF        	sD   A*G 7BG D# "G #D96G 8D99BG 
G>G99G>c                     t          | dd          }|r1| j        r,	 |                     d|           dS # t          $ r Y dS w xY wdS dS )u  Re-send the compression warning through ``status_callback``.

        During ``__init__`` the gateway's ``status_callback`` is not yet
        wired, so ``_emit_status`` only reaches ``_vprint`` (CLI).  This
        method is called once at the start of the first
        ``run_conversation()`` — by then the gateway has set the callback,
        so every platform (Telegram, Discord, Slack, etc.) receives the
        warning.
        r  Nr  )rg   rG  r   )rP   r   s     rR   _replay_compression_warningz#AIAgent._replay_compression_warning  s     d2D99 	4' 	$$[#66666   	 	 	 	s   4 
AAc                 H    |p| j                                         }d|v od|vS )z8Return True when a base URL targets OpenAI's native API.zapi.openai.comrl  )r  r  )rP   r  urls      rR   r  zAIAgent._is_direct_openai_url  s0    /4/66883&B<s+BBrT   c                     d| j         v S )z1Return True when the base URL targets OpenRouter.rl  r  ra   s    rR   r  zAIAgent._is_openrouter_url  s    t333rT   c                     |                                  }d|v r|                    dd          d         }|                    d          S )a>  Return True for models that require the Responses API path.

        GPT-5.x models are rejected on /v1/chat/completions by both
        OpenAI and OpenRouter (error: ``unsupported_api_for_model``).
        Detect these so the correct api_mode is set regardless of
        which provider is serving the model.
        rc  r   zgpt-5)r  rsplitr  )r+  ms     rR   _model_requires_responses_apiz%AIAgent._model_requires_responses_api  sD     KKMM!88a  $A||G$$$rT   rk  c                    |pd                                                                 }|dk    r"	 ddlm}  ||           S # t          $ r Y nw xY wt
                              |           S )zCReturn True when this provider/model pair should use Responses API.r  copilotr   )!_should_use_copilot_responses_api)r   r  rJ  r8  r   r  r5  )r+  r%  normalized_providerr8  s       rR   r  z.AIAgent._provider_model_requires_responses_api  s      (~24466<<>>)++OOOOOO88???     44U;;;s   A 
AAc                 :    |                                  rd|iS d|iS )zReturn the correct max tokens kwarg for the current provider.
        
        OpenAI's newer models (gpt-4o, o-series, gpt-5+) require
        'max_completion_tokens'. OpenRouter, local models, and older
        OpenAI models use 'max_tokens'.
        max_completion_tokensrH  )r  r  s     rR   _max_tokens_paramzAIAgent._max_tokens_param  s.     %%'' 	4+U33e$$rT   r   c                 v    |sdS |                      |          }t          |                                          S )a  
        Check if content has actual text after any reasoning/thinking blocks.

        This detects cases where the model only outputs reasoning but no actual
        response, which indicates an incomplete generation that should be retried.
        Must stay in sync with _strip_think_blocks() tag variants.

        Args:
            content: The assistant message content to check

        Returns:
            True if there's meaningful content after think blocks, False otherwise
        F)_strip_think_blocksr   r   )rP   r   cleaneds      rR   _has_content_after_think_blockz&AIAgent._has_content_after_think_block  s>      	5 **733 GMMOO$$$rT   c                    |sdS t          j        dd|t           j                  }t          j        dd|t           j        t           j        z            }t          j        dd|t           j                  }t          j        dd|t           j                  }t          j        dd|t           j        t           j        z            }t          j        dd|t           j                  }|S )	zKRemove reasoning/thinking blocks from content, returning only visible text.r  z<think>.*?</think>flagsz<thinking>.*?</thinking>z<reasoning>.*?</reasoning>z0<REASONING_SCRATCHPAD>.*?</REASONING_SCRATCHPAD>z<thought>.*?</thought>z@</?(?:think|thinking|reasoning|thought|REASONING_SCRATCHPAD)>\s*)r@  r   DOTALL
IGNORECASE)rP   r   s     rR   r>  zAIAgent._strip_think_blocks5  s     	2 &.G29MMM&4b'UWUbIbccc&6G29UUU&LbRYacajkkk&2BrySUS`G`aaa&\^`biqsq~rT   c                 |    | sdS |                                  }|sdS |                    d          rdS |d         dv S )zCHeuristic: does visible assistant text look intentionally finished?Fz```Tr2  u$   .!?:)"']}。！？：）】」』》)r  r  )r   strippeds     rR   _has_natural_response_endingz$AIAgent._has_natural_response_endingC  sX      	5>>## 	5U## 	4|FFFrT   c                     | j         pd                                }| j        pd                                }d|vr|dk    rdS d| j        v s	d| j        v rdS t	          | j        ot          | j                            S )zHDetect the narrow backend family affected by Ollama/GLM stop misreports.r  glmzaiFollamaz:11434T)r+  r  r%  r  r   r  r0   )rP   model_lowerprovider_lowers      rR   _is_ollama_glm_backendzAIAgent._is_ollama_glm_backendO  s    z'R..00--24466##%(?(?5t+++x4;O/O/O4DMF&7&F&FGGGrT   finish_reasonr   c                    |dk    s| j         dk    rdS |                                 sdS t          d |pg D                       sdS |t          |dd          rdS t          |dd          }t	          |t
                    sdS |                     |                                          }|sdS t          |          dk     st          j
        d	|          sdS |                     |           S )
zIDetect conservative stop->length misreports for Ollama-hosted GLM models.stopr\  Fc              3   r   K   | ]2}t          |t                    o|                    d           dk    V  3dS r   r  Nr  r   r   s     rR   r   z:AIAgent._should_treat_stop_as_truncated.<locals>.<genexpr>d  sT       
 
 sD!!?cggfoo&?
 
 
 
 
 
rT   Nr   r   r  z\s)r&  rO  r   rg   rZ   r[   r>  r   r\   r@  r   rH  )rP   rP  assistant_messager   r   visible_texts         rR   _should_treat_stop_as_truncatedz'AIAgent._should_treat_stop_as_truncatedY  s&    F""dm7I&I&I5**,, 	5 
 
 B
 
 
 
 
 	 5$0A<QU(V(V$5+Y=='3'' 	5//88>>@@ 	5|r!!5,)G)G!544\BBBBrT   user_messageassistant_contentc                 F  
 t          d |D                       rdS |                     |pd                                                                          

sdS t	          
          dk    rdS t          t          j        d
                    }|sdS d}d}|pd                                                                t          fd|D                       pd	v pd
v }t          
fd|D                       }t          
fd|D                       }	|s|	o|S )zNDetect a planning/ack message that should continue instead of ending the turn.c              3   r   K   | ]2}t          |t                    o|                    d           dk    V  3dS rT  r  rU  s     rR   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s@      WWsz#t$$BF)BWWWWWWrT   Fr  i  u@   \b(i['’]ll|i will|let me|i can do that|i can help with that)\b)z	look intozlook atinspectscancheckanalyzreviewexplorereadopenruntestfixr   r   findwalkthroughzreport back	summarize)	directoryzcurrent directoryzcurrent dirr   repo
repositorycodebaseprojectfolder
filesystemz	file treefilesr   c              3       K   | ]}|v V  	d S r_   ro   )r   marker	user_texts     rR   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s(      DD)#DDDDDDrT   z~/rc  c              3       K   | ]}|v V  	d S r_   ro   r   rt  assistant_texts     rR   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s(      '^'^V.(@'^'^'^'^'^'^rT   c              3       K   | ]}|v V  	d S r_   ro   rw  s     rR   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s9       *
 *
)/Fn$*
 *
 *
 *
 *
 *
rT   )r   r>  r   r  r\   r   r@  r   )rP   rY  rZ  r   has_future_ackaction_markersworkspace_markersuser_targets_workspaceassistant_mentions_actionassistant_targets_workspacerx  ru  s             @@rR   "_looks_like_codex_intermediate_ackz*AIAgent._looks_like_codex_intermediate_ackx  s    WWhWWWWW 	5112C2IrJJPPRRXXZZ 	5~%%5IY[ijj
 
  	5
*
  "'R..006688	DDDD2CDDDDD  y  i 	
 %('^'^'^'^~'^'^'^$^$^!&) *
 *
 *
 *
3D*
 *
 *
 '
 '
# 'E*EdKddrT   c                 ~   g }t          |d          r!|j        r|                    |j                   t          |d          r*|j        r#|j        |vr|                    |j                   t          |d          r|j        r|j        D ]}t          |t                    ro|                    d          p>|                    d          p)|                    d          p|                    d          }|r||vr|                    |           t          |dd          }|st          |t                    rk|rid	}|D ]d}t          j        t          j        z  }t          j        |||
          D ]1}	|	                                }
|
r|
|vr|                    |
           2e|rd                    |          S dS )ay  
        Extract reasoning/thinking content from an assistant message.
        
        OpenRouter and various providers can return reasoning in multiple formats:
        1. message.reasoning - Direct reasoning field (DeepSeek, Qwen, etc.)
        2. message.reasoning_content - Alternative field (Moonshot AI, Novita, etc.)
        3. message.reasoning_details - Array of {type, summary, ...} objects (OpenRouter unified)
        
        Args:
            assistant_message: The assistant message object from the API response
            
        Returns:
            Combined reasoning text, or None if no reasoning found
        	reasoningreasoning_contentreasoning_detailssummarythinkingr   r   N)<think>(.*?)</think>z<thinking>(.*?)</thinking>z<thought>(.*?)</thought>z<reasoning>(.*?)</reasoning>z2<REASONING_SCRATCHPAD>(.*?)</REASONING_SCRATCHPAD>rB  

)rL  r  r   r  r  rZ   r   r   rg   r[   r@  rD  rE  findallr   rV  )rP   rV  reasoning_partsdetailr  r   inline_patternspatternrC  blockr?  s              rR   _extract_reasoningzAIAgent._extract_reasoning  s"     $k22 	@7H7R 	@""#4#>??? $&9:: 	L?P?b 	L 2/II&&'8'JKKK $&9:: 	8?P?b 	8+= 
8 
8fd++ 	8 

9-- .!::j11.!::i00. "::f--	   87/#A#A'..w777
 +Y== 	8:gs#;#; 	8 	8O + 8 8	BM1ZFFF 8 8E#kkmmG 87/#A#A'..w7778  	0;;///trT   task_idc                    	 t          |          r | j        rt          j        d| d           nt	          |           n8# t
          $ r+}| j        rt          j        d| d|            Y d}~nd}~ww xY w	 t          |           dS # t
          $ r2}| j        r t          j        d| d|            Y d}~dS Y d}~dS d}~ww xY w)aH  Clean up VM and browser resources for a given task.

        Skips ``cleanup_vm`` when the active terminal environment is marked
        persistent (``persistent_filesystem=True``) so that long-lived sandbox
        containers survive between turns. The idle reaper in
        ``terminal_tool._cleanup_inactive_envs`` still tears them down once
        ``terminal.lifetime_seconds`` is exceeded. Non-persistent backends are
        torn down per-turn as before to prevent resource leakage (the original
        intent of this hook for the Morph backend, see commit fbd3a2fd).
        z0Skipping per-turn cleanup_vm for persistent env z; idle reaper will handle it.zFailed to cleanup VM for task : Nz#Failed to cleanup browser for task )r   r1  r   r   r   r   rl  r   )rP   r  r  s      rR   _cleanup_task_resourceszAIAgent._cleanup_task_resources	  sU   	Q )) $' M77 7 7 7  
 7### 	Q 	Q 	Q# Q O O OA O OPPP	Q	VG$$$$$ 	V 	V 	V# V Tg T TQR T TUUUUUUUUUV V V V V V	Vs/   >A 
A6!A11A6:B 
C!CCu  Review the conversation above and consider saving to memory if appropriate.

Focus on:
1. Has the user revealed things about themselves — their persona, desires, preferences, or personal details worth remembering?
2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?

If something stands out, save it using the memory tool. If nothing is worth saving, just say 'Nothing to save.' and stop.a  Review the conversation above and consider saving or updating a skill if appropriate.

Focus on: was a non-trivial approach used to complete a task that required trial and error, or changing course due to experiential findings along the way, or did the user expect or desire a different method or outcome?

If a relevant skill already exists, update it with what you learned. Otherwise, create a new skill if the approach is reusable.
If nothing is worth saving, just say 'Nothing to save.' and stop.u  Review the conversation above and consider two things:

**Memory**: Has the user revealed things about themselves — their persona, desires, preferences, or personal details? Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate? If so, save using the memory tool.

**Skills**: Was a non-trivial approach used to complete a task that required trial and error, or changing course due to experiential findings along the way, or did the user expect or desire a different method or outcome? If a relevant skill already exists, update it. Otherwise, create a new one if the approach is reusable.

Only act if there's something genuinely worth saving. If nothing stands out, just say 'Nothing to save.' and stop.messages_snapshotreview_memoryreview_skillsc                      ddl }|r
|r j        n|r j        n j         fd} |j        |dd          }|                                 dS )a  Spawn a background thread to review the conversation for memory/skill saves.

        Creates a full AIAgent fork with the same model, tools, and context as the
        main session. The review prompt is appended as the next user turn in the
        forked conversation. Writes directly to the shared memory/skill stores.
        Never modifies the main conversation history or produces user-visible output.
        r   Nc            
         dd l } dd l}d }	 t          |j        d          5 }|                     |          5  |                     |          5  t          j        ddj        j	                  }j
        |_
        j        |_        j        |_        d|_        d|_        |                               d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   g }t!          |dg           D ]}t#          |t$                    r|                    d          d	k    r2	 t)          j        |                    d
d                    }n# t(          j        t.          f$ r Y tw xY w|                    d          s|                    dd          }|                    dd          }d|                                v r|                    |           d|                                v r|                    |           d|                                v s|rBd|                                v r,|dk    rdn	|dk    rdn|}	|                    |	 d           md|v r,|dk    rdn	|dk    rdn|}	|                    |	 d           d|                                v sd|                                v r*|dk    rdn	|dk    rdn|}	|                    |	 d           |rnd                    t$                              |                    }
                    d|
            j        }|r 	  |d|
            n# t<          $ r Y nw xY wn2# t<          $ r%}t>                               d|           Y d }~nd }~ww xY w|(	 |!                                 d S # t<          $ r Y d S w xY wd S # |&	 |!                                 w # t<          $ r Y w w xY ww xY w) Nr   wr   T)r+  r,  r2  r  r%  )rY  conversation_historyrc  r   r  r   {}successr  r  rp  createdupdatedaddedr  r  MemoryuserzUser profilez updatedzEntry addedremovedreplacedu    · u     💾 u   💾 z)Background memory/skill review failed: %s)"
contextlibr   rd  devnullredirect_stdoutredirect_stderrr  r+  r  r%  ro  rp  rq  rr  r  run_conversationrg   rZ   r   r   r   r   JSONDecodeErrorr  r  r   rV  fromkeysr
  r  r   r2  r   close)r  _osreview_agent_devnullactionsr   r]   r  rp  labelr  _bg_cbr  r  promptrP   s                rR   _run_reviewz5AIAgent._spawn_background_review.<locals>._run_review^	  s   ((((((((LF#+s++ x//99 //99  $+"j'(#'!%!%$ $ $L 261CL.373GL09=9SL6:;L79:L6 11%+-> 2   !                                            . "<1DbII ; ;C%c400 !CGGFOOv4M4M !#z#'')T*B*BCC 0)< ! ! ! !88I.. ! "hhy"55G!XXh33F GMMOO33w////"gmmoo55w//// GMMOO3335GMMOOC[C[,2h,>,>V\`fVfVfNNlr%'9'9'9::::&'11,2h,>,>V\`fVfVfNNlr%'9'9'9::::"gmmoo55w}}9V9V,2h,>,>V\`fVfVfNNlr%'9'9'9::: !$kk$--*@*@AAG$$%8w%8%8999!<F !!"F#47#4#45555( ! ! ! D!  M M MH!LLLLLLLLM  +$**,,,,,$    ,+<+$**,,,,$    ,s  M9 C5CA-C;CCCCCC5C"	"C5%C"	&C5)M9 5C99M9 <C9=AM9 (E/.M9 /FM9 FGM9 M( 'M9 (
M52M9 4M55M9 8O 9
N(N#O #N((O .O 
OOPO0/P0
O=:P<O==PTz	bg-review)rp  rq  rh   )r~   _COMBINED_REVIEW_PROMPT_MEMORY_REVIEW_PROMPT_SKILL_REVIEW_PROMPTr  r  )rP   r  r  r  r~   r  r  r  s   ``     @rR   _spawn_background_reviewz AIAgent._spawn_background_reviewG	  s     	  	/] 	/1FF 	//FF.FI	 I	 I	 I	 I	 I	 I	V IK;OOO						rT   c                    t          | dd          }t          | dd          }||dS d|cxk    rt          |          k     rAn dS ||         }t          |t                    r"|                    d          dk    r||d<   dS dS dS dS )a  Rewrite the current-turn user message before persistence/return.

        Some call paths need an API-only user-message variant without letting
        that synthetic text leak into persisted transcripts or resumed session
        history. When an override is configured for the active turn, mutate the
        in-memory messages list in place so both persistence and returned
        history stay clean.
        r:  Nr;  r   r   r  r   )rg   r\   rZ   r   r   )rP   r   r  overrider   s        rR   $_apply_persist_user_message_overridez,AIAgent._apply_persist_user_message_override	  s     d7>>4!A4HHs{F####c(mm######3-C#t$$ *F)B)B!)I $#* *)B)BrT   r  c                     | j         sdS |                     |           || _        |                     |           |                     ||           dS )zSave session state to both JSON log and SQLite on any exit path.

        Ensures conversations are never lost, even on errors or early returns.
        Skipped when ``persist_session=False`` (ephemeral helper flows).
        N)rW  r  rc  _save_session_log_flush_messages_to_session_db)rP   r   r  s      rR   _persist_sessionzAIAgent._persist_session	  sa     # 	F11(;;;!)x(((**85IJJJJJrT   c                    | j         sdS |                     |           	 | j                             | j        | j        pd| j                   |rt          |          nd}t          || j                  }||d         D ]<}|	                    dd          }|	                    d          }d}t          |d          r|j        rd	 |j        D             }n0t          |	                    d          t                    r|d         }| j                             | j        |||	                    d
          ||	                    d          |	                    d          |dk    r|	                    d          nd|dk    r|	                    d          nd|dk    r|	                    d          nd
  
         >t          |          | _        dS # t          $ r&}	t                               d|	           Y d}	~	dS d}	~	ww xY w)u%  Persist any un-flushed messages to the SQLite session store.

        Uses _last_flushed_db_idx to track which messages have already been
        written, so repeated calls (from multiple exit paths) only write
        truly new messages — preventing the duplicate-write bug (#860).
        Nr  )r  r+  r   r   r  r   r   c                 @    g | ]}|j         j        |j         j        d S )rh   r   )r   rh   r   r   s     rR   r   z9AIAgent._flush_messages_to_session_db.<locals>.<listcomp>	  s:     ' ' ' "$!1@UVV' ' 'rT   r   tool_call_idrP  	assistantr  r  codex_reasoning_items)
r<  r   r   r   r   r  rP  r  r  r  z$Session DB append_message failed: %s)rg  r  ensure_sessionr<  r  r+  r\   r   ri  r   rL  r   rZ   r   append_messager   r2  rl  )
rP   r   r  	start_idx
flush_fromr   r   r   tool_calls_datar  s
             rR   r  z%AIAgent._flush_messages_to_session_db	  sX     	F11(;;;$	F ++}-j ,   
 6JP0111qIY(ABBJ
,  wwvy11''),,"&3-- 8#. 8' '"%.' ' 'OO   5 5t<< 8&),&7O //##!ggk22.!$!8!8"%''/":":6:k6I6Icggk222tFJkFYFYcgg.A&B&B&B_cNRVaNaNa#''2I*J*J*Jgk 0     ),HD%%% 	F 	F 	FNNA1EEEEEEEEE	Fs   F2G 
HG??Hc                     |sg S d}t          t          |          dz
  dd          D ]%}||                             d          dk    r|} n&||                                S |d|         S )a  
        Get messages up to (but not including) the last assistant turn.
        
        This is used when we need to "roll back" to the last successful point
        in the conversation, typically when the final assistant message is
        incomplete or malformed.
        
        Args:
            messages: Full message list
            
        Returns:
            Messages up to the last complete assistant turn (ending with user/tool message)
        Nr   r2  r   r  )ranger\   r   copy)rP   r   last_assistant_idxis       rR   "_get_messages_up_to_last_assistantz*AIAgent._get_messages_up_to_last_assistant	  s      	I "s8}}q("b11 	 	A{v&&+55%&" 6 %==??" +++,,rT   c                     | j         sdS g }| j         D ]T}|d         }|d         |                    dd          |                    di           dd}|                    |           Ut          j        |d	
          S )z
        Format tool definitions for the system message in the trajectory format.
        
        Returns:
            str: JSON string representation of tool definitions
        z[]r   rh   descriptionr  
parametersN)rh   r  r  requiredFensure_ascii)r   r   r   r   dumps)rP   formatted_toolsr  funcformatted_tools        rR    _format_tools_for_system_messagez(AIAgent._format_tools_for_system_message
  s     z 	4 J 	3 	3D
#DV#xxr::"hh|R88 	 N "">2222z/>>>>rT   
user_query	completedc                    g }d|                                   d}|                    d|d           |                    d|d           d}|t          |          k     r||         }|d         dk    rd	|v r-|d	         r$d
}|                    d          r&|d                                         rd|d          d}|                    d          r5|d                                         r|t          |d                   dz   z  }|d	         D ]}	|	rt          |	t                    s	 t          |	d         d         t                    r t          j
        |	d         d                   n|	d         d         }
nB# t          j        $ r0 t          j        d|	d         d         dd                     i }
Y nw xY w|	d         d         |
d}|dt          j        |d           dz  }d|vrd|z   }|                    d|                                d           g }|dz   }|t          |          k     r8||         d         dk    r%||         }d}|d         }	 |                                                    d           rt          j
        |          }n# t          j        t"          f$ r Y nw xY wt          |          }|t          |d	                   k     r|d	         |         d         d         nd!}|t          j        |                    d"d
          ||d#d          z  }|d$z  }|                    |           |dz  }|t          |          k     r||         d         dk    %|r0|                    dd                    |          d           |dz
  }nd
}|                    d          r&|d                                         rd|d          d}|d         pd
}|t          |          z  }d|vrd|z   }|                    d|                                d           n*|d         d%k    r|                    d|d         d           |dz  }|t          |          k     |S )&ay  
        Convert internal message format to trajectory format for saving.
        
        Args:
            messages (List[Dict]): Internal message history
            user_query (str): Original user query
            completed (bool): Whether the conversation completed successfully
            
        Returns:
            List[Dict]: Messages in trajectory format
        a  You are a function calling AI model. You are provided with function signatures within <tools> </tools> XML tags. You may call one or more functions to assist with the user query. If available tools are not relevant in assisting with user query, just respond in natural conversational language. Don't make assumptions about what values to plug into functions. After calling & executing the functions, you will be provided with function results within <tool_response> </tool_response> XML tags. Here are the available tools:
<tools>
a  
</tools>
For each function call return a JSON object, with the following pydantic model json schema for each:
{'title': 'FunctionCall', 'type': 'object', 'properties': {'name': {'title': 'Name', 'type': 'string'}, 'arguments': {'title': 'Arguments', 'type': 'object'}}, 'required': ['name', 'arguments']}
Each function call should be enclosed within <tool_call> </tool_call> XML tags.
Example:
<tool_call>
{'name': <function-name>,'arguments': <args-dict>}
</tool_call>r  )fromr   humanr   r   r  r   r  r  z<think>
z

</think>
r   
r   r   z2Unexpected invalid JSON in trajectory conversion: Nr"  rh   r  z<tool_call>
Fr  z
</tool_call>
<think>z<think>
</think>
gptr  z<tool_response>
){[r  r  )r  rh   r   z
</tool_response>r  )r  r   r\   r   r   rE   rZ   r   r[   r   r   r  r   rl  r  r  r  r  rV  )rP   r   r  r  
trajectory
system_msgr  r   r   r   r   tool_call_jsontool_responsesjtool_msgtool_responsetool_content
tool_indexr   raw_contents                       rR   _convert_to_trajectory_formatz%AIAgent._convert_to_trajectory_format2
  s!    

f
 ==??
f 
f 
f 	 	
 
 	 	 	 	
 
 	 	 	 #h--1+C6{k))3&&3|+<& !G ww{++ MK0@0F0F0H0H M"Lc+.>"L"L"Lwwy)) Vc)n.B.B.D.D V  #>s9~#N#NQU#UU &)%6 t t	(U
9d0K0KUX+Zdenoyez  |G  fH  JM  [N  [N  )v
9Z3H3U(V(V(V  T]  ^h  Ti  ju  TvII#3 + + + $O  -Lajkuav  xC  bD  EI  FI  EI  bJ  -L  -L  M  M  M(*III	+ %.j$9&$A)2* *  #s4:n[`3a3a3a#s#s#ss !//"7'"A%% %!(!1!1' '    &(NAAc(mm++F0Cv0M0M#+A;(; (0	':!+1133>>zJJ H/3z,/G/G $ 4nE ! ! ! D! &)%8%8
  *CL0A,B,BBB  -j9*EfMM!* "
 &,4LL,L,L$-'35 5 ).	*/ */ */ /
 &)==&--m<<<Q5 c(mm++F0Cv0M0M: & ""))$*%)YY~%>%>+ +    E
 !G ww{++ MK0@0F0F0H0H M"Lc+.>"L"L"L #&i."6BK:;GGGG !//"7'"A%% %!(' '    
 V&&!!# ^# #   
 FAi #h--l s%   .AE>><F=<F=#;J J87J8c                 r    | j         sdS |                     |||          }t          || j        |           dS )a  
        Save conversation trajectory to JSONL file.
        
        Args:
            messages (List[Dict]): Complete message history
            user_query (str): Original user query
            completed (bool): Whether the conversation completed successfully
        N)r0  r  _save_trajectory_to_filer+  )rP   r   r  r  r  s        rR   _save_trajectoryzAIAgent._save_trajectory
  sE     % 	F77*iXX
 TZCCCCCrT   errorc                    ddl }t          |           }d|v sd|v r|                    d||j                  }|r'|                    d                                          nd}|                    d|          }|r'|                    d                                          nd}t          | d	d          }g }|r|                    d
|            |                    |           |r|                    d|            d                    |          S t          | dd          }	t          |	t                    rt          |	                    d          t                    r)|	                    di                               d          n|	                    d          }
|
r)t          | d	d          }|rd
| dnd}| |
dd          S t          | d	d          }|rd
| dnd}| |dd          S )zExtract a human-readable one-liner from an API error.

        Handles Cloudflare HTML error pages (502, 503, etc.) by pulling the
        <title> tag instead of dumping raw HTML.  Falls back to a truncated
        str(error) for everything else.
        r   Nz	<!DOCTYPE<htmlz<title[^>]*>([^<]+)</title>r   z!HTML error page (title not found)z2Cloudflare Ray ID:\s*<strong[^>]*>([^<]+)</strong>status_codezHTTP zRay u    — bodyr  r  r  r  ,    )r@  r[   r   rE  rA  r   rg   r   rV  rZ   r   r   )r  r  rawr4  titlerayray_idr  r   r  r   prefixs               rR   _summarize_api_errorzAIAgent._summarize_api_error
  s0    	%jj #C

93OOA*+TAGGAJJ$$&&&1TE**RTWXXC-0:SYYq\\'')))dF!%==KE 42[22333LL ._F__---<<&&& ufd++dD!! 	.:DTXXgEVEVX\:]:]v$((7B''++I666cgckcklucvcvC .%e]DAA4?G00000R -#dsd)--- e]D99,7?(((((R%#dsd)%%%rT   r   c                 b    |sd S t          |          dk    rdS |d d          d|dd           S )Nr  z***r   r  r  r\   )rP   r   s     rR   _mask_api_key_for_logszAIAgent._mask_api_key_for_logs  sG     	4s88r>>5bqb'((c"##h(((rT   	error_msgc                     |sdS |                                                     d          sd|v rdS d                    |                                          }t	          |          dk    r|dd         dz   }|S )	a  
        Clean up error messages for user display, removing HTML content and truncating.
        
        Args:
            error_msg: Raw error message from API or exception
            
        Returns:
            Clean, user-friendly error message
        zUnknown errorz<!DOCTYPE htmlr  z:Service temporarily unavailable (HTML error page returned)rY     Nr  )r   r  rV  splitr\   )rP   r  r?  s      rR   _clean_error_messagezAIAgent._clean_error_message  s      	#"? ??''(899 	PW	=Q=QOO ((9??,,-- w<<#dsdme+GrT   c                    i }t          | dd          }d}t          |t                    r?t          |                    d          t                    r|                    d          n|}t          |t                    rU|                    d          p|                    d          }t          |t                    r+|                                r|                                |d<   |                    d          p|                    d          }t          |t                    r+|                                r|                                |d<   dD ]"}|                    |          }|d	vr||d
<    n#|                    d          }|d	vrCd
|vr?	 t          j                    t          |          z   |d
<   n# t          t          f$ r Y nw xY wt          | dd          }	t          |	dd          }
|
r|
                    d          p|
                    d          }|rCd
|vr?	 t          j                    t          |          z   |d
<   n# t          t          f$ r Y nw xY w|
                    d          }|r	d
|vr||d
<   d|vr0t	          |                                           }|r|dd         |d<   d
|vr|                    d          pd}t          |t                    rt          j        d|t          j                  }|rnt          |                    d                    }|                    d                                          dk    r|dz  n|}t          j                    |z   |d
<   n[t          j        d|t          j                  }|r9t          j                    t          |                    d                    z   |d
<   |S )z;Extract structured rate-limit details from provider errors.r  Nr  coder  r  error_description)	resets_atreset_atr  r  retry_afterresponser  retry-afterRetry-Afterzx-ratelimit-resetr  r  z/quotaResetDelay[:\s\"]+(\\d+(?:\\.\\d+)?)(ms|s)r      msg     @@z?retry\s+(?:after\s+)?(\d+(?:\.\d+)?)\s*(?:sec|secs|seconds|s\b))rg   rZ   r   r   r[   r   r*  r  r  rY   r@  r   rE  rA  r  )r  r  r  r  r  r  r   r   r  r  r  ratelimit_resetraw_messagedelay_matchseconds	sec_matchs                   rR   _extract_api_error_contextz"AIAgent._extract_api_error_context0  s    #%ufd++dD!! 	Y+5dhhw6G6G+N+NXdhhw'''TXGgt$$ 	[[((@GKK,@,@F&#&& 36<<>> 3$*LLNN!kk),,P<O0P0PG'3'' 5GMMOO 5%,]]__	"0  C((
***/GJ'E + "++m44K*,,71J1J*.)++k8J8J*JGJ''!:.   D 5*d33(It44 		6!++m44RM8R8RK z88*.)++k8J8J*JGJ''!:.   D%kk*=>>O 6:W#<#<&5
#G##e****,,K 7%0#%6	"W$$kk),,2G'3'' V i(Z\cegerss V!+"3"3A"6"677E0;0A0A!0D0D0J0J0L0LPT0T0TefnnZ_G*.)++*?GJ'' "	Z! !I
 ! V.2ikkE)//RSBTBT<U<U.U
+s$   &F> >GG*&I I%$I%r  c                     |dS t          |dd          }|sdS ddlm} t          || j        | j                  } ||          }|                    dd           |j        |d<   |j        |d<   |S )	zLToken buckets for ``post_api_request`` plugins (no raw ``response`` object).Nusager   )asdictr%  r&  	raw_usageprompt_tokenstotal_tokens)	rg   dataclassesr  r?   r%  r&  popr  r  )rP   r  r  r  cur  s         rR   #_usage_summary_for_api_request_hookz+AIAgent._usage_summary_for_api_request_hookq  s    4Hgt44	 	4&&&&&&YWWW&**K&&&#%#3 "$/rT   )r  
api_kwargsr  c          	         	 t          j        |          }|                    dd           d |                                D             }d}	 t	          | j        dd          }n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wt          j
                                                    | j        |d| j                            d           | j        dk    rd	nd
 d|                     |           dd|dd}|t#          |          j        t'          |          d}dD ]}	t	          ||	d          }
|
|
||	<   t	          |dd          }|||d<   t	          |dd          }|R	 t	          |dd          |d<   |j        |d<   n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w||d<   t          j
                                        d          }| j        d| j         d| dz  }|                    t1          j        |ddt&                    d !           |                     | j         d"|            t9          d#          r*t;          t1          j        |ddt&                               |S # t          $ r)}| j        rt?          j         d$|            Y d}~dS d}~ww xY w)%a  
        Dump a debug-friendly HTTP request record for the active inference API.

        Captures the request body from api_kwargs (excluding transport-only keys
        like timeout). Intended for debugging provider-side 4xx failures where
        retries are not useful.
        timeoutNc                     i | ]
\  }}|||S r_   ro   r   kvs      rR   
<dictcomp>z3AIAgent._dump_api_request_debug.<locals>.<dictcomp>  s    CCCTQQ]Aq]]]rT   r$  z,Could not extract API key for debug dump: %sPOSTrc  rZ  z
/responsesz/chat/completionszBearer zapplication/json)AuthorizationzContent-Type)methodr.  r  r  )	timestampr<  r  request)r   r  )r  
request_idr	  paramr   r  r  r  response_statusresponse_textz,Could not extract error response details: %sr  z%Y%m%d_%H%M%S_%frequest_dump_r  r  Fr  )r  indentdefaultutf-8encodingu$   🧾 Request debug dump written to: HERMES_DUMP_REQUEST_STDOUTz*Failed to dump API request debug payload: )!r  deepcopyr!  r   rg   rE  r   r2  r   r	   rZ  	isoformatr<  r  r  r&  r  r   rj   r[   r   r\  r`  
write_textr   r  r  r5  rI   rG  r1  r   rl  )rP   r$  r  r  r  r$  r  dump_payload
error_info	attr_name
attr_value	body_attrresponse_objr/  	dump_file
dump_errors                   rR   _dump_api_request_debugzAIAgent._dump_api_request_debug  s   B	=,,DHHY%%%CCTZZ\\CCCDGP!$+y$?? P P PKQOOOOOOOOP &\^^5577"o $"m22377  GZkIkIk  rE  G  G)Y43N3Nw3W3W)Y)Y(:    ! 	, ,L   KK0"5zz. .
 "X ; ;I!(	4!@!@J!-0:
9-#E6488	()2Jv&&uj$??+X8?m]a8b8b
#456B6G
?33$ X X X%SUVWWWWWWWWX )3W% //0BCCI(Z(Z(Z)(Z(Z(ZZI  
<eAsSSS  !   
 LLDO\\QZ\\]]];<< [djE!UXYYYZZZ 	 	 	# [ YZ Y YZZZ44444	sn   A
J A$ #J $
B.B	J BC'J ;F J 
G	$G?J G		CJ 
K#KKc                     | s| S t          |           } t          j        dd|           } t          j        dd|           } |                                 S )zCConvert REASONING_SCRATCHPAD to think tags and clean up whitespace.z\n+(<think>)z\n\1z(</think>)\n+z\1\n)rE   r@  r   r   )r   s    rR   _clean_session_contentzAIAgent._clean_session_content  sS      	N-g66&'7;;&)7G<<}}rT   c                 <   |p| j         }|sdS 	 g }|D ]r}|                    d          dk    rB|                    d          r-t          |          }|                     |d                   |d<   |                    |           s| j                                        r	 t          j        | j        	                    d                    }|                    dt          |                    dg                               }|t          |          k    r%t          j        d	|t          |                     dS n# t          $ r Y nw xY w| j        | j        | j        | j        | j                                        t)          j                                                    | j        pd
| j        pg t          |          |d
}t1          | j        |dt2                     dS # t          $ r/}| j        rt          j        d|            Y d}~dS Y d}~dS d}~ww xY w)a  
        Save the full raw session to a JSON file.

        Stores every message exactly as the agent sees it: user messages,
        assistant messages (with reasoning, finish_reason, tool_calls),
        tool responses (with tool_call_id, tool_name), and injected system
        messages (compression summaries, todo snapshots, etc.).

        REASONING_SCRATCHPAD tags are converted to <think> blocks for consistency.
        Overwritten after each turn so it always reflects the latest state.
        Nr   r  r   r8  r9  message_countr   zHSkipping session log overwrite: existing has %d messages, current has %dr  )
r<  r+  r  r  r[  last_updatedsystem_promptr   rK  r   r  )r6  r7  zFailed to save session log: )rc  r   r   rI  r   rb  existsr   r   	read_textr\   r   r   r   r<  r+  r  r  r[  r=  r	   rZ  rd  r   rH   r[   r1  rl  )rP   r   r?  r   r   existing_countentryr  s           rR   r  zAIAgent._save_session_log  s    5t5 	F0	DG $ $776??k11cggi6H6H1s))C%)%@%@Y%P%PC	Ns#### $++-- 
#z$*?*I*ISZ*I*[*[\\H%-\\/3x||T^`bGcGcCdCd%e%eN%G44f*CLL    5 !   D #o M M!%!3!=!=!?!? ( 8 8 : :!%!;!Ar)r!$W# E %	       	D 	D 	D# D Bq B BCCCCCCCCCD D D D D D	Ds>   BG"  BD= <G" =
E
G" 	E

BG" "
H,HHc                    d| _         || _        | j        t          d| j                   d| _        nd| _        | j        5  t          | j                  }ddd           n# 1 swxY w Y   |D ]J}	 |                    |           # t          $ r%}t                              d|           Y d}~Cd}~ww xY w| j        s?t          d|r!t          |          dk    rd|dd          dn	|rd| d	nd
z              dS dS )a  
        Request the agent to interrupt its current tool-calling loop.
        
        Call this from another thread (e.g., input handler, message receiver)
        to gracefully stop the agent and process a new message.
        
        Also signals long-running tool executions (e.g. terminal commands)
        to terminate early, so the agent can respond immediately.
        
        Args:
            message: Optional new message that triggered the interrupt.
                     If provided, the agent will include this in its response context.
        
        Example (CLI):
            # In a separate input thread:
            if user_typed_something:
                agent.interrupt(user_input)
        
        Example (Messaging):
            # When new message arrives for active session:
            if session_has_running_agent:
                running_agent.interrupt(new_message.text)
        TNFz0Failed to propagate interrupt to child agent: %su   
⚡ Interrupt requested(   z: 'z...''r  )r  r  r  _set_interruptr  r$  r   r#  	interruptr   r2  r   r2  rG  r\   )rP   r  children_copychildr  s        rR   rV  zAIAgent.interrupt  s   0 %)!") $04!:;;;49D11 59D1' 	8 	8 !677M	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8" 	T 	TET(((( T T TOQRSSSSSSSST 	V-W  2TY\]dYeYehjYjYj1Iwss|1I1I1I1I  EL  qT  qAv}  qA  qA  qA  qA  RT  U  V  V  V  V  V	V 	Vs*   A""A&)A&2B
B7B22B7c                 l    d| _         d| _        d| _        | j        t	          d| j                   dS dS )zMClear any pending interrupt request and the per-thread tool interrupt signal.FN)r  r  r  r  rU  ra   s    rR   clear_interruptzAIAgent.clear_interruptP  sD    $)!"&05-$05$";<<<<< 10rT   descc                 D    t          j                     | _        || _        dS )zAUpdate the last-activity timestamp and description (thread-safe).N)r*  r+  r,  )rP   r[  s     rR   _touch_activityzAIAgent._touch_activityX  s    !%#'   rT   http_responsec                     |dS t          |dd          }|sdS 	 ddlm}  ||| j                  }|	|| _        dS dS # t
          $ r Y dS w xY w)zParse x-ratelimit-* headers from an HTTP response and cache the state.

        Called after each streaming API call.  The httpx Response object is
        available on the OpenAI SDK Stream via ``stream.response``.
        Nr  r   )parse_rate_limit_headersrk  )rg   agent.rate_limit_trackerr`  r%  r/  r   )rP   r^  r  r`  states        rR   _capture_rate_limitszAIAgent._capture_rate_limits]  s      F-D99 	F	IIIIII,,Wt}MMME ).&&& !  	 	 	DD	s   !A   
AAc                     | j         S )z1Return the last captured RateLimitState, or None.)r/  ra   s    rR   get_rate_limit_statezAIAgent.get_rate_limit_statep  s    %%rT   c           	          t          j                     | j        z
  }| j        | j        t          |d          | j        | j        | j        | j        j        | j        j	        dS )zReturn a snapshot of the agent's current activity for diagnostics.

        Called by the gateway timeout handler to report what the agent was doing
        when it was killed, and by the periodic "still working" notifications.
        r   )last_activity_tslast_activity_descseconds_since_activitycurrent_toolapi_call_countr,  budget_used
budget_max)
r*  r+  r,  roundr-  r.  r,  rR  r   r{   )rP   elapseds     rR   get_activity_summaryzAIAgent.get_activity_summaryt  sc     )++ 66 $ 6"&":&+GQ&7&7 ."2"105/9	
 	
 		
rT   c                 h   | j         rY	 | j                             |pg            n# t          $ r Y nw xY w	 | j                                          n# t          $ r Y nw xY wt	          | d          r?| j        r:	 | j                            | j        pd|pg            dS # t          $ r Y dS w xY wdS dS )uC  Shut down the memory provider and context engine — call at actual session boundaries.

        This calls on_session_end() then shutdown_all() on the memory
        manager, and on_session_end() on the context engine.
        NOT called per-turn — only at CLI exit, /reset, gateway
        session expiry, etc.
        r  r  N)rx  on_session_endr   shutdown_allrL  r  r<  rP   r   s     rR   shutdown_memory_providerz AIAgent.shutdown_memory_provider  s!     	$33HNCCCC   $113333    4-.. 	43J 	'66O)rN        	 	 	 	s/   & 
33A 
AA9$B 
B-,B-c                 t    | j         sdS 	 | j                             |pg            dS # t          $ r Y dS w xY w)u  Trigger end-of-session extraction without tearing providers down.
        Called when session_id rotates (e.g. /new, context compression);
        providers keep their state and continue running under the old
        session_id — they just flush pending extraction now.N)rx  rr  r   rt  s     rR   commit_memory_sessionzAIAgent.commit_memory_session  s\    
 # 	F	 //B????? 	 	 	DD	s   ) 
77c                    t          | dd          pd}	 ddlm} |                    |           n# t          $ r Y nw xY w	 ddlm}  ||           n# t          $ r Y nw xY w	 ddlm}  ||           n# t          $ r Y nw xY w	 | j	        5  t          | j                  }| j                                         ddd           n# 1 swxY w Y   |D ]'}	 |                                 # t          $ r Y $w xY wn# t          $ r Y nw xY w	 t          | d	d          }|!|                     |d
d           d| _        dS dS # t          $ r Y dS w xY w)a   Release all resources held by this agent instance.

        Cleans up subprocess resources that would otherwise become orphans:
        - Background processes tracked in ProcessRegistry
        - Terminal sandbox environments
        - Browser daemon sessions
        - Active child agents (subagent delegation)
        - OpenAI/httpx client connections

        Safe to call multiple times (idempotent).  Each cleanup step is
        independently guarded so a failure in one does not prevent the rest.
        r<  Nr  r   )process_registryr  )r   r   rE  agent_closeTr  )rg   tools.process_registryry  kill_allr   tools.terminal_toolr   tools.browser_toolr   r$  r   r#  clearr  _close_openai_clientrE  )rP   r  ry  r   r   childrenrX  rE  s           rR   r  zAIAgent.close  sa    $d339r	??????%%g%6666 	 	 	D		666666Jw 	 	 	D		::::::OG$$$$ 	 	 	D	
	+ . . 566%++---. . . . . . . . . . . . . . . "  KKMMMM    D
  	 	 	D		T8T22F!))&t)TTT" "!  	 	 	DD	s   2 
??A 
A"!A"&A8 8
BB	D  .C
>D  
CD  CD  C/.D  /
C<9D  ;C<<D   
DD2E 
EEhistoryc                    d}t          |          D ]}|                    d          dk    r|                    dd          }d|vr7	 t          j        |          }d|v r%t	          |d         t
                    r
|d         } nv# t          j        t          f$ r Y w xY w|rP| j        	                    |d	           | j
        s-|                     | j         d
t          |           d           t          d           dS )a  
        Recover todo state from conversation history.
        
        The gateway creates a fresh AIAgent per message, so the in-memory
        TodoStore is empty. We scan the history for the most recent todo
        tool response and replay it to reconstruct the state.
        Nr   r  r   r  z"todos"todosF)mergeu   📋 Restored z todo item(s) from history)reversedr   r   r   rZ   r   r  r  rn  rW   r2  r  r5  r\   rU  )rP   r  last_todo_responser   r   r]   s         rR   _hydrate_todo_storezAIAgent._hydrate_todo_store  s6    "G$$ 	 	Cwwv&((ggi,,G''z'**d??z$w-'F'F?)-g&E()4     	t""#5U"CCC? trrsCU?V?Vrrrsssus   
;BB! B!c                     | j         S )z)Check if an interrupt has been requested.r  ra   s    rR   is_interruptedzAIAgent.is_interrupted  s     ((rT   system_messagec                 
    d} j         st                      }|r|g}d}|st          g}g }d j        v r|                    t
                     d j        v r|                    t                     d j        v r|                    t                     |r(|                    d                    |                     t           j                  }|r|                    |            j        ro j
        }d}|du s+t          |t                    r|                                dv rd}n|du s+t          |t                    r|                                dv rd}nt          |t                    r7 j        pd	                                t!          fd
|D                       }n; j        pd	                                t!          fdt"          D                       }|ry|                    t$                      j        pd	                                }	d|	v sd|	v r|                    t&                     d|	v sd|	v r|                    t(                     ||                    |            j        rp j        r1 j                            d          }
|
r|                    |
            j        r1 j                            d          }|r|                    |            j        rB	  j                                        }|r|                    |           n# t6          $ r Y nw xY wt!           fddD                       }|r2d d  j        D             D             }t9           j        |          }nd	}|r|                    |            j         s>t;          j        d          pd}t?          ||          }|r|                    |           ddl m!}  |            }d|"                    d           } j#        r j$        r|d j$         z  } j        r|d j         z  } j%        r|d j%         z  }|                    |            j%        d k    rQd! j        v r  j        &                    d!          d"         n j        }|                    d#| d$ j         d%           tO                      }|r|                    |            j(        pd	                                )                                }|tT          v r |                    tT          |                    d&                    d' |D                       S )(a;  
        Assemble the full system prompt from all layers.
        
        Called once per session (cached on self._cached_system_prompt) and only
        rebuilt after context compression events. This ensures the system prompt
        is stable across all turns in a session, maximizing prefix cache hits.
        FTr  r   skill_managerY  )r  alwaysr  on)falsenevernooffr  c              3   n   K   | ]/}t          |t                    |                                v V  0d S r_   )rZ   r[   r  r   prM  s     rR   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>P  sA      __1JWXZ]L^L^_aggii;6______rT   c              3       K   | ]}|v V  	d S r_   ro   r  s     rR   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>T  s(      TT1a;.TTTTTTrT   geminigemmar  codexNr  c              3   *   K   | ]}|j         v V  d S r_   )rX  )r   rh   rP   s     rR   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>|  s+      wwtt'<<wwwwwwrT   )r   r   r  c                     h | ]}||S ro   ro   )r   toolsets     rR   r  z/AIAgent._build_system_prompt.<locals>.<setcomp>~  s0          rT   c              3   4   K   | ]}t          |          V  d S r_   )r   )r   r   s     rR   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>  s<          8A(33           rT   )available_toolsavailable_toolsetsr  )r   	skip_soulr   )rZ  zConversation started: z%A, %B %d, %Y %I:%M %pz
Session ID: z
Model: z
Provider: alibabarc  r2  z#You are powered by the model named z. The exact model ID is zt. When asked what model you are, always answer based on this information, not on any model name returned by the API.r  c              3   f   K   | ],}|                                 |                                 V  -d S r_   r   r   r  s     rR   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>  s7      HHaggiiH17799HHHHHHrT   )+rO  r8   r"   rX  r   r$   r%   r&   rV  r'   r  rZ   r[   r  r   r+  r   r:   r9   r<   r=   ro  rp  format_for_system_promptrq  rx  build_system_promptr   r5   r   r  r6   hermes_timerZ  r\  rV  r<  r%  r  r7   r  r   r#   )rP   r  _soul_loaded_soul_contentprompt_partstool_guidancenous_subscription_prompt_enforce_inject_model_lower	mem_block
user_block_ext_mem_blockhas_skills_toolsavail_toolsetsskills_prompt_context_cwdcontext_files_prompt_hermes_nowrZ  timestamp_line_model_short
_env_hintsplatform_keyrM  s   `                       @rR   _build_system_promptzAIAgent._build_system_prompt  so   $ & 	$(NNM $ -# 	423L t,,,  111t444  !8999T222  111 	9 7 7888#A$BW#X#X # 	: 8999   	I1HG4Jx$=$=(..BRBRVuBuBuU""z(C'@'@"X^^EUEUYxExExHd++ U#z/R6688_________  $z/R6688TTTT8STTTTT 
I##$ABBB $
 0b7799 |++w,/F/F ''(IJJJ L((G|,C,C ''(GHHH %/// 		4# 3 .GGQQ	 3 ''	222) 4!/HHPP
 4 ''
333  	!%!5!I!I!K!K! 8 ''777    wwwwIvwwwww 	    EIEZ       N 7 $ 5#1  MM
 M 	/...& 		:
 9^44<L#= L$: $: $: # :##$8999222222kmmZ#,,?W2X2XZZ 	ADO 	A@t@@@N: 	76$*666N= 	=<T]<<<NN+++
 =I%%8;tz8I8I4:++C0044tzL>l > >)-> > >   -..
 	,
++++2244::<<>))| <==={{HHlHHHHHHs   80L) )
L65L6c                     t          | t                    r|                     dd          pdS t          | dd          pdS )z8Extract call ID from a tool_call entry (dict or object).r   r  )rZ   r   r   rg   )r   s    rR   _get_tool_call_id_staticz AIAgent._get_tool_call_id_static  sF     b$ 	*66$##)r)r4$$**rT   >   r  r  r  r   r  	developerc                 H  
 g }| D ]V}|                     d          }|t          j        vrt                              d|           A|                    |           W|} t                      }| D ]f}|                     d          dk    rK|                     d          pg D ]3}t                              |          }|r|                    |           4gt                      }| D ]G}|                     d          dk    r,|                     d          }|r|                    |           H||z
  

r6
fd| D             } t                              dt          
                     ||z
  }|rg }	| D ]}|	                    |           |                     d          dk    rQ|                     d          pg D ]9}t                              |          }||v r|	                    dd	|d
           :|	} t                              dt          |                     | S )u	  Fix orphaned tool_call / tool_result pairs before every LLM call.

        Runs unconditionally — not gated on whether the context compressor
        is present — so orphans from session loading or manual message
        manipulation are always caught.
        r   z9Pre-call sanitizer: dropping message with invalid role %rr  r   r  r  c                 t    g | ]4}|                     d           dk    r|                     d          v 2|5S r   r  r  r   )r   r4  orphaned_resultss     rR   r   z2AIAgent._sanitize_api_messages.<locals>.<listcomp>  sO       f//AEE.4I4IM]4]4] 4]4]4]rT   z6Pre-call sanitizer: removed %d orphaned tool result(s)u2   [Result unavailable — see context summary above]r   r   r  z0Pre-call sanitizer: added %d stub tool result(s))
r   r  _VALID_API_ROLESr2  r   r   rW  r  r  r\   )r   filteredr   r   surviving_call_idsr   cidresult_call_idsmissing_resultspatchedr  s             @rR   _sanitize_api_messageszAIAgent._sanitize_api_messages  s     	! 	!C776??D7333O   OOC    "%%% 	4 	4Cwwv+--'',//52 4 4B!::2>>C 4*..s333"uu 	- 	-Cwwv&((ggn-- -#'',,, +-?? 	   #  H LLH$%%   -> 	,.G 
 
s###776??k11!ggl339r  %>>rBB/11#NN(.+_03, ,   
 HLLBO$$   rT   r   c                 D   ddl m}  |            }t          d | D                       }||k    r| S d}g }| D ]H}|j        j        dk    r!||k     r|                    |           |dz  }3|                    |           It                              d||z
  |           |S )aj  Truncate excess delegate_task calls to max_concurrent_children.

        The delegate_tool caps the task list inside a single call, but the
        model can emit multiple separate delegate_task tool_calls in one
        turn.  This truncates the excess, preserving all non-delegate calls.

        Returns the original list if no truncation was needed.
        r   )_get_max_concurrent_childrenc              3   :   K   | ]}|j         j        d k    dV  dS )delegate_taskr   Nr   r   s     rR   r   z3AIAgent._cap_delegate_task_calls.<locals>.<genexpr>  s1      [[2r{7G?7Z7ZQ7Z7Z7Z7Z[[rT   r  r   zUTruncated %d excess delegate_task call(s) to enforce max_concurrent_children=%d limit)tools.delegate_toolr  sumr   rh   r   r2  rl  )r   r  max_childrendelegate_countkept_delegates	truncatedr   s          rR   _cap_delegate_task_callsz AIAgent._cap_delegate_task_calls  s     	EDDDDD3355[[[[[[[\))	 	% 	%B{?22!L00$$R((("a'N  $$$$/\)<	
 	
 	

 rT   c                 L   t                      }g }| D ]n}|j        j        |j        j        f}||vr+|                    |           |                    |           It                              d|j        j                   ot          |          t          |           k     r|n| S )zRemove duplicate (tool_name, arguments) pairs within a single turn.

        Only the first occurrence of each unique pair is kept.
        Returns the original list if no duplicates were found.
        zRemoved duplicate tool call: %s)	rW  r   rh   r   r  r   r2  rl  r\   )r   seenuniquer   r   s        rR   _deduplicate_tool_callszAIAgent._deduplicate_tool_calls.  s     EE 	T 	TB;#R[%:;C$b!!!!@"+BRSSSSVs:66vvJFrT   r   c                     ddl m} |                                }|| j        v r|S |                    dd                              dd          }|| j        v r|S  ||| j        dd          }|r|d         S d	S )
a  Attempt to repair a mismatched tool name before aborting.

        1. Try lowercase
        2. Try normalized (lowercase + hyphens/spaces -> underscores)
        3. Try fuzzy match (difflib, cutoff=0.7)

        Returns the repaired name if found in valid_tool_names, else None.
        r   )get_close_matches-r  rY  r   gffffff?)ncutoffN)difflibr  r  rX  replace)rP   r   r  lowered
normalizedmatchess         rR   _repair_tool_callzAIAgent._repair_tool_call@  s     	.----- //##d+++N __S#..66sC@@
... $#GT-BaPSTTT 	1:trT   c                 X    d| _         | j        r| j                                         dS dS )z
        Invalidate the cached system prompt, forcing a rebuild on the next turn.
        
        Called after context compression events. Also reloads memory from disk
        so the rebuilt prompt captures any writes from this session.
        N)rd  ro  rw  ra   s    rR   _invalidate_system_promptz!AIAgent._invalidate_system_prompt\  s<     &*" 	0--/////	0 	0rT   r   c                    ||n| j         }|sdS g }|D ]}t          |t                    r|                    di           ni }|                    d          }t          |t                    r|                                sn|                    d||                    dd          d|                    ddi d	          d
           |pdS )zIConvert chat-completions tool schemas to Responses function-tool schemas.Nr   rh   r  r  Fr  rN   )r   
propertiesr   rh   r  strictr  )r   rZ   r   r   r[   r   r   )rP   r   source_tools	converteditemr   rh   s          rR   _responses_toolszAIAgent._responses_toolsg  s     % 1uutz 	4*,	  	 	D-7d-C-CK*b)))B66&>>DdC(( 

 "!vvmR88 ff\HTV3W3WXX       D rT   r   r   r   indexc                     ddl }|  d| d| } |j        |                    dd                                                    dd         }d| S )	u  Generate a deterministic call_id from tool call content.

        Used as a fallback when the API doesn't provide a call_id.
        Deterministic IDs prevent cache invalidation — random UUIDs would
        make every API call's prefix unique, breaking OpenAI's prompt cache.
        r   N:r8  r  r   r  call_)hashlibsha256r   	hexdigest)r   r   r  r  seeddigests         rR   _deterministic_call_idzAIAgent._deterministic_call_id|  so     	//I////GI F FGGQQSSTWUWTWXvrT   raw_idc                 4   t          | t                    sdS |                                 }|sdS d|v rI|                    dd          \  }}|                                pd}|                                pd}||fS |                    d          rd|fS |dfS )z8Split a stored tool id into (call_id, response_item_id).NN|r   Nfc_)rZ   r[   r   r  r  )r   r   call_idresponse_item_ids       rR   _split_responses_tool_idz AIAgent._split_responses_tool_id  s     &#&& 	: 	:%<<(-C(;(;%G%mmoo-G/5577?4,,,E"" 	;d{rT   r  r  c                 r   t          |t                    r+|                                }|                    d          r|S |pd                                }|                    d          r|S |                    d          r:t	          |          t	          d          k    rd|t	          d          d          S t          j        dd|          }|                    d          r|S |                    d          r:t	          |          t	          d          k    rd|t	          d          d          S |rd|dd          S |p(t          |pd          pt          j                    j	        }t          j        |                    d                                                    dd         }d| S )	zCBuild a valid Responses `function_call.id` (must start with `fc_`).r  r  r  Nz[^A-Za-z0-9_-]0   r8     )rZ   r[   r   r  r\   r@  r   r]  r^  r_  r  sha1r   r  )rP   r  r  	candidater  r   r  r  s           rR   "_derive_responses_function_call_idz*AIAgent._derive_responses_function_call_id  s    &,, 	!(..00I##E** !  -R&&((U## 	MW%% 	1#f++G*D*D0G.000F,b&99	&& 	(( 	4S^^c'll-J-J33w<<==1333 	*)3B3)))H-344H
8Hdkk'2233==??DV~~rT   c                 \
   g }t                      }|D ]}t          |t                    s|                    d          }|dk    r5|dv r|                    dd          }|t	          |          nd}|dk    r|                    d          }d	}	t          |t
                    r|D ]}
t          |
t                    r}|
                    d
          rh|
                    d          }|r||v rHd |
                                D             }|                    |           |r|                    |           d}	|	                                r|                    d|d           n|	r|                    ddd           |                    d          }t          |t
                    r\|D ]X}t          |t                    s|                    di           }|                    d          }t          |t                    r|	                                sn| 
                    |                    d                    \  }}|                    d          }t          |t                    r|	                                s|}t          |t                    r|	                                st          |t                    rP|                    d          r;t          |          t          d          k    rd|t          d          d          }nGt	          |                    dd                    }|                     ||t          |                    }|	                                }|                    dd          }t          |t                    rt          j        |d	          }n$t          |t                    st	          |          }|	                                pd}|                    d|||d           Z|                    ||d           |dk    r|                    d          }| 
                    |          \  }}t          |t                    r|	                                s=t          |t                    r(|	                                r|	                                }t          |t                    r|	                                s|                    d|t	          |                    dd          pd          d           |S )z>Convert internal chat-style messages to Responses input items.r   r  >   r  r  r   r  Nr  r  Fencrypted_contentr   c                 &    i | ]\  }}|d k    ||S )r   ro   r(  s      rR   r+  z=AIAgent._chat_messages_to_responses_input.<locals>.<dictcomp>  s$    .X.X.X1aSWiiq!iiirT   Tr   r   r   r   rh   r  r  r  r   r  r  function_callr   r  rh   r   r  r  function_call_outputr   r  output)rW  rZ   r   r   r[   r   r   r   r  r   r  r  r\   r  r   r  )rP   r   r   seen_item_idsr   r   r   content_textcodex_reasoninghas_codex_reasoningriitem_idreplay_itemr   r   r   r   embedded_call_idembedded_response_item_idr  	_raw_argsr   raw_tool_call_idr  s                           rR   !_chat_messages_to_responses_inputz)AIAgent._chat_messages_to_responses_input  sE   &( UU d	 d	Cc4(( 776??Dx,,,'')R00/6/Bs7|||;&& '*gg.E&F&FO*/'!/488 ;"1 ; ;B)"d33 ;?R8S8S ;*,&&,,#* !-w-/G/G$,
 /Y.X

.X.X.X %[ 9 9 9#* !?$1$5$5g$>$>$>6: 3#))++ Kkl%S%STTTT, K kb%I%IJJJ!$!6!6J!*d33 '", & &B#-b$#7#7 ) (!#
B!7!7B&(ffVnnG#-gs#;#; )7==?? ) (JNJgJg "tK KG,.G ')ffY&7&7G#-gs#;#; ;7==?? ;*:#-gs#;#; 	j7==?? 	j$./H#$N$N!j(A(L(LU(S(S!j ),,E(F(FU(S(S.^6OPSTYPZPZP[P[6\.^.^GG03BFF;4M4M0N0NI.2.I.I'S\^abg^h^h.i.iG&-mmooG(*{D(A(AI))T:: ;,0Jyu,U,U,U		%/	3%?%? ;,/	NN	(1(9(9(ATI!LL(7+2(/-6	* *     d|DDEEEv~~#&77>#:#: !::;KLL
!'3// ;w}} ;!"2C88 ;=M=S=S=U=U ;"2"8"8":":!'3// w}} 2&!#'')R"8"8">B??     rT   	raw_itemsc           
         t          |t                    st          d          g }t                      }t	          |          D ]\  }}t          |t
                    st          d| d          |                    d          }|dk    r^|                    d          }|                    d          }t          |t                    r|                                st          d| d          t          |t                    r|                                st          d| d	          |                    d
d          }	t          |	t
                    rt          j
        |	d          }	n$t          |	t                    st          |	          }	|	                                pd}	|                    d|                                |                                |	d           |dk    r|                    d          }t          |t                    r|                                st          d| d          |                    dd          }
|
d}
t          |
t                    st          |
          }
|                    d|                                |
d           j|dk    r|                    d          }t          |t                    r|r|                    d          }t          |t                    r|r||v r|                    |           d|d}|                    d          }t          |t                    r||d<   ng |d<   |                    |           4|                    d          }|dv rX|                    dd          }|d}t          |t                    st          |          }|                    ||d           t          d| d|d|d          |S ) Nz4Codex Responses input must be a list of input items.zCodex Responses input[] must be an object.r   r  r  rh   z#] function_call is missing call_id.z ] function_call is missing name.r   r  Fr  r  r  z*] function_call_output is missing call_id.r  r  r  r  r  r   r   r  r  r   >   r  r  r   r  z#] has unsupported item shape (type=z, role=).)rZ   r   rY   rW  r  r   r   r[   r   r   r  r   r  )rP   r#  r  seen_idsr  r  	item_typer  rh   r   r  	encryptedr  reasoning_itemr  r   r   s                    rR   _preflight_codex_input_itemsz$AIAgent._preflight_codex_input_items$  s>   )T** 	USTTT+-
"9-- S	 S	ICdD)) U !S#!S!S!STTT((IO++((9--xx''!'3// hw}} h$%fc%f%f%fggg!$,, eDJJLL e$%cc%c%c%cddd HH[$77	i.. / $
95 I I III#Is33 / #II%OO--5	!! /#*==?? $

%.	    222((9--!'3// ow}} o$%mc%m%m%mnnn(B//>F!&#.. ) [[F!! 6#*==??"(    K'' HH%899	i-- 6) 6"hhtnnG!'3// .G ."h..$ W---.9PY%Z%ZN
 #hhy11G!'400 74;y1146y1%%n55588F##D,,,((9b11? G!'3// +!'llG!!4G"D"DEEEoooQZooeiooo   rT   allow_streamr.  c          	      |   t          t                    st          d          h d}fd|D             }|r3t          dd                    t	          |                     d                              d          }t          |t                    r|                                st          d          |                                }                    d	          }|d
}t          |t                    st          |          }|                                pt          }| 	                                        d                    }                    d          }d }	|t          |t                    st          d          g }	t          |          D ]\  }
}t          |t                    st          d|
 d          |                    d          dk    r)t          d|
 d|                    d          d          |                    d          }|                    d          }t          |t                    r|                                st          d|
 d          t          |t                    st          d|
 d          |                    dd
          }|d
}t          |t                    st          |          }|                    dd          }t          |t                    st          |          }|	                    d|                                |||d                               dd          }|durt          d          h d|||dd}|	|	|d<                       d          }t          |t                    r||d<                       d           }t          |t                    r||d <                       d!          }t          |t                    r+|                                r|                                |d!<                       d"          }t          |t          t          f          r|d#k    rt          |          |d"<                       d$          }t          |t          t          f          rt          |          |d$<   d%D ]}                    |          }||||<                       d&          }|t          |t                    st          d'          i }|                                D ]d\  }}t          |t                    r|                                st          d(          |@t          |          ||                                <   e|r||d&<   |rI                    d)          }||d*urt          d+          |d*u rd*|d)<                       d)           nd)v rt          d,          t	          fd-D                       }|r&t          d.d                    |           d          |S )/Nz'Codex Responses request must be a dict.>   inputr+  instructionsc                     g | ]}|v|	S ro   ro   )r   r   r$  s     rR   r   z7AIAgent._preflight_codex_api_kwargs.<locals>.<listcomp>  s#    DDD3c.C.C3.C.C.CrT   z3Codex Responses request missing required field(s): r  .r+  z;Codex Responses request 'model' must be a non-empty string.r1  r  r0  r   z=Codex Responses request 'tools' must be a list when provided.zCodex Responses tools[r%  r   r   z] has unsupported type rh   r  z] is missing a valid name.z] is missing valid parameters.r  r  Fr  storez6Codex Responses contract requires 'store' to be false.>   r0  r+  r4  r   includer  temperaturetool_choicer1  rJ  extra_headersprompt_cache_keymax_output_tokensparallel_tool_calls)r+  r1  r0  r4  r  r5  rJ  r:  r   r6  )r7  r;  r9  r8  z:Codex Responses request 'extra_headers' must be an object.zGCodex Responses request 'extra_headers' keys must be non-empty strings.rw   Tz/Codex Responses 'stream' must be true when set.zKCodex Responses stream flag is only allowed in fallback streaming requests.c              3   $   K   | ]
}|v|V  d S r_   ro   )r   r   allowed_keyss     rR   r   z6AIAgent._preflight_codex_api_kwargs.<locals>.<genexpr>  s-      QQCL9P9PC9P9P9P9PQQrT   z2Codex Responses request has unsupported field(s): )rZ   r   rY   rV  rY  r   r[   r   r"   r,  r   r  r   r   r   r  r   r  ) rP   r$  r.  r  missingr+  r1  normalized_inputr   normalized_toolsr  r  rh   r  r  r  r4  r  r  r5  rJ  r:  r6  passthrough_keyvalr8  normalized_headersr   r   rw   
unexpectedr=  s     `                             @rR   _preflight_codex_api_kwargsz#AIAgent._preflight_codex_api_kwargs  s    *d++ 	HFGGG555DDDD(DDD 	rpSWS\S\]cdk]l]lSmSmpppqqqw''%%% 	\U[[]] 	\Z[[[!~~n55L,,, 	-|,,L#))++E/E<<Z^^G=T=TUUw''eT** b !`aaa!&u--  	T!$-- Y$%Wc%W%W%WXXX88F##z11$%oc%o%oZ^ZbZbciZjZj%o%o%opppxx''!XXl33
!$,, _DJJLL _$%]c%]%]%]^^^!*d33 c$%ac%a%a%abbb"hh}b99&"$K!+s33 3"%k"2"2K(E22!&$// *!&\\F '' * $

'2"(&0     w..UVVV
 
 
 (%	&
 &

 '"2Jw NN;//	i&& 	0&/J{#..++gt$$ 	,$+Jy!!~~n55lC(( 	>\-?-?-A-A 	>)5););)=)=J~& 'NN+>??'#u66 	E;Lq;P;P.12C.D.DJ*+ nn]33kC<00 	;(-k(:(:J}%  Z 	2 	2O..11C.1
?+"77$mT22 _ !]^^^13+1133 = =
U!#s++ p399;; p$%nooo=25e**"399;;//! A.@
?+ 	l^^H--F!fD&8&8 !RSSS~~'+
8$X&&&&##jkkkQQQQ:QQQQQ
 	]TYYzEZEZ]]]   rT   r  c                 T   t          |dd          }t          |t                    sdS g }|D ]U}t          |dd          }|dvrt          |dd          }t          |t                    r|r|                    |           Vd                    |                                          S )z<Extract assistant text from a Responses message output item.r   Nr  r   >   r   output_textr   rg   rZ   r   r[   r   rV  r   )rP   r  r   chunksr   ptyper   s          rR   _extract_responses_message_textz'AIAgent._extract_responses_message_text  s    $	400'4(( 	2 	$ 	$DD&$//E3334..D$$$ $ $d###wwv$$&&&rT   c                    t          |dd          }t          |t                    rmg }|D ]?}t          |dd          }t          |t                    r|r|                    |           @|r'd                    |                                          S t          |dd          }t          |t                    r|r|                                S dS )zAExtract a compact reasoning text from a Responses reasoning item.r  Nr   r  r  rH  )rP   r  r  rI  r   r   s         rR   !_extract_responses_reasoning_textz)AIAgent._extract_responses_reasoning_text   s    $	400gt$$ 	1 "F ( (tVT22dC(( (T (MM$''' 1yy((..000tVT**dC   	 T 	 ::<<rrT   c                 b   t          |dd          }t          |t                    r|st          |dd          }t          |t                    r|                                rxt
                              dt          |                                                     t          dddt          d|                                          g	          g}||_	        nt          d
          t          |dd          }t          |t                    r'|                                                                }nd}|dv rqt          |dd          }t          |t                    r%|                    d          pt          |          }n|rt          |          nd| d}t          |          g }g }g }	g }
|dv }d}d}|D ]}t          |dd          }t          |dd          }t          |t                    r'|                                                                }nd}|dv rd}|dk    rt          |dd          }t          |t                    r3|                                                                }|dv rd}n|dv rd}|                     |          }|r|                    |           |dk    r|                     |          }|r|                    |           t          |dd          }t          |t                    r|rd|d}t          |dd          }t          |t                    r|r||d<   t          |dd          }t          |t                    rJg }|D ]@}t          |dd          }t          |t                    r|                    d|d           A||d<   |	                    |           	|dk    r|dv rt          |dd           pd }t          |d!d"          }t          |t                    st#          j        |d#          }t          |d$d          }t          |dd          }|                     |          \  } }!t          |t                    r|                                r|n| }"t          |"t                    r|"                                s$|                     ||t          |
                    }"|"                                }"t          |t                    r|nd}#|                     |"|#          }#|
                    t          |"|"|#d%t          ||&          '                     |d(k    r|t          |dd           pd }t          |d)d"          }t          |t                    st#          j        |d#          }t          |d$d          }t          |dd          }|                     |          \  } }!t          |t                    r|                                r|n| }"t          |"t                    r|"                                s$|                     ||t          |
                    }"|"                                }"t          |t                    r|nd}#|                     |"|#          }#|
                    t          |"|"|#d%t          ||&          '                     d*                    d+ |D                                                       }$|$sJt/          |d          r:t          |dd           }t          |t                    r|                                }$t          |$|
|r'd,                    |                                          nddd|	pd-          }%|
rd.}&n|s|r|sd/}&n	|	r|$sd/}&nd0}&|%|&fS )1zENormalize a Responses API object to an assistant_message-like object.r  NrG  z`Codex response has empty output but output_text is present (%d chars); synthesizing output item.r  r  r  r   r   r   r   statusr   z&Responses API returned no output itemsrQ  >   failed	cancelledr  zResponses API returned status 'rT  >   queued
incompletein_progressFr   Tphase>   analysis
commentary>   finalfinal_answerr  r  r&  r   r  r   summary_textr  rh   r  r   r  r  r  r   r  r   r  r  r   r   custom_tool_callr0  r  c                     g | ]}||S ro   ro   r  s     rR   r   z5AIAgent._normalize_codex_response.<locals>.<listcomp>  s    >>>aA>>>>rT   r  )r   r   r  r  r  r  r   rU  rR  )rg   rZ   r   r[   r   r2  r   r\   r   r  rP  r  r   r   rK  r   rM  r   r  r  r  r  rV  rL  )'rP   r  r  out_textr3  	error_objr  content_partsr  reasoning_items_rawr   has_incomplete_itemssaw_commentary_phasesaw_final_answer_phaser  r)  item_status
item_phasenormalized_phasemessage_textreasoning_textr*  raw_itemr  r  raw_summaryr   r   r   r   raw_call_idraw_item_idr  r  r  r  
final_textrV  rP  s'                                          rR   _normalize_codex_responsez!AIAgent._normalize_codex_response0  s{   8T22&$'' 	Mv 	M x==H(C(( MX^^-=-= M014X^^5E5E1F1F   *"[,-hnnFVFVWWWX    #)"#KLLL!(Hd;;os++ 	#-3355;;==OO"O555'488I)T** r%MM)44FI		.7qC	NNN=q_n=q=q=q	y)))#%%'46 "
.2YY$!& X	 X	Dfd33I!$$77K+s++ #)//117799"EEE'+$I%%$T7D99
j#.. 6'1'7'7'9'9'?'?'A'A$'+EEE/3,,)-FFF15.#CCDII 7!((666k))!%!G!G!M!M! ;#**>::: $D*=tDD	i-- 9) 9(3)TTH%dD$77G!'3// 1G 1)0%dIt<<G!'400 :&($+ [ [D#*4#>#>D)$44 [ + 2 2NTX3Y3Y Z Z Z.9+'..x888o--"III!$339r#D+t<<	!)S11 J $
95 I I II%dIt<<%dD$77&*&C&CK&P&P# !)3K)E)Es+J[J[J]J]s++cs!'3// _w}} _"99'9cR\oo^^G!--//2<[#2N2N#X;;TX #'#J#J7Td#e#e !!/#%5#,'YOOO# # #     000!$339r#D'488	!)S11 J $
95 I I II%dIt<<%dD$77&*&C&CK&P&P# !)3K)E)Es+J[J[J]J]s++cs!'3// _w}} _"99'9cR\oo^^G!--//2<[#2N2N#X;;TX #'#J#J7Td#e#e !!/#%5#,'YOOO# # #    YY>>=>>>??EEGG
 	.gh>> 	.x;;H(C(( .%^^--
+!>MWfkk/2288:::SW"""5"=
 
 
  	#(MM! 	#&: 	#CY 	#(MM  		# 		# )MM"M -//rT   c                 J    t          j                    }|j         d|j         S )Nr  )r~   current_threadrh   ident)rP   threads     rR   _thread_identityzAIAgent._thread_identity  s(    )+++.....rT   c                     t          | dd          }t          | dd          }t          | dd          }d|                                  d| d| d| S )	Nr%  r  r  r+  zthread=
 provider=z
 base_url=z model=)rg   rv  )rP   r%  r  r+  s       rR   _client_log_contextzAIAgent._client_log_context  s}    4Y774Y77gy111d++-- 1 1 1 1 1 1).1 1	
rT   c                 `    t          | dd           }|t          j                    }|| _        |S )Nr!  )rg   r~   r   r!  )rP   locks     rR   _openai_client_lockzAIAgent._openai_client_lock  s2    t^T22<?$$D $DrT   rE  c                    ddl m} t          | |          rdS t          | dd          }|-t	          |          r |            rdS nt          |          rdS t          | dd          }|t          t          |dd                    S dS )a  Check if an OpenAI client is closed.

        Handles both property and method forms of is_closed:
        - httpx.Client.is_closed is a bool property
        - openai.OpenAI.is_closed is a method returning bool

        Prior bug: getattr(client, "is_closed", False) returned the bound method,
        which is always truthy, causing unnecessary client recreation on every call.
        r   MockF	is_closedNT_client)unittest.mockr  rZ   rg   callabler   )rE  r  is_closed_attrhttp_clients       rR   _is_openai_client_closedz AIAgent._is_openai_client_closed  s     	'&&&&&fd## 	5 d;;%'' !>##  4 n%% tfi66"[%@@AAAurT   r   r  c                @   ddl m}m} t          |          } |              ||                    d                     | j        dk    s6t          |                    dd                                        d          r?ddlm	}  |di |}t                              d|||                                            |S | j        d	k    s6t          |                    dd                                        d
          r]ddlm} d |                                D             }	 |di |	}t                              d|||                                            |S d|vr 	 dd l}
dd l}|j        |j        dfg}t)          |d          rg|                    |j        |j        df           |                    |j        |j        df           |                    |j        |j        df           n2t)          |d          r"|                    |j        |j        df           |
                    |
                    |                    |d<   n# t:          $ r Y nw xY wt=          di |}t                              d|||                                            |S )Nr   )_validate_base_url_validate_proxy_env_urlsr  ri  r  rj  )CopilotACPClientz-Copilot ACP client created (%s, shared=%s) %szgoogle-gemini-clizcloudcode-pa://)GeminiCloudCodeClientc                 "    i | ]\  }}|d v 	||S )>   r$  r&  r  
project_idr  ro   r(  s      rR   r+  z1AIAgent._create_openai_client.<locals>.<dictcomp>"  s4       A[[[ 1[[[rT   z:Gemini Cloud Code Assist client created (%s, shared=%s) %sr  r   TCP_KEEPIDLE   r  r  TCP_KEEPALIVE)socket_options)	transportz(OpenAI client created (%s, shared=%s) %sro   )rK  r  r  r   r   r%  r[   r  agent.copilot_acp_clientr  r2  r3  ry  agent.gemini_cloudcode_adapterr  r   httpxsocket
SOL_SOCKETSO_KEEPALIVErL  r   IPPROTO_TCPr  TCP_KEEPINTVLTCP_KEEPCNTr  ClientHTTPTransportr   r   )rP   r   r  r  r  r  r  rE  r  safe_kwargs_httpx_socket
_sock_optss                rR   rQ  zAIAgent._create_openai_client  s?   WWWWWWWW ]++  """=,,Z88999=M))S1B1B:r1R1R-S-S-^-^_n-o-o)AAAAAA%%6666FKK?((**	   M=///3}7H7HUW7X7X3Y3Y3d3dev3w3w/LLLLLL !.!4!4!6!6  K +*99[99FKKL((**	   M$ --&&&&((((&173GKL
7N33 X%%w':G<PRT&UVVV%%w':G<QSU&VWWW%%w':G<OQR&STTTTWo66 X%%w':G<QSU&VWWW/5}}$22*2MM 0= 0 0m,,    ((-((6$$&&		
 	
 	
 s   $C.I 
I I c                    ddl }d}	 t          | dd          }|dS t          |dd          }|dS t          |dd          }|dS t          |dd          pt          |dd          pg }t          |          D ]}t          |dd          pt          |dd          }|'t          |d	d          }	|	$t          |d
d          }	|	t          |	d	d          }	|	a	 |	                    |j                   n# t
          $ r Y nw xY w	 |	                                 n# t
          $ r Y nw xY w|dz  }n2# t          $ r%}
t          	                    d|
           Y d}
~
nd}
~
ww xY w|S )a  Force-close underlying TCP sockets to prevent CLOSE-WAIT accumulation.

        When a provider drops a connection mid-stream, httpx's ``client.close()``
        performs a graceful shutdown which leaves sockets in CLOSE-WAIT until the
        OS times them out (often minutes).  This method walks the httpx transport
        pool and issues ``socket.shutdown(SHUT_RDWR)`` + ``socket.close()`` to
        force an immediate TCP RST, freeing the file descriptors.

        Returns the number of sockets force-closed.
        r   Nr  
_transport_pool_connections_network_stream_stream_sockrw   r   z'Force-close TCP sockets sweep error: %s)
r  rg   r   shutdown	SHUT_RDWRrX   r  r   r2  r   )rE  r  closedr  r  poolconnectionsconnrw   sockr  s              rR   _force_close_tcp_socketsz AIAgent._force_close_tcp_socketsZ  s    	!   )	I!&)T::K"q\4@@I q9gt44D|q nd33 4$// 
 [))  D"3T:: 6tY55  >vw55<"68T::D'&tWd;;<MM'"34444   DJJLLLL   D!-.  	I 	I 	ILLBCHHHHHHHH	Isp   D4 D4 D4 BD4 C76D4 7
DD4 DD4 DD4 
D*'D4 )D**	D4 4
E#>EE#c                R   |d S |                      |          }	 |                                 t                              d||||                                            d S # t
          $ r;}t                              d|||                                 |           Y d }~d S d }~ww xY w)Nz<OpenAI client closed (%s, shared=%s, tcp_force_closed=%d) %sz6OpenAI client close failed (%s, shared=%s) %s error=%s)r  r  r2  r3  ry  r   r   )rP   rE  r  r  force_closedr  s         rR   r  zAIAgent._close_openai_client  s    >F 44V<<	LLNNNKKN((**      	 	 	LLH((**        	s   AA! !
B&+0B!!B&c                   |                                  5  t          | dd           }	 |                     | j        |d          }nR# t          $ rE}t
                              d||                                 |           Y d }~d d d            dS d }~ww xY w|| _        d d d            n# 1 swxY w Y   | 	                    |d| d           dS )NrE  Tr  z7Failed to rebuild shared OpenAI client (%s) %s error=%sFzreplace:)
r|  rg   rQ  rF  r   r2  rl  ry  rE  r  )rP   r  
old_client
new_clientr  s        rR   _replace_primary_openai_clientz&AIAgent._replace_primary_openai_client  sU   %%'' 	% 	% x66J	!778KTZcg7hh

   M,,..	   uuu	% 	% 	% 	% 	% 	% 	% 	% %DK	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	!!*5H5H5HQU!VVVts:   B+AB+
B/B?B+B
B++B/2B/c                   |                                  5  t          | dd           }|#|                     |          s|cd d d            S d d d            n# 1 swxY w Y   t                              d||                                            |                     d|           st          d          |                                  5  | j        cd d d            S # 1 swxY w Y   d S )NrE  zCDetected closed shared OpenAI client; recreating before use (%s) %szrecreate_closed:r  z'Failed to recreate closed OpenAI client)	r|  rg   r  r2  rl  ry  r  rP  rE  )rP   r  rE  s      rR   _ensure_primary_openai_clientz%AIAgent._ensure_primary_openai_client  s   %%'' 	 	T8T22F!$*G*G*O*O!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 	Q$$&&	
 	
 	

 22:UV:U:U2VV 	JHIII%%'' 	 	;	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s#   *AAAC!!C%(C%c                 ,   t          | dd          }|dS 	 t          |dd          }|dS t          |dd          }|dS t          |dd          }|dS t          |dd          pt          |dd          pg }d}t          |          D ]}t          |d	d          pt          |d
d          }|(t          |dd          }	|	$t          |dd          }	|	t          |	dd          }	|	bddl}
	 |	                    d           |	                    d|
j        |
j        z            }|dk    r|dz  }n # t          $ r Y nt          $ r |dz  }Y nw xY w	 |	                    d           # t          $ r Y w xY w# 	 |	                    d           w # t          $ r Y w w xY wxY w|dk    r3t          
                    d|           |                     d           dS n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wdS )aY  Detect and clean up dead TCP connections on the primary client.

        Inspects the httpx connection pool for sockets in unhealthy states
        (CLOSE-WAIT, errors).  If any are found, force-closes all sockets
        and rebuilds the primary client from scratch.

        Returns True if dead connections were found and cleaned up.
        rE  NFr  r  r  r  r   r  r  r  rw   r   rT   Tu@   Found %d dead connection(s) in client pool — rebuilding clientdead_connection_cleanupr  zDead connection check error: %s)rg   r   r  setblockingrecvMSG_PEEKMSG_DONTWAITBlockingIOErrorrX   r2  rl  r  r   r   )rP   rE  r  r  r  r  
dead_countr  rw   r  r  r]   r  s                rR   _cleanup_dead_connectionsz!AIAgent._cleanup_dead_connections  s    x..>57	A!&)T::K"u\4@@I u9gt44D|und33 4$// 
 J[))   D"3T:: 6tY55  >vw55<"68T::D'&tWd;;<(((($$U+++99Q(87;O(OPPDs{{"a
&   D $ $ $!OJJJ$((...."   ((...."   A~~V   33;T3UUUt   	A 	A 	ALL:C@@@@@@@@	Aus   G" G" G" BG" 2AD65E=6
E E=EE=EE=E-,G" -
E:7G" 9E::G" =F%?FF%
F"	F%!F"	"F%%:G" "
H,HHc                   ddl m} |                     |          }t          ||          r|S |                                 5  t          | j                  }d d d            n# 1 swxY w Y   |                     ||d          S )Nr   r~  r  Fr  )r  r  r  rZ   r|  r   rF  rQ  )rP   r  r  primary_clientrequest_kwargss        rR   _create_request_openai_clientz%AIAgent._create_request_openai_client  s    &&&&&&;;6;JJnd++ 	"!!%%'' 	7 	7!$"566N	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7)).PU)VVVs   A$$A(+A(c                6    |                      ||d           d S )NFr  )r  )rP   rE  r  s      rR   _close_request_openai_clientz$AIAgent._close_request_openai_client  s#    !!&!FFFFFrT   on_first_deltac                    ddl }|p|                     d          }d}d}d}g | _        t          |dz             D ]8}	g }
	  |j        j        d'i |5 }|D ]}|                     d           | j        r nzt          |dd	          }d
|v s|dk    rit          |dd	          }|r| j        	                    |           |r9|s7|s d}|r	  |             n# t          $ r Y nw xY w|                     |           d|v rd}d|v r-d|v r)t          |dd	          }|r|                     |           |dk    r*t          |dd          }||
	                    |           |dv rt          |dd          }|rt          |dd          nd}|rt          |dd          nd}t                              d|||t          d | j        D                       |                                            |                                }t          |dd          }t%          |t&                    r|s|
r=t'          |
          |_        t                              dt-          |
                     n| j        r|s~d	                    | j                  }t1          dddt1          d|          g          g|_        t                              d t-          | j                  t-          |                     |cddd           c S # 1 swxY w Y   # |j        |j        |j        t8          f$ r}|	|k     r<t                              d!|	dz   |dz   |                                 |           Y d}~5t                              d"|                                 |           |                     ||#          cY d}~c S d}~wt<          $ r}t?          |          }d$|v }|rA|	|k     r;t                              d%|	dz   |dz   |                                            Y d}~|rKt                              d&|                                            |                     ||#          cY d}~c S  d}~ww xY wdS )(zJExecute one streaming Responses API request and return the final response.r   Ncodex_stream_directr  r   Freceiving stream responser   r  zoutput_text.deltaresponse.output_text.deltadeltaTr  r  response.output_item.doner  )response.incompleteresponse.failedr  rQ  incomplete_detailszkCodex Responses stream received terminal event %s (status=%s, incomplete_details=%s, streamed_chars=%d). %sc              3   4   K   | ]}t          |          V  d S r_   r  r  s     rR   r   z,AIAgent._run_codex_stream.<locals>.<genexpr>]  s(      #T#TqCFF#T#T#T#T#T#TrT   r  z;Codex stream: backfilled %d output items from stream eventsr  r  r  rG  rO  rP  z?Codex stream: synthesized output from %d text deltas (%d chars)zNCodex Responses stream transport failed (attempt %s/%s); retrying. %s error=%szYCodex Responses stream transport failed; falling back to create(stream=True). %s error=%s)rE  response.completedzGResponses stream closed before completion (attempt %s/%s); retrying. %szYResponses stream did not emit response.completed; falling back to create(stream=True). %sro   ) r  r  _codex_streamed_text_partsr  	responsesrw   r]  r  rg   r   r   _fire_stream_delta_fire_reasoning_deltar2  rl  r  ry  get_final_responserZ   r   r  r   r\   rV  r   RemoteProtocolErrorReadTimeoutConnectErrorConnectionError!_run_codex_create_stream_fallbackrP  r[   )rP   r$  rE  r  r  active_clientmax_stream_retrieshas_tool_callsfirst_delta_firedattemptcollected_output_itemsrw   event
event_type
delta_textrk  	done_itemresp_objrQ  r  final_response_out	assembledr  err_textmissing_completeds                             rR   _run_codex_streamzAIAgent._run_codex_stream!  s3   b$"D"DLa"D"b"b! 13'/!344 m	 m	G+-"k3],3AAjAA H*V!' . .,,-HIII4 "!E%,UFB%?%?
.*<<
Nj@j@j)0)D)DJ) S $ ? F Fz R R R) D. D'8 !18<$5'5 %1)1,:N,<,<,<,</8 )1 )1 )1,0D)1 $ 7 7
 C C C,
::-1NN(J667j;P;P-4UGR-H-HN- K $ : :> J J J
 (+FFF(/vt(D(DI(4 6 = =i H H H'+UUU'.uj$'G'GHJR%\WXx%F%F%FX\Fbj1tCWY]1^1^1^pt."NN!\ *F4F ##T#TD4S#T#T#T T T $ 8 8 : :   &,%>%>%@%@N #>8TBBD!$-- d 1 489O4P4PN1"LL ] #$: ; ;    "< ^ (*0O(P(PI5D%.%0'2)8mR[)\)\)\(]	6 6 6 5N1 #LL a #D$C D Dc)nn   *QH* H* H* H* H* H* H* H* H* H* H* H* H* H* H* H* H* H* H*R .0BFDWYhi ` ` `///LLh!*Q.0022   HHHHo,,..  
 ==jQ^=__________   s88$8H$D!$ 3E)E)ELLa!*Q.0022	   HHHH$ dLLs0022    AA*UbAcccccccccc#ym	 m	s   LA7L
CL
C$	!L#C$	$HL6LL			LL		LQ3/<N=1AN=5Q3=Q3
AQ. AQ.%Q3-Q..Q3c           
         |p|                      d          }t          |          }d|d<   |                     |d          } |j        j        di |}t          |d          r|S t          |d          s|S d}g }g }	 |D ]l}	|                     d	           t          |	d
d          }
|
s*t          |	t                    r|		                    d
          }
|
dk    rUt          |	dd          }|*t          |	t                    r|		                    d          }||
                    |           nY|
dv rUt          |	dd          }|s+t          |	t                    r|		                    dd          }|r|
                    |           |
dvrt          |	dd          }|*t          |	t                    r|		                    d          }|t          |dd          }t          |t                    r|s|r=t          |          |_        t                              dt          |                     nv|rtd                    |          }t#          dddt#          d|          g          g|_        t                              dt          |          t          |                     |c t          |dd          }t%          |          r	  |             S # t&          $ r Y S w xY wS n	 t          |dd          }t%          |          r	  |             nR# t&          $ r Y nFw xY wnA# t          |dd          }t%          |          r	  |             w # t&          $ r Y w w xY ww xY w||S t)          d          )zQFallback path for stream completion edge cases on Codex-style Responses backends.codex_create_stream_fallbackr  Trw   r-  r  __iter__Nr  r   r  r  )r  r  r  >   r  r  r  r  z1Codex fallback stream: backfilled %d output itemsr  r  r  rG  rO  rP  z<Codex fallback stream: synthesized from %d deltas (%d chars)r  zHResponses create(stream=True) fallback did not emit a terminal response.ro   )r  r   rE  r  createrL  r]  rg   rZ   r   r   r   r  r2  r   r\   rV  r   r  r   rP  )rP   r$  rE  r  fallback_kwargsstream_or_responseterminal_responser  collected_text_deltasr  r  r  r  r  r  close_fns                   rR   r  z)AIAgent._run_codex_create_stream_fallback  s`   k$"D"DLj"D"k"kz**$(!::?Y]:^^;]4;NNoNN %x00 	&%%):66 	&%% ')&(7	+ /- /-$$%@AAA$UFD99
! 3j&=&= 3!&6!2!2J !<<< 'vt < <I (Zt-D-D($)IIf$5$5	 ,.55i@@@#BBB#E7B77E  7Zt%<%< 7 %		'2 6 6 <-44U;;;%eee$+E:t$D$D!$,E41H1H,(-		*(=(=%$0"#4hEED!$-- d 1 7;<R7S7S-4"LL S #$: ; ;    3 
(*0E(F(FI8G%.['2)8mR[)\)\)\(]9 9 9 8-4
 #LL ^ #$9 : :C	NN   -,,17DAAH!! HJJJJ    D1 15/-b 17DAAH!! HJJJJ    D 17DAAH!! HJJJJ    D ($$efffs[   H1L/ 
K
K+*K+/L/ 
L 
L+*L+/!M-
MM-
M)&M-(M))M-c                   | j         dk    s| j        dk    rdS 	 ddlm}  ||          }n3# t          $ r&}t
                              d|           Y d }~dS d }~ww xY w|                    d          }|                    d	          }t          |t                    r|
                                sdS t          |t                    r|
                                sdS |
                                | _        |
                                                    d
          | _        | j        | j        d<   | j        | j        d	<   |                     d          sdS dS )NrZ  r^  Fr   )!resolve_codex_runtime_credentials)force_refreshz#Codex credential refresh failed: %sr$  r  rc  codex_credential_refreshr  T)r&  r%  rN  r  r   r2  r   r   rZ   r[   r   r$  r  r  rF  r  )rP   r  r  credsr  r$  r  s          rR   %_try_refresh_codex_client_credentialsz-AIAgent._try_refresh_codex_client_credentials  sp   =---.1P1P5	IIIIII55EJJJEE 	 	 	LL>DDD55555	 ))I&&99Z(('3'' 	w}} 	5(C(( 	0@0@ 	5}} ((//44)-I&*.-J'22:T2UU 	5ts   - 
AAAc                   | j         dk    s| j        dk    rdS 	 ddlm}  |t	          dt          t          j        dd                              t          t          j        d	d
                    |          }n3# t          $ r&}t                              d|           Y d }~dS d }~ww xY w|                    d          }|                    d          }t          |t                    r|                                sdS t          |t                    r|                                sdS |                                | _        |                                                    d          | _        | j        | j        d<   | j        | j        d<   | j                            dd            |                     d          sdS dS )Nr\  nousFr   ) resolve_nous_runtime_credentialsr  HERMES_NOUS_MIN_KEY_TTL_SECONDS1800HERMES_NOUS_TIMEOUT_SECONDS15)min_key_ttl_secondstimeout_seconds
force_mintz"Nous credential refresh failed: %sr$  r  rc  r  nous_credential_refreshr  T)r&  r%  rN  r  r   r   r   r  r  r   r2  r   r   rZ   r[   r   r$  r  r  rF  r!  r  )rP   r  r  r  r  r$  r  s          rR   $_try_refresh_nous_client_credentialsz,AIAgent._try_refresh_nous_client_credentials  s   =...$-62I2I5
	HHHHHH44$'C	:[]c0d0d,e,e$f$f %bi0Mt&T&T U U   EE
  	 	 	LL=sCCC55555	 ))I&&99Z(('3'' 	w}} 	5(C(( 	0@0@ 	5}} ((//44)-I&*.-J' 1488822:S2TT 	5ts   A"A= =
B-B((B-c                    | j         dk    st          | d          sdS | j        dk    rdS 	 ddlm}m}  |            }n3# t          $ r&}t                              d|           Y d }~dS d }~ww xY wt          |t                    r|                                sdS |                                }|| j        k    rdS 	 | j                                         n# t          $ r Y nw xY w	  ||t          | dd                     | _        n3# t          $ r&}t                              d	|           Y d }~dS d }~ww xY w|| _        dd
lm}  ||          | _        dS )Nr]  rC  Frb  r   )r|  r{  z'Anthropic credential refresh failed: %srD  z?Failed to rebuild Anthropic client after credential refresh: %sr  T)r&  rL  r%  r?  r|  r{  r   r2  r   rZ   r[   r   rC  r=  r  rg   rl  r  r>  )rP   r|  r{  	new_tokenr  r  s         rR   )_try_refresh_anthropic_client_credentialsz1AIAgent._try_refresh_anthropic_client_credentials*  s   =000FZ8[8[05 =K''5	________//11II 	 	 	LLBCHHH55555	 )S)) 	1B1B 	5OO%%	///5	"((**** 	 	 	D		%;%;IwtUjlpGqGq%r%rD"" 	 	 	NN\^abbb55555	 #,;;;;;;#2?9#=#= ts?   ? 
A/	A**A/?C 
C&%C&* D 
D;D66D;c                 F   ddl m} |pd                                }d|v rt          |          | j        d<   d S d|v rddlm}  |            | j        d<   d S d|v rd	d
i| j        d<   d S d|v rt                      | j        d<   d S | j                            dd            d S )Nr   )_OR_HEADERSr  rl  r  r  r  r  r  r  r  )	rK  r  r  r   rF  rJ  r  r  r!  )rP   r  r  r  r  s        rR   "_apply_client_headers_for_base_urlz*AIAgent._apply_client_headers_for_base_urlQ  s    666666n"++--
:%%59+5F5FD 1222$
22AAAAAA5L5L5N5ND 1222z))6BDT5UD 1222++5I5K5KD 1222##$5t<<<<<rT   c                    t          |dd           pt          |dd          }t          |dd           pt          |dd           p| j        }| j        dk    rrddlm}m} 	 | j                                         n# t          $ r Y nw xY w|| _	        || _
         |||          | _         ||          | _        || _        || _        d S || _        t          |t                    r|                    d	          n|| _        | j        | j        d
<   | j        | j        d<   |                     | j                   |                     d           d S )Nruntime_api_keyaccess_tokenr  runtime_base_urlr  r]  r   )r{  r  rc  r$  credential_rotationr  )rg   r  r&  r?  r{  r  r=  r  r   rC  rD  r>  r$  rZ   r[   r  rF  r  r  )rP   rQ  runtime_keyruntime_baser{  r  s         rR   _swap_credentialzAIAgent._swap_credentialb  s   e%6==cP^`bAcAcu&8$??t75R\^bCcCctgkgt=000WWWWWWWW&,,....    '2D#'3D$%;%;K%V%VD"'6{'C'CD$&DL(DMF"4>|S4Q4Qc++C000Wc)-I&*.-J'//>>>++3H+IIIIIs    A: :
BB)classified_reasonerror_contextr  has_retried_429r  r  c          	         | j         }|d|fS |}|8|dk    rt          j        }n%|dk    rt          j        }n|dk    rt          j        }|t          j        k    re||nd}|                    ||          }|Bt                              d|t          |dd	                     | 	                    |           d
S d|fS |t          j        k    rg|sdS ||nd}|                    ||          }|Bt                              d|t          |dd	                     | 	                    |           d
S dS |t          j        k    r|
                                }	|	Et                              dt          |	dd	                      | 	                    |	           d|fS ||nd}|                    ||          }|Bt                              d|t          |dd	                     | 	                    |           d
S d|fS )a  Attempt credential recovery via pool rotation.

        Returns (recovered, has_retried_429).
        On rate limits: first occurrence retries same credential (sets flag True).
                        second consecutive failure rotates to next credential.
        On billing exhaustion: immediately rotates.
        On auth failures: attempts token refresh before rotating.

        `classified_reason` lets the recovery path honor the structured error
        classifier instead of relying only on raw HTTP codes. This matters for
        providers that surface billing/rate-limit/auth conditions under a
        different status code, such as Anthropic returning HTTP 400 for
        "out of extra usage".
        NFi      )r  r  u4   Credential %s (billing) — rotated to pool entry %sr   ?)TF)FTu7   Credential %s (rate limit) — rotated to pool entry %su1   Credential auth failure — refreshed pool entry Tu@   Credential %s (auth refresh failed) — rotated to pool entry %s)r  r!   billing
rate_limitauthmark_exhausted_and_rotater2  r3  rg   r  try_refresh_current)
rP   r  r  r  r  r  effective_reasonrotate_status
next_entry	refresheds
             rR   _recover_with_credential_poolz%AIAgent._recover_with_credential_pool}  sx   , $</)),#c!!#1#9  ###1#<  ###1#6 ~555+6+BKKM77Man7ooJ%J!Jc22  
 %%j111"{/))~888" #"{+6+BKKM77Man7ooJ%M!Jc22  
 %%j111"{;~2220022I$oPWXacgilPmPmooppp%%i000_,, ,7+BKKM77Man7ooJ%V!Jc22  
 %%j111"{o%%rT   c                 n    | j         dk    r|                                   | j        j        j        di |S )Nr]  ro   )r&  r  r=  r   r  )rP   r$  s     rR   _anthropic_messages_createz"AIAgent._anthropic_messages_create  sA    =000::<<<5t%.5CC
CCCrT   c           	      x    dddddi fd}t          t          j        dd                    }t           dd          pd}|dk    r!|rt	          |          rt          d	          }n`t          d
                     dg           D                       dz  }|dk    rt          |d          }n|dk    rt          |d          }n|}t          j                    } 	                    d           t          j        |d          }|                                 d}	|                                r|                    d           |	dz  }	|	dz  dk    r<t          j                    |z
  }
 	                    dt          |
           d           t          j                    |z
  }
|
|k    rt          d                     dg           D                       dz  }t                               d|
|                    dd          |d                                d t          |
           d!                    dd           d"           	  j        d#k    rEdd$lm}  j                                          | j        t           d%d                     _        n.                    d          }|                     |d&'           n# t4          $ r Y nw xY w 	                    d(t          |
           d)           |                    d*           d+         ;d,         3t7          d-t          |
           d.t          |           d/          d+<   n j        r	  j        d#k    rEdd$lm}  j                                          | j        t           d%d                     _        n.                    d          }|                     |d0'           n# t4          $ r Y nw xY wt;          d1          |                                d+         d+         d,         S )2ae  
        Run the API call in a background thread so the main conversation loop
        can detect interrupts without waiting for the full HTTP round-trip.

        Each worker thread gets its own OpenAI client instance. Interrupts only
        close that worker-local client, so retries and other requests never
        inherit a closed transport.

        Includes a stale-call detector: if no response arrives within the
        configured timeout, the connection is killed and an error raised so
        the main retry loop can try again with backoff / credential rotation /
        provider fallback.
        Nr  r  rE  c            	      <   	 
j         dk    rJ
                    d          d<   
                    d         t          
dd                     	d<   nÉ
j         dk    r
                              	d<   n
j         d	k    r[d
dlm} m}                     dd          }                    dd             | |          } |j	        di } ||          	d<   n9
                    d          d<    d         j
        j        j        di 	d<   n# t          $ r}|	d<   Y d }~nd }~ww xY w                    d          }|
                    |d           d S d S #                     d          }|
                    |d           w w xY w)NrZ  codex_stream_requestr  rE  _codex_on_first_delta)rE  r  r  r]  r[  r   )_get_bedrock_runtime_clientnormalize_converse_response__bedrock_region__r~  __bedrock_converse__chat_completion_requestr  request_completero   )r&  r  r  rg   r+  agent.bedrock_adapterr1  r2  r!  conversechatcompletionsr  r   r   r  )r1  r2  regionrE  raw_responser  request_clientr$  request_client_holderresultrP   s          rR   _callz.AIAgent._interruptible_api_call.<locals>._call  s;   a=$5556:6X6X`v6X6w6w)(3)-)?)?"4X>'.t5Ld'S'S *@ * *F:&&
 ]&:::)-)H)H)T)TF:&&]&888        (^^,@+NNFNN#94@@@88@@F#26?#@#@Z#@#@L)D)D\)R)RF:&&6:6X6X`y6X6z6z)(3)`)>x)H)M)Y)`)n)ncm)n)nF:& $ $ $"#w$ "7!:!:8!D!D!-55nM_5````` .- "7!:!:8!D!D!-55nM_5```` .s0   DD E* 
D5&D0+E* 0D55E* *1FHERMES_API_CALL_STALE_TIMEOUT     r@r  r  infc              3   N   K   | ] }t          t          |                    V  !d S r_   r\   r[   r   r*  s     rR   r   z2AIAgent._interruptible_api_call.<locals>.<genexpr>  .      RRac#a&&kkRRRRRRrT   r      順 g     @P  g      |@z&waiting for non-streaming API responseTro  r   333333?r&  r   r"  z$waiting for non-streaming response (z
s elapsed)c              3   N   K   | ] }t          t          |                    V  !d S r_   rE  rF  s     rR   r   z2AIAgent._interruptible_api_call.<locals>.<genexpr>0  .      SSqs3q66{{SSSSSSrT   zjNon-streaming API call stale for %.0fs (threshold %.0fs). model=%s context=~%s tokens. Killing connection.r+  r  r  %   ⚠️ No response from provider for zs (non-streaming, model: z). Aborting call.r]  r{  rD  stale_call_killr  z&stale non-streaming call killed after s       @r  r  z'Non-streaming API call timed out after zs with no response (threshold: s)interrupt_abortz!Agent interrupted during API call)r  r   r  rg   r0   r  r   r   r*  r]  r~   r  r  is_aliverV  r   r2  rl  r  r&  r?  r{  r=  r  rC  r  r   TimeoutErrorr  InterruptedError)rP   r$  r@  _stale_baser  _stale_timeout_est_tokens_call_startr  _poll_count_elapsed_est_ctxr{  rcr=  r>  r?  s   ``             @@rR   _interruptible_api_callzAIAgent._interruptible_api_call  s(    #T22!)4 0	a 	a 	a 	a 	a 	a 	a 	aL BI&EuMMNND+t44:	%I2CI2N2N"5\\NNRR:>>*b3Q3QRRRRRVWWKW$$!$[%!8!8v%%!$[%!8!8!,ikkEFFFE$777				jjll J	LFF3F1K S A%%9;;4$$T3x==TTT   y{{[0H.((SSJNN:r4R4RSSSSSWXXGnNN7I668	   !!&CMM & &.8nnWi.P.P& & &  
}(<<<RRRRRR.446661G1G 3#D*?FF2 2..
 366x@@> ==bIZ=[[[    D$$MS]]MMM   s###'?*vj/A/I&2P#h-- P P8;N8K8KP P P' 'F7O ( L}(<<<RRRRRR.446661G1G 3#D*?FF2 2..
 *?)B)B8)L)L)5 ==nUf=ggg    D&'JKKKU jjll J	LV '?&/!j!!s&   A>K 
K&%K&1A>O0 0
O=<O=c                     d| _         dS )zDReset tracking for text delivered during the current model response.r  N)r9  ra   s    rR   _reset_stream_delivery_trackingz'AIAgent._reset_stream_delivery_trackingq  s    02---rT   r   c                 n    t          |t                    r|rt          | dd          |z   | _        dS dS dS )zCAccumulate visible assistant text emitted through stream callbacks.r9  r  N)rZ   r[   rg   r9  )rP   r   s     rR   _record_streamed_assistant_textz'AIAgent._record_streamed_assistant_textu  sR    dC   	T 	@"EEL 111	 	 	 	rT   c                     t          | t                    sdS t          j        dd|                                           S )Nr  z\s+rY  )rZ   r[   r@  r   r   r   s    rR   _normalize_interim_visible_textz'AIAgent._normalize_interim_visible_text|  s9    $$$ 	2vfc4((..000rT   c           	          |                      |                     |pd                    }|sdS |                      |                     t          | dd          pd                    }t          |          o||k    S )Nr  Fr9  )rg  r>  rg   r   )rP   r   visible_contentstreameds       rR   _interim_content_was_streamedz%AIAgent._interim_content_was_streamed  s    >>$$W]33
 
  	577$$WT3UWY%Z%Z%`^`aa
 
 H~~=(o"==rT   assistant_msgc                    t          | dd          }|t          |t                    sdS |                    d          }|                     |pd                                          }|r|dk    rdS |                     |          }	  |||           dS # t          $ r  t          	                    dd	           Y dS w xY w)
zESurface a real mid-turn assistant commentary message to the UI layer.rE  Nr   r  (empty))already_streamedz interim_assistant_callback errorTr  )
rg   rZ   r   r   r>  r   rk  r   r2  r   )rP   rl  cbr   visiblero  s         rR   _emit_interim_assistant_messagez'AIAgent._emit_interim_assistant_message  s    T7>>:Zt<<:F##I..**7=b99??AA 	'Y..F==gFF	LBw)9:::::: 	L 	L 	LLL;dLKKKKKK	Ls   	B &CCc                    t          | dd          r"|r |                                rd| _        d|z   }d | j        | j        fD             }d}|D ] }	  ||           d}# t
          $ r Y w xY w|r|                     |           dS dS )z;Fire all registered stream delta callbacks (display + TTS).r8  Fr  c                     g | ]}||S r_   ro   )r   rp  s     rR   r   z.AIAgent._fire_stream_delta.<locals>.<listcomp>  s    hhhBY[YgRYgYgYgrT   TN)rg   r   r8  rD  r7  r   re  )rP   r   	callbacks	deliveredrp  s        rR   r  zAIAgent._fire_stream_delta  s     4.66 	!4 	!DJJLL 	!',D$D=Dhh4#=t?T"Uhhh		 	 	B4 		    	70066666	7 	7s   A!!
A.-A.c                 V    | j         }|	  ||           dS # t          $ r Y dS w xY wdS )z&Fire reasoning callback if registered.N)rA  r   )rP   r   rp  s      rR   r  zAIAgent._fire_reasoning_delta  sN    $>4    >    
&&c                 V    | j         }|	  ||           dS # t          $ r Y dS w xY wdS )a  Notify display layer that the model is generating tool call arguments.

        Fires once per tool name when the streaming response begins producing
        tool_call / tool_use tokens.  Gives the TUI a chance to show a spinner
        or status line so the user isn't staring at a frozen screen while a
        large tool payload (e.g. a 45 KB write_file) is being generated.
        N)rF  r   )rP   r   rp  s      rR   _fire_tool_gen_startedzAIAgent._fire_tool_gen_started  sP     #>9    >rx  c                 :    | j         dupt          | dd          duS )z4Return True if any streaming consumer is registered.Nr7  )rD  rg   ra   s    rR   r  zAIAgent._has_stream_consumers  s/     &d2 Ct/66dB	
rT   r  c          	      ~     j         dk    r0 _        	                                d _        S # d _        w xY w j         dk    rdddddiddifd fd	}t          j        |d
          }|                                 |                                r@|                    d            j        rt          d          |                                @d         d         d         S dddddiddiddidt          j
                    ifd fd fd fd}t          t          j        dd                    }|dk    rK j        rDt           j                  r0t          d          }t                               d j                   n`t%          d                     dg           D                       dz  }|dk    rt)          |d          }n|d k    rt)          |d!          }n|}t          j        |d
          }|                                 t          j
                    }	d"}
|                                r|                    d           t          j
                    }||	z
  |
k    r3|}	t+          |d         z
            }                     d#| d$           t          j
                    d         z
  }||k    rIt%          d%                     dg           D                       dz  }t                               d&||                    d'd(          |d)                                d*t+          |           d+                    d'd(           d,|d)d-           	                     d          }|                     |d./           n# t4          $ r Y nw xY w	                      d0/           n# t4          $ r Y nw xY wt          j
                    d<                        d1t+          |           d2            j        r	  j         d3k    rEd4d5lm}  j                                          | j         tC           d6d                     _        n.                    d          }|                     |d7/           n# t4          $ r Y nw xY wt          d8          |                                d         d         rtC           d9d:          pd:"                                pd}t                               d;tG          |pd:          d                    tI          d<|dd=          }tI          d>tC           d'd(          tI          d4|d?@          gdA          S d         d         S )Bu  Streaming variant of _interruptible_api_call for real-time token delivery.

        Handles all three api_modes:
        - chat_completions: stream=True on OpenAI-compatible endpoints
        - anthropic_messages: client.messages.stream() via Anthropic SDK
        - codex_responses: delegates to _run_codex_stream (already streaming)

        Fires stream_delta_callback and _stream_callback for each text token.
        Tool-call turns suppress the callback — only text-only final responses
        stream to the consumer.  Returns a SimpleNamespace that mimics the
        non-streaming response shape so the rest of the agent loop is unchanged.

        Falls back to _interruptible_api_call on provider errors indicating
        streaming is not supported.
        rZ  Nr[  r-  doneFr  c                  f     d         s%r%d d<   	               d S # t           $ r Y d S w xY wd S d S Nr~  Tr   r  r  s   rR   _fire_firstz>AIAgent._interruptible_streaming_api_call.<locals>._fire_first  sq    (0 ^ 04%f-&((((($   	      
 
,,c                  z   	 ddl m} m} 
                    dd          }
                    dd             | |          } |j        di 
}	fd}	fd}	fd} ||                                r|nd |j        sj        r|nd fd	
          d<   d S # t          $ r}|d<   Y d }~d S d }~ww xY w)Nr   )r1  stream_converse_with_callbacksr3  r~  r4  c                 P                                       |            dd<   d S )NTr  )r  )r   r  deltas_were_sentrP   s    rR   _on_textzRAIAgent._interruptible_streaming_api_call.<locals>._bedrock_call.<locals>._on_text  s3    #//55526(///rT   c                 F                                       |            d S r_   )rz  )rh   r  rP   s    rR   _on_toolzRAIAgent._interruptible_streaming_api_call.<locals>._bedrock_call.<locals>._on_tool  s(    #33D99999rT   c                 F                                       |            d S r_   )r  )r   r  rP   s    rR   _on_reasoningzWAIAgent._interruptible_streaming_api_call.<locals>._bedrock_call.<locals>._on_reasoning  s(    #22488888rT   c                       j         S r_   r  ra   s   rR   rn  zRAIAgent._interruptible_streaming_api_call.<locals>._bedrock_call.<locals>.<lambda>  s
    43L rT   )on_text_deltaon_tool_starton_reasoning_deltaon_interrupt_checkr  r  ro   )	r7  r1  r  r!  converse_streamr  rA  rD  r   )r1  r  r;  rE  r<  r  r  r  r  r  r$  r  r?  rP   s            rR   _bedrock_callz@AIAgent._interruptible_streaming_api_call.<locals>._bedrock_call  s   (        (^^,@+NNFNN#94@@@88@@F#96#9#G#GJ#G#GL7 7 7 7 7 7 7
: : : : : :9 9 9 9 9 9 *H)G$262L2L2N2N&XhhTX&.<@<S+{W[Wq+{==w{+L+L+L+L* * *F:&&& ! ( ( (&'F7OOOOOOO(s   BB   
B:*B55B:Tro  rK  rL  z)Agent interrupted during Bedrock API callr  r  rE  r  c                  f     d         s%r%d d<   	               d S # t           $ r Y d S w xY wd S d S r  r  r  s   rR   _fire_first_deltazDAIAgent._interruptible_streaming_api_call.<locals>._fire_first_delta0  sq    $V,  ,0!&)"N$$$$$    DD	   r  c                     ddl } t          t          j        dd                    }t          t          j        dd                    }|dk    r>(j        r7t          (j                  r#|}t                              d(j        |           i $dd	di|                     d
||d
          d}(	                    d          'd<   t          j
                    &d<   (                    d            'd         j        j        j        d0i |}(                    t!          |dd                     g }i }t#                      }i }i }	d}
d}d}g }d}|D ]}t          j
                    &d<   (                    d           (j        r na|j        s=t)          |d          r|j        r|j        }t)          |d          r|j        r|j        }||j        d         j        }t)          |d          r|j        r|j        }t!          |dd          pt!          |dd          }|r4|                    |            #             (                    |           |r|j        r|                    |j                   |s* #             (                    |j                   d%d<   nM(j        rF	 (                    |j                   (                    |j                   n# t<          $ r Y nw xY w|r|j        r|j        D ]}|j         |j         nd}|j!        pd}||	vr||	|<   |r)||v r%|||         k    rtE          |d          dz   }||	|<   |r|||<   |	|         }||vr|j!        pddddddd ||<   ||         }|j!        r
|j!        |d!<   |j#        rX|j#        j$        r |d         d"xx         |j#        j$        z  cc<   |j#        j%        r |d         d#xx         |j#        j%        z  cc<   t!          |d$d          }|,t)          |d%          r|j&        pi '                    d$          }|)t)          |d&          r|(                                }||d$<   |d         d"         }|r8||vr4|)                    |            #             (*                    |           |j        d         j+        r|j        d         j+        }
t)          |d          r|j        r|j        }d,                    |          pd}d}d'}|rg }t[          |          D ]}||         }|d         d#         }|rA|.                                r-	 t_          j0        |           n# t^          j1        $ r d}Y nw xY w|                    te          |d!         |d(         |'                    d$          te          |d         d"         |          )                     |
pd*}|rd+}d,                    |          pd} te          |||| ,          }!te          d|!|-          }"te          d.tg          ti          j5                              z   ||"g|/          S )1z#Stream a chat completions response.r   NHERMES_API_TIMEOUT      @HERMES_STREAM_READ_TIMEOUT      ^@uD   Local provider detected (%s) — stream read timeout raised to %.0fsTinclude_usage      >@)connectrc  rW   r  )rw   stream_optionsr&  chat_completion_stream_requestr  rE  r  z)waiting for provider response (streaming)r  r  r  r+  r  r  r  r  r  r2  )r7  r   r   r  )r   r   r   extra_contentr   rh   r   r  model_extra
model_dumpFr   )r   r   r  r   rR  lengthr   r   r   r  r  r  rP  zstream-r   r+  choicesr  ro   )6r  r  r   r  r  r0   r2  r   Timeoutr  r*  r]  r9  r:  r  rc  rg   rW  r  r  rL  r+  r  r  r   r  r   r  rD  re  r   r   r  r   r   r   rh   r   r  r   r  r  rz  rP  rV  rY  r   r   r   r  r   r[   r]  r^  ))r  _base_timeout_stream_read_timeoutstream_kwargsrw   rb  tool_calls_acctool_gen_notified_last_id_at_idx_active_slot_by_idxrP  
model_namer   r  	usage_objchunkr  rk  tc_deltaraw_idxdelta_idnew_slotr  rQ  extrarh   full_contentmock_tool_callshas_truncated_tool_argsr   r   effective_finish_reasonfull_reasoningmock_messagemock_choicer  r$  r  last_chunk_timer>  rP   s)                                      rR   _call_chat_completionszIAIAgent._interruptible_streaming_api_call.<locals>._call_chat_completions8  s   """"!"),@&"I"IJJM#(3OQV)W)W#X#X 
 $u,,,CTUYUbCcCc,'4$ZM#7  

#2D"9!>> -'	 *  	
 
 
M /3.P.P7 /Q / /!(+
 $(9;;OC   !LMMML*849EL]]}]]F
 %%gfj$&G&GHHH"$M#%N%(UU
 %'O(* MJD$&OI k, k,'+y{{$$$%@AAA, E} ug.. 15; 1%*[
ug.. 05; 0$)K	a(.5'** -u{ -!&J ")0CT!J!J!ogV[]hjnNoNo! ?#**>:::%%'''..~>>>  %U] %!((777) %))+++//>>>26(//  5 %% $ : :5= I I I $ D DU] S S S S#, % % % $%  />U- />$)$4 .> .>4<N4N(..TU#+;#4" #*===;B/8$D '? : : (OG,D D D'*>2'F'F'F'JH;C/8# @7?OG41':n44&.k&7R(257b,I,I15	3 3N3/ !/s 3#; 6*2+E$K#, ^'05 T %j 1& 9 9 9X=N=S S 9 9 9'0: ^ %j 1+ > > >(BSB] ] > > > '/4 H H =WX}-M-M=%-%9%?R$D$D_$U$UE ,&ul;; ;(-(8(8(:(:5:E/2$Z08 >C/@$@$@-11#666--/// 77====#1 C$)M!$4$BM 5'** ,u{ , %I 77=119TL"O&+# "$!.11  C',B ":{ ;I  ;Y__%6%6 ;; Jy1111#3 ; ; ;6:333;#**?d8Z&(ff_&=&=!0!#J!7&/" " "	, , ,     '4&=v#& 3*2'WW_55=N*$*"0	  L *$5  K
 #s4:<<000 $	   s$   34K((
K54K5U##U76U7c                  d   d} t          j                     d<    j        j        j        di 5 }|D ]O}t          j                     d<                       d           j        r nt          |dd          }|dk    r]t          |dd          }|rIt          |dd          dk    r4d	} t          |d
d          }|r 
                                 |           |dk    rt          |dd          }|rt          |dd          }|dk    r;t          |dd          }|r&| s$ 
                                 |           d	d<   |dk    r2t          |dd          }	|	r 
             	                    |	           Q|
                                cddd           S # 1 swxY w Y   dS )a8  Stream an Anthropic Messages API response.

            Fires delta callbacks for real-time token delivery, but returns
            the native Anthropic Message object from get_final_message() so
            the rest of the agent loop (validation, tool extraction, etc.)
            works unchanged.
            Fr  r  r   Ncontent_block_startcontent_blocktool_useTrh   content_block_deltar  
text_deltar   r  r  thinking_deltar  ro   )r*  r=  r   rw   r]  r  rg   rz  r  r  get_final_message)has_tool_userw   r  r  r  r   r  
delta_typer   thinking_textr  r$  r  r  rP   s             rR   _call_anthropiczBAIAgent._interruptible_streaming_api_call.<locals>._call_anthropic
  sc    !L $(9;;OC 7'07EE*EE *2# &N &NE ,09;;OC((()DEEE0 !(!=!=J!%::: ' E E  GWUFD%A%AZ%O%O+/L(/vt(D(DI( G 1 1 3 3 3 $ ; ;I F F F#'<<< 'w = =  N)0)E)EJ)\99'.ufb'A'A#' !C !C$5$5$7$7$7$($;$;D$A$A$A>B$4U$;!+/?!?!?07z20N0N#0 !N$5$5$7$7$7$($>$>}$M$M$M //11U*2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2 *2s   E'F%%F),F)c                  B   dd l } t          t          j        dd                    }	 t	          |dz             D ]|}	 j        dk    r"                                              d<   n             d<                        d          }|                    |d	           d S d S # t          $ r}d
         rWt                              d|           |d<   Y d }~                     d          }|                    |d	           d S d S t          || j        | j        | j        f          }t          || j        | j        t$          f          }d}|sg|seddlm} t          ||          rOt+          |dd           s>t-          |                                          d}	t1          fd|	D                       }|s|s|rG||k     rt                              d|dz   |dz   t5          |          j        |                               dt5          |          j         d|dz    d|dz    d                               d|dz    d|dz    dt5          |          j                                        d          }
|
                    |
d	           d d<   	                     d	           n# t          $ r Y nw xY wY d }~                    d|dz    d           t                              d|dz   |           nbt-          |                                          }d|v od|v }|rd _                             d!           t                              d"|           |d<   Y d }~                     d          }|                    |d	           d S d S d }~ww xY w	                     d          }|                    |d	           d S d S #                     d          }|                    |d	           w w xY w)#Nr   HERMES_STREAM_RETRIESr  r   r]  r  rE  stream_request_completer  r  z9Streaming failed after partial delivery, not retrying: %sr  F)APIErrorr  )
connection lostconnection resetconnection closedzconnection terminatednetwork errornetwork connection
terminatedzpeer closedzbroken pipezupstream connect errorc              3       K   | ]}|v V  	d S r_   ro   )r   phrase_err_lower_sses     rR   r   zKAIAgent._interruptible_streaming_api_call.<locals>._call.<locals>.<genexpr>|  s<       7" 7"(. %+n$<7" 7" 7" 7" 7" 7"rT   zJStreaming attempt %s/%s failed (%s: %s), retrying with fresh connection...u'   ⚠️ Connection to provider dropped (u   ). Reconnecting… (attempt rc  r  zstream retry z after stream_retry_cleanupstream_retry_pool_cleanupu(   ❌ Connection to provider failed after uM    attempts. The provider may be experiencing issues — try again in a moment.z5Streaming exhausted %s retries on transient error: %srw   znot supportedTu   
⚠  Streaming is not supported for this model/provider. Switching to non-streaming.
   To avoid this delay, set display.streaming: false in config.yaml
z$Streaming failed before delivery: %s)!r  r   r   r  r  r&  r  r   r  r   r2  rl  rZ   r  ConnectTimeoutPoolTimeoutr  r  r  openair  rg   r[   r  r   r3  r   rj   r  r]  r  _disable_streamingr
  )r  _max_stream_retries_stream_attemptr=  r  _is_timeout_is_conn_err_is_sse_conn_err	_APIError_SSE_CONN_PHRASESstale
_err_lower_is_stream_unsupportedr  r  r  r  r>  r?  rP   s                @rR   r@  z8AIAgent._interruptible_streaming_api_call.<locals>._callC  s   """""%bi0G&K&K"L"LFh',-@1-D'E'E A AO@=,@@@ JJLLL1@1B1BF:..1G1G1I1IF:.x "7!:!:8!D!D!-55nMf5ggggg .-y % y y y+E2 # #NN []^   /0F7O"FFFFd "7!:!:8!D!D!-55nMf5ggggg .-c '1 2F4I6K]^' ' (2 3V5OQ`a( ( ,1(* "< "DDDDDD)!Y77 "=Z^@_@_ "14Q5" 1 47 7" 7" 7" 7"2C7" 7" 7" 4" 4" 0
 ' A, A:J A  /1DDD &%H$3a$7$7!$;$(GG$4$%!" !" !" !% 1 1%a(,Q(8%a %a0?!0C%a %aFY\]F]%a %a %a!" !" !"
 !% 4 4%@Oa4G %@ %@J]`aJa %@ %@-1!WW-=%@ %@!" !" !"
 )>(A(A((K(K#(#4$($E$E(-6L %F %& %& %& GK$9($C!)$($G$G/J %H %& %& %& %& (1 !) !) !)$(D!) ( --!9#6#:!9 !9 !9   #NN W 3a 7 !    *-QJ (J 6 !B$3z$A 3  6 ":> 7 $ 0 0%7!" !" !" #KK F !   +,w!6!:!:8!D!D!-55nMf5ggggg .-yyAF "7!:!:8!D!D!-55nMf5ggggg .- "7!:!:8!D!D!-55nMf5gggg .ss   O-  :B-:O- -N78(N2 O- FN2+KN2
KN2KN2O- B#N2;O- 2N77O- -1PHERMES_STREAM_STALE_TIMEOUTg     f@rC  u>   Local provider detected (%s) — stale stream timeout disabledc              3   N   K   | ] }t          t          |                    V  !d S r_   rE  rF  s     rR   r   z<AIAgent._interruptible_streaming_api_call.<locals>.<genexpr>  rG  rT   r   rH  rI  rB  rJ  g      n@r  zwaiting for stream response (zs, no chunks yet)c              3   N   K   | ] }t          t          |                    V  !d S r_   rE  rF  s     rR   r   z<AIAgent._interruptible_streaming_api_call.<locals>.<genexpr>  rN  rT   uq   Stream stale for %.0fs (threshold %.0fs) — no chunks received. model=%s context=~%s tokens. Killing connection.r+  r  r  rO  z
s (model: z, context: ~z tokens). Reconnecting...stale_stream_killr  stale_stream_pool_cleanupzstale stream detected after zs, reconnectingr]  r   rP  rD  stream_interrupt_abortz+Agent interrupted during streaming API callr9  r  zPartial stream delivered before error; returning stub response with %s chars of recovered content to prevent duplicate messages: %sr  r  zpartial-stream-stubrR  r  r  )%r&  r0  ra  r~   r  r  rV  rV  r  rX  r*  r  r   r  r  r0   r2  r   r  r   r   r   r]  rl  r  r  r   r  r?  r{  r=  r  rC  rg   r   r\   r   )rP   r$  r  r  r  r@  _stream_stale_timeout_base_stream_stale_timeoutr[  _last_heartbeat_HEARTBEAT_INTERVAL_hb_now_waiting_secs_stale_elapsedr_  r`  r{  r=  _partial_text	_stub_msgr  r  r  r  r  r  r  r>  r?  s   ```                 @@@@@@@@@rR   !_interruptible_streaming_api_callz)AIAgent._interruptible_streaming_api_call  s   $ =---
 *8D&233J??-1**T*1111 =..."&66F!' %u~      (  (  (  (  (  (  (  (  (D  dCCCAGGIII**,, Xs###, X*+VWWW **,, X g*Wo%*%%"T22!)4 0#UO!5> 	,	 	 	 	 	 	P	 P	 P	 P	 P	 P	 P	 P	 P	 P	d7	2 7	2 7	2 7	2 7	2 7	2 7	2 7	2 7	2rK	h K	h K	h K	h K	h K	h K	h K	h K	h K	hZ &+295RTY+Z+Z%[%[" &..4=.EVW[WdEeEe.$)%LL!LLY[_[hiiii RR:>>*b3Q3QRRRRRVWWKW$$(+,F(N(N%%v%%(+,F(N(N%%(B%E$777				)++"jjll H	VFF3F ikkG(,???") #Goc.B$B C C$$TMTTT   "Y[[?3+??N 555SSJNN:r4R4RSSSSSWXXG"$9NN7I668	   !!'C<O<O ' ')~~gyAA' '!)7' ' '  .228<<B~99"EX9YYY    D77?Z7[[[[    D (,y{{$$$W3~3F3FWWW   ( V}(<<<RRRRRR.446661G1G 3#D*?FF2 2..
 *?)B)B8)L)L)5 ==nUm=nnn    D&'TUUUQ jjll H	VR '?&&  D"DbIIOR%''!"!  - +,,7O   ,$m&*  	 ',!$;;,&        /!j!!s@   < 	A#.O 
OO#O: :
PPA>S 
SSc           
      "	   | j         t          | j                  k    rdS | j        | j                  }| xj         dz  c_         |                    d          pd                                                                }|                    d          pd                                }|r|s|                                 S 	 ddlm} |                    d          pd                                pd	}|                    d
          pd                                pd	}|r.d|                                v r|st          j
        d          pd	} |||d||          \  }}|)t          j        d|           |                                 S 	 ddlm}	  |	||          }n# t          $ r Y nw xY wd}
t!          |j                  }|dk    rd}
n|dk    s:|                    d                                                              d          rd}
nP|                     |          rd}
n8|                     ||          rd}
n|dk    sd|                                v rd}
| j        }|| _        || _        || _        |
| _        d| _        |
dk    rvddlm}m}m} |dk    r|j        p |            pdn|j        pd}|| _        || _        || _          ||| j                   | _!         ||          | _"        d	| _#        i | _$        n[|j        | _        || _#        tK          |dd	          }|stK          |dd	          }|j        |d|rdtM          |          ini | _$        |
dk    o|dk    }d |                                v rd!|                                v p|| _'        tQ          | d"          rm| j)        rfdd#l*m+}  || j        | j        | j        | j        $          }| j)        ,                    | j        || j        tK          | d
d          | j        %           | -                    d&| d'|            t          j.        d(|||           dS # t          $ r4}t          j/        d)||           |                                 cY d	}~S d	}~ww xY w)*u  Switch to the next fallback model/provider in the chain.

        Called when the current model is failing after retries.  Swaps the
        OpenAI client, model slug, and provider in-place so the retry loop
        can continue with the new backend.  Advances through the chain on
        each call; returns False when exhausted.

        Uses the centralized provider router (resolve_provider_client) for
        auth resolution and client construction — no duplicated provider→key
        mappings.
        Fr   r%  r  r+  r   r  r  Nr$  z
ollama.comOLLAMA_API_KEYT)r+  r  explicit_base_urlexplicit_api_keyz.Fallback to %s failed: provider not configured)rh  r\  r^  rZ  rb  rc  rd  r]  rk  re  rf  r[  r   _custom_headersr  r  rl  rr  r  r  )r  r$  r%  r  u5   🔄 Primary model failed — switching to fallback: z via u"   Fallback activated: %s → %s (%s)z"Failed to activate fallback %s: %s)0rS  r\   rR  r   r   r  _try_activate_fallbackrK  r  r   r  r   rl  r  rh  r   r[   r  r  r  r  r  r+  r%  r&  rT  r?  r{  r|  r  r$  rC  rD  r=  r>  rE  rF  rg   r   r&  rL  r  r  r  r  r  r3  r  )rP   r  fb_providerfb_modelr  fb_base_url_hintfb_api_key_hint	fb_client_resolved_fb_modelrh  fb_api_modefb_base_urlr  r{  r|  r  r  
fb_headersr  r  fb_context_lengthr  s                         rR   r   zAIAgent._try_activate_fallbackX  s    3t';#<#<<<5!$"67!vvj))/R6688>>@@FF7OO)r0022 	1( 	1..000
z	1FFFFFF !#z 2 2 8b??AAIT!vvi006B==??G4O   FL4D4J4J4L4L$L$LUd$L"$),<"="="E,C,C8t"2!0-2 -2 -2)I)  D! ! ! 22444SSSSSS77+NN    -Ki011Kn,,/++{/A/A#/F/F/L/L/N/N/W/WXd/e/e+2++K88 1/<<$ =   	1 0	))->+BSBSBUBU-U-U0
I!DJ'DM'DM'DM'+D$222ttttttttttZeitZtZt!2!U6M6M6O6O!USU  |E  |M  |S  QS,*7'+6()?)?tOg)h)h&+:?=+I+I("&(##  )0' %Y0A4HH
! M!(4Et!L!LJ(0 +' ' AKR)4
+;+;<<PR'# #.1E"E"d+YdJd!2!2!4!44UX^^EUEU9U '& $ t122 t7N IIIIII$<$<J L4=% % %! '44*#4!]#D)R88!] 5    00 0"-0 0   L48[   4 	1 	1 	1M>!LLL..00000000	1sD   ?C	Q 
F Q 
F*'Q )F**J$Q 
R)R	R	Rc                 F   | j         sdS | j        }	 |d         | _        |d         | _        |d         | _        |d         | _        |d         | _        t          |d                   | _        |d         | _	        | j        d	k    rRd
dl
m} |d         | _        |d         | _         ||d         |d                   | _        |d         | _        d| _        n0|                     t          |d                   dd          | _        | j        }|                    |d         |d         |d         |d         |d                    d| _         d
| _        t+          j        d| j        | j                   dS # t.          $ r }t+          j        d|           Y d}~dS d}~ww xY w)a  Restore the primary runtime at the start of a new turn.

        In long-lived CLI sessions a single AIAgent instance spans multiple
        turns.  Without restoration, one transient failure pins the session
        to the fallback provider for every subsequent turn.  Calling this at
        the top of ``run_conversation()`` makes fallback turn-scoped.

        The gateway caches agents across messages (``_agent_cache`` in
        ``gateway/run.py``), so this restoration IS needed there too.
        Fr+  r%  r  r&  r$  r   r  r]  r   rP  r	  r
  r  Nrestore_primaryTr  r  r  r  r  r  r  z.Primary runtime restored for new turn: %s (%s)z%Failed to restore primary runtime: %s)rT  r  r+  r%  r  r&  r$  r   rF  r&  r?  r{  rC  rD  r=  r>  rE  rQ  r  r  rS  r   r3  r   rl  )rP   rtr{  ccr  s        rR   _restore_primary_runtimez AIAgent._restore_primary_runtime  s    ' 	5"0	GDJzNDMzNDMzNDMi=DL"&r/':";";D')*>'?D$ } 444JJJJJJ*,-@*A'+-.B+C()?)?*+R0D-E* *& ,..B+C(""88O,--, 9   (BOO+,!"=>12/012     (-D$#$D L@
DM   4 	 	 	OCQGGG55555	s   E"E6 6
F  FF >   r  r  r  r  APITimeoutErrorAPIConnectionErrorr  	api_errorretry_countmax_retriesc          
      J   | j         rdS t          |          j        }|| j        vrdS |                                 rdS | j        pd                                                                }|dv rdS 	 t          | dd          /	 | 	                    | j
        dd           n# t          $ r Y nw xY w| j        }t          |d	                   | _        |d
         | _        |d         | _        |d         | _        |d         | _        |d         | _        | j        dk    rRddlm} |d         | _        |d         | _         ||d         |d                   | _        |d         | _        d| _
        n0|                     t          |d	                   dd          | _
        t5          d|z   d          }|                     | j         d| d| j         d| dd           t;          j        |           dS # t          $ r }	t?          j         d|	           Y d}	~	dS d}	~	ww xY w)u  Attempt one extra primary-provider recovery cycle for transient transport failures.

        After ``max_retries`` exhaust, rebuild the primary client (clearing
        stale connection pools) and give it one more attempt before falling
        back.  This is most useful for direct endpoints (custom, Z.AI,
        Anthropic, OpenAI, local models) where a TCP-level hiccup does not
        mean the provider is down.

        Skipped for proxy/aggregator providers (OpenRouter, Nous) which
        already manage connection pools and retries server-side — if our
        retries through them are exhausted, one more rebuilt client won't help.
        Fr  )r   znous-researchrE  Nprimary_recoveryTr  r   r+  r%  r  r&  r$  r]  r   rP  r	  r
  r  r  r   u   🔁 Transient z on u    — rebuilt client, waiting z"s before one last primary attempt.r  z%Primary transport recovery failed: %s)!rT  r   rj   _TRANSIENT_TRANSPORT_ERRORSr  r%  r   r  rg   r  rE  r   r  r   rF  r+  r  r&  r$  r?  r{  rC  rD  r=  r>  rQ  r   r  r5  r*  sleepr   rl  )
rP   r  r  r  
error_typerN  r  r{  	wait_timer  s
             rR   _try_recover_primary_transportz&AIAgent._try_recover_primary_transport8  s    # 	5 )__-
T===5 ""$$ 	5--24466<<>>6665-	tXt,,8--,>t .     !   D &B"&r/':";";DGDJzNDMzNDMzNDMi=DL} 444JJJJJJ*,-@*A'+-.B+C()?)?*+R0D-E* *& ,..B+C(""88O,--- 9   AOQ//ILL? Y Y: Y Y4= Y Y+4Y Y Y    
 Jy!!!4 	 	 	OCQGGG55555	s=   3G8 B# "G8 #
B0-G8 /B00EG8 8
H"HH"c                     t          | t                    sdS | D ]1}t          |t                    r|                    d          dv r dS 2dS )NFr   >   	image_urlinput_imageT)rZ   r   r   r   )r   r   s     rR   _content_has_image_partsz AIAgent._content_has_image_parts  s^    '4(( 	5 	 	D$%% $((6*:*:>Z*Z*ZtturT   r  c                 f   t          | pd                              d          \  }}}d}|                    d          rZ|t          d          d                              dd          d                                         }|                    d          r|}d	d
dddd                    |d          }t          j        d|d          }|5  |	                    t          j        |                     d d d            n# 1 swxY w Y   t          |j                  }t          |          |fS )Nr  r  
image/jpegdata:;r   r   zimage/z.pngz.gifz.webpz.jpg)z	image/pngz	image/gifz
image/webpr!  z	image/jpganthropic_image_F)r  suffixdelete)r[   	partitionr  r\   r  r   r   tempfileNamedTemporaryFilerW   base64	b64decoder
   rh   )	r  headerr  r]   mime	mime_partr%  tmpr   s	            rR    _materialize_data_url_for_visionz(AIAgent._materialize_data_url_for_vision  sq   io2..88==4W%% 	!s7||}}-33C;;A>DDFFI##H-- ! ! 
 
 #dF

 	 )1CF[`aaa 	. 	.IIf&t,,---	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.CH~~4yy$s   (DD
Dr   c                 D   t          j        t          |pd                              d                                                    }| j                            |          }|r|S ddd                    |d          }d}t          |pd          }d }|                    d          r|                     |          \  }}d}		 d	d
l	m
}
 t          j         |
||                    }t          |t                    rt          j        |          ni }|                    d          pd                                }	n# t"          $ r}d| }	Y d }~nd }~ww xY w|r:|                                r&	 |                                 nS# t(          $ r Y nGw xY wnB# |r:|                                r'	 |                                 w # t(          $ r Y w w xY ww w xY w|	sd}	d| d|	 d}|r-t          |pd                              d          s	|d| dz  }|| j        |<   |S )Nr  r8  r  ztool result)r  r  r  zDescribe everything visible in this image in thorough detail. Include any text, code, UI, data, objects, people, layout, colors, and any other notable visual information.r"  r   )vision_analyze_tool)r  user_promptrX  zImage analysis failed: zImage analysis failed.z[The z- attached an image. Here's what it contains:
]z@
[If you need a closer look, use vision_analyze with image_url: )r  r  r[   r   r  r<  r   r  r0  tools.vision_toolsr2  asynciore  rZ   r   r   r   r   rN  unlinkrX   )rP   r  r   	cache_keycached
role_labelanalysis_promptvision_sourcecleanup_pathr  r2  result_jsonr?  r  notes                  rR   &_describe_image_for_anthropic_fallbackz.AIAgent._describe_image_for_anthropic_fallback  s   N3yB#7#7#>#>w#G#GHHRRTT	599)DD 	M %!
 
 #dF

 	
8 	 IO,,'+##G,, 	_*.*O*OP]*^*^'M<	>>>>>>!+##mYYY K 1;;0L0LTTZ,,,RTF!::j117R>>@@KK 	8 	8 	87A77KKKKKK	8   3 3 5 5  ''))))   D   3 3 5 5  ''))))   D   	32K_z__Q\___ 	Y_"!5!5!@!@!I!I 	dTadddD ;?,Y7sg   A9D? >F ?
E	EF EF 2F 
FFG0GG
GGGGc                    |                      |          s|S g }g }|D ]}t          |t                    r<|                                r'|                    |                                           Tt          |t
                    sj|                    d          }|dv rOt          |                    dd          pd                                          }|r|                    |           |dv r|                    di           }t          |t
                    r|                    dd          nt          |pd          }	|	r*|                    |                     |	|                     n|                    d           kt          |                    dd          pd                                          }|r|                    |           d	                    d
 |D                                                       }
d                    d |D                                                       }|
r	|r|
 d	| S |
r|
S |r|S dS )Nr   >   r   
input_textr   r  >   r  r  r  r.  z:[An image was attached but no image source was available.]r  c              3      K   | ]}||V  	d S r_   ro   )r   r?  s     rR   r   z8AIAgent._preprocess_anthropic_content.<locals>.<genexpr>  s'      BBdTBTBBBBBBrT   r  c              3      K   | ]}||V  	d S r_   ro   )r   r   s     rR   r   z8AIAgent._preprocess_anthropic_content.<locals>.<genexpr>  s'      ??D$?4??????rT   zI[A multimodal message was converted to text for Anthropic compatibility.])	r  rZ   r[   r   r   r   r   r@  rV  )rP   r   r   
text_partsimage_notesr   rJ  r   
image_datar  r  r%  s               rR   _preprocess_anthropic_contentz%AIAgent._preprocess_anthropic_content  sy   ,,W55 	N "
!# 	( 	(D$$$ ::<< 4%%djjll333dD)) HHV$$E...488FB//5266<<>> ,%%d+++444!XXk266
9CJPT9U9UpJNN5"555[^_i_omo[p[p	 e&&t'R'RS\^b'c'cdddd&&'cdddtxx++1r2288::D (!!$'''BBkBBBBBHHJJ??J?????EEGG 	+f 	+**&*** 	M 	MZZrT   api_messagesc           
      >    t           fd|D                       s|S t          j        |          }|D ]g}t          |t                    s                     |                    d          t          |                    dd          pd                    |d<   h|S )Nc              3      K   | ]A}t          |t                    o'                    |                    d                     V  BdS )r   N)rZ   r   r  r   )r   r   rP   s     rR   r   z>AIAgent._prepare_anthropic_messages_for_api.<locals>.<genexpr>  s`       
 
 sD!!Wd&C&CCGGIDVDV&W&W
 
 
 
 
 
rT   r   r   r  )r   r  r<  rZ   r   rH  r   r[   )rP   rI  transformedr   s   `   rR   #_prepare_anthropic_messages_for_apiz+AIAgent._prepare_anthropic_messages_for_api  s     
 
 
 
#
 
 
 
 
 	   mL11 	 	Cc4(( !??	""CGGFF++5v66 C	NN rT   c                     t          | dd          pd                                dv rdS t          | dd          pd                                }d|v pd|v pd|v pd	|v pd
|v S )aG  True when using an anthropic-compatible endpoint that preserves dots in model names.
        Alibaba/DashScope keeps dots (e.g. qwen3.5-plus).
        MiniMax keeps dots (e.g. MiniMax-M2.7).
        OpenCode Go/Zen keeps dots for non-Claude models (e.g. minimax-m2.5-free).
        ZAI/Zhipu keeps dots (e.g. glm-4.7, glm-5.1).r%  r  >   
minimax-cnrK  r  minimaxr  r  Tr  	dashscopealiyuncsrP  zopencode.ai/zen/zbigmodel.cn)rg   r  )rP   bases     rR   _anthropic_preserve_dotsz AIAgent._anthropic_preserve_dots  s     D*b))/R6688  =G  G  G4j"--3::<<d"  EjD&8  EI<M  EQcgkQk  Eo|  AE  pE  	ErT   c                     d| j         v S )z2Return True when the base URL targets Qwen Portal.r  r0  ra   s    rR   _is_qwen_portalzAIAgent._is_qwen_portal   s    4#777rT   c                    t          j        |          }|s|S |D ]}t          |t                    s|                    d          }t          |t
                    r
d|dg|d<   Lt          |t                    rfg }|D ]Z}t          |t
                    r|                    d|d           0t          |t                    r|                    |           [|r||d<   |D ]}t          |t                    ro|                    d          dk    rV|                    d          }t          |t                    r*|r(t          |d         t                    rddi|d         d	<    n|S )
Nr   r   rO  r   r  r2  r   	ephemeralcache_control)r  r<  rZ   r   r   r[   r   r   )rP   rI  preparedr   r   normalized_partsr   s          rR   _qwen_prepare_chat_messagesz#AIAgent._qwen_prepare_chat_messages$  s   =.. 	O 	6 	6Cc4(( ggi((G'3'' 6+17"C"C!DIGT** 
6 $& # 6 6D!$,, 6(//0N0NOOOO#D$// 6(//555# 6%5C	N  	 	C#t$$ H)D)D''),,gt,, I IZPRUY=Z=Z I4:K3HGBK0rT   c                    |sdS |D ]}t          |t                    s|                    d          }t          |t                    r
d|dg|d<   Lt          |t                    rfg }|D ]Z}t          |t                    r|                    d|d           0t          |t                    r|                    |           [|r||d<   |D ]}t          |t                    rp|                    d          dk    rW|                    d          }t          |t                    r*|r(t          |d         t                    rdd	i|d         d
<    dS dS )u<   In-place variant — mutates an already-copied message list.Nr   r   rO  r   r  r2  r   rX  rY  )rZ   r   r   r[   r   r   )rP   r   r   r   r[  r   s         rR   #_qwen_prepare_chat_messages_inplacez+AIAgent._qwen_prepare_chat_messages_inplaceE  s    	F 	6 	6Cc4(( ggi((G'3'' 
6+17"C"C!DIGT** 6#% # 6 6D!$,, 6(//0N0NOOOO#D$// 6(//555# 6%5C	N 	 	C#t$$ H)D)D''),,gt,, I IZPRUY=Z=Z I4:K3HGBK0	 	rT   c                   $ | j         dk    rddlm} |                     |          }t	          | dd          }|r|j        nd}t	          | dd          }|d| _         || j        || j        ||n| j	        | j
        | j        |                                 |t	          | dd          | j        pi                     d          d	k    

  
        S | j         dk    rQddlm} t	          | dd          pd}t	          | dd          }d|d || j        || j        | j	        pdd|          S | j         dk    rUd}	|}
|re|d                             d          dk    rFt#          |d                             d          pd                                          }	|dd         }
|	st&          }	d| j                                        v pd| j                                        v }| j        dk    pd| j                                        v }d}d}| j
        r`t/          | j
        t0                    rF| j
                            d          d u rd }n'| j
                            d!          r| j
        d!         }d"d#i}|                    ||          }| j        |	|                     |
          |                                 d$dd d%}|s
| j        |d&<   | j        d'k    pd(| j        pd                                v }|r	|rd)g|d*<   n8|r-|r|                                 }|||d+<   n|d$d,|d+<   d)g|d*<   n	|s|sg |d*<   | j        r|                    | j                   | j	        |s
| j	        |d-<   |rt	          | d.d          rd/| j        i|d0<   |S |}d }|D ]u}t/          |t0                    sd1|v rd} nV|                    d2          }t/          |t<                    r+|D ]$}t/          |t0                    sd3|v sd4|v rd} n%|r nv|rt?          j         |          }|D ]}t/          |t0                    s|!                    d1d           |                    d2          }t/          |t<                    rF|D ]C}t/          |t0                    r,|!                    d3d           |!                    d4d           D| "                                r/||u r| #                    |          }n| $                    |           | j        pd                                $|r_|d                             d          dk    r@tK          $fd5tL          D                       r t=          |          }i |d         dd6i|d<   i }| j'        r
| j'        |d7<   | j(        r
| j(        |d8<   | j)        r
| j)        |d9<   | j*        r
| j*        |d:<   | j+        rd|d;<   | j,        r
| j,        |d<<   | j        |t[          t]          j/        d=d>                    d?}| "                                r-| j        pd@t#          ta          j1                              dA|dB<   | j        r
| j        |dC<   | j	        .|                    | 2                    | j	                             n| "                                r)|                    | 2                    dD                     ng| 3                                s	dE| j4        v rJdF| j        pd                                v r-	 ddGlm5}  || j                  }||dH<   n# tl          $ r Y nw xY wi }| 3                                }d| j4        v pd| j4        v }|r|r||dI<   dE| j4        v }| 7                                ra|r|                                 }|||d+<   nC| j
        4t1          | j
                  } |r|                     d          d u rn| |d+<   ndddJ|d+<   |rdKg|dL<   | j8        r%|                    dMi           }!| j8        |!dN<   |!|dM<   | j        dOk    r| j
        rt/          | j
        t0                    rj| j
                            d!          pd                                                                }"| j
                            dd          }#|"dPk    s|#d u rd |dQ<   | "                                rd|dR<   |r||dS<   | j        r|                    | j                   |S )Tz9Build the keyword arguments dict for the active API mode.r]  r   build_anthropic_kwargsr  N_ephemeral_max_output_tokensrD  speedfast)
r+  r   r   rH  rI  is_oauthpreserve_dotsr  r  	fast_moder[  )build_converse_kwargsrB  r~  rH  T)r4  r3  i   )r+  r   r   rH  r6  guardrail_configrZ  r  r   r  r   r   models.github.air  r^  r`  mediumr  Feffortminimallowr  )r+  r1  r0  r   r7  r;  r4  r9  r_  ra  zreasoning.encrypted_contentr5  r  )rl  r  r:  r<  zx-grok-conv-idr8  r  r   r  r  c              3       K   | ]}|v V  	d S r_   ro   )r   r  r  s     rR   r   z,AIAgent._build_api_kwargs.<locals>.<genexpr>  s(      EE!A%EEEEEErT   r  onlyr   ordersortrequire_parametersdata_collectionr  r  )r+  r   r&  r  )	sessionIdpromptIdmetadatar   i   nousresearchrr  )_get_anthropic_max_outputrH  r%  r  rl  product=hermes-agenttagsoptionsnum_ctxr  r  thinkvl_high_resolution_images
extra_body)9r&  r?  ra  rM  rg   r  rb  r+  r   rH  rI  r>  rT  rK  r   r7  rh  r[   r   r"   r  r  r%  rZ   r   r"  r  r<  #_github_models_reasoning_extra_bodyr  r   r  r<  r!  rV  r\  r^  r   r;   r6  r7  r8  r9  r:  r;  r  r   r  r]  r^  r<  r  r  ry  r   _supports_reasoning_extra_bodyr  )%rP   rI  ra  r]  ctx_lenephemeral_outrh  r;  r  r1  payload_messagesis_github_responsesis_codex_backendreasoning_effortreasoning_enabled_effort_clampr	  is_xai_responsesgithub_reasoningsanitized_messagesneeds_sanitizationr   r   r   provider_preferencesr$  ry  _model_output_limitr  _is_openrouter_is_github_models_is_nousr`  r}  _effort_enabledr  s%                                       @rR   _build_api_kwargszAIAgent._build_api_kwargsa  s   =000FFFFFF!%!I!I,!W!W d$8$??G07Ag,,TG $D*H$OOM(481))j+j,9,E==4?!%!61";;==& '<dCC17R<<WEEO    =...CCCCCCT#4d;;J{F&A4HHI(,&,  ('*)*#6$ $%.    =---L+ 4Q 3 3F ; ;x G G"<?#6#6y#A#A#GRHHNNPP#/#3  65 #dm&9&9&;&;; D*dm.A.A.C.CC  
 / L2dm6I6I6K6KK   ( $$ GD4I4)P)P G(,,Y775@@(-%%*..x88 G'+'<X'F$
 '.M,001ACSTT  ,??@PQQ..00%'+ F ' =-1_)*#}5dH[Y[GbGbGdGd9d  '%5 '%B$Cy!!" '& 	H (,'O'O'Q'Q$'3.>{+5ERX*Y*YF;')F(GF9%%( '1A '$&y!% 6d4555*3C*.2o*+ NGD,$E$E N+;T_*M'M)" 	 	Cc4(( &#--%)"..J*d++ !+  I%i66 !  I--1Cy1P1P-1* 2Q & E 	D!%|!<!<) D D!#t,,  /666 WW\22
j$// D%/ D D	%i66 D%MM)T:::%MM*<dCCC
 !! 	M!\11%)%E%EFX%Y%Y"" 889KLLL
 
(b//11	S"1%))&11X==EEEE/DEEEEE > "&&8!9!9$R'9!'<$Rfk$R$Rq!!! 	B+/+A (! 	D-1-C * 	A,0,@ ) 	>+/+= (+ 	>9= !56( 	T6:6S !23 Z*RY';VDDEE
 


 !! 	!_8
--& &Jz" : 	-"&*Jw?&d44T_EEFFFF!!## 	 d44U;;<<<<%%'' 	>T=Q+Q+QW_dhdndtrtc{c{c}c}W}W}MMMMMM&?&?
&K&K#+>
<((    
0022$"66 ?&$*>> 	   	:N 	:%9Jz"!T%99..00 	  #'#K#K#M#M #/.>J{+(4d344B   5BFF9$5$5$>$>24
;// $("*/ /J{+  	:"8!9Jv  	, nnY33G!%!5GI$+Jy! =H$$)>$:dNceiCjCj$,00::@bGGIIOOQQG,00DAAH&  H$5$5&+
7#!! 	;6:J23 	2'1J|$ ! 	6d4555s   \' '
\43\4c                 Z   d| j         v rdS d| j         v rdS d| j         v s	d| j         v r5	 ddlm} t           || j                            S # t
          $ r Y dS w xY wd	| j         vrdS d
| j         v rdS | j        pd                                d}t          fd|D                       S )a3  Return True when reasoning extra_body is safe to send for this route/model.

        OpenRouter forwards unknown extra_body fields to upstream providers.
        Some providers/routes reject `reasoning` with 400s, so gate it to
        known reasoning-capable model families and direct Nous Portal.
        rx  Tzai-gateway.vercel.shrj  r  r   github_model_reasoning_effortsFrl  zapi.mistral.air  )z	deepseek/z
anthropic/zopenai/zx-ai/zgoogle/gemini-2z
qwen/qwen3c              3   B   K   | ]}                     |          V  d S r_   )r  )r   r  r+  s     rR   r   z9AIAgent._supports_reasoning_extra_body.<locals>.<genexpr>  s1      SS5##F++SSSSSSrT   )r  rJ  r  r   r+  r   r  r   )rP   r  reasoning_model_prefixesr+  s      @rR   r  z&AIAgent._supports_reasoning_extra_body  s	    T1114!T%9994!5559PTXTh9h9hLLLLLL::4:FFGGG   uut3335t3335!r((**$
  SSSS:RSSSSSSs   "A 
AAc                    	 ddl m} n# t          $ r Y dS w xY w || j                  }|sdS | j        rt          | j        t                    rk| j                            d          du rdS t          | j                            dd                    	                                
                                }nd}|dk    rd	|v rd	}n ||vr|d
k    rd|v rd}nd|v rd}n|d         }d|iS )zDFormat reasoning payload for GitHub Models/OpenAI-compatible routes.r   r  Nr  Frl  rk  xhighhighrm  rn  )rJ  r  r   r+  rI  rZ   r   r   r[   r   r  )rP   r  supported_effortsrequested_efforts       rR   r  z+AIAgent._github_models_reasoning_extra_body  sZ   	HHHHHHH 	 	 	44	 ;:4:FF  	4  	(Z0Et%L%L 	($((33u<<t"%))(H==   eggeegg   (w&&65F+F+F%%6669,,:K1K1K#(  ...#+  #4Q#7 *++s   	 
c                 `   |                      |          }t          |          }|sO|j        pd}t          j        d|t          j                  }|r#d                    d |D                       }|pd}|r.| j        r't          j	        dt          |           d|            |r5| j        r.| j        s'	 |                     |           n# t          $ r Y nw xY w|j        pd}t          |          }	|rt          |          }d	|	||d
}
t          |d          r|j        r|j        }g }|D ]}t#          |t$                    r|                    |           -t          |d          r|                    |j                   Xt          |d          r'|                    |                                           |r||
d<   t-          |dd          }|r||
d<   |j        rHg }|j        D ]8}t-          |dd          }t-          |dd          }t#          |t0                    r|                                s|                     |          \  }}|}t#          |t0                    r|                                st#          |t0                    r)|                                r|                                }n_t-          |dd          }|rt-          |dd          nd}|rt-          |dd          nd}|                     ||t          |                    }|                                }t-          |dd          }t#          |t0                    r|                                s|                     |          \  }}|}|                     |t#          |t0                    r|nd          }||||j        |j        j        |j        j         dd}t-          |dd          }|)t          |d          r|                                }||d<   |                    |           :||
d<   |
S )zBuild a normalized assistant message dict from an API response message.

        Handles reasoning extraction, reasoning_details, and optional tool_calls
        so both the tool-call path and the final-response path share one builder.
        r  r  rB  r  c              3   f   K   | ],}|                                 |                                 V  -d S r_   r  )r   bs     rR   r   z3AIAgent._build_assistant_message.<locals>.<genexpr>  s7      &T&TQ!''))&Tqwwyy&T&T&T&T&T&TrT   NzCaptured reasoning (	 chars): r  )r   r   r  rP  r  __dict__r  r  r   r  r   rh   r   r  r  r  r]  r  r   )!r  r   r   r@  r  rD  rV  r1  r   r   r\   rA  rD  r   r   rL  r  rZ   r   r   r  r  rg   r   r[   r   r  r  r  r   r   rh   r   )rP   rV  rP  rk  _from_structuredr   think_blockscombined_raw_content_san_contentr   raw_details	preserveddcodex_itemsr   r   r   r  r  r  _fn_fn_name_fn_argsr  r  tc_dictr  s                               rR   _build_assistant_messagez AIAgent._build_assistant_message  s    001BCC//
  	2'/52G:&=wbiXXXL 2!;;&T&T,&T&T&TTT!)!1T 	ad2 	aM_^1D1D__~__``` 	d5 	 - ++N;;;;    D
 )06B+L99 	B1.AAN  #'*	
 
 $&9:: 	5?P?b 	5
 ,=KI  5 5a&& 5$$Q''''Q
++ 5$$QZ0000Q-- 5$$Q\\^^444 5+4'( /1H$OO 	7+6C'(' /	+J.9 ,+ ,+	 D$77!)Y==!'3// /w}} /*.*G*G*O*O'$a.G!'3// cw}} c!&#.. c6<<>> c"(,,..%iTBB?B#J73#;#;#;FI#S73T#B#B#Bt"&"="=hRUV`RaRa"b"b!--//#*96H$#O#O !"2C88 A@P@V@V@X@X A373P3PQW3X3X0A0'@$#'#J#J(23CS(I(IS$$t$ $  "&(8%N ) 2 7%.%7%A! !	 	  	?DAA$ul33 3 % 0 0 2 2/4GO,!!'**** *C
s   7C 
CCapi_msgc                     |                      d          }t          |t                    s| S ddhfd|D             | d<   | S )u  Strip Codex Responses API fields from tool_calls for strict providers.

        Providers like Mistral, Fireworks, and other strict OpenAI-compatible APIs
        validate the Chat Completions schema and reject unknown fields (call_id,
        response_item_id) with 400 or 422 errors. These fields are preserved in
        the internal message history — this method only modifies the outgoing
        API copy.

        Creates new tool_call dicts rather than mutating in-place, so the
        original messages list retains call_id/response_item_id for Codex
        Responses API compatibility (e.g. if the session falls back to a
        Codex provider later).

        Fields stripped: call_id, response_item_id
        r   r  r  c                 ~    g | ]9}t          |t                    r fd |                                D             n|:S )c                 $    i | ]\  }}|v	||S ro   ro   )r   r)  r*  _STRIP_KEYSs      rR   r+  zJAIAgent._sanitize_tool_calls_for_strict_api.<locals>.<listcomp>.<dictcomp>m  s)    AAAdaA[,@,@Q,@,@,@rT   )rZ   r   r   )r   r   r  s     rR   r   z?AIAgent._sanitize_tool_calls_for_strict_api.<locals>.<listcomp>l  s_     !
 !
 !
  "d##,AAAAbhhjjAAAA)+!
 !
 !
rT   )r   rZ   r   )r  r   r  s     @rR   #_sanitize_tool_calls_for_strict_apiz+AIAgent._sanitize_tool_calls_for_strict_apiW  sn    " [[..
*d++ 	N "45!
 !
 !
 !
 !!
 !
 !

 rT   c                     | j         dk    S )a  Determine if tool_calls need sanitization for strict APIs.

        Codex Responses API uses fields like call_id and response_item_id
        that are not part of the standard Chat Completions schema. These
        fields must be stripped when calling any other API to avoid
        validation errors (400 Bad Request).

        Returns:
            bool: True if sanitization is needed (non-Codex API), False otherwise.
        rZ  )r&  ra   s    rR   _should_sanitize_tool_callsz#AIAgent._should_sanitize_tool_callss  s     } 111rT   	min_turnsc           	         | j         dk    r|dS d| j        vs| j        sdS ||n| j         }| j        |k     rdS |t	          | dd          }|rt          |          dk     rdS d}dt          |            dt          j                     }d	||d
}|	                    |           	 | 
                                }g }|D ]}	|	                                }
|	                    d          dk    r|	                    d          }|r||
d<   |
                    dd           |
                    dd           |
                    dd           |
                    dd           |r|                     |
           |	                    |
           | j        rd| j        dg|z   }d}| j        pg D ]3}|                    di                               d          dk    r|} n4|s|                                 	 |rW|d                             d          |k    r8|                                 |sn!|r|d                             d          |k    8|r5|d                             d          |k    r|                                 dS dS dS ddlm} d}	  |d||gdd          }n# t&          $ r d}d}Y nw xY w|s]| j        dk    rR|                     |          }|                     |g          |d<   d|d <   d!|v rd|d!<   |                     |          }n|sP| j        d"k    rEdd#lm}  || j        ||gdd|                                 $          }|                     |          }nb|s`| j        ||gdd%|                     d          }dd&lm}  |                     d'          j         j!        j"        d5i |d( |d          i}g }| j        dk    r+|s)| #                    |          \  }}|r|j$        r|j$        }np| j        d"k    r.|s,dd)lm%}  ||| j&        *          \  }}|r|j$        r|j$        }n7tO          |d+          r'|j(        r |j(        d         j)        }|j$        r|j$        }|D ]}|j*        j+        dk    r	 tY          j-        |j*        j.                  }|                    d,d          }dd-l/m0}  ||                    d.          ||                    d/          |                    d0          | j        1           | j1        s&te          d2|                    d,d                      # tf          $ r%} th          5                    d3|            Y d} ~ d} ~ ww xY wn2# tf          $ r%} th          5                    d4|            Y d} ~ nd} ~ ww xY w|rW|d                             d          |k    r8|                                 |sn!|r|d                             d          |k    8|r5|d                             d          |k    r|                                 dS dS dS # |rW|d                             d          |k    r8|                                 |sn!|r|d                             d          |k    8|r4|d                             d          |k    r|                                 w w w xY w)6a  Give the model one turn to persist memories before context is lost.

        Called before compression, session reset, or CLI exit. Injects a flush
        message, makes one API call, executes any memory tool calls, then
        strips all flush artifacts from the message list.

        Args:
            messages: The current conversation messages. If None, uses
                      self._session_messages (last run_conversation state).
            min_turns: Minimum user turns required to trigger the flush.
                       None = use config value (flush_min_turns).
                       0 = always flush (used for compression).
        r   Nr  rc  r  u   [System: The session is being compressed. Save anything worth remembering — prioritize user preferences, corrections, and recurring patterns over task-specific details.]__flush_r  r  )r   r   _flush_sentinelr   r  r  r  rP  r  _thinking_prefillr  r  r   rh   r2  )call_llmTflush_memoriesrK  i   )taskr   r   r6  rH  FrZ  r   r6  r:  r]  r`  )r+  r   r   rH  rI  rf  )r+  r   r   r6  )_get_task_timeoutr  r&  normalize_anthropic_responsestrip_tool_prefixr  rp  memory_toolactionr   old_textr  rp  r   r  r4  u     🧠 Memory flush: saved to z!Memory flush tool call failed: %sz Memory flush API call failed: %sro   )6rs  rX  ro  r  rg   r\   r   r*  	monotonicr   r  r  r   r!  r  rd  r   rK  r  rP  r&  r  r  r  r?  ra  r+  rT  r+  r<  r  r  r9  r:  r  rq  r   r  r>  rL  r  r  r   rh   r   r   r   rv  r  r2  rG  r   r2  r   )!rP   r   r  effective_minflush_content	_sentinel	flush_msg_needs_sanitizerI  r   r  r  memory_tool_defr  	_call_llm_aux_availabler  codex_kwargs_build_ant_kwargs
ant_kwargsr$  r  r   rl  r  
_nar_flush
_flush_msgrV  r   r*  flush_target_memory_toolr  s!                                    rR   r  zAIAgent.flush_memories  s    '1,,1BF40008J0F%.%:		@\ =00Ft%8$??H 	3x==1,,FO 	
 =r$xx<<$.*:*:<<	#R[\\		"""{	">>@@OL - -((**776??k11 # 4 4I  A7@ 34K...OT222-t444/666" F<<WEEE##G,,,,) j)1d>X Y YZ]ii #Oj&B  55R((,,V44@@&'OE A # p  x|//0ABBiOO   x|//0ABBiOO  HRL,,->??9LL LLq EDDDDD!N $9))*+ ##          !&  " dm7H&H&H#55lCC(,(=(=>O(P(PW%.1]+&,668<L!4511,??# 9M(M(M______..*|*+%)"&"?"?"A"A	  
  :::FF# !Z ,-.#&	 
 ,,T22
 EDDDDDn4==EU=VV[gn    *;*;<L*M*M  
 J} 111.1#'#A#A(#K#K q  :]%= :!.!9J"666~6^^^^^^ *
8tG_ ` ` `
A 7*"7 7!+!6J9-- >(2B >$,$4Q$7$?!$/ >!2!=J  M M;#x//M#z"+*?@@'+xx('C'CQQQQQQ$#'88H#5#5#/$(HHY$7$7%)XXj%9%9"&"4     $ c!"a488HV^C_C_"a"abbb$ M M M%H!LLLLLLLLM 0M"  	@ 	@ 	@LL;Q????????	@
  x|//0ABBiOO   x|//0ABBiOO  HRL,,->??9LL LL	  x|//0ABBiOO   x|//0ABBiOO  HRL,,->??9LLLs   (EU8 U8 J* )U8 *J;8U8 :J;;GU8 B5UU8 
U3U.)U8 .U33U8 7X> 8
V'V"X> "V''X> >B[r7  )approx_tokensr  focus_topicr  r  c                r   t          |          }t                              d| j        pd||r|dnd| j        |           |                     |d           | j        r,	 | j                            |           n# t          $ r Y nw xY w| j	        
                    |||          }| j                                        }|r|                    d|d	           |                                  |                     |          }	|	| _        | j        r	 | j                            | j                  }
|                     |           | j                            | j        d
           | j        }t+          j                                        d           dt1          j                    j        dd          | _        | j        d| j         dz  | _        | j                            | j        | j        pt>          j         !                    dd          | j        |           |
ru	 | j        "                    |
          }| j        #                    | j        |           n9# tH          t          f$ r%}t          %                    d|           Y d}~nd}~ww xY w| j        &                    | j        |	           d| _'        n2# t          $ r%}t          (                    d|           Y d}~nd}~ww xY w| j	        j)        }|dk    r"| *                    | j+         d| dd           tY          |	          t[          |          z   }|| j	        _.        d| j	        _/        	 ddl0m1}  ||           n# t          $ r Y nw xY wt                              d| j        pd|t          |          |d           ||	fS )u  Compress conversation context and split the session in SQLite.

        Args:
            focus_topic: Optional focus string for guided compression — the
                summariser will prioritise preserving information related to
                this topic.  Inspired by Claude Code's ``/compact <focus>``.

        Returns:
            (compressed_messages, new_system_prompt) tuple
        zPcontext compression started: session=%s messages=%d tokens=~%s model=%s focus=%rr  r  r  r   )r  )current_tokensr  r  r  r  r  r  Nr  r  r  r  r  )r<  r  r+  rQ  z,Could not propagate title on compression: %suK   Session DB compression split failed — new session will NOT be indexed: %sr  u   ⚠️  Session compressed u>    times — accuracy may degrade. Consider /new to start fresh.Tr  )reset_file_dedupz?context compression done: session=%s messages=%d->%d tokens=~%s)2r\   r2  r3  r<  r+  r  rx  on_pre_compressr   r  compressrn  format_for_injectionr   r  r  rd  rg  r  rw  end_sessionr	   rZ  r\  r]  r^  r_  r`  rb  rj  r  r   rk  r   get_next_title_in_lineageset_session_titlerY   r   update_system_promptri  rl  compression_countr  r5  r)   r*   last_prompt_tokenslast_completion_tokenstools.file_toolsr  )rP   r   r  r  r  r  _pre_msg_count
compressedtodo_snapshotnew_system_prompt	old_titleold_session_id	new_titler  r  _compressed_estr  s                    rR   _compress_contextzAIAgent._compress_context!  sk    X^O%v~$1@}   y$*		
 	
 	
 	H222  	$44X>>>>    ,55h}ju5vv
(==?? 	Jv-HHIII&&((( 55nEE%6" 	qq ,>>tOO	**8444 ,,T_mLLL!%%-\^^%<%<_%M%M"f"fPTPZP\P\P`acbcacPd"f"f(,8Y4?8Y8Y8Y(Y% //#=ZBJNN;RTY,Z,Z*&4	 0     XX$($4$N$Ny$Y$Y	(::4?IVVVV&	2 X X X%SUVWWWWWWWWX 55doGXYYY,-)) q q qlnoppppppppq %7!88LL? G Gs G G G     ""344,Z889 	 6E29:6
	999999W%%%% 	 	 	D	 	MO%v~s:""	
 	
 	

 ,,,sg    A; ;
BBDK %:I  K  J1JK J*K 
K0K++K0M1 1
M>=M>effective_task_idrk  c                     |j         }d| _        	 t          |          s|                     ||||          d| _        S |                     ||||          d| _        S # d| _        w xY w)a=  Execute tool calls from the assistant message and append results to messages.

        Dispatches to concurrent execution only for batches that look
        independent: read-only tools may always share the parallel path, while
        file reads/writes may do so only when their target paths do not overlap.
        TF)r   r  r   _execute_tool_calls_sequential_execute_tool_calls_concurrent)rP   rV  r   r  rk  r   s         rR   _execute_tool_callszAIAgent._execute_tool_calls  s     '1
 !%
	*1*== ::%x1BN  %*D!!	 66!8->  %*D!!ED!))))s   &A A 	A&function_namer   r  c           
      L   d}	 ddl m}  ||||pd          }n# t          $ r Y nw xY w|t          j        d|id          S |d	k    r@dd
lm}  ||                    d          |                    dd          | j                  S |dk    ry| j	        st          j        ddd          S ddl
m}  ||                    dd          |                    d          |                    dd          | j	        | j                  S |dk    r|                    dd          }	ddlm}
  |
|                    d          |	|                    d          |                    d          | j                  }| j        rm|                    d          dv rV	 | j                            |                    dd          |	|                    dd                     n# t          $ r Y nw xY w|S | j        r5| j                            |          r| j                            ||          S |dk    r@dd lm}  ||                    d!d          |                    d"          | j        #          S |d$k    rvdd%lm}  ||                    d&          |                    d'          |                    d(          |                    d)          |                    d*          | +          S t3          ||||| j        pd| j        rt7          | j                  ndd,-          S ).a@  Invoke a single tool and return the result string. No display logic.

        Handles both agent-level tools (todo, memory, etc.) and registry-dispatched
        tools. Used by the concurrent execution path; the sequential path retains
        its own inline invocation for backward-compatible display handling.
        Nr   get_pre_tool_call_block_messager  rz  r  Fr  todo	todo_toolr  r  r  r  r4  r   Session database not available.r  r  r   queryrole_filterlimitr  r  r	  r
  dbcurrent_session_idr  rp  r  r  r   r  r  r  r  r   clarify_toolquestionr  r  r  callbackr  r  goalr  toolsetstasksr,  r  r  r  r  r,  parent_agentTr  r<  enabled_toolsskip_pre_tool_call_hook)r  r   r   r   r  rm  r  r   rn  rg  tools.session_search_toolr   r<  rv  r  ro  rx  on_memory_writehas_toolhandle_tool_calltools.clarify_toolr  rB  r  r  r   rX  r   )rP   r  r   r  r  block_messager   
_todo_tool_session_searchrp  r  r?  _clarify_tool_delegate_tasks                 rR   _invoke_toolzAIAgent._invoke_tool  s#    (,	JJJJJJ;;}6G6M2  MM  	 	 	D	$:w6UKKKKF""??????:#''00#''77&   
 ...# bze>_"`"`aaaSSSSSS"?#''44)--m<<#''33##'?    h&&"&&x::FEEEEEE!\$((22%)))44&**:66(  F # (9(9((C(CGY(Y(Y(88%))(B77%)))R88   
 !   DM! 	d&:&C&CM&R&R 	'88VVVi''HHHHHH =&**:r::%)))44.   
 o--KKKKKK!>"&&v..%)))44&**:66#''00,001ABB!    (}.?)?0b=A=R\d4#8999X\(,   s    
((AG 
G+*G+     r  r6  c                    ddl }ddl}|                    d          j        }t	          d|t          |          z
            }g }|                    d          D ]\}t          |          |k    r|                    |           +|                    ||dd          }	|	                    |	p|g           ]d|z   
                    |          }
| |  |
 S )	aF  Word-wrap verbose tool output to fit the terminal width.

        Splits *text* on existing newlines and wraps each line individually,
        preserving intentional line breaks (e.g. pretty-printed JSON).
        Returns a ready-to-print string with *label* on the first line and
        continuation lines indented.
        r   N)x   r
  rS  r  TF)widthbreak_long_wordsbreak_on_hyphens)shutiltextwrapget_terminal_sizecolumnsr   r\   r  r   wrapextendrV  )r  r   r6  _shutil_twcols
wrap_width	out_linesraw_linewrappedr  s              rR   _wrap_verbosezAIAgent._wrap_verbose  s    	!   ((33;TCKK/00
!	

4(( 	8 	8H8}}
**  ****((8:4849 # ; ;   !6XJ7777v##I..'%''''rT   c                    /01 |j         }t          |          } j        rMt           j         d| d           |D ].}|                    dd|j        j         d|j        d           /dS g 0|D ]}|j        j        }	|	dk    rd	 _	        n|	d
k    rd	 _
        	 t          j        |j        j                  }
n# t          j        $ r i }
Y nw xY wt          |
t                     si }
|	dv rn j        j        rb	 |
                    dd          }|r8 j                            |          } j                            |d|	            n# t,          $ r Y nw xY w|	dk    r j        j        r	 |
                    dd          }t/          |          ra|
                    d          p%t1          j        dt1          j                              } j                            |d|dd                     n# t,          $ r Y nw xY w0                    ||	|
f           d                    d 0D                       } j        s#t          d| d|            t;          0d          D ]\  }\  }}}t          j        |d          } j        rqt          d| d| dtA          |!                                           d           t           "                    d t          j        |d!d"                               t          |           j#        k    r|d j#                 d#z   n|}t          d| d| dtA          |!                                           d$|            0D ]e\  }}} j$        rX	 tK          ||          } $                    d%|||           7# t,          $ r!}tM          j'        d&|            Y d}~]d}~ww xY wf0D ]Y\  }}} j(        rL	  (                    |j        ||           +# t,          $ r!}tM          j'        d'|            Y d}~Qd}~ww xY wZdg|z  1| _)         *                    d(| d)|            1 fd*}d} +                                rj ,                                rVt[          j.        t_          j0                              }t_          | d+| d,d- j1        .          }|2                                 	 tg          |th                    }tj          j6        7                    |/          5 }g /t;          0          D ]7\  }\  }}}|8                    |||||          }/                    |           8ts          j9                    }d}	 tj          j6        :                    /d12          \  }} | sn j        rn|s1d0} ;                     j         d3t          |            d4d05           | D ]}|<                                 tj          j6        :                    | d62           nt{          ts          j9                    |z
            }!|!d	k    r_|!d7z  d8k     rV/0fd9| D             }" *                    d:|! d;t          |            d<d                    |"dd=                    d           &ddd           n# 1 swxY w Y   |rRt}          d> 1D                       }#t}          d? 1D                       }$|?                    d@|# dA| dB|$dCdD           nZ# |rSt}          d> 1D                       }#t}          d? 1D                       }$|?                    d@|# dA| dB|$dCdD           w w xY wt;          0          D ]\  }\  }}}1|         }%|% j        rd| d}&ndE| dF}&dG}'n|%\  }	}
}&}'}(|(r<t          |&          dHk    r
|&ddH         n|&})t          A                    dI|	|'|)            j$        rK	  $                    dJ|	dd|'|(K           n.# t,          $ r!}tM          j'        d&|            Y d}~nd}~ww xY w j        rCtM          j'        dL|	 dM|'dNdO           tM          j'        dPt          |&           dQ|&             +                                r,t          |||'|&R          }* C                    dS|*            n j        s j        r>t          dT|dz    dM|'dNdO           t           "                    dU|&                     nHt          |&           j#        k    r|&d j#                 d#z   n|&}+t          dT|dz    dM|'dNdV|+            d _)         *                    dW| dX|'dCdY            jD        rM	  D                    |j        |||&           n.# t,          $ r!}tM          j'        dZ|            Y d}~nd}~ww xY wt          |&||j        t                    [          }& jG        H                    ||          },|,r|&|,z  }&d|&|j        d}-|                    |-           t          0          }|d	k    r+|| d         }.t          |.t                    \           dS dS )]zExecute multiple tool calls concurrently using a thread pool.

        Results are collected in the original tool-call order and appended to
        messages so the API sees them in the expected sequence.
           ⚡ Interrupt: skipping  tool call(s)r     [Tool execution cancelled — # was skipped due to user interrupt]r  Nr  r   r  r   r   r   r  before terminalr)  workdirr  before terminal: r  r  c              3   "   K   | ]
\  }}}|V  d S r_   ro   )r   r  rh   s      rR   r   z9AIAgent._execute_tool_calls_concurrent.<locals>.<genexpr>M  s(      "G"GJAtQ4"G"G"G"G"G"GrT   u     ⚡ Concurrent: u    tool calls — r   Fr       📞 Tool r  (r  Args: r  r6  r  r  ) - tool.startedTool progress callback error: Tool start callback error: z
executing z tools concurrently: c                 @   	 ddl m}  |j                   n# t          $ r Y nw xY wt	          j                    }	                     |||j                  }n=# t          $ r0}d| d| }t                              d||d           Y d}~nd}~ww xY wt	          j                    |z
  }t          ||          \  }	}
|	r&t          
                    d	|||dd
                    n*t          
                    d||t          |                     |||||	f| <   dS )z%Worker function executed in a thread.r   set_activity_callbackError executing tool '': z_invoke_tool raised for %s: %sTr  Nztool %s failed (%.2fs): %sr   #tool %s completed (%.2fs, %d chars))tools.environments.baserQ  r]  r   r*  r'  r   r2  r  rC   r3  r\   )r  r   r  r   rQ  r  r?  
tool_errordurationis_errorr  r  resultsrP   s              rR   	_run_toolz9AIAgent._execute_tool_calls_concurrent.<locals>._run_toolq  sx   IIIIII%%d&:;;;;   IKKEi**=-IZ\e\hii i i iP-PPJPP=}jcghhhhhhhhi y{{U*H.}fEEKHa i8-SYZ^[^Z^S_````A=RZ\_`f\g\ghhh+]FHhWGENNNs#    
''A 
B&&BBu    ⚡ running z tools concurrentlydotsspinner_typeprint_fn)max_workersT      @rL  u   ⚡ Interrupt: cancelling z pending concurrent tool(s)r  g      @r  r  c                 Z    g | ]'}|v                      |                   d          (S )r   )r  )r   r  futuresparsed_callss     rR   r   z:AIAgent._execute_tool_calls_concurrent.<locals>.<listcomp>  s@     * * * ! G|| )q)9)9:1=+||rT   zconcurrent tools running (zs, z remaining: r  c              3      K   | ]}|dV  	d S )Nr   ro   r   rs     rR   r   z9AIAgent._execute_tool_calls_concurrent.<locals>.<genexpr>  s"      DDaammmmmDDrT   c              3   *   K   | ]}||d         V  d S )Nr  ro   re  s     rR   r   z9AIAgent._execute_tool_calls_concurrent.<locals>.<genexpr>  s&      GG!GGrT   u   ⚡ rc  z tools completed in .1fzs totalrR  z!': thread did not return a resultr  r   "Tool %s returned error (%.2fs): %stool.completedrW  rX  Tool  completed in .2frR  Tool result (r  r?         ✅ Tool Result: s - tool completed: r
  rT  Tool complete callback error: r   r   tool_use_idenvry  )Jr   r\   r  rG  r5  r   r   rh   r   rt  ru  r   r   r   r  rZ   r   rf  r  r   get_working_dir_for_pathensure_checkpointr   r   r   r  getcwdrV  r2  r  r  r1  r   keysr;  r4  r=  _build_tool_previewr   r   r>  r-  r]  r  r  randomchoicer@   get_waiting_facesr  r  r   _MAX_TOOL_WORKERS
concurrentrb  ThreadPoolExecutorsubmitr*  waitr  cancelr   r  rR  r2  rl  _get_cute_tool_message_implr
  r?  r   r   r  check_tool_callr   )2rP   rV  r   r  rk  r   	num_toolsr   r   r  r   	file_pathwork_dirr   r   tool_names_strr  rh   r*  args_strargs_previewpreviewcb_errrZ  spinnerfacer_  executorr  _conc_start_interrupt_loggedr~  not_done_conc_elapsed_still_runningr  	total_durrf  function_resulttool_durationrX  result_previewcute_msgresponse_previewsubdir_hintsr  turn_tool_msgsrb  rc  rY  s2   `  `                                           @@@rR   r  z&AIAgent._execute_tool_calls_concurrent  s`    '1

OO	 $ 	T_VViVVVWWW   "u@Puuu$&E! !    
 F # &	K &	KI%.3M ((+,((.00*+'# $
9+=+G H H' # # # "#mT22 # "  777D<P<X7 - 1 1&" = =I  d#'#7#P#PQZ#[#[,>>xIbS`IbIbccc    D 
**t/C/K*'++Ir::C.s33 +//	::dbiXZXaXcXc>d>d,>>!?S"X!?!?   !   D M= IJJJJ "G"G,"G"G"GGG 		\RyRR.RRSSS'0q'A'A \ \##Bd:d???' \IIIdIIT$))++5F5FIIIJJJ$,,Xtz$q_d7e7e7effggggORS[}}_c_tOtOt8,BT-B,B#Ce#K#K  {CLZZZdZZT$))++5F5FZZLZZ[[[[* 	M 	MNBd* MM1$==G//gtTTTT  M M MM"K6"K"KLLLLLLLLM	M + 	J 	JNBd' JJ,,RUD$????  J J JM"H"H"HIIIIIIIIJJ &9$ ,Z)ZZ.ZZ[[[	X 	X 	X 	X 	X 	X 	X4 0022 	t7W7W7Y7Y 	=!@!B!BCCD#t$X$X)$X$X$Xgmx|  yG  H  H  HGMMOOO;	gi):;;K#66;6OO 3S[+4\+B+B & &'A'D$ 	1b$EEANN1%%%% #ikk$)!&%/%7%<%< &= & &ND( $  0 0 04- LL#'? !N !N#&x==!N !N !N&* )   
 "* ' 'AHHJJJJ #*//#/FFF$'	k(A$B$BM$q((]R-?!-C-C* * * * *%-* * *
 ,,[ [ ["8}}[ [:>))NSUTUSUDV:W:W[ [ [  G&3 3 3 3 3 3 3 3 3 3 3 3 3 3 3j  gDD7DDDDD	GGgGGGGG	eIee	eeyeeeefff	  gDD7DDDDD	GGgGGGGG	eIee	eeyeeeeffff	g $-\#:#: B	& B	&AD$
Ay, g&pt&p&p&pOO&ft&f&f&fO #YZV}o}h w>A/>R>RUX>X>X_TcT%:%:^mNNN#GXeguvvv. QQ33,mT4%2X 4     % Q Q Q&Ov&O&OPPPPPPPPQ ' dM"[-"["[}"["["["[\\\M"b#o2F2F"b"bQ`"b"bccc 4466 	f6tT=Yhiii  h1111_ f' fO!OO=OOOOPPP$,,ZIIJJJJZ]^mZnZnqu  rG  [G  [G7M8M7M'NQV'V'V  M\$d!dd=dddRbddeee!%D  !QD!Q!QM!Q!Q!Q!QRRR* MM//tT?SSSS  M M MM"K6"K"KLLLLLLLLM 8'E"#455	  O  3CCD$OOL 0</ * " H
 OOH%%%% %%	q==%yjkk2NNCT4U4UVVVVVV =s   B>>CC=AE
EE1BG88
HH<(N%%
O/OO$P
P,P''P, 5\ FZ'\ 'Z++\ .Z+/\ A])`
`0`++`0=f
g%ggc                 (   t          |j        d          D ]!\  }}| j        r{|j        |dz
  d         }|r/|                     | j         dt          |           dd           |D ]2}|j        j        }	dd|	 d	|j        d
}
|	                    |
           3 n|j        j        }	 t          j        |j        j                  }n5# t          j        $ r#}t          j        d|            i }Y d}~nd}~ww xY wt!          |t"                    si }d}	 ddlm}  ||||pd          }n# t(          $ r Y nw xY w|n|dk    rd| _        n|dk    rd| _        | j        st          j        |d          }| j        rqt5          d| d| dt7          |                                           d           t5          |                     dt          j        |dd                               nft          |          | j        k    r|d| j                 dz   n|}t5          d| d| dt7          |                                           d|            ||| _        |                      d|            |(	 ddl!m"}  || j                    n# t(          $ r Y nw xY w|_| j#        rX	 tI          ||          }| #                    d|||           n.# t(          $ r!}t          j%        d |            Y d}~nd}~ww xY w|S| j&        rL	 | &                    |j        ||           n.# t(          $ r!}t          j%        d!|            Y d}~nd}~ww xY w|r|d"v rn| j'        j(        rb	 |)                    d#d          }|r8| j'        *                    |          }| j'        +                    |d$|            n# t(          $ r Y nw xY w||d%k    r| j'        j(        r	 |)                    d&d          }tY          |          ra|)                    d'          p%t[          j.        d(t[          j/                              }| j'        +                    |d)|dd*                     n# t(          $ r Y nw xY wta          j0                    }|t          j        d+|id          }d,}n&|d-k    rdd.l1m2}  ||)                    d/          |)                    d0d          | j3        1          }ta          j0                    |z
  }| 4                                r)|                     d2tk          d-|||3                      n|d4k    r| j6        st          j        dd5d6          }n[dd7l7m8}  ||)                    d8d          |)                    d9          |)                    d:d;          | j6        | j9        <          }ta          j0                    |z
  }| 4                                r)|                     d2tk          d4|||3                      
n|dk    r3|)                    d=d          }dd>l:m;}  ||)                    d?          ||)                    d@          |)                    dA          | j<        B          }| j=        rm|)                    d?          dCv rV	 | j=        >                    |)                    d?d          ||)                    d@d                     n# t(          $ r Y nw xY wta          j0                    |z
  }| 4                                r)|                     d2tk          d|||3                      	n||dDk    rddEl?m@}   | |)                    dFd          |)                    dG          | jA        H          }ta          j0                    |z
  }| 4                                r)|                     d2tk          dD|||3                      n|dIk    rGddJlBmC}! |)                    dK          }"|"r)t!          |"t6                    rdLt          |"           dM}#n(|)                    dN          pdddO         }$|$rdP|$ ndQ}#d}%| 4                                ri| D                                rUt          jF        t          jH                              }&t          |& dR|# dS| jI        T          }%|%J                                 |%| _K        d}'	  |!|)                    dN          |)                    dU          |)                    dV          |"|)                    dW          | X          }|}'d| _K        ta          j0                    |z
  }tk          dI|||'3          }(|%r|%L                    |(           n;| 4                                r|                     d2|(            n# d| _K        ta          j0                    |z
  }tk          dI|||'3          }(|%r|%L                    |(           w | 4                                r|                     d2|(            w w xY w| jM        r|| jM        v rd}%| j        r| j#        syt          jF        t          jH                              }&t          |          })tI          ||          p|}t          |& dR|) dR| dS| jI        T          }%|%J                                 d}*	 | jO        P                    |||Y          }|}*nQ# t(          $ rD}+t          j        d+dZ| d[|+ i          }t          R                    d\||+d]           Y d}+~+nd}+~+ww xY wta          j0                    |z
  }tk          ||||*3          }(|%r|%L                    |(           nB| j        r|                     d2|(            n!# ta          j0                    |z
  }tk          ||||*3          }(|%r|%L                    |(           w | j        r|                     d2|(            w w xY w| j=        r| j=        S                    |          rd}%| 4                                r| D                                ryt          jF        t          jH                              }&t          |          })tI          ||          p|}t          |& dR|) dR| dS| jI        T          }%|%J                                 d},	 | j=        P                    ||          }|},nQ# t(          $ rD}+t          j        d+d^| d[|+ i          }t          R                    d_||+d]           Y d}+~+nd}+~+ww xY wta          j0                    |z
  }tk          ||||,3          }(|%r|%L                    |(           nA| 4                                r|                     d2|(            n# ta          j0                    |z
  }tk          ||||,3          }(|%r|%L                    |(           w | 4                                r|                     d2|(            w w xY w| j        rd}%| 4                                r| D                                ryt          jF        t          jH                              }&t          |          })tI          ||          p|}t          |& dR|) dR| dS| jI        T          }%|%J                                 d}-	 t          ||||j        | j9        pd| jU        rt7          | jU                  ndd`          }|}-n=# t(          $ r0}+da| db|+ }t          R                    dc||+d]           Y d}+~+nd}+~+ww xY wta          j0                    |z
  }tk          ||||-3          }(|%r|%L                    |(           n3| 4                                r|                     d2|(            n# ta          j0                    |z
  }tk          ||||-3          }(|%r|%L                    |(           w | 4                                r|                     d2|(            w w xY w	 t          ||||j        | j9        pd| jU        rt7          | jU                  ndd`          }n=# t(          $ r0}+da| db|+ }t          R                    dc||+d]           Y d}+~+nd}+~+ww xY wta          j0                    |z
  }| j        r|nt          |          ddk    r
|ddd         n|}.t          ||          \  }/}0|/rt                              de|||.           n*t          W                    df||t          |                     | j#        rK	 | #                    dg|dd||/h           n.# t(          $ r!}t          j%        d |            Y d}~nd}~ww xY wd| _        |                      di| dj|dkdl           | j        rCt          j%        dm| dn|dodp           t          j%        dqt          |           dr|            | jX        rM	 | X                    |j        |||           n.# t(          $ r!}t          j%        ds|            Y d}~nd}~ww xY wt          |||j        t          |          t          }| j[        \                    ||          }1|1r||1z  }d||j        d
}2|	                    |2           | j        s| j        r;t5          du| dn|dodp           t5          |                     dv|                     nEt          |          | j        k    r|d| j                 dz   n|}3t5          du| dn|dodw|3            | j        r|t          |j                  k     r}t          |j                  |z
  }4|                     | j         d|4 dxd           |j        |d         D ]2}|j        j        }	ddy|	 dz|j        d
}
|	                    |
           3 n>| j]        dk    r1|t          |j                  k     rta          j^        | j]                   #t          |j                  }5|5dk    r)t          ||5 d         t          |          {           dS dS )|z`Execute tool calls sequentially (original behavior). Used for single calls or interactive tools.r   Nr=  r>  Tr  r  r?  r@  r  z(Unexpected JSON error after validation: r   r  r  rz  r  r  Fr  rG  r  rH  r  rI  r  rJ  r  rK  zexecuting tool: rP  rL  rM  rN  rA  r   rB  rC  r)  rD  r  rE  r  r  r  r  r  r  r  r  rq  rp  r   r  r  r  r  r	  r
  r  r  rp  r  r  r   r  r  r  r   r  r  r  r  r  r  r  u   🔀 delegating z tasksr  r  u   🔀 u   🔀 delegatingrY  r[  r\  r  r  r,  r  )r   zContext engine tool 'z
' failed: z1context_engine.handle_tool_call raised for %s: %sr  zMemory tool 'z1memory_manager.handle_tool_call raised for %s: %sr  rR  rS  z&handle_function_call raised for %s: %sr   ri  rT  rj  rk  ru  r
  rh  rT  rl  rm  rn  rR  ro  r  rv  rw  rr  rs  rt  z remaining tool call(s)u   [Tool execution skipped — z* was not started. User sent a new message]rz  )`r  r   r  r  r5  r\   r   rh   r   r   r   r   r   r  r   rl  rZ   r   r  r   r   rt  ru  r2  r  r1  rG  r   r~  r;  r4  r-  r]  rU  rQ  r=  r  r   r>  rf  r  r   r{  r|  r   r   r  r}  r*  rm  r  rn  r  r  rg  r  r   r<  rv  r  ro  rx  r  r!  r  rB  r  r  r  r  r  r@   r  r  r  _delegate_spinnerrR  r  _get_tool_emojir  r   r2  r  r  r   rX  rC   r3  r?  r   r   r  r  r-  r  r   )6rP   rV  r   r  rk  r  r   remaining_calls
skipped_tcskipped_nameskip_msgr  r   r  
_block_msgr   r  r  rQ  r  r  r  r  r   r   tool_start_timer  r  r#  r$  rp  r  r%  r&  	tasks_argspinner_labelgoal_previewr  r  _delegate_resultr  emoji
_ce_resultrV  _mem_result_spinner_resultr  _is_error_resultr  r  r  r  r   num_tools_seqs6                                                         rR   r  z&AIAgent._execute_tool_calls_sequential  s   %&7&BAFF r	, r	,LAy ( "3">qstt"D" ~LLDO!p!pSQ`MaMa!p!p!px|L}}}"1 . .J#-#6#;L &#uL#u#u#u(2   H
 OOH----%.3M# $
9+=+G H H' # # # N1 N NOOO "# mT22 # " )-JNNNNNN<<!=:K:Qr  

     %  !H,,/0D,,"n44./D+? n:m%HHH' n[[[m[[d=CUCUCWCW>X>X[[[\\\$,,Xtz-XYhm7n7n7nooppppORS[}}_c_tOtOt8,BT-B,B#Ce#K#K  {CLlllmlld=CUCUCWCW>X>Xll^jllmmm!%2"$$%G%G%GHHH
 !MMMMMM))$*>????    D !d&A!M1-OOG//wXeffff  M M MM"K6"K"KLLLLLLLLM !d&>!J,,Y\=-XXXX  J J JM"H"H"HIIIIIIIIJ !m7N&N&NSWSgSo&N - 1 1&" = =I  #'#7#P#PQZ#[#[,>>$&?&?&?   !   D !mz&A&AdFZFb&A'++Ir::C.s33 +//	::dbiXZXaXcXc>d>d,>>!?S"X!?!?   !   D #ikkO%"&*gz-BQV"W"W"W #&((CCCCCC",*'++G44'++GU;;*# # #
 !%	o =88:: CLL  "B&A&-Yfo~&&&  "B  "B  C  C  C"222' 
&*jUMn1o1o&p&pOO[[[[[[&5o+//<<$1$5$5m$D$D+//;;++/?' ' 'O !%	o =88:: MLL  "L&ABRTacp  zI  'J  'J  'J  "L  "L  M  M  M(**&**8X>>IIIIII".,(,,X66!)--i88*..z::,# # # ' M,=,=h,G,GK],],],<<)--h;;")--i<<   
 %    $	o =88:: ELL  "D&A(M[h  rA  'B  'B  'B  "D  "D  E  E  E)++LLLLLL"/-*..z2>>)--i88!2# # #
 !%	o =88:: FLL  "E&A)]\i  sB  'C  'C  'C  "E  "E  F  F  F/11OOOOOO)--g66	 bIt!<!< b$Ms9~~$M$M$MMM$1$5$5f$=$=$CSbS#IL>J$a$:L$:$:$:PaM88:: $t?_?_?a?a $!=)H)J)JKKD+t,E,Em,E,ETZeiestttGMMOOO)0&#' 6&4n*..v66 - 1 1) < <!.!2!2:!>!>''4'8'89I'J'J%)' ' 'O (7$-1D*$(IKK/$AM:?M[h  rB   C   C   CH 6X....>>@@ 6_(__555 .2D*$(IKK/$AM:?M[h  rB   C   C   CH 6X....>>@@ 6_(__555560 W>]dFe5e5e? $4+F $!=)H)J)JKKD+M::E1-OO`S`G+t,G,Ge,G,Gg,G,GV\gkguvvvGMMOOO!
6&*&=&N&N}^kv~&N&&O!0JJ  @ @ @&*j';xS`;x;xlv;x;x1y&z&zOLL!TVceoz~L@ %)IKK/$AM:=-YfoyzzzH 6X.... 6_(__555 %)IKK/$AM:=-YfoyzzzH 6X.... 6_(__55556% @>$*>*G*G*V*V @> 88:: $t?_?_?a?a $!=)H)J)JKKD+M::E1-OO`S`G+t,G,Ge,G,Gg,G,GV\gkguvvvGMMOOO"6&*&:&K&KM[h&i&iO"1KK  @ @ @&*j';p=;p;pdn;p;p1q&r&rOLL!TVceoz~L@ %)IKK/$AM:=-Yfoz{{{H 6X....>>@@ 6_(__555 %)IKK/$AM:=-Yfoz{{{H 6X....>>@@ 6_(__55556 (>88:: $t?_?_?a?a $!=)H)J)JKKD+M::E1-OO`S`G+t,G,Ge,G,Gg,G,GV\gkguvvvGMMOOO"&6&:%}6G%.\#'?#8bEIEZ&dd4+@&A&A&A`d04' ' 'O '6OO  u u u&]}&]&]Q[&]&]OLL!I=ZdosLttttttttu %)IKK/$AM:=-Yfo~H 6X....>>@@ 6_(__555 %)IKK/$AM:=-Yfo~H 6X....>>@@ 6_(__55556
u&:%}6G%.\#'?#8bEIEZ&dd4+@&A&A&A`d04' ' 'OO ! u u u&]}&]&]Q[&]&]OLL!I=ZdosLttttttttu !%	o =040D __),_)=)=)C)C%%  #7}o"V"Va wC]TacqrrrrA=R_adetauauvvv* MM//(-t!.9I 0     ! M M MM"K6"K"KLLLLLLLLM "&D  !ZM!Z!Z]!Z!Z!Z!Z[[[# `WmWW=WWWWXXX^c/.B.B^^_^^___* MM//	m]\kllll  M M MM"K6"K"KLLLLLLLLM 8''%L"#455	  O  3CCMS`aaL 0</ * ) H
 OOH%%%? d' dMMMMMMMNNN$,,ZIIJJJJZ]^mZnZnqu  rG  [G  [G7M8M7M'NQV'V'V  M\$bbbbbbP`bbccc( Q5F5Q1R1R-R-R 1 <==A	kkkkkswxxx"3">qrr"B . .J#-#6#;L &#z,#z#z#z(2   H
 OOH----""q3/@/K+L+L'L'L
4?+++ -8991- 9~N_?`?`aaaaaa s  +C

C<C77C<D00
D=<D==J
J! J!.(K
L!K==LL,,
M6MM-AN>>
O
O#BQ**
Q76Q7+A[00
[=<[=.AgA7h;k<;n0<
m
:m n0m

n00A#ps=<v>=
u:uv>uv>>A0x.?|
})&}}A0A@<A =AA>A>
AB8B&AB3B3AB8EAE:E:
AF%FAF F AF%HAH<H<
AI'IAI"I"AI'c           
      z   t          d| j         d           d}|                    d|d           	 |                                 }g }|D ]]}|                                }dD ]}|                    |d           |r|                     |           |                    |           ^| j        pd}	| j        r|	d	z   | j        z   	                                }	|	r	d
|	dg|z   }| j
        rK|	rdnd}
t          | j
                  D ]0\  }}|                    |
|z   |                                           1i }d| j        v }|                                 r| j        | j        |d<   nddd|d<   |rdg|d<   | j        dk    ry|                     |          }|                    dd           |                     |          }|                     |          \  }}|r|j        pd	                                nd}n| j        |d}| j        -|                    |                     | j                             i }| j        r
| j        |d<   | j        r
| j        |d<   | j        r
| j        |d<   | j        r
| j        |d<   |r||d<   |r||d<   | j        dk    rddlm}m}  || j        |d| j        | j        | j         | !                                          }| "                    |          } ||| j                    \  }}|j        pd	                                }nc | #                    d!"          j$        j%        j&        d-i |}|j'        r/|j'        d         j(        j        r|j'        d         j(        j        }nd}|rXd#|v r4tS          j*        d$d|tR          j+        %          	                                }|r|                    d&|d           nd'}n| j        dk    ry|                     |          }|                    dd           |                     |          }|                     |          \  }}|r|j        pd	                                nd}n9| j        dk    rddlm}m}  || j        |d| j         | j        | j        | !                                (          }| "                    |          } ||| j                    \  }}|j        pd	                                }n| j        |d}| j        -|                    |                     | j                             |r||d<    | #                    d)"          j$        j%        j&        d-i |}|j'        r/|j'        d         j(        j        r|j'        d         j(        j        }nd}|rVd#|v r4tS          j*        d$d|tR          j+        %          	                                }|r|                    d&|d           nd'}nd'}nH# tX          $ r;} t[          j.        d*|             d+| j         d,t_          |            }Y d} ~ nd} ~ ww xY w|S ).zSRequest a summary when max iterations are reached. Returns the final response text.u$   ⚠️  Reached maximum iterations (z). Requesting summary...zYou've reached the maximum number of tool-calling iterations allowed. Please provide a final response summarizing what you've found and accomplished so far, without calling any more tools.r  r  )r  rP  r  Nr  r  r  r   r   rx  r  Trk  rz  r{  r|  rZ  r   )r+  r   rp  r   rq  rr  r%  r  r]  )ra  r  )r+  r   r   rH  rI  re  rf  r  iteration_limit_summaryr  r  z<think>.*?</think>\s*rB  r  z>I reached the iteration limit and couldn't generate a summary.)r+  r   r   re  rH  rI  rf  iteration_limit_summary_retryz Failed to get summary response: z"I reached the maximum iterations (z!) but couldn't summarize. Error: ro   )0rG  r,  r   r  r  r!  r  rd  r3  r   rL  r  insertr  r  rI  r&  r  r  rq  r   r+  rH  r  r<  r6  r7  r8  r9  r?  ra  r  r>  rT  r+  r  r9  r:  r  r  r  r@  r   rD  r   r   rl  r[   )!rP   r   rk  summary_requestr  rI  r   r  internal_fieldeffective_system
sys_offsetr  pfmsummary_extra_bodyr  r  summary_responserV  r  r  summary_kwargsr  _bak_nar_ant_kw_msgretry_response	retry_msg_bak2_nar2_ant_kw2
_retry_msgr  s!                                    rR   _handle_max_iterationszAIAgent._handle_max_iterations  s   bT5Hbbbccc. 	
 	ODDEEEH	A #>>@@OL - -((**&Y 6 6NKK5555" F<<WEEE##G,,,,#9?R+ f$4v$=@\$\#c#c#e#e  `)1>N O OPS__$ F"29QQ
 )$*? @ @ F FHC ''
S(8#((**EEEE!#%)==H2244 (46:6K&{33 $("*7 7&{3  F.D-E"6*} 111#55lCC  $///#'#9#9,#G#G '+'E'EFV'W'W$!1N_!g"3";"Ar!H!H!J!J!Jeg "Z ," " ?."))$*@*@*Q*QRRR (*$) J373I(0) L595K(2' I484H(1% F373E(0' J5I&z2% F3EN<0=$888||||||||"dlRV.2oPTPe,0,D151N1N1P1PR R RG (,'F'Fw'O'O$"d#3tG_```GD!&*l&8b%?%?%A%ANN (Dt'I'IQj'I'k'k'p'|  (D  (V  (V  GU  (V  (V$'/ ,4D4LQ4O4W4_ ,)9)A!)D)L)T)+ 1f..%'V,Db.`b`i%j%j%j%p%p%r%rN! fOO[^$T$TUUUU%eNN =$555#'#9#9,#G#GL $$Wd333%)%;%;L%I%IN#'#A#A.#Q#QLIqJS%[i&7&=2%D%D%F%F%FY[NN]&:::~~~~~~~~$u4:TX-1-E/3QUQf262O2O2Q2Q S  S  SH &*%D%DX%N%NN$)E.DLd$e$e$eMJ&0&8&>B%E%E%G%GNN "&$0& &N 2&--d.D.DT_.U.UVVV) J7I|4 (Jt'I'IQp'I'q'q'v  (C  (J  (\  (\  M[  (\  (\$'/ ,4D4LQ4O4W4_ ,)9)A!)D)L)T)+! f N22)+0H"ndfdm)n)n)n)t)t)v)v% j (X(XYYYY)i%eN 	A 	A 	AOBqBBCCC A$BU  A  Ax{|}x~x~  A  ANNNNNN	A s   V>W3 3
X8=1X33X8stream_callbackpersist_user_messagec                    	 t                       ddlm}  | j                                                     t          |t                    rt          |          }t          |t                    rt          |          }t          |t                    rt          |          }t          |t                    rt          |          }| _	        d _
        | _        |pt          t          j                              }d _        d _        d _        d _        d _        d _        d _        d _        d _        d _        d _         j        dk    r;	                                  r                     d           n# t8          $ r Y nw xY w j        r                                  d _        t?           j                    _!        tE          |          dk    r|dd         dz   n|}	|	#                    d	d
          }	tH          %                    d j        pd j&         j'        pd j(        pdtE          |pg           |	           |rtS          |          ng }
|r. j*        +                                s ,                    |            xj-        dz  c_-        ||n|}d} j.        dk    r9d j/        v r0 j0        r) xj1        dz  c_1         j1         j.        k    r	d}d _1        d|d}|
2                    |           tE          |
          dz
  }| _
         j3        s8 4                    d|dd          tE          |          dk    rdnd d            j5        =d}|rQ j6        rJ	  j6        7                     j                  }|r|8                    d          pd}n# t8          $ r Y nw xY w|r| _5        nމ 9                    |           _5        	 ddl:m;}  |d j         j&        ty           dd          pd           n2# t8          $ r%}tH          =                    d|           Y d}~nd}~ww xY w j6        rY	  j6        >                     j         j5                   n2# t8          $ r%}tH          ?                    d|           Y d}~nd}~ww xY w j5        } j@        rjtE          |
           jA        jB         jA        jC        z   dz   k    r<t          |
|pd jE        pd          }| jA        jF        k    rtH          %                    d|d  jA        jF        d  j&         jA        jG        d             j3        s( 4                    d!|d d" jA        jF        d d#           t          d$          D ]}tE          |
          } I                    |
|||%          \  }
}tE          |
          |k    r nSd}d _        d _        d _        d _        d _        t          |
|pd jE        pd          }| jA        jF        k     r nd}	 ddl:m;}  |d& j        |tS          |
          t          |            j&        ty           dd          pdty           d'd          pd(          }g }|D ]}t          |t                    r>|8                    d)          r)|2                    t          |d)                              Ut          |t                    r)|L                                r|2                    |           |rd*M                    |          }n2# t8          $ r%}tH          =                    d+|           Y d}~nd}~ww xY wd}d}d}d}d} d}!d}"d}#d}$t          jO                    jP         _Q        t          d jQ                    jS        rt          d jQ                   d _T        nd _U        d _T         jV        rK	 t          |t                    r|nd}% jV        W                     j-        |%           n# t8          $ r Y nw xY wd}& jV        rG	 t          |t                    r|nd}' jV        X                    |'          pd}&n# t8          $ r Y nw xY w| j         k     r j!        jY        dk    s jZ        Rr j[        \                                  jS        r"d}d,}$ j3        s 4                    d-           Rn|dz  }| _]         ^                    d.|             jZ        rd _Z        nT j!        _                                s;d/}$ j3        s0 4                    d0 j!        j`         d1 j!        ja         d2           Rn2 jb        "	 g }(t          t          |
                    D ]\  })}*|*8                    d3          d4k    r|*8                    d5          rtE          |
          |)z
  }+i |
|+d         D ]N},|,8                    d3          d6k    r n2|,8                    d7          }-|-r|,8                    d8d          |-<   Ofd9|*d5         D             }( n b                    ||(           n3# t8          $ r&}.tH          ?                    d:||.           Y d}.~.nd}.~.ww xY w je        dk    rd; j/        v r xjf        dz  c_f        g }/t          |
          D ]\  }0}1|1g                                }2|0|k    r|18                    d3          dk    rg }3|&r&t          |&          }4|4r|32                    |4           |r|32                    |           |3rI|28                    d8d          }5t          |5t                    r|5d*z   d*M                    |3          z   |2d8<   |18                    d3          d4k    r|18                    d<          }6|6r|6|2d=<   d<|2v r|2i                    d<           d>|2v r|2i                    d>           |2i                    d?d            j                                r k                    |2           |/2                    |2           |pd}7 jl        r|7d*z    jl        z   L                                }7|7r	d@|7dg|/z   }/ jm        rK|7rdnd}8t           jm                  D ]0\  }0}9|/n                    |8|0z   |9g                                           1 jo        r t          |/ jq         j        dk    A          }/ r                    |/          }/|/D ]G}:t          |:8                    d8          t                    r|:d8         L                                |:d8<   H|/D ]}:|:8                    d5          };|;sg }<|;D ]t          t                    rddBv r_	 t          jt        dB         dC                   }=i dBi dB         dCt          ju        |=dDdE          iin# t8          $ r Y nw xY w|<2                               |<|:d5<   t          |/           t          dF |/D                       }>t          |/          }?d	 j3        s y                    d	 jz         dG| d1 j          d            y                     jz         dHtE          |/           dI|?d dJ|>d dK            y                     jz         dL jE        rtE           jE                  nd            nt          j|        t          j~                              }@t          j|        t          j                              }A j        r                     |@ d
|A d           nq                                 s]                                 rIt          j|        g dM          }Bt          |@ d
|A d|B j        N          		                                  j        rt          j?        dO j&         dPtE          |
           dQ jE        rtE           jE                  nd            t          j?        dR|
r|
dS         d3         nd            t          j?        dT|?d dU           t          j                    }Cd}Dd$}Ed}Fd$}Gd}Hd}Id}Jd}Kd}Ld}Md}NdV}Od}Pd}Q|D|Ek     0r؉ j'        dWk    r	 ddXlm}Rm}S  |R            }T|T|Tdk    rdY |S|T           dZ}U y                     jz         d[|U d\d]                                d[|U                                             rd}Dd}#d}F                     |
|           d[|U d^|
|dd|Ud_S n# t          $ r Y nt8          $ r Y nw xY w	                                                        |/          }Q j        rt#          |Q            j        d`k    r                     |Qda          }Q	 ddl:m;}  |db| j        pd j(        pd j&         j'         j         j        |tE          |/          tE           jE        pg           |?|> j        c           n# t8          $ r Y nw xY wt+          dd          r                     |Qdef            	fdg}Vd}Wty           dhd          rd}Wn;                                 s'ddilm}X t          ty           djd          |X          rd}W|Wr                     |Q|Vk          }Pn                     |Q          }Pt          j                    |Cz
  }Y	r	                    d           d	 j        r                     d            j3        s! y                     jz         dl|Ydmdn            j        rH|Prty          |Pdodp          ndp}Zt          j?        dq|Z drt9          |Pds          r|Pj        ndp            d}[g }\ j        d`k    r@|Pty          |Pdtd          nd}]|Pd}[|\2                    du           n%t          |]tR                    sd}[|\2                    dv           n|]sty          |Pdwd          }^t          |^t                    r|^L                                nd}_|_r*tH          ?                    dxtE          |_                     nty          |Pdyd          }`ty          |Pdzd          }atH          =                    d{|`|aty          |Pdod          d| j         d} j'                    d}[|\2                    d~           n j        dk    rv|Pty          |Pd8d          nd}b|Pd}[|\2                    du           nt          |btR                    sd}[|\2                    d           n|bsd}[|\2                    d           n|Pt9          |Pd          r|Pj        |Pj        ssd}[|P|\2                    du           nYt9          |Pd          s|\2                    d           n2|Pj        |\2                    d           n|\2                    d           |[r|	r	                    d           d	 j        r                     d           |Ddz  }D j        tE           j                  k     r                     d                                            rd}Dd}#d}Fdd}c|Prpt9          |Pd          r_|Pj        rXt          |Pj                  t9          |Pj        d          r,|Pj        j        r |Pj        j        8                    dd          }cn/|Pr-t9          |Pd          r|Pj        rt          |Pj                  |cdk    r$|Pr"t9          |Pdo          r|Pj&        r
d|Pj&         }c|cdk    rM|PrKd tI          |P                                          D             }d j        rt          j?        d|d            d}e|Prt9          |Pd          r|Pj        ryty          |Pj        dd          }f|f4t          |Pj        t                    r|Pj        8                    d          }f|f+	 tM          |f          }en# tN          tP          f$ r Y nw xY w|edk    rd|Ydd}gna|edk    rd|Ydd}gnS|edk    rd}gnJ|edv rd|e d|Ydd}gn;|edv rd|e d}gn0|ed|e d|Ydd}gn#|Ydk     rd|Ydd}gn|Ydk    rd|Ydd}gnd|Yddn}g y                     jz         d|D d1|E ddM                    |\           d]            y                     jz         d|c d]                                          }h y                     jz         d|h d]            y                     jz         d|g d]           |D|Ek    r                     d|E d                                            rd}Dd}#d}F	)                     d|E d           t          j         jz         d|E d                                |
|           |
d|d|E d|g ddS tU          |Ddd          }i y                     jz         d|idd|g dd]           t          j=        d|D d1|E ddM                    |\           d|c            t          j                    |iz   }jd}kt          j                    |jk     r߉ jS        r[ y                     jz         dd]                                |
|                                             d|g d|D d1|E d|
|dddS t          j        d           |kdz  }k|kdz  dk    rB ^                    d|D d1|E dÐtM          |jt          j                    z
             dĝ           t          j                    |jk     ߐ j        d`k    rpty          |Pdyd          }lty          |Pdzd          }md}nt          |mt                    r|m8                    dŦ          }nnty          |mdd          }n|ldk    r|ndv rd}OndV}On j        dk    r#dVd5ddVdɜ}o|o8                    |Pj        dV          }On\|Pj        d         j        }O|Pj        d         j        }p                     |O|p|
          r! y                     jz         dʝd]           d}O|Odk    r) y                     jz         d˝d]           d}qd}r j        dv rdt9          |Pd          r|Pj        r|Pj        d         j        nd}s|srty          |sd8d          nd}q|srt          ty          |sd5d                    nd}rns j        dk    rhg }tty          |Pd8g           D ];}uty          |udd          dk    r$|t2                    ty          |udd                     <|trd	M                    |t          nd}qt          |qo!ta          j        d|qt`          j                            }v|r o|vo|qdur                     |q           p|qdu }w|wrWd}x y                     jz         dѝd]           d}y                     |                                |
|           |y|
|dd|xdӜS  j        dv r|Pj        d         j        }p|pj        s| dz  }                      |p|O          }z|
2                    |z           |pj        r
|"|pj        z  }"| d$k     rZ y                     jz         d|  d՝           ddd}{|
2                    |{           |
 _                             |
           d}N"nZ                     |"          L                                }|                     |                                |
|           ||pd|
|ddddӜS  j        dv r|Pj        d         j        }p|pj        r|!dk     r&|!dz  }! y                     jz         d؝d]           0 y                     jz         dٝd]                                |                                |
|           d|
|ddddӜS tE          |
          dk    rf y                     jz         d۝                                |
          }}                     |                                |
|           d|}|ddddӜS  y                     jz         dܝd]                                |
|           d|
|dddd_S t9          |Pds          r |Pj        rty          |Pj         j'         j        ަ          }~|~j        }|~j        }|~j        }|||dߜ} jA                            |           ty           jA        dd          r~ jA        jG        }ty           jA        dd          rDt           j&         j        |            4                     jz         d|d d j&                    d jA        _        d jA        _         xj        |z  c_         xj        |z  c_         xj        |z  c_         xj        dz  c_         xj        |~j        z  c_         xj        |~j        z  c_         xj        |~j        z  c_         xj        |~j        z  c_         xj        |~j        z  c_        d}|~j        r|rd|~j         d1| dd|~j        z  |z  dd}tH          %                    d j         j&         j'        pd||||Y|	  	         t           j&        |~ j'         j        ty           dd                    }|j        # xj        t          |j                  z  c_        |j         _        |j         _         j6        r j        r	  j6                             j        |~j        |~j        |~j        |~j        |~j        |j        t          |j                  nd|j        |j         j'         j        |j        dk    rdnd j&                   n# t8          $ r Y nw xY w j        r3t          j?        d|d         d d|d         d d|d         d             jo        r̉ j        dk    r1ty          |Pj        dd          pd}ty          |Pj        dd          pd}nDty          |Pj        dd          }|rty          |dd          pdnd}|rty          |dd          pdnd}|d         }|dk    r||z  dz  nd} j3        s- y                     jz         d|d d1|d d|dd|d d
           d}L j'        dWk    r"	 ddlm}  |             n# t8          $ r Y nw xY w ^                    d| d           n)# t          $ r 	r	                    d           d	 j        r                     d           t          j                    |Cz
  } y                     jz         d d]                                |
|           d}d|dd}Y nt8          $ rw}	r	                    d           d	 j        r                     d           t          |t                    rrty           dd          dk     rZt          |                                          }d|v pd|v }t          |
          }|r6 xj        dz  c_         y                     jz         dd]           Y d}~8|rd _        t          |
          }t          |/tR                    rt          |/           t          |Qt                    rt#          |Q           d}t          ty           d	d          tR                    rt           jm                  }d}t          ty           d
d          tR                    rt           jE                  }d}t          |t                    r!t          |          }||k    r|}| _5        d}t          ty           dd          t                    r)t           jl                  }| jl        k    r	| _l        d}d}t          ty           dd          t                    r j        8                    d          nd}t          |t                    rt#          |          }d}ty           dd          pd}|rt          |          }||k    r| _        t          ty           dd          t                    r
| j        d<   ty           djd          "t9           j        d          r| j        _        d} y                     jz         dd]            xj        dz  c_        |p	|p|p|p|p|}|r! y                     jz         dd]           n  y                     jz         dd]           Y d}~ ty          |dd          }                     |          }ty           dd          }|rty          |dd          nd}t          |ty           dd          pdty           dod          pd|?||/rtE          |/          nd          }tH          ?                    d|j        j        |j        |j        |j        |j        |j                                        ||L|j        |          \  }}L|rY d}~* j        d`k    rQ j'        dk    rE|dk    r>|Hs<d}H                     d]          r$ y                     jz         d           Y d}~ j        dk    rK j'        dWk    r@|dk    r9|Js7d}J                     d]          rt           jz         d           Y d}~݉ j        dk    r|dk    rt9           d          r|Isd}Iddlm}                                  rt           jz         d            Y d}~C j        } ||          rd!nd"}t           jz         d#           t           jz         d$|            t          |r+tE          |          d%k    r jz         d&|dd%          dn
 jz         d'           t           jz         d(           dd)lm}  |            }t           jz         d*| d+           t           jz         d,| d-           t           jz         d.           t           jz         d/           t           jz         d0           t           jz         d1           |j        t          j        k    r|Ksd}K|
D ].}*t          |*t                    r|*i                    d2d           / y                     jz         d3d]           t          j=        d4 jz        tE          |
                     Y d}~8|Ddz  }Dt          j                    |Cz
  } ^                    d5|D d1|E d           t          |          j        }t          |                                                               |          }tH          =                    d6|D|E|                                 |           ty           dd          }ty           d7d          }5ty           dod          }|rd8| d9nd} y                     jz         d:|D d1|E d| | d]            y                     jz         d;| d<| d]            y                     jz         d=|5 d]            y                     jz         d>| d]           |rY|d?k     rRty          |d@d          }|rt          |          ddA         nd}|r" y                     jz         dB| d]            y                     jz         dC|dmdDtE          |/           dE|?d dU                                            rdFv r y                     jz         dG| dHd]            j        r@ y                     jz         dId]            y                     jz         dJd]            y                     jz         dK| d]            jS        r y                     jz         dLd]                                |
|                                             dM| dN                     t          |                     d|
|dddcY d}~S ty          |dd          }|j        t          j        k    r)d} jA        }|jG        }||k    r|                      j&        | j        ty           dd           j'        O           t9          |d          rd|_        d|_         y                     jz         dP|d dQ|d dUd]           |#dz  }#|#|Gk    rtE          |
          } I                    |
||?|%          \  }
}d}tE          |
          |k     s||k    r?                     dR|d dS|d dT           t          j        d           d}MY d}~n|j        t          j        t          j        fv }|rv j        tE           j                  k     rY j        }|duo|                                }|s6                     dU                                            rd}Dd}#d}FY d}~"r|r| j'        dWk    rq|j        t          j        k    rZ|sX	 ddVlm} ty          |dWd          }|rty          |dXd          nd} |||Y           n# t8          $ r Y nw xY w|E}DY d}~"|j        t          j        k    }|r|#dz  }#|#|Gk    r y                     jz         dZ|G d[d]            y                     jz         d\d]           t          j         jz         d]|G d^                                |
|           |
d|d_|G d`ddddacY d}~S                      db|# d1|G d           tE          |
          } I                    |
||?|%          \  }
}d}tE          |
          |k     rJ                     dc| dQtE          |
           dd           t          j        d           d}MY d}~n y                     jz         ded]            y                     jz         d\d]           t          j         jz         df                                |
|           |
d|dgddddacY d}~S |j        t          j        k    }|r jA        }|jG        }t                    }|t          d|dhz
            }| _
         y                     jz         di|d dj|d dk|d dd]           |#dz  }#|#|Gk    r y                     jz         dZ|G d`d]            y                     jz         d\d]           t          j         jz         dl|G d^                                |
|           |
d|dm|G d`ddddacY d}~S d}MY d}~
nt                    }|r2||k     r,|} y                     jz         dn|d dS|d dd]           nt          |          }|r||k     r|                      j&        | j        ty           dd           j'        O           t9          |d          r!d|_        t          |o||k              |_         y                     jz         do|d dQ|d dUd]           n  y                     jz         dpd]           |#dz  }#|#|Gk    r y                     jz         dZ|G d`d]            y                     jz         d\d]           t          j         jz         dl|G d^                                |
|           |
d|dm|G d`ddddacY d}~S                      dq|?d dr|# d1|G d           tE          |
          } I                    |
||?|%          \  }
}d}tE          |
          |k     s|rc||k     r]tE          |
          |k     r,                     dc| dQtE          |
           dd           t          j        d           d}MY d}~nj y                     jz         dsd]            y                     jz         dtd]           t          j         jz         du|?d dv                                |
|           |
d|dw|?d dxddddacY d}~S t          |tP          tN          f          ot          |t                     }|pq|j         oi|j         oa|j        t          j        t          j        t          j        t          j        t          j        t          j        t          j        fvo| }|r                     dy| dz                                            rd}Dd}#d}FY d}~)|Q                     |Qd{||                                d}| d                     |                       y                     jz         d~| dd]            y                     jz         d;| d<| d]            y                     jz         d=|5 d]           |j        s|j        t          j        k    r8|dk    r|dk    r y                     jz         dd]            y                     jz         dd]            y                     jz         dd]            y                     jz         dd]           nɉ y                     jz         dd]            y                     jz         dd]            y                     jz         d| dd]           dt          |5                                          v r  y                     jz         dd]           n  y                     jz         dd]           t          j         jz         d|            |dk    r;|?dk    stE          |/          dk    r! y                     jz         dd]           n                     |
|           d|
|ddt          |          d_cY d}~S |D|Ek    r|Fs$                     ||D|E          r
d}Fd}DY d}~,މ                     d|E d                                            rd}Dd}#d}FY d}~-                     |          }|r                     d|E d|            n                     d|E d|             y                     jz         d| d]           ty          |dd           ot!          fddD                       }|r@ y                     jz         dd]            y                     jz         dd]           t          j        d jz        |E|||tE          |/          |?d            |Q                     |Qd||                                |
|           d|E d| }|r|Đdz  }||
|dd|d_cY d}~S d}|rty          ty          |dWd          dXd          }|r{t9          |Ɛd          ri|Ơ8                    d          p|Ơ8                    d          }|r;	 t#          tM          |Ǧ          d          }n# tN          tP          f$ r Y nw xY w|r|ntU          |Ddd          }i|r%                     d|i d|Ddz    d1|E d           n                      d|i d|D d1|E d           tH          =                    d|i|D|E                                 |           t          j                    |iz   }jd}kt          j                    |jk     r jS        r^ y                     jz         dd]                                |
|                                             d|D d1|E d|
|dddcY d}~S t          j        d           |kdz  }k|kdz  dk    rC ^                    d|D d1|E dÐtM          |jt          j                    z
             dĝ           t          j                    |jk     Y d}~nd}~ww xY w|D|Ek     0|rd}$n(|Mr(|dz  } j!                                         |Ddz  }Dd}M9 |Nr9$|P4d}$t           jz         d                                |
|           n	  j        d`k    r                     |P          \  }p}On= j        dk    r ddlm}  ||P j                  \  }p}On|Pj        d         j        }p|pj        t          |pj        t                    sr|pj        }t          |t                    rG|ɠ8                    dd          p)|ɠ8                    d8d          pt          ju        |ɦ          |p_        nt          |tR                    rg }|D ]}t          |t                    r|ʠ2                    |˦           -t          |t                    rC|ˠ8                    dͦ          dk    r*|ʠ2                    |ˠ8                    dd                     t          |t                    r,d|v r(|ʠ2                    t          |d                              d	M                    |ʦ          |p_        nt          |ɦ          |p_        	 ddl:m;} ty          |pd5d          pg }|pj        pd} |	 d/| j        pd j(        pd j&         j'         j         j        ||Y|OtE          |/          ty          |Pdod                               |P          tE          |ͦ          tE          |̦          d n# t8          $ r Y nw xY w|pj        r} j3        sv j        r& y                     jz         d|pj                    nI y                     jz         d|pj        dd          tE          |pj                  dk    rdnd            |pj        r j        r|pj        L                                }ΐta          j        dd|Φ          L                                }|r$|ΐ                    d	          d         dd         nd}|r@ty           dd          dk    r*	                      d|Ϧ           nH# t8          $ r Y n<w xY w|r6	                      dd|dd?         d           n# t8          $ r Y nw xY wt5          |pj        pd          rԉ xj        dz  c_         y                     jz         d            j        dk    r) y                     jz         d j         d           = y                     jz         dd]           d _                             |
          }}                     |                                |
|           d|}|ddddӜS d _         j        d`k    r|Odk    r xj        dz  c_                             |p|O          }zt          |z8                    d8          pdL                                          }t          |z8                    d<          t                    r5t          |z8                    d<d          L                                          nd}t          |z8                    d                    }|s|s|Ґr)|
r|
dS         nd}t          |t                    r|Ӡ8                    d          nd}|z8                    d          }t          |t                    o|Ӡ8                    d3          d4k    o~|Ӡ8                    d>          dk    oe|Ӡ8                    d8          pd|z8                    d8          pdk    o5|Ӡ8                    d<          pd|z8                    d<          pdk    o||k    }|s+|
2                    |z                                |z            j        d$k     rL j3        s' y                     jz         d j         d           |
 _                             |
           @d _                             |
|           d|
|ddddӜS t9           d          rd _        |pj        r j3        s4 y                     jz         dtE          |pj                   d            j        rL|pj        D ]Dt          j?        dj        j         dj        j        ddÅ          d           E|pj        D ]zj        j         j/        vra                     j        j                  }|r<t           jz         dĐj        j         d|כ d           |אj        _        { fdƄ|pj        D             }|ؐrl xj        dz  c_        dM                    tA           j/                            }|d         }tE          |ڦ          dk    r|dd         dz   n|}ۉ y                     jz         d|ۛ dȉ j         d            j        d$k    rJ y                     jz         dɝd]           d _                             |
|           d|
|ddd|ۛ dӜS                      |p|O          }|
2                    |ܦ           |pj        D ]Uj        j         j/        vrdːj        j         d|ٛ }nd}|
2                    d6j!        |ݐdΜ           VCd _        g |pj        D ]j        j        }t          |t          tR          f          r"t          ju        |ަ          j        _        Q|ށ@t          |t                    s+t          |ަ          j        _        j        j        }|r|ޠL                                sdϐj        _        	 t          jt        |ަ           # t          j"        $ r=}2                    j        j        t          |          f           Y d}~d}~ww xY wrt!          fdЄ|pj        D                       }|r_ y                     jz         d|Odҝd]           d _                             |                                |
|           d|
|ddddӜS  xj        dz  c_        d         \  } y                     jz         d| dԐ             j        d$k     r( y                     jz         d j         d՝           E y                     jz         d՝           d _                             |p|O          }|
2                    |           dք D             }|pj        D ]`j        j        |v r(tG          fdׄD                       }d| dٝ}nd}|
2                    d6j!        |dΜ           aFd _         $                    |pj                  |p_         %                    |pj                  |p_                             |p|O          }|pj        pd}|r                     |          r| _        tM          h dۣ          tO          fd܄|pj        D                       }| _        |r                                 rd _        nI j3        rB                     |          L                                }|r y                    d|            d}|
rt          |
dS         t                    ri|
dS         8                    d?          rN|
i                                 d}|
r6t          |
dS         t                    r|
dS         8                    d?          N|rd _        d _        d _        |
2                    |ܦ                                |ܦ            j(        r(	  (                    d           n# t8          $ r Y nw xY w )                    |p|
||           d}!d _*        dބ |pj        D             }|dhk    r j!                                          jA        }|j+        dk    r|j+        |j,        z   }nt          |
          } j@        rT|                    |          r? 4                    d            I                    |
| jA        j+        |%          \  }
}d}|
 _                             |
           I|pj        pd}d _                             |          sFty           dd          pd}                     |          rud}$                     |          L                                }tH          %                    dtE          |                                          d           |}d _-        ntty           dd          }|rty           dd          rzd}$tH          %                    d                                d           d _        d _        d _                             |          L                                }d _-        nԐt!          d |
dd         D                       }|rty           dd          sd _        d _        d _        tH          %                    d                                d                                |p|O          }d|d8<   |
2                    |           |
2                    ddd           Lt          ty          |pd<d          p"ty          |pd=d          pty          |pd2d                    }|r j        dk     r xj        dz  c_        tH          %                    d j                                        d j         d                                |pdƦ          }zd|zd?<   |
2                    |z           |
 _                             |
           M                     |          L                                 }|o j        dk    }|rh|r|rd j        d$k     rY xj        dz  c_        tH          =                    d j         j&                                        d j         d           M|r j        rtH          =                    d j         j&         j'                                        d                                            rWd _                             d j&         d j'         d           tH          %                    d j&         j'                   NYd}$ .                    |p          }6                     |p|O          }ܐd|d8<   |
2                    |ܦ           |6rWtE          |6          d?k    r|6dd?         dz   n|6}tH          =                    d|                                d           nQtH          =                    d j         j&         j'                                        d j        rdnd z              d}nd _        d _         j        d`k    r j/        r|dk     r /                    |||
          r|dz  }                     |pdƦ          }z|
2                    |z                                |z           ddd}{|
2                    |{           |
 _                             |
           Pd}|"r	|"|z   }d}"d}                      |          L                                }                     |p|O          }|
rt          |
dS         t                    rg|
dS         8                    d?          rL|
i                                 |
r6t          |
dS         t                    r|
dS         8                    d?          L|
2                    |           d|O d}$ j3        s 4                    d| d           n# t8          $ r}d| dNt          |           	 t          d            n4# t`          tP          f$ r tH                                         Y nw xY wtH          ?                    d|d	           t          tE          |
          dz
  dSdS          D ]}0|
|0         }1t          |1t                    s n|18                    d3          d6k    r;|18                    d3          d4k    r|18                    d5          rsd
 |
|0dz   d         D             }|1d5         D ]Rrt          t                    sd         |vr)d6d         d dΜ}|
2                    |           S | j         dz
  k    r4ddd          d}$d }|
2                    d4|d           Y d}~n1Y d}~nd}~ww xY w| j         k     r j!        jY        dk    R jZ        R|| j         k    s j!        jY        dk    rrd| d1 j          d}$                     d| d1 j          d            j3        s" 4                    d0| d1 j          d            1                    |
|          }|duo
| j         k     } 2                    |
||                                |                                |
|           |
r|
dS         8                    d3          nd}d}|d6k    rt          |
          D ]}*|*8                    d3          d4k    rl|*8                    d5          rW|*d5         }|rKt          |d         t                    r0|dS         8                    dBi           8                    d          } nt          d |
D                       }|rtE          |          nd} j!        r j!        j`        nd} j!        r j!        ja        nd}d}|$ j&        | j         ||||| j        pdf
} |d6k    r |stI          j=        d|z   dz   g| |R   ntI          j%        |g| R   |ry|sw	 ddl:m;}  |d j        ||tS          |
           j&        ty           dd          pd           n3# t8          $ r&}tH          =                    d|           Y d}~nd}~ww xY wd}t          |
          D ];}1|18                    d3          d4k    r |18                    d<          r|1d<         } n<i d|d|d|
d|d|d dd!|d"ty           d#d          do j&        d j'        d7 j        d$ j        d% j        d& j        d j        d' j        d j         j         j        ty           jA        d(d          pd j         j         j        d)}d _-        |r jU        r jU        |d*<                                     d _	        d} je        dk    r# jf         je        k    rd; j/        v r
d}d _f         jV        rM|rK|rI	  jV        3                    ||            jV        4                    |           n# t8          $ r Y nw xY w|rA|s?|s|r:	  5                    tS          |
          ||+           n# t8          $ r Y nw xY w	 ddl:m;}  |d, j        || j&        ty           dd          pd-           n3# t8          $ r&}tH          =                    d.|           Y d}~nd}~ww xY w|S (0  a[  
        Run a complete conversation with tool calling until completion.

        Args:
            user_message (str): The user's message/question
            system_message (str): Custom system message (optional, overrides ephemeral_system_prompt if provided)
            conversation_history (List[Dict]): Previous conversation messages (optional)
            task_id (str): Unique identifier for this task to isolate VMs between concurrent tasks (optional, auto-generated if not provided)
            stream_callback: Optional callback invoked with each text delta during streaming.
                Used by the TTS pipeline to start audio generation before the full response.
                When None (default), API calls use the standard non-streaming path.
            persist_user_message: Optional clean user message to store in
                transcripts/history when user_message contains API-only
                synthetic prefixes.
                    or queuing follow-up prefetch work.

        Returns:
            Dict: Complete conversation result with final response and message history
        r   )set_session_contextNFr]  u~   🔌 Detected stale connections from a previous provider issue — cleaned up automatically. Proceeding with fresh connection.P   r  r  rY  zPconversation turn: session=%s model=%s provider=%s platform=%s history=%d msg=%rr  r  r   r  Tr  r  u   💬 Starting conversation: 'r  r  rT  rM  )invoke_hookr  r  )r<  r+  r  z on_session_start hook failed: %sz*Session DB update_system_prompt failed: %s)rM  r   zDPreflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)r  u   📦 Preflight compression: ~z tokens >= z
 thresholdr  )r  r  pre_llm_callr  )r<  rY  r  is_first_turnr+  r  	sender_idr  r  zpre_llm_call hook failed: %sinterrupted_by_useru2   
⚡ Breaking out of tool loop due to interrupt...zstarting API call #budget_exhaustedu%   
⚠️  Iteration budget exhausted (rc  z iterations used)r   r  r   r  r  r   c                     g | ]N}t          |t                    |d          d                             |                    d                    dOS )r   rh   r   )rh   r?  r  )r   r   _results_by_ids     rR   r   z,AIAgent.run_conversation.<locals>.<listcomp>!  si     * * *
 %'#-b$#7#7*,.zN6,B.<.@.@.N.N!" !"* * *rT   z&step_callback error (iteration %s): %sr  r  r  rP  r  r  )	cache_ttlnative_anthropicr   r   )r  r  )
separators	sort_keysc              3   N   K   | ] }t          t          |                    V  !d S r_   rE  rU  s     rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>P"  s.      DDc#c((mmDDDDDDrT   u   🔄 Making API call #u      📊 Request size: z messages, ~z
 tokens (~z chars)u      🔧 Available tools: )brainsparklepulsemoonstarr\  zAPI Request - Model: z, Messages: z	, Tools: zLast message role: r2  zTotal message size: ~z tokensrR  r   )nous_rate_limit_remainingformat_remainingu,   Nous Portal rate limit active — resets in r3  u   ⏳ z Trying fallback...r  zg

No fallback provider available. Try again after the reset, or add a fallback provider in config.yaml.)r  r   	api_callsr  rR  r  rZ  r-  pre_api_request)r  r<  r  r+  r%  r  r&  rk  rK  
tool_countapprox_input_tokensrequest_char_countrH  HERMES_DUMP_REQUESTS	preflightr  c                  v    r                     d           d  j        r                     d           d S d S r  )rR  r@  )rP   thinking_spinners   rR   _stop_spinnerz/AIAgent.run_conversation.<locals>._stop_spinner"  sT    + 4,11"555/3,1 7 222666667 7rT   r  r~  rE  r|  u   ⏱️  API call completed in rn  rR  r+  zN/AzAPI Response received - Model: z	, Usage: r  r  zresponse is Nonezresponse.output is not a listrG  zaCodex response.output is empty but output_text is present (%d chars); deferring to normalization.rQ  r  zeCodex response.output is empty after stream backfill (status=%s, incomplete_details=%s, model=%s). %sz	api_mode=rx  zresponse.output is emptyzresponse.content is not a listzresponse.content is emptyr  z#response has no 'choices' attributezresponse.choices is Nonezresponse.choices is emptyu   (´;ω;`) oops, retrying...u<   ⚠️ Empty/malformed response — switching to fallback...Unknownr  rw  r  r  zmodel=c                 n    i | ]2\  }}|                     d           |t          |          dd         3S )r  Nr"  )r  r[   r(  s      rR   r+  z,AIAgent.run_conversation.<locals>.<dictcomp>n#  sA    )v)v)vdadedpdpqtdudu)v!SVVDSD\)v)v)vrT   z*Response attributes for invalid response: r	  i  z-upstream provider timed out (Cloudflare 524, z.0frT  i  zupstream gateway timeout (504, r  z'rate limited by upstream provider (429))r  i  zupstream server error (r  )i  i  zupstream provider overloaded (r  zupstream error (code r  zfast response (rh  u   s) — likely rate limitedzslow response (u   s) — likely upstream timeoutzresponse time u&   ⚠️  Invalid API response (attempt z): u      🏢 Provider: u      📝 Provider message: u      ⏱️  u   ⚠️ Max retries (u.   ) for invalid responses — trying fallback...u   ❌ Max retries (z,) exceeded for invalid responses. Giving up.zInvalid API response after z	 retries.z
 retries: )r   r  r  r  rR  r`  r  )
base_delay	max_delayu   ⏳ Retrying in zs (z)...zInvalid API response (retry z | Provider: u3   ⚡ Interrupt detected during retry wait, aborting.z$Operation interrupted during retry (z
, attempt r'  )r  r   r  r  interruptedr  r  zretry backoff (z), zs remainingr  rU  >   r  r:  r  )end_turnr  rH  stop_sequenceuA   ⚠️  Treating suspicious Ollama/GLM stop response as truncateduQ   ⚠️  Response truncated (finish_reason='length') - model hit max output tokens)r\  r[  r   r   z8<(?:think|thinking|reasoning|REASONING_SCRATCHPAD)[^>]*>zModel used all output tokens on reasoning with none left for the response. Try lowering reasoning effort or increasing max_tokens.uV   💭 Reasoning exhausted the output token budget — no visible response was produced.u  ⚠️ **Thinking Budget Exhausted**

The model used all its output tokens on reasoning and had none left for the actual response.

To fix this:
→ Lower reasoning effort: `/thinkon low` or `/thinkon minimal`
→ Increase the output token limit: set `model.max_tokens` in config.yaml)r  r   r  r  partialr  u   ↻ Requesting continuation (z/3)...z[System: Your previous response was truncated by the output length limit. Continue exactly where you left off. Do not restart or repeat prior text. Finish the answer directly.]z9Response remained truncated after 3 continuation attemptsu=   ⚠️  Truncated tool call detected — retrying API call...uf   ⚠️  Truncated tool call response detected again — refusing to execute incomplete tool arguments.z-Response truncated due to output length limitu3      ⏪ Rolling back to last complete assistant turnu-   ❌ First response truncated - cannot recoverz3First response truncated due to output length limitr  )r  completion_tokensr  _context_probed_context_probe_persistableu   💾 Cached context length: z tokens for z cache=r
  r"  z%)zHAPI call #%d: model=%s provider=%s in=%d out=%d total=%d latency=%.1fs%sr$  )r%  r  r$  includedsubscription_included)input_tokensoutput_tokenscache_read_tokenscache_write_tokensreasoning_tokensestimated_cost_usdcost_statuscost_sourcebilling_providerbilling_base_urlbilling_moder+  zToken usage: prompt=r  z, completion=r  z, total=r  cache_read_input_tokenscache_creation_input_tokensprompt_tokens_detailscached_tokensr 	  u      💾 Cache: z	 tokens (z% hit, z	 written))clear_nous_rate_limitz
API call #z
 completedu    ⚡ Interrupted during API call.z3Operation interrupted: waiting for model response (zs elapsed).u   (╥_╥) error, retrying..._unicode_sanitization_passesr  z'ascii'r   uH   ⚠️  Stripped invalid surrogate characters from messages. Retrying...rL  r   r3  rF  r  u   ⚠️  API key contained non-ASCII characters (bad copy-paste?) — stripped them. If auth fails, re-copy the key from your provider's dashboard.ud   ⚠️  System encoding is ASCII — stripped non-ASCII characters from request payload. Retrying...uT   ⚠️  System encoding is ASCII — enabling full-payload sanitization for retry...r  r  r  i@ r%  )r%  r+  r  r  num_messageszTError classified: reason=%s status=%s retryable=%s compress=%s rotate=%s fallback=%s)r  r  r  r  r^  r  u8   🔐 Codex auth refreshed after 401. Retrying request...r\  u<   🔐 Nous agent key refreshed after 401. Retrying request...rC  r  uC   🔐 Anthropic credentials refreshed after 401. Retrying request...zBearer (OAuth/setup-token)zx-api-key (API key)u-   🔐 Anthropic 401 — authentication failed.z   Auth method: r  z   Token prefix: z   Token: (empty or short)z   Troubleshooting:)display_hermes_homeu"        • Check ANTHROPIC_TOKEN in z+/.env for Hermes-managed OAuth/setup tokensu$        • Check ANTHROPIC_API_KEY in z)/.env for API keys or legacy token valuesuL        • For API keys: verify at https://console.anthropic.com/settings/keysuD        • For Claude Code: run 'claude /login' to refresh, then retryu=        • Legacy cleanup: hermes config set ANTHROPIC_TOKEN ""uA        • Clear stale keys: hermes config set ANTHROPIC_API_KEY ""r  uV   ⚠️  Thinking block signature invalid — stripped all thinking blocks, retrying...zP%sThinking block signature recovery: stripped reasoning_details from %d messageszAPI error recovery (attempt z;API call failed (attempt %s/%s) error_type=%s %s summary=%sr  z [HTTP r4  u!   ⚠️  API call failed (attempt u      🔌 Provider: z	  Model: u      🌐 Endpoint: u      📝 Error: r  r  r  u      📋 Details: u      ⏱️  Elapsed: zs  Context: z msgs, ~zsupport tool useu$      💡 No OpenRouter providers for z1 support tool calling with your current settings.zU      Your provider_routing.only restriction is filtering out tool-capable providers.zY      Try removing the restriction or adding providers that support tools for this model.zH      Check which providers support tools: https://openrouter.ai/models/u?   ⚡ Interrupt detected during error handling, aborting retries.z+Operation interrupted: handling API error (r  r  uO   ⚠️  Anthropic long-context tier requires extra usage — reducing context: r  u   🗜️ Context reduced to z tokens (was z), retrying...u9   ⚠️ Rate limited — switching to fallback provider...)record_nous_rate_limitr  r  )r  r  u   ❌ Max compression attempts (z&) reached for payload-too-large error.uR      💡 Try /new to start a fresh conversation, or /compress to retry compression.z413 compression failed after z
 attempts.z5Request payload too large: max compression attempts (z
) reached.)r   r  r  r  r  rR  compression_exhaustedu@   ⚠️  Request payload too large (413) — compression attempt u   🗜️ Compressed z messages, retrying...u2   ❌ Payload too large and cannot compress further.z/413 payload too large. Cannot compress further.z9Request payload too large (413). Cannot compress further.@   uM   ⚠️  Output cap too large for current prompt — retrying with max_tokens=z (available_tokens=z; context_length unchanged at z!Context compression failed after z3Context length exceeded: max compression attempts (u)   ⚠️  Context limit detected from API: u3   ⚠️  Context length exceeded — stepping down: uM   ⚠️  Context length exceeded at minimum tier — attempting compression...u   🗜️ Context too large (~u    tokens) — compressing (u8   ❌ Context length exceeded and cannot compress further.u      💡 The conversation has accumulated too much content. Try /new to start fresh, or /compress to manually trigger compression.zContext length exceeded: z! tokens. Cannot compress further.zContext length exceeded (z" tokens). Cannot compress further.u!   ⚠️ Non-retryable error (HTTP u   ) — trying fallback...non_retryable_client_error)r  r  u   ❌ Non-retryable error (HTTP u%   ❌ Non-retryable client error (HTTP z). Aborting.uK      💡 Codex OAuth token was rejected (HTTP 401). Your token may have beenz?      refreshed by another client (Codex CLI, VS Code). To fix:z?      1. Run `codex` in your terminal to generate fresh tokens.z3      2. Then run `hermes auth` to re-authenticate.u9      💡 Your API key was rejected by the provider. Check:u-         • Is the key valid? Run: hermes setupu+         • Does your account have access to r  rl  u?         • Check credits: https://openrouter.ai/settings/creditsu6      💡 This type of error won't be fixed by retrying.zNon-retryable client error: i  rJ  uU   ⚠️  Skipping session persistence for large failed session to prevent growth loop.)r  r  u"   ) exhausted — trying fallback...u   ❌ Rate limited after u    retries — u   ❌ API failed after u      💀 Final error: c              3       K   | ]}|v V  	d S r_   ro   )r   r  r  s     rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>'  s7       $ $qAN $ $ $ $ $ $rT   )r  r  r  r  r  r  u      💡 The provider's stream connection keeps dropping. This often happens when the model tries to write a very large file in a single tool call.z~      Try asking the model to use execute_code with Python's open() for large files, or to write the file in smaller sections.zP%sAPI call failed after %s retries. %s | provider=%s model=%s msgs=%s tokens=~%smax_retries_exhaustedzAPI call failed after u  

The provider's stream connection keeps dropping — this often happens when generating very large tool call responses (e.g. write_file with long content). Try asking me to use execute_code with Python's open() for large files, or to write in smaller sections.r   r  r  r*  rS  g      N@u#   ⏱️ Rate limit reached. Waiting zs before retry (attempt zs (attempt z4Retrying API call in %ss (attempt %s/%s) %s error=%sz<Operation interrupted: retrying API call after error (retry zerror retry backoff (interrupted_during_api_call!all_retries_exhausted_no_responseu:   ❌ All API retries exhausted with no successful response.r  r  post_api_request)r  r<  r  r+  r%  r  r&  rk  api_durationrP  rK  response_modelr  assistant_content_charsassistant_tool_call_countu   🤖 Assistant: z,</?(?:REASONING_SCRATCHPAD|think|reasoning)>r"  	_thinkingzreasoning.availableuL   ⚠️  Incomplete <REASONING_SCRATCHPAD> detected (opened but never closed)u   🔄 Retrying API call (z/2)...uA   ❌ Max retries (2) for incomplete scratchpad. Saving as partial.z/Incomplete REASONING_SCRATCHPAD after 2 retriesr  u0   ↻ Codex response incomplete; continuing turn (z/3)z@Codex response remained incomplete after 3 continuation attempts_codex_incomplete_retriesu   🔧 Processing z tool call(s)...zTool call: z with args: r   u   🔧 Auto-repaired tool name: 'z' -> 'c                 N    g | ]!}|j         j        j        v|j         j        "S ro   )r   rh   rX  )r   r   rP   s     rR   r   z,AIAgent.run_conversation.<locals>.<listcomp>4)  s;     * * *-/;+43HHH (HHHrT   u   ⚠️  Unknown tool 'u2   ' — sending error to model for self-correction (uI   ❌ Max retries (3) for invalid tool calls exceeded. Stopping as partial.z#Model generated invalid tool call: zTool 'z#' does not exist. Available tools: zZSkipped: another tool call in this turn used an invalid name. Please retry this tool call.)r   r  r   r  c              3      K   | ]P}|j         j        d  D             v |j         j        pd                                                    d           V  QdS )c                     h | ]\  }}|S ro   ro   )r   r  r  s      rR   r  z5AIAgent.run_conversation.<locals>.<genexpr>.<setcomp>})  s    3T3T3T$!QA3T3T3TrT   r  )}r4  N)r   rh   r   r  r  )r   r   invalid_json_argss     rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>z)  sw       ) ) "!{/3T3TBS3T3T3TTT "$!6!<" D D F F O OPZ [ [[TTTT) )rT   u>   ⚠️  Truncated tool call arguments detected (finish_reason=u   ) — refusing to execute.u1   ⚠️  Invalid JSON in tool call arguments for 'rS  u;   ⚠️  Injecting recovery tool results for invalid JSON...c                     h | ]\  }}|S ro   ro   )r   rh   r  s      rR   r  z+AIAgent.run_conversation.<locals>.<setcomp>)  s    ,S,S,SgdAT,S,S,SrT   c              3   B   K   | ]\  }}|j         j        k    |V  d S r_   r   )r   r  r  r   s      rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>)  s9      .h.hTQRSWYWbWgRgRgqRgRgRgRg.h.hrT   zError: Invalid JSON arguments. z_. For tools with no required parameters, use an empty object: {}. Please retry with valid JSON.z;Skipped: other tool call in this response had invalid JSON.>   r  r  r  r   c              3   4   K   | ]}|j         j        v V  d S r_   r   )r   r   _HOUSEKEEPING_TOOLSs     rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>)  sB       0 0 " K,0CC0 0 0 0 0 0rT   u     ┊ 💬 c                 &    h | ]}|j         j        S ro   r   r   s     rR   r  z+AIAgent.run_conversation.<locals>.<setcomp>*  s     Y Y Yb!1 Y Y YrT   execute_codeu     ⟳ compacting context…r9  partial_stream_recoveryuG   Partial stream content delivered (%d chars) — using as final responseuD   ↻ Stream interrupted — using delivered content as final response_last_content_with_tools$_last_content_tools_all_housekeepingfallback_prior_turn_contentuO   Empty follow-up after tool calls — using prior turn content as final responseuM   ↻ Empty response after tool calls — using earlier content as final answerc              3   H   K   | ]}|                     d           dk    V  dS rT  r  r   r4  s     rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>*  sE       . . ! EE&MMV3. . . . . .rT   _post_tool_empty_retrieduH   Empty response after tool calls — nudging model to continue processinguD   ⚠️ Model returned empty after tool calls — nudging to continuern  z~You just executed tool calls but returned an empty response. Please process the tool results above and continue with the task.uM   Thinking-only response (no visible content) — prefilling to continue (%d/2)u7   ↻ Thinking-only response — prefilling to continue (z/2)uB   Empty response (no content or reasoning) — retry %d/3 (model=%s)u/   ⚠️ Empty response from model — retrying (uO   Empty response after %d retries — attempting fallback (model=%s, provider=%s)uL   ⚠️ Model returning empty responses — switching to fallback provider...u   ↻ Switched to fallback: z<Fallback activated after empty responses: now using %s on %sempty_response_exhaustedzaReasoning-only response (no visible content) after exhausting retries and fallback. Reasoning: %su[   ⚠️ Model produced reasoning but no visible response after all retries. Returning empty.zfEmpty response (no content or reasoning) after %d retries. No fallback available. model=%s provider=%su/   ❌ Model returned no content after all retriesz and fallback attempts.z#. No fallback providers configured.)rY  rZ  r   zr[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]ztext_response(finish_reason=u"   🎉 Conversation completed after z OpenAI-compatible API call(s)z)Error during OpenAI-compatible API call #u   ❌ z Outer loop error in API call #%dr  c                 z    h | ]8}t          |t                    r!|                    d           dk    0|d         9S r  r  r/	  s     rR   r  z+AIAgent.run_conversation.<locals>.<setcomp>+  sP     ( ( ( !)!T22( 89uuV}}7N7N n-7N7N7NrT   r   zError executing tool: zerror_near_max_iterations(z0I apologize, but I encountered repeated errors: zmax_iterations_reached(u#   ⚠️ Iteration budget exhausted (u   ) — asking model to summariseu   ) — requesting summary...rh   c              3      K   | ]I}t          |t                    r2|                    d           dk    0|                    d          EdV  JdS )r   r  r   r   Nr  r/	  s     rR   r   z+AIAgent.run_conversation.<locals>.<genexpr>+  sf       
 
!T""
'(uuV}}'C'ClH[H['C 'C'C'C'C
 
rT   zuTurn ended: reason=%s model=%s api_calls=%d/%d budget=%d/%d tool_turns=%d last_msg_role=%s response_len=%d session=%sz>Turn ended with pending tool result (agent may appear stuck). z last_tool=%spost_llm_call)r<  rY  assistant_responser  r+  r  zpost_llm_call hook failed: %sr  last_reasoningr   r  r  r  r  response_previewed_response_was_previewedr  r  r  r	  r  )r  r  r  r	  r	  r	  interrupt_message)r  r  r  rr  )r<  r  r  r+  r  zon_session_end hook failed: %s)r	  (6  rx   r0  r  r<  r  rZ   r[   r   r   r7  r:  r;  r]  r^  _invalid_tool_retries_invalid_json_retries_empty_content_retries_incomplete_scratchpad_retriesr	  _thinking_prefill_retriesr1	  r+	  r,	  r  r	  r&  r  r  r   r  r,  rz   r,  rR  r\   r  r2  r3  r+  r%  r  r   rn  	has_itemsr  r  rr  rX  ro  rt  r   r2  r
  rd  rg  get_sessionr   r  r  r  rg   rl  r  r   r  r  r  r  r+   r   r  r  r  r  r   r   r   rV  r~   rs  rt  r  rU  r  r  r  rx  on_turn_startprefetch_allr   r)  rf  new_turnr.  r]  r   r   r{   rC  r  r  r  ru  r  r   r!  r  r  r3  rL  r  r&  r4   r'  r  r   r   r  r   r  r*   r  r5  r  r  r@   get_thinking_facesget_thinking_verbsr@  r  r  r  r  r1  r   r*  agent.nous_rate_guardr  r  r   r  ImportErrorrc  r  r%  r   rE  r  rH  rI   rG  r  r  r  ra  rR  rL  r  r  rS  rR  r  rw  r  varsr   r   r  rY   r  r   rZ  r  stop_reasonrP  rX  r@  r   rE  r@  r  r   r  r   rc  r  r>  r  r?   r  r  r  update_from_responser/   r  r  r  r  r  r  r  r  r  r  r  r  r 	  r  r	  r>   
amount_usdr  r  rQ  r  r  r  update_token_countsr	  rX  UnicodeEncodeErrorr  r   r  r   rF  r$  rE  r  r    r  r   r  	retryableshould_compressshould_rotate_credentialshould_fallbackr)  r  r
  rG  r?  r  r  rC  r  r	  r!   thinking_signaturer   rj   r  ry  r  r6  long_context_tierr  r!  r   r  has_availabler	  payload_too_largecontext_overflowr.   r   rb  r-   r,   
overloadedis_authr  r   r   r   rq  r  r>  r#  r=  r   r  rF   rr  r   rh   r   r  rY  r   r  nextr  r  	frozensetallrD  r  r8  r  r  r9	  r  r  rX   r  r  sync_allqueue_prefetch_allr  (
  rP   rY  r  r  r  r  r  r  r  _msg_previewr   original_user_message_should_review_memoryuser_msgcurrent_turn_user_idxstored_promptsession_row_invoke_hookr  r  active_system_prompt_preflight_tokens_pass	_orig_len_plugin_user_context_pre_results
_ctx_partsrf  rk  r  r  codex_ack_continuationslength_continue_retriestruncated_tool_call_retriestruncated_response_prefixcompression_attempts_turn_exit_reason	_turn_msg_ext_prefetch_cache_query
prev_tools_idx_m
_fwd_start_tm_tcid	_step_errrI  r  r   r  _injections_fenced_baserk  r  r  r  amtcsnew_tcsargs_objtotal_charsr  r  verbr]  api_start_timer  r  primary_recovery_attemptedmax_compression_attemptscodex_auth_retry_attemptedanthropic_auth_retry_attemptednous_auth_retry_attemptedthinking_sig_retry_attemptedr   restart_with_compressed_messages restart_with_length_continuationrP  r  r$  r  _fmt_nous_remaining_nous_remaining	_nous_msgr  _use_streamingr  r	  
resp_modelresponse_invaliderror_detailsoutput_items	_out_text_out_text_stripped_resp_status_resp_incompletecontent_blocksr  
resp_attrs_resp_error_code	_code_raw_failure_hintcleaned_provider_errorr  	sleep_end_backoff_touch_counterrQ  r  incomplete_reasonstop_reason_maprV  _trunc_content_trunc_has_tool_calls
_trunc_msg_text_parts_blk_has_think_tags_thinking_exhausted_exhaust_error_exhaust_responseinterim_msgcontinue_msgpartial_responserolled_back_messagescanonical_usager  r  r  
usage_dictctx
_cache_pctcost_resultr9  writtendetailsr  hit_pctr	  api_elapsedr  _err_str_is_ascii_codec_surrogates_found_messages_sanitized_prefill_sanitized_tools_sanitized_system_sanitized_sanitized_system_sanitized_ephemeral_headers_sanitizedr  _credential_sanitized_raw_key
_clean_key_any_sanitizedr  r  _compressor_ctx_len
classifiedrecovered_with_poolr  r   auth_method_dhh_fn_dhhelapsed_timer  _error_summary	_provider_model_status_code_str	_err_body_err_body_str_reduced_ctxr  old_ctxoriginal_lenis_rate_limitedr  pool_may_recoverr	  	_err_resp	_err_hdrsis_payload_too_largeis_context_length_erroravailable_outsafe_outparsed_limitnew_ctxis_local_validation_erroris_client_error_final_summary_is_stream_drop_final_response_retry_after_resp_headers_ra_rawr  r  r   r   _assistant_tool_calls_assistant_text_think_text
first_lineinterim_has_contentinterim_has_reasoninginterim_has_codex_reasoninglast_msglast_codex_itemsinterim_codex_itemsduplicate_interimrepairedinvalid_tool_callsr  invalid_nameinvalid_previewrl  r   r*  
_truncatedr   recovery_assistantinvalid_nameserrtool_resultturn_content_all_housekeepingclean_had_prefill	_tc_names_real_tokens_partial_streamed
_recoveredfallback_prior_was_tool
_nudge_msg_has_structured_truly_empty_prefill_exhaustedreasoning_preview	final_msganswered_idserr_msgr  _last_msg_role_last_tool_name_tcs_turn_tool_count	_resp_len_budget_used_budget_max	_diag_msg
_diag_argsr7	  r?  _should_review_skillsr'	  r  r  r#	  r   r  s
  `                                                                                                                                                                                                                                                                   @@@@@@rR   r  zAIAgent.run_conversation-   s   < 	 	766666DO,,,
 	%%'''
 lC(( 	>/==L*C00 	N#78L#M#M  lC(( 	:+L99L*C00 	J#34H#I#I  !0)-&.B+#8s4:<<'8'8 &'"%&"&'#./+)*&)*&(-%(,%491#( ,-)
 =0001133 %%&  
     $ 	-,,...(,D%
 !00C D D 7:,6G6G"6L6LSbS)E11R^#++D#66^O%vtz4=3MIM&Y,@,FB(G(G		
 	
 	
 2FM4,---2
   	;(8(B(B(D(D 	;$$%9::: 	" 9M8X 4 4^j
 !&'!++ 555& 6$$)$$'4+FFF(,%+,( #|<<!!! #H 1)>& 	|z\#2#=NzY\]iYjYjmoYoYoPUPUuwzzz{{{ %- M# (8 "&"2">">t"O"OK" Q(3(H(H(PD    D  V .;** .2-F-F~-V-V*
	LNNNNNN L*#'?"j!(z4!@!@!FB	     ! L L LNN#EsKKKKKKKKL # VV(==dotOijjjj$ V V V%QSTUUUUUUUUV  $9 $;	H 7 G"&"9"H!IKL!M M M
 !>28bj(D! ! ! !D$;$LLLZ(,,.?CCJ.=AA    $$U8IU U U"5FTU U U   #1XX  E #HI595K5K .@Q 1 6L 6 62H2 8}}	11 ,0( 34D/56D248D1@ED=/4D,(E &:&@b"j0D) ) )%
 )4+B+SSS T  "	@FFFFFF'<?2%)(^^#'(<#=#==j z488>B!$
D99?R	 	 	L %'J! ) )a&& )155+;+; )%%c!I,&7&788883'' )AGGII )%%a((( ?'-{{:'>'>$ 	@ 	@ 	@NN93????????	@ "#"#&'#$&! %
 %.$<$>$>$D!
 	ud7888$ 	:4!:;;;49D11&*D#49D1
  	5?@UWZ5[5[c11ac	$2243H)TTTT    ! 	2<=RTW2X2X`..^`&*&:&G&G&O&O&USU##     3338M8WZ[8[8[`d`w8[ ))+++ ( "$9! \$$%Z[[[aN#1D   !G~!G!GHHH
 & */''*2244 $6! _$$  &^dNcNh  &^  &^ko  lA  lK  &^  &^  &^  _  _  _ !-f!#J$-hx.@.@$A$A " "b66&>>[88RVVL=Q=Q8),X)=J-/N'/
'< S S#&776??f#<#<$)E(+(?(?#( !S<?GGIr<R<RN5$9* * * *
 +-\*:* * *J "E&&~zBBBB  f f fLL!I>[deeeeeeeef
 *Q..&$*???''1,'' L%h// .- .-S((** ///CGGFOOv4M4M"$K* 8"<=P"Q"Q" 8'..w777+ A#**+?@@@" [ 'Ir : :%eS11 [16&++kBZBZ1ZGI. 776??k11%(WW[%9%9N% F7E 34 '))KK,,,"g--KK000/666
 3355 F<<WEEE ##G,,,,  49r+ f$4v$=@\$\#c#c#e#e 
   `)1>N O OPS__ $ F"29QQ
 )$*? @ @ F FHC ''
S(8#((**EEEE ' `<\UYUdx|  yF  J^  y^   `   `   `  66|DDL # : :bffY//55 :$&yM$7$7$9$9ByM" + +ff\**  ' 'B!"d++ !
b0@0@
!'+z"Z.2M'N'NH"B "
 5"$Z.5 +TZ$,.2." ." ."5 5 " "BB  ) ! ! ! D!NN2&&&&#*<   *,777 DD|DDDDDK:<HHM  $? -r$/rrrrZ^Zmrrrsss  X  Xs<GXGX  X  Xfs  X  X  X  BM  X  X  X  X  Y  Y  Ypp]a]gJn#dj///mnppqqqq }]%E%G%GHH}]%E%G%GHH) 	- **d+>+>T+>+>+>????3355 -$:Z:Z:\:\ - $*=1^1^1^#_#_L'45H5Ht5H5H5HWcnrn|'}'}'}$$**,,, # P  Mdj  M  McRZmm  M  My}  zD  gKfijnjtfufufu  JK  M  M  N  N  NbH4`HRL4H4HZ`bbcccNmNNNNOOO!Y[[NKK).&'($',&+0*&+%+0(#O/4,/4,"MHJ++ =F**'        +D*C*E*E*6?Q;N;N!U-@-@-Q-Q!U !U !U & !LL#'? V V	 V V V&* )    !--.@Y.@.@AAA#::<< )./78 4=B : ( 11(<PQQQ%H9 %H %H %H
 -5-;-2*.)2$ $  '   $   o88:::!%!7!7!E!EJ0 B5jAAA}(999%)%E%Ej_d%E%e%e
RRRRRR$-$5'+'<"%)]%8b"&*%)]%)]%)]+9*-l*;*;'*4:+;'<'<0=/:'+      %    ''=>> U44Z4TTT7 7 7 7 7 7 &*N t%95AA 3).!7799 3 766666%gdHd&C&CTJJ 3-2N% L#'#I#I&} $J $ $ $(#?#?
#K#K#'9;;#?L ( 0(--b111+/(- 3..r222? l%j%jWc%j%j%j%jkkk+ XJR%]WXw%F%F%FX]
  'W
  'W  'Wovw  BI  pJ  pJ  ^U]e]k]k  PU  'W  'W  X  X  X (-$$&M}(999LTL`wx4'H'H'Hfj#+/3,)001CDDDD!+L$!?!? Q/3,)001PQQQQ!- Q
 )0-(N(NIFPQZ\_F`F`1h1B1B1Bfh.1 Q &%N$'(:$;$;!" !" !" !" 07x4/P/P3:8EY[_3`3` 0 &%W$02B$+Hgt$D$D$X$X$X$X$X!" !" !" 48 0 - 4 45O P P P*>>>OWOc9d)K)K)Kim#+/3,)001CDDDD!+ND!A!A N/3,)001QRRRR!/ N/3,)001LMMM#+78Y3O3O+S[ScSks{  tDSk/3,'/ - 4 45G H H H H%,Xy%A%A R - 4 45Z [ [ [ [!)!1!9 - 4 45O P P P P - 4 45P Q Q Q' D!+ 4,112OPPP/3,1 7 222666 $q(
  /#d6J2K2KKK --.lmmm6688 %*+K3409>6$ %.	(1# >'(B(B >x~ >(+HN(;(;I&x~zBB hx~G^ h080G0K0KO]f0g0g% >'(I*F*F >8K[ >(+H,<(=(=I )I55(5wxY`GaGa5fnft5,EX^,E,EM )I55(5)v)vd8nnFZFZF\F\)v)v)vJ#3 i '.g[e.g.g h h h ,0(# )'(B(B )x~ )(/(M(MI(0ZPT5U5U0,4N,>,>v,F,F	(4!)7:9~~$4$4(1:'> !) !) !)$(D!)
 ,s22,p\h,p,p,p,pMM-44,bl,b,b,b,bMM-44,VMM-;;,nFV,n,nZf,n,n,n,nMM-;;,`M],`,`,`MM-9,lDT,l,lXd,l,l,l,lMM)B..,jl,j,j,j,jMM)B..,nl,n,n,n,nMM,P\,P,P,P,PM  &X  &X_j  &X  &Xmx  &X  &X  ~B  ~G  ~G  HU  ~V  ~V  &X  &X  `d  e  e  e%Z%Z=%Z%Zbfggg151J1J91U1U.%k%kSi%k%kswxxx%S%SM%S%S[_```&+55 --  /A[  /A  /A  /A  B  B  B#::<< )./78 4=B : ( --.{+.{.{.{|||#MT_*o*oYd*o*o*oppp 11(<PQQQ,4-2-;)m{)m)m^k)m)m*.$ $  %5[S\a$b$b$b	%n%n%n%n%n[h%n%n%nvz{{{  )\{  )\  )\U`  )\  )\eieneno|e}e}  )\  )\  MZ  )\  )\  ]  ]  ] %)IKK)$;	12."ikkI55#8 
" $-t-t-t  }A  !B  !B  !B $ 5 5h@T U U U $ 4 4 6 6 6 7T]j  7T  7T  wB  7T  7T  EP  7T  7T  7T081?1637(" (" !" !JsOOO 3a725;q@@ $ 4 4%Qk %Q %QK %Q %Q'*9ty{{+B'C'C%Q %Q %Q!" !" !"# #ikkI55* ! }(999!(8T!B!B-4X?SUY-Z-Z*,0)%&8$?? \0B0F0Fx0P0P--078JHVZ0[0[-!\116GKj6j6j,4MM,2MM*>>>7=<go  CI  +J  +J(7(;(;H<PRX(Y(Y(0(8(;(I,4,<Q,?,G)??)-$  	5
 !LL#'? u u u&* )    -5M$00  &K  &K  &K  SW  X  X  X *.05-=,TTTIPQY[dIeIe  *Fjrjz  *F)9!)<)D)D  BFJU_-iWZD-Q-Q-QeiNeo4zD\[_9`9`4a4a4auz11!].BBB*,K(/)R(H(H R R#*4#>#>&#H#H$/$6$6wtVR7P7P$Q$Q$QGR-\TYY{-C-C-CX\N +/* ry [ . "0 0+ + !65  / "0t!;!wDDgDghvDwDw@w !:#1T#9 , /  !9 +
 !LL#'? !E !E !E&* )   !H . !889JKKK 11(<PQQQ2C,4-;-2+/)7$ $   =,TTT080@0C0K-#4#? $" 71 < 7.2.K.KL]_l.m.m ( < < <#4#< ![$=ARAZ$Z$=#:Q#>#>$(LL+/? )L )L,C)L )L )L%& %& %&
 17-i4& 4&L %-OOL$A$A$A=ED$:$($:$:8$D$D$DGK$D$)373K3KLe3f3f3l3l3n3n 0 $ < <=N O O O $ 5 5h@T U U U6F6N$081?16/3-h(" (" !"  =,TTT080@0C0K-0; "#>#B#B$?1$D$?$(LL+/?(y(y(y.2 %1 %& %& %& %- $'+  %_  %_  %_*. !- !" !" !" !% < <=N O O O $ 5 5h@T U U U6:081?16/3-\(" (" !" x==1,, LLDO)p)p)pqqq373Z3Z[c3d3d0 889JKKK 11(<PQQQ 37,@-;-2+/)X$ $  !LLDO)j)j)jrvLwww 11(<PQQQ26,4-;-2*.)^$ $  x11 jXhn jX*9$N%)]%)]+ + +
 )8(E,;,I)'6'C-:1B,8& &

 /DDZPPP
 #4#:<MuUU W"&"9"HC&t'>@\^cdd B 3DJs S S S $ 0 0DO  2A  2Aad  2A  2A  2Atxt~  2A  2A  !B  !B  !BFKD3CQVD3N22mC2266:KK6611\A11..!3..11_5QQ1122o6SS2266/:[[6677?;]]77559YY55 &(
*< d d *d?3T  *d  *dWd  *d  *dhkl{  mN  iN  O\  i\  *d  *d  *d  *dJf 2DJ@ZQZ)+<l(*	   ': J+%)]%)]$+D)R$@$@' ' ' '1= ;;u[E[?\?\\;;3>3E03>3E0  + % %% $ 0 D D$(O1@1M2A2O6E6W7F7Y5D5U'2'='I 8=[=S7T7T7TOS0;0B0;0B59]59]'2'9Z'G'G 2I1HMQ*.* !E !" !" !" !"" $- % % % $%  / x#M  +wOA\  +w  +w  +wmw  yL  nM  +w  +w  +w  Yc  dr  Ys  +w  +w  +w  x  x  x  3 X#}0DDD)0AZ\])^)^)cbc*1(.B_ab*c*c*hgh +2(.BY[_*`*`V])d/1)M)M)RQRcd\c*j'';OQR*S*S*XWXij%/%@FAG!v'<'<QRG#'? X $  .W  .WPV  .W  .W  .W[a  .W  .W  .Wnu  .W  .W  .W  CJ  .W  .W  .W  .W  !X  !X  !X&+O }..!SSSSSS113333( ! ! ! D!(()Pn)P)P)PQQQ'   ' 0(--b111+/(- 3..r222"&)++">KLLDO!U!U!U]aLbbb))(4HIII"&K%w[f%w%w%w%wNE    ' 0(--.LMMM+/(- 3..r222 ")-?@@ q%WTSqstEuEuxyEyEy#&y>>#7#7#9#9*3x*?*V7hCV,I(,S,S), % ==B== LL#'? | | |&* )    %HHHH* f%8<D5 3Ox2X2X/),== K <\ J J J
  **d;; J =j I I I16.)'$8JD*Q*QSWXX i5QRVRg5h5h 2/4,)'$*F*FMM Y3LTZ3X3X 005-)*>DD =4DEY4Z4Z 1#48L#L#L;L$8ARD$>8<$5)'$8QSW*X*XZ]^^ =7GHd7e7e 4#74;W#W#WCWD$@8<$516. $.gd<Ld.S.SUY#Z#Z!* 3 7 78I J J J%) -
  **:DAA e5RSc5d5d 2 5:1'.tY'E'E'KH' &-=h-G-G
#-#9#93=DL'1'$@PRV2W2WY]'^'^ %TIS(;I(F (/tXt'D'D'PU\]a]hjsUtUt'P>H(;<@$9$(LL+/? )[ )[ )[ /3	 %1 %& %& %& !==B== 3 !9#5!9#3!9 $5!9 $6	!9
 $9 +  . 	" $'+  %]  %]  %]*. !- !" !" !" !"
 !%'+  %M  %M  %M*. !- !" !" !" %HHHH"))]D"I"IK$($C$CI$N$NM #*$0Dd"K"KKQ\hw{4DfMMMbhH!3!!(z2!>!>!D"%dGR88>B&3'/:F%MS%6%6%6A" " "J LLn")/1G",j.H";Z=W	   <@;];]$/(7*4*;&3	 <^ < <8' + ! )::: M^;;'3.. : / 6:2EEDEQQ % LLDO)u)u)uvvv$HHHH);;; MV33'3.. 9 / 591DD4DPP %!T_"r"r"rsss$HHHH)==='3..#D*>?? / > / :>6KKKKKKIIKK %!T_"y"y"yzzz$HHHH"5FUoVYFZFZ&u&B&B`u___```OO+OOPPPTW  ^\_`c\d\dgi\i\iPP3ss8PPPPrv  sB  p^  p^  p^  _  _  _EEEFFFSSSSSS&wyy  F  FTX  F  F  F  G  G  G  F  FVZ  F  F  F  G  G  G~~~vvvwwwqqqrrruuuvvv #)^-NNN < O 8<4"* B BB)"d33 B "':D A A A# I I I"& %   
  A OS]]  
 !1$K#'9;;#?L((S{SS[SSS   "&i!9J #I 4 4 6 6I%)%>%>y%I%INNNU##"0022&   !(j) D DI#D*i@@E$T7I>>FCN'V'?'?'?'?'?TV$LLDO  "S  "SVa  "S  "Sdo  "S  "St~  "S  AQ  "S  "S  [_L  `  `  `LLDO!c!cy!c!c[a!c!ckoLpppLLDO!N!Nu!N!NVZL[[[LLDO!T!TN!T!T\`Laaa" k{S'8'8$+Ivt$D$D	@I(SItt(<(<t( k LLDO)])]m)])]eiLjjjLLDO  "[  "[  "[  "[  "[gjkwgxgx  "[  "[  CP  "[  "[  "[  "[  \  \  \ //11.);;#  N  NTZ  N  N  N"& %     1  LL#'?  !J  !J  !J&* )    !LL#'?  !N  !N  !N&* )    #  A  Ax~  A  A"& %    0 
%x%x%x  AE  F  F  F--h8LMMM,,... /X\f  /X  /Xjn  kD  kD  EH  IR  ES  ES  kT  kT  /X  /X  /X(0)7).+/          #*)]D"I"IK "(N,LLL'-%)%<
",";"\11&33&*j/;)-(/i(D(D)- 4     'z3DEE N=A
 :
 IN
 E LL#'? !K !K#* J!K !K3? J!K !K !K '+	 )    -1,/3KKK+.x==L=A=S=S (..;(9 >T > >:H&: 480"8}}|;;w?U?U $ 1 1%F,$Z %F %F,3$E%F %F %F!" !" !" !%
1CG @ % '1&7&1&.< 'O ' )4+?#dFZB[B[+[+[
  $4+/t+;+T@R@R@T@T(/ ) --.ijjj#::<< )./78 4=B : ( (! MV33&-1JJJ 3 K!TTTTTT(/	:t(L(LI $-!7	9d C C C26 & 32(1.;      ) ! ! ! D! '2  #)^-MM ) , .,1,/2JJJ LLDO  *\  *\[s  *\  *\  *\  dhL  i  i  i LLDO  *P  *P  *P  X\L  ]  ]  ]#MT_**[s***  A  A  A 11(<PQQQ,4-2-; *Fay  *F  *F  *F+/*.9=$ $       ))  +b  nB  +b  +b  E]  +b  +b  +b  c  c  c'*8}}9=9O9O$nM$5 :P : :6"6 04,x==<77 --.|L.|.|WZ[cWdWd.|.|.|}}} JqMMM?C<!EEEE LLDO)o)o)ow{L||| LLDO  *P  *P  *P  X\L  ]  ]  ]#MT_*m*m*mnnn 11(<PQQQ,4-2-;)d+/*.9=$ $       #)^-LL , / @%)%<
","; )QQZ([([(4 (+1mb.@'A'AH@HD= LL#'? !q !q<D I!q !q5B p!q !qdk p!q !q !q '+	 )    1A5036NNN $  .D  .D_w  .D  .D  .D  LP  !Q  !Q  !Q $  .T  .T  .T  \`  !a  !a  !a '  /H  /Hc{  /H  /H  /H  !I  !I  !I $ 5 5h@T U U U08161? .Hc{  .H  .H  .H/3.2=A(" (" !" !" !" !" !" !" @D<!EEEE (Fi'P'P' CL7,B,B&2G LLDO  *K  *Kfm  *K  *K  *K  F  *K  *K  *K  *K  SWL  X  X  X  X ':'&B&BG" Xw'8'8&33&*j/6)-(/i(D(D)- 4     'z3DEE 	"=A
 : IM$0$L\W5LI" I"
 E !LLDO  *S  *Spw  *S  *S  *S  AH  *S  *S  *S  *S  [_L  `  `  `  ` LLDO  *K  *K  *K  SWL  X  X  X,1,/2JJJ LLDO))[s)))  HLL  M  M  M LLDO  *P  *P  *P  X\L  ]  ]  ]#MT_  +D  +D_w  +D  +D  +D  E  E  E 11(<PQQQ,4-2-; *D_w  *D  *D  *D+/*.9=$ $       ))  +j  +j  +j  +j  uI  +j  +j  Ld  +j  +j  +j  k  k  k'*8}}9=9O9O$nM$5 :P : :6"6 04,x==<7777wQXGXGX"8}}|;; $ 1 1  3A  3A  3A[^_g[h[h  3A  3A  3A  !B  !B  !B JqMMM?C<!EEEE !LLDO)u)u)u  ~BL  C  C  C LLDO  *  *  *  GKL  L  L  L#MT_  +J  +JWd  +J  +J  +J  +J  K  K  K 11(<PQQQ,4-2-;)x])x)x)x)x+/*.9=$ $       #9z9.EFF J *96H I II .
 2  * 44 
$.$> >
 * 1 . 9 . 6 . 9 . ? . @ . @ . A: !'6 65 $" ' 8 ))*sk*s*s*sttt6688 %*+K3409>6$HHHH%1 88 *3OW` 9    ))F[ F F#88CCF F   %w%w^i%w%w%w  @D  E  E  E%g%g9%g%g_e%g%gosttt%R%R5%R%RZ^___%- A1BnF\1\1\(N::{c?Q?Q $  .M  .M  .M  UY  !Z  !Z  !Z $  .A  .A  .A  IM  !N  !N  !N $  .A  .A  .A  IM  !N  !N  !N $-t-t-t  }A  !B  !B  !B  !B $-z-z-z  CG  !H  !H  !H $-n-n-nvz { { { $-u-ulr-u-u-u  ~B  !C  !C  !C#/3u::3C3C3E3E#E#E$(LLDO  2E  2E  2E  MQL  %R  %R  %R LLDO)s)s)s{L  A  A  A&a&aV_&a&abbb '#--=53H3HCP\L]L]`bLbLb LL#'? !T !T !T&* )     !11(<PQQQ.2(0)7).&*%(^^          #k11
  : %d>a>a%;K ?b ? ? % :>6*+K$HHHH))*p*p*p*pqqq6688 %*+K3409>6$HHHH)-)B)B9)M)M* r --.r.r.rbp.r.rssss --.pk.p.p`n.p.pqqq%^%^n%^%^fjkkk !(	=$ G GG  # $ $ $ $ = $ $ $ ! ! ( +  LL#'? !? !? !? '+ )    !LL#'? !- !- !- '+ )     n O[.%vs</@/@]BVBV  
 &1 88 *3JR[ 9    --h8LMMM*j;*j*jZh*j*j* +!JO />(0)7).&*%3          $(L& )(/	:t0T0TV_ae(f(f( )W]E-J-J )&3&7&7&F&F&j-J[J[\iJjJjG& )!)36s7||S3I3ILL(1:'> !) !) !)$(D!)0< BRS^knz~BBBI& t))  +WPY  +W  +Ws~  BC  tC  +W  +W  FQ  +W  +W  +W  X  X  X  X))*rY*r*rS^*r*ral*r*r*rsssNNN!##0022!   !%	i 7I-.*)++	114 
 LLDO)p)p)px|L}}} 11(<PQQQ 00222 3Oq|  3O  3O  @K  3O  3O  3O,4-;-2/3$ $       
3 /!3.1C71<< 00!M !M !Mk !M !M#&y49;;'>#?#?!M !M !M  # )++	11WA ++D/  $A!/ !#%,,... q 380/ 
 $G!dddeee%%h0DEEEm=$5557;7U7UV^7_7_4%}}]&:::TTTTTT7S7S D4L8 8 84%}} )1(8(;(C%
 %,8L]LegjAkAk8+3C!#t,, =47GGFB4G4G4t377S\^`KaKa4teieopsetet)11#C.. = "$' @ @D)$44 @ %T 2 2 2 2!+D$!7!7 @DHHV<L<LPV<V<V %TXXfb-A-A B B B B!+D$!7!7 @FdNN %Sf->-> ? ? ?48IIe4D4D)1147HH)1NNNNNN,34E|UY,Z,Z,`^`)&7&?&E2O L* 1#'?#8b!%!4""j!%!%!%'5%1&3&),&7&7'.x$'G'G"FFxPP03O0D0D256K2L2L!    $ !   D %, cT_ c+ c%d%dIZIb%d%deeee  &b  &bIZIbcgdgcgIh  &bsv  xI  xQ  tR  tR  UX  tX  tXjojo  ^`  &b  &b  c  c  c &- !$2M !"3";"A"A"C"CK"$&G[# #egg  
 EP!W!2!24!8!8!;CRC!@!@UWJ! 	!gd4Eq&I&IA&M&M! 77ZPPPP( ! ! ! D!$ !! 778M{\ghlilhl\mostttt( ! ! ! D!
 -->-F-L"MM 771<77LLDO  "B  "B  "B  C  C  C:a??%|%|QUQt%|%|%|}}}  %z%z%z  CG  H  H  H>?;/3/V/VW_/`/`,445FGGG--h8LMMM /3(<)7).'+%V     783=$555-<:W:W22a722"&"?"?@QS`"a"aK*.	0J0J0Pb/W/W/Y/Y*Z*Z'^hitixix  zE  jF  jF  HK  _L  _L  -WDb1Q1Q1W1W1Y1Y,Z,Z,Z  RW)26{G^7_7_2`2`/* N.C NGb N3;#E8B<< U__gimTnTn+x8<<8O+P+P+Ptx(.9oo>U.V.V+&x66 H (V 4 4 CH (_ = = MH "*i!8!8!>BKOOT]D^D^Ddbd eH "*k!:!:!@bkooVaFbFbFhfh i	H
 !14G G *  1 N$OOK888 @@MMM599# R LLDO  *Q  *Qmq  nL  *Q  *Q  *Q  R  R  R19...x888 56D2))(4HIII*.$,%3%*#'!c   T#>?? 756D2 %/ S	? ~%|%|M^MiIjIj%|%|%|}}}+ x"3"> x xB#M*v8H*v*vVXVaVklpmplpVq*v*v*vwwww 0: < <;+43HHH'+'='=bk>N'O'OH' < %&|&|Y[YdYi&|&|qy&|&|&| } } }3; 0* * * *3D3O* * *& * #!22a722 %)IIfT5J.K.K$L$L	'9!'<GJ<GXGX[]G]G],ss*;e*C*Cco  &r  &r  &r  &r  SW  Sm  &r  &r  &r  s  s  s5:: LLDO  *G  *G  *G  OSL  T  T  T9:D6 11(<PQQQ26,4-;-2+/)`)`)`$ $  )-(E(EFWYf(g(g 666"3"> 	 	B!{/t7LLL*s2;3C*s*shq*s*s +G$OO(.02+2- -    
 !12D. )+%/: Q Q!{4%dT4L99 %48Jt4D4DBK1$+JtS4I4I+47IIBK1#%;#8D# %4::<< %48BK1$Q Jt,,,,#3 Q Q Q-44bk6FA5OPPPPPPPPQ ) C% &) ) ) ) )&7&B) ) ) & &

 &  LL#'? !^ !^2?!^ !^ !^&* )   
 :;D6 889JKKK 11(<PQQQ26,4-;-2+/)X$ $  22a722/@/C,	9  &D  &Djs  &D  &D  yB  &D  &D  E  E  E599 LLDO)w)wUYUo)w)w)wxxx$ !LLDO)x)x)xyyy9:D6 261N1NO`bo1p1p.$OO,>??? -T,SAR,S,S,SM&7&B # ##%;#3}#D#D*..h.h.h.h=N.h.h.h*h*hC)I# )I )I )I %0K 3pK (,246E/:1" 1" !# !# !# !#
 % 23D. 483P3P)44 4%0 483O3O)44 4%0 %)$A$ABSUb$c$cM $5#<#BL# D(K(KL(Y(Y D8D5 /8 9 9 9 / /+ -0 0 0 0 0&7&B0 0 0 - -) EVA, D1K1K1M1M D7;D44!_ D$($<$<\$J$J$P$P$R$RE$ D $-B5-B-B C C C $)L ,&x|T::, %RL,,-@AA,
 !'+ !,&x|T::, %RL,,-@AA, $ 89:6673 5:D1OOM22288GGG 1 !! 66t<<<<( ! ! ! D! ,,->J[]klll
 34/ 04D,
 !Z Y<M<X Y Y YI ^$444-44666  #'"9K"599':)@A %
 (Fh'O'O/ 
4K4O4OP\4]4] 
4(()FGGG9=9O9O$n*.*A*T$5 :P : :6"6 04, .6D***8444  &7%>%D"N 05D,  >>~NN e $D*LbQQWUW *  >>?PQQ "0I-)-)A)ABS)T)T)Z)Z)\)\J"KK!> #J  
 !--!4   .8N;?D8! $+41KT#R#R# "6\^c(d(d "0M-"KK(yzzz --.}~~~<@D9HMDE:;D7
 .2-E-Eh-O-O-U-U-W-WN;?D8! +. . .%-bcc]. . . + +
 ,!%$+D2Le$T$T!% =AD9 =AD9HMDE"KK!9   !--!6   *.)F)FGXZg)h)hJ4=Jy1$OOJ777$OO(.%P- -    % +/#$5{DII U&'8:MtTTU&'8:MtTT+ +
 + %t/MPQ/Q/Q ::a?::"KK!@ $ >  
 !--!H$($B!H !H !H   +/*G*G 1<+ +K @DK(;<$OOK8885=D2 228<<<$ ,0+C+C*, ,%''(" , D $ >! C + ( % %DV %\`\wz{\{\{ 771<77"NN!8 $ ;TZ  
 !--!E$($?!E !E !E   % ( )D,@ )"NN!N $ ;TZ $	   !--!D    $::<< )>? ; $ 1 1%9 %9 %9(,%9 %9 %9!" !" !" !'%9$(J!" !" !"
 !)
 -G))-)@)@AR)S)S(,(E(EFWYf(g(g3<i0 666) PSTbPcPcfiPiPitt0Du0L0Lo}-"NN!01B  
 !--!O   
 #NN!7 !% ;TZ $   !-- Q@D@T $I#<#<#H!J   *3 34D/56D2 )::: 1 ;3a77 CC)5.<%- D   8 014/&*&C&CDUWc&d&d 444<<[III %+!U( ( !55519...x888 ./+0 4)B^)S46123/ &*%=%=n%M%M%S%S%U%UN $ = =>OQ^ _ _I !'&x|T::' %RL,,-@AA'
 !	 !'&x|T::' %RL,,-@AA' OOI...(W}(W(W(W%? ~(()|n)|)|)|}}} 0 0 0bbbZ]^_Z`Z`bb	,,,,----, , , ,LL+++++, ?Z^___
 !X!2B;;  C"3-C%c400 wwv&00 wwv+55#'',:O:O5( (%-cAghh%7( ( (
 #&l"3 9 9B#%KZD-A-AK8!$x|;;,246tH/S	/S/S+" +"
 !) 8 8 8 "T%81%<<<(VYsPRs^(V(V(V%%cXa%c%cN OO[^$T$TUUUEEEE =<<<<U0EO  3338M8WZ[8[8[`d`w8[hP !d111$.!33
 !b. a a4K^ a a a0n 0 0tGZ 0 0 0   ?   0^ 0 0dNa 0 0 0   "88>RRN #$.W>DDW3W	 	hi@@@ 	$$%6777 	h(<=== 6>G"))&1114V##x((  66&>>[00RVVL5I5I0l+D S
47D 9 9 S*.r(,,z2*F*F*J*J6*R*RE 
 

 
 
 
 
 ,:@C'''q	595JQt,11PQ9=9NUd+55TUH 	
 tz>4;N+niO%v	

 V##K#NP-.  -     K	/J////  	E+ 	EEJJJJJJ##!6'5)-h*$T:t<<B      E E E>DDDDDDDDE H%% 	 	Cwwv+--#''+2F2F-!$[!1
n
n
 
 	

 
 u
 ;
 !'$0I5"Q"Q
 TZ
 
 
 D5
 T7
  !?
 !$"A
   =!
" T7#
$ "&!? 5")$*ACWYZ"["["`_`"&"A33/
 
 
2 (-$  	B42 	B*.*AF&' 	 !% !&&**+t/III"d&;;;$(!&'D#
  	N 	7L 	$--.C^TTT$778MNNNN   
  	+ 	3H 	La 	--&*8nn"7"7 .    
    	BFFFFFFL ?#'j z488>B      	B 	B 	BNN;SAAAAAAAA	B s(  &)F 
FF8N: :
OO/0P   
Q*Q

Q%R   
R/
R**R/.D\> >
]-]((]-.9`( (
`54`55a8 8
bb=C-i+ +
j5jj!Aw//
w<;w<B+A=AE D)"AE EAE&E	AE&E%AE&E*A"BU GA'AH5 H4BU H5
AIH?BU IAIIQ(BU Z,FBU `:Aa a
BU aAa!aBU a Aa!a!EBU gABU hC?BU lA=BU nJ;BU yCBU |ABU }:ABU ABU @A8BU B=BU CJBU MBBO' O&BU O'
BO4O1BU O3BO4O4DBU TBT# T"BU T#
BT0T-BU T/BT0T0BU UBDE-W,
DE-W6CDE([K"DE(f8DDE(kADE(lADE(m5A DE(oG/DE(wMDE(DDE-DEDE(I/BDE(L
&DE(L1>CM0M/DE(M0
CM=M:DE(M<CM=M=DE(NB1DE(P9DE-P?B!DE(S&A?DE(U%DE-U+DDE(ZDE-ZDE(ZF*DE(a DE-aCDE(dB
DE(fDE-fC$DE(jJ<DE(uDE-u	'DE(u64DE(v0E$DE(|DE-|A(DE(~ C~$~#DE(~$C~:~7DE(~9C~:~:D%DE(CDE-C%A>DE(E(DE-G#G7Ef( OB'DR REf( R
DRREf( RDRRDEf( V+DW WEf( W
DWWEf( WDWWEf( W$DW< W;Ef( W<
DX	XEf( XDX	X	A;Ef( ZA0Ef( [7I=Ef( e6&Ef( fH)Ef( oBEf( qCEf( tDt2t1Ef( t2Du?u2Du:u4Ef( u:Du?u?B
Ef( x
A3Ef( y?CEf( }G;Ef( EEE EEf( E
EE'E$Ef( E&EE'E'DEf( I.CEf( L2BEf( OCEf( RC,Ef( V
BEf( X*B5Ef( [!C7Ef( _B>Ef( bDEf( f(Em?f3Em:gEg"g!Em:g".EhhEm:hEhhEEm:m:Em?w;AEx> x>
Ey.yEy)y)Ey.07F@( @(
F@5@4F@5A(FA+ A+
FA8A7FA8A<4FB1 B1
FC!B;FCCFC!c                 @    |                      ||          }|d         S )a  
        Simple chat interface that returns just the final response.

        Args:
            message (str): User message
            stream_callback: Optional callback invoked with each text delta during streaming.

        Returns:
            str: Final assistant response
        )r  r  )r  )rP   r  r  r?  s       rR   r9  zAIAgent.chatm,  s(     &&w&PP&''rT   )8NNNNNNNNr  r   r!  NNFFFNr"  r  NNNNFNNNNNNNNNNNNNNNNNNNNNFFNNNNNFr#  FT)r  r  r  r   r_   )FF)r   r  )r(  )NNNNN)rj   rk   rl   rm   r   r[   r  setterr   r   r  r   r   r  r   r   rS   r  r  r
  r  r  r  r  r  r  r,  r  r  staticmethodr5  r   r  r   r<  r@  r>  rH  rO  rX  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r#  r
   rG  rI  r  rV  rZ  r]  rc  re  rp  ru  rw  r  r  r  r  r  r[	  r  r  r  r  r  r  r  r  tupler  r  r"  r,  rE  rK  rM  rq  rv  ry  r~   r   r|  r  rQ  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r!   r)  r+  ra  rc  re  rg  rk  rr  r  r  rz  r  r  r   r  r  r  r  r0  r@  rH  rM  rT  rV  r\  r^  r  r  r  r  r  r  r  r  r  r'  r;  r  r  r  r  r9  ro   rT   rR   r  r    s         #    X _>c >d > > > _> %)!% &*'+"' % '+ #'+'+%)!,1(,+/(,+/&*'+%)"&*./3&*$(+/ ,015#'#(!!%.2)-$)(* % $sm mm m 	m
 m m s)d"m m 3i$m m m m s)m  9m  m  !m" #m$ "%%m& 'm( )m*  9+m,  9-m. c/m0 1m2 &*3m4 #&5m6 7m8 !)9m: &;m< !)=m> $?m@ %AmB #CmD  EmF  (GmH %-ImJ $KmL "MmN OmP sCx.QmR SmT  S>UmV tCH~.WmX YmZ [m\ !]m^ !_m` amd emf ,gmh S#Ximl "mmn #&omp qmr sm m m m^!%7 %7 %7NL
 L
 L
 L
\  $ ,1 * * *D * * * *6T    &	C$ 	C 	C 	C 	CUC UD U U U U(
tCH~ 
 
 
 
a a a aF   "C Cc CT C C C C
4D 4 4 4 4 %S %T % % % \%  #'< < << 3-< 
	< < < \<"	%s 	%t 	% 	% 	% 	%%c %d % % % %.3 3     	Gc 	Gd 	G 	G 	G \	GH H H H H $(	C CC 4.	C
 
C C C C>EeEe Ee tCH~&	Ee
 
Ee Ee Ee EePAx} A A A AFVs Vt V V V VD	L 	L 
	G " $#	c c:c c 	c
 
c c c cJ*T$Z *D * * * *$K Kd K4PT: K K K K.F .Fd4j .FX\]aXb .F .F .F .F`-4: -$t* - - - ->?# ? ? ? ?0cd4S>6J cX[ chl cquvz{~  AD  |D  wE  rF c c c cJDd38n)= D3 D[_ D D D D &&I &&# && && && \&&P)(3- )HSM ) ) ) )c c    4 >) >S#X > > > \>@C HTRUWZRZ^D\    * &*P P PcNP 	P
 	"P 
$P P P Pd      \@D @D$tCH~*> @D @D @D @DD/V /V /V /V /V /V /Vb= = = =(C (D ( ( ( (
# $    && & &
d 
 
 
 
$      6
 
d 
d 
 
 
 
8 8 8 8t4S#X+? D    @ ) ) ) ) X)eI eI3 eI# eI eI eI eIV + + + + \+ !y!a!a!abbCd38n)= C$tCQTH~BV C C C \CJ T d    \< GD GT G G G \G"3 3:    8	0 	0 	0! !htDcN/C&D !PXY]^bcfhkck^lYmPn ! ! ! !* 
  
  
  
 C 
 PS 
  
  
  \
   x}hsm7S1T    \& +/  #3- 
	   :k$tCH~:N kSWX\]`be]eXfSg k k k kZ[c [d4S>>R [ [ [ [B #	M M MM 	M
 
c3hM M M M^'C 'C ' ' ' ' c c     b0# b0%S/ b0 b0 b0 b0H/# / / / /
S 
 
 
 
Y_          \:R4 RC RQU RZ] R R R Rh 8 8 8 8 8 \8t3 3  QU    0     "s s     D4 D D D DLWs Ws W W W WG3 G3 G4 G G G Gy yD y# yV^ y y y yvLg LgD Lg# Lg Lg Lg Lg\ FJ   d d    : EI ! ! !T !T ! ! ! !F%4 % % % %N=3 =4 = = = ="J J J J@ 7;26R& R& R& c]R& 	R&
 $N3R&  S#X/R& 
tTz	R& R& R& R&hDT D D D D
W"$ W" W" W" W"v3 3 3 3C D     1c 1c 1 1 1 \1
	>S 	>T 	> 	> 	> 	>LT#s(^ LPT L L L L7s 7t 7 7 7 7(# $         
t 
 
 
 
 ?CE
" E
" E
"E
"3;E
" E
" E
" E
"RS1 S1 S1 S1 S1n?$ ? ? ? ?F #,) - - - # #K"K47KFIK	K K K K^ # $    \ C E#xPT~BU<V    \(1 13 1SV 1 1 1 1f*[S *[ *[ *[ *[ *[ *[X     "	E$ 	E 	E 	E 	E8 8 8 8 8     BD T    8ud ut u u u un	 T  T  T  T  TD,TD[ , , , ,@{ {QU { { { {z T d    \62T 2 2 2 2_ _t _s _ _ _ _B ^br{  QU d- d- d-$ d- d-WZ d-lo d-  KN d-  Z_ d- d- d- d-L* *t *X[ *mp *y} * * * *0 48U U# Ud UWZ U#+C=U<?U U U Un ( (S ( (S (s ( ( ( \(0IW IW$ IWcf IWx{ IW  EI IW IW IW IWVyb yb$ ybcf ybx{ yb  EI yb yb yb ybzUt US US U U U Ut #59.2.2~0 ~0~0 ~0 #4S>2	~0
 ~0 "(+~0 'sm~0 
c3h~0 ~0 ~0 ~0@b( (C ((82D (PS ( ( ( ( ( (rT   r  r  r  Fr  r  r+  r$  r  	max_turnsr.  r/  
list_toolsr0  save_sampleverboser4  c                    t          d           t          d           |rddlm}m}m} ddlm}m} t          d           t          d           t          d           t          d	            |            }g }g }g }|                                D ]_\  }} ||          }|rM||f}|d
v r|	                    |           0|dv r|	                    |           J|	                    |           `t          d           |D ]X\  }}|d         rd
                    |d                   nd}t          d|dd|d                     t          d|            Yt          d           |D ]p\  }}|d         rd
                    |d                   nd}t          d|dd|d                     t          d|            t          d|d                     qt          d           |D ]9\  }}t          d|dd|d                     t          d|d                     :t          d            |            }|                                D ]b\  }}|d         rdnd}t          d | d!| d"|d                     |d         s+t          d#d
                    |d$                               c |            }t          d%t          |           d&           t          |          D ]#} ||          }t          d'| d(| d)           $t          d*           t          d+           t          d,           t          d-           t          d.           t          d            t          d/           t          d0           t          d            t          d1           t          d2           t          d            t          d3           t          d4           d5S d5}d5} |r1d6 |                    d7          D             }t          d8|            |r1d9 |                    d7          D             } t          d:|             |r-t          d;           t          d<           t          d=           	 t          |||||| ||
|>	  	        }!n*# t          $ r}"t          d?|"            Y d5}"~"d5S d5}"~"ww xY w| d@}#n| }#t          dA|#            t          dB           |!                    |#          }$t          dB           t          dC           t          d           t          dD|$dE                     t          dF|$dG                     t          dHt          |$dI                               |$dJ         r3t          dK           t          dL           t          |$dJ                    |	rt#          t%          j                              d5dM         }%dN|% dO}&|!                    |$dI         |#|$dE                   }'|'t+          j                                                    ||$dE         |#dP}	 t1          |&dQdRS          5 }(|(                    t5          j        |dTdUV                     d5d5d5           n# 1 swxY w Y   t          dW|&            n)# t8          $ r}"t          dX|"            Y d5}"~"nd5}"~"ww xY wt          dY           d5S )Za  
    Main function for running the agent directly.

    Args:
        query (str): Natural language query for the agent. Defaults to Python 3.13 example.
        model (str): Model name to use (OpenRouter format: provider/model). Defaults to anthropic/claude-sonnet-4.6.
        api_key (str): API key for authentication. Uses OPENROUTER_API_KEY env var if not provided.
        base_url (str): Base URL for the model API. Defaults to https://openrouter.ai/api/v1
        max_turns (int): Maximum number of API call iterations. Defaults to 10.
        enabled_toolsets (str): Comma-separated list of toolsets to enable. Supports predefined
                              toolsets (e.g., "research", "development", "safe").
                              Multiple toolsets can be combined: "web,vision"
        disabled_toolsets (str): Comma-separated list of toolsets to disable (e.g., "terminal")
        list_tools (bool): Just list available tools and exit
        save_trajectories (bool): Save conversation trajectories to JSONL files (appends to trajectory_samples.jsonl). Defaults to False.
        save_sample (bool): Save a single trajectory sample to a UUID-named JSONL file for inspection. Defaults to False.
        verbose (bool): Enable verbose logging for debugging. Defaults to False.
        log_prefix_chars (int): Number of characters to show in log previews for tool calls/responses. Defaults to 20.

    Toolset Examples:
        - "research": Web search, extract, crawl + vision tools
    u   🤖 AI Agent with Tool Callingz2==================================================r   )get_all_tool_namesr   get_available_toolsets)get_all_toolsetsget_toolset_infou    📋 Available Tools & Toolsets:z2--------------------------------------------------u'   
🎯 Predefined Toolsets (New System):z(----------------------------------------)webrC  visioncreativer  )researchdevelopmentrX  content_creation
full_stacku   
📌 Basic Toolsets:resolved_toolsr  r  u     • r  z - r  z    Tools: u5   
📂 Composite Toolsets (built from other toolsets):includesz    Includes: z    Total tools: r  u!   
🎭 Scenario-Specific Toolsets:20u3   
📦 Legacy Toolsets (for backward compatibility):r  u   ✅u   ❌rq  rY  r  z    Requirements: r  u   
🔧 Individual Tools (z available):u     📌 z (from r  u   
💡 Usage Examples:z  # Use predefined toolsetszR  python run_agent.py --enabled_toolsets=research --query='search for Python news'zN  python run_agent.py --enabled_toolsets=development --query='debug this code'zP  python run_agent.py --enabled_toolsets=safe --query='analyze without terminal'z  # Combine multiple toolsetszM  python run_agent.py --enabled_toolsets=web,vision --query='analyze website'z  # Disable toolsetszQ  python run_agent.py --disabled_toolsets=terminal --query='no command execution'z&  # Run with trajectory saving enabledzF  python run_agent.py --save_trajectories --query='your question here'Nc                 6    g | ]}|                                 S ro   r  r  s     rR   r   zmain.<locals>.<listcomp>,  s      P P Pq P P PrT   r  u   🎯 Enabled toolsets: c                 6    g | ]}|                                 S ro   r  r  s     rR   r   zmain.<locals>.<listcomp>,  s     !R!R!R!''))!R!R!RrT   u   🚫 Disabled toolsets: u   💾 Trajectory saving: ENABLEDu:      - Successful conversations → trajectory_samples.jsonlu7      - Failed conversations → failed_trajectories.jsonl)	r  r+  r$  r,  r.  r/  r0  r1  r4  u    ❌ Failed to initialize agent: zTell me about the latest developments in Python 3.13 and what new features developers should know about. Please search for current information and try it out.u   
📝 User Query: z3
==================================================u   📋 CONVERSATION SUMMARYu   ✅ Completed: r  u   📞 API Calls: r  u   💬 Messages: r   r  u   
🎯 FINAL RESPONSE:z------------------------------r   sample_r  )conversationsr/  r+  r  r  r  r8  r9  Fr  )r  r6  u"   
💾 Sample trajectory saved to: u   
⚠️ Failed to save sample: u    
👋 Agent execution completed!)rG  model_toolsr&
  r   r'
  r  r(
  r)
  r   r   rV  r\   rY  r  r  rP  r  r[   r]  r^  r  r	   rZ  r=  rd  rW   r   r  r   ))r  r+  r$  r  r!
  r.  r/  r"
  r0  r#
  r$
  r4  r&
  r   r'
  r(
  r)
  all_toolsetsbasic_toolsetscomposite_toolsetsscenario_toolsetsrh   r  r3  rQ  	tools_strincludes_strlegacy_toolsetsrQ  	all_toolsr   enabled_toolsets_listdisabled_toolsets_listr  r  r  r?  	sample_idsample_filenamer  r  s)                                            rR   mainrE
  |,  s   H 

+,,,	(OOO  P``````````????????0111h 	8999h'')) )//11 		4 		4MD'##D))D 4tQQQ"))%0000fff&--e4444%,,U333 	&'''( 	- 	-JD$=ABR=S_		$'7"8999Y_I<4<<<tM':<<===+	++,,,, 	FGGG, 	< 	<JD$:>z:JV499T*%5666PVL<4<<<tM':<<===1<11222:d<&8::;;;; 	2333+ 	< 	<JD$<4<<<tM':<<===:d<&8::;;;; 	DEEE0022)//11 	N 	NJD$";/:UUUF=v====](;==>>>$ NL499T.5I+J+JLLMMM '&((	F#i..FFFGGG	** 	: 	:I**955G8I88g8889999&'''+,,,bccc^___`aaad-...]^^^d$%%%abbbd6777VWWW !! A P P4D4J4J34O4O P P P?(=??@@@ C!R!R5F5L5LS5Q5Q!R!R!RA)?AABBB I/000JKKKGHHH$24/#-

 

 

    444555
 }b 	

 
	
,

,
,---	/ ##J//F	/	
%&&&	(OOO	
1F;/
1
1222	
2VK0
2
2333	
5Cz 233
5
5666 (&'''hf%&'''  :
%%bqb)	4I444 88:;
 

 (!1133,
 
	:osW=== I
5uQGGGHHHI I I I I I I I I I I I I I I IIIJJJJ 	: 	: 	:8Q8899999999	: 

-.....sT   R 
S)SS	Z0 +ZZ0 ZZ0 ZZ0 0
[:[[__main__r   )Nr  Nr  r  NNFFFFr  )rm   r6  r*  concurrent.futuresr  r  r  r   r   r4  rj   r2  r   r  r@  rt   r(  r*  r~   typesr   r]  typingr   r   r   r   r  r   firer	   pathlibr
   r  r   hermes_cli.env_loaderr   r1  __file__parent_project_env_loaded_env_paths	_env_pathr3  r8
  r   r   r   r   r~  r   r   r   tools.tool_result_storager   r   tools.interruptr   rU  r  r   r   r|  r   r   agent.retry_utilsr   agent.error_classifierr    r!   agent.prompt_builderr"   r#   r$   r%   r&   r'   r  r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   agent.context_compressorr2   agent.subdirectory_hintsr3   agent.prompt_cachingr4   r5   r6   r7   r8   r9   r:   r;   r<   r=   agent.usage_pricingr>   r?   agent.displayr@   rA   r  rB   r  rC   rD   r  agent.trajectoryrE   rF   rG   r  utilsrH   rI   rK   rx   rz   r[	  r   r   r   r  compileVERBOSEr   r   r[   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r  r   rE
  Firero   rT   rR   <module>ra
     s   *          		8	$	$ 				  				 



       ! ! ! ! ! !  , , , , , , , , , , , ,                    , , , , , , 5 4 4 4 4 4  tH~~$v-&&<\ZZZ  K& G G	:IFFFFG KKIJJJ            N M M M M M M M M M T T T T T T T T ; ; ; ; ; ; . . . . . . 1 0 0 0 0 0 N M M M M M M M . . . . . . E E E E E E E E               
                        7 6 6 6 6 6 < < < < < < > > > > > > V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V  V D D D D D D D D                       5 4 4 4 4 4 4 4.* .* .* .* .* .* .* .*b; ; ; ;)7 )7 )7 )7 )7 )7 )7 )7\ "	9+..  !y " " "    YCCCDD    #
	 J   !bj!455      )$ ) ) ) )X=C = =PT = = = ="? ?d ?t ? ? ? ? 
-..
s s    -D -T - - - -`A3 A3 A A A A84 8D 8 8 8 8v0T 0d 0 0 0 0
3 4    T  
d 
 
 
 
bi( bi( bi( bi( bi( bi( bi( bi(LS  !#S/ S/S/S/ S/ 	S/
 S/ S/ S/ S/ S/ S/ S/ S/ S/ S/ S/l zDIdOOOOO rT   