
    Ki                    *   d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	 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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/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z7 ddl8m9Z9 ddl#m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJ ddlKmLZL ddlMmNZN ddl;mOZOmPZPmQZQmRZRmSZSmTZTmUZU ddlVmWZWmXZX ddlYmZZZm[Z\m]Z^m_Z_m`Za ddlbmcZcmdZdmeZf ddlgmhZhmiZi  G d d          ZjdLdZk G d  d!          Zl emd"h          Zn emh d#          Zo emh d$          Zpd%Zq ejr        d&ejs                  Zt ejr        d'          Zud(evdewfd)Zxdewfd*Zyd+evd,ezde"dz  fd-Z{d.e"d/e"dewfd0Z| ejr        d1          Z} ejr        d2ej~                  Zd3evdevfd4Zd5edewfd6Zd5eddfd7Z G d8 d9          Z	 	 	 	 	 	 	 	 	 	 	 	 dMd>evd?evd@evdAevdBedCevdDevdEewdFewdGewdHewdIefdJZedKk    r ej        e           dS dS )Nao  
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)set_interrupt)cleanup_browser)OPENROUTER_BASE_URL)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save_context_lengthis_local_endpoint)ContextCompressor)apply_anthropic_cache_control)build_skills_system_promptbuild_context_files_promptload_soul_mdTOOL_USE_ENFORCEMENT_GUIDANCETOOL_USE_ENFORCEMENT_MODELSDEVELOPER_ROLE_MODELS!GOOGLE_MODEL_OPERATIONAL_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 )Nr=   )object__setattr__)selfinners     &/home/ubuntu/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   )r=   writeOSError
ValueError
isinstancestrlen)rA   datas     rC   rH   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)r=   flushrI   rJ   rA   s    rC   rQ   z_SafeWriter.flush   sH    	K$ 	 	 	DD	s    22c                 4    | j                                         S rP   )r=   filenorR   s    rC   rT   z_SafeWriter.fileno   s    {!!###rE   c                 f    	 | j                                         S # t          t          f$ r Y dS w xY w)NF)r=   isattyrI   rJ   rR   s    rC   rV   z_SafeWriter.isatty   sB    	;%%'''$ 	 	 	55	s    00c                 ,    t          | j        |          S rP   )getattrr=   )rA   names     rC   __getattr__z_SafeWriter.__getattr__   s    t{D)))rE   N)__name__
__module____qualname____doc__	__slots__rD   rH   rQ   rT   rV   rZ    rE   rC   r<   r<   l   s         $ I2 2 2= = =  $ $ $  * * * * *rE   r<   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)rX   sysrK   r<   setattr)stream_namestreams     rC   _install_safe_stdiori      s\    + ; ;k400j&E&ECk&&9&9:::; ;rE   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 rG   )rl   _used	threadingLock_lock)rA   rl   s     rC   rD   zIterationBudget.__init__   s#    "
^%%


rE   ra   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)rq   rn   rl   rR   s    rC   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   rs   N)rq   rn   rR   s    rC   refundzIterationBudget.refund   s    Z 	  	 zA~~

a

	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 s   155c                     | j         S rP   )rn   rR   s    rC   usedzIterationBudget.used   s
    zrE   c                 ~    | j         5  t          d| j        | j        z
            cd d d            S # 1 swxY w Y   d S rG   )rq   maxrl   rn   rR   s    rC   	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ra   N)r[   r\   r]   r^   intrD   boolrt   rv   propertyrx   r{   r`   rE   rC   rk   rk      s         &# & & & &
            c    X 73 7 7 7 X7 7 7rE   rk   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    rC   _is_destructive_commandr      sJ     u##C(( t!!#&& t5rE   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.rs   Fc                 &    g | ]}|j         j        S r`   functionrY   .0tcs     rC   
<listcomp>z2_should_parallelize_tool_batch.<locals>.<listcomp>  s    888r"+"888rE   c              3   (   K   | ]}|t           v V  d S rP   )_NEVER_PARALLEL_TOOLS)r   rY   s     rC   	<genexpr>z1_should_parallelize_tool_batch.<locals>.<genexpr>  s(      
@
@T4((
@
@
@
@
@
@rE   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 rP   )_paths_overlap)r   existingscoped_paths     rC   r   z1_should_parallelize_tool_batch.<locals>.<genexpr>'  s-      XXX>+x88XXXXXXrE   T)rM   anyr   rY   jsonloads	arguments	ExceptionloggingdebugrK   dicttyper[   _PATH_SCOPED_TOOLS_extract_parallel_scope_pathappend_PARALLEL_SAFE_TOOLS)
tool_calls
tool_namesreserved_paths	tool_call	tool_namefunction_argsr   s         @rC   _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   getrK   rL   stripr
   
expanduseris_absoluteosr   abspathcwd)r   r   raw_pathexpandeds       rC   r   r   2  s    ***t  ((Hh$$ HNN,<,< tH~~((**H 4BGOOCMM22333 DHJJ$9 : :;;<<<rE   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~   minrM   )r   r   
left_partsright_parts
common_lens        rC   r   r   C  s    J+K J[ JJ4#4#44Ij9I9IIS__c+&6&677Jkzk"k+:+&>>>rE   z[\ud800-\udfff]z5\[BUDGET(?:\s+WARNING)?:\s+Iteration\s+\d+/\d+\..*?\]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    rC   _sanitize_surrogatesr   W  s5     D!! 1  4000KrE   messagesc                 4   d}| D ]}t          |t                    s|                    d          }t          |t                    r;t                              |          r!t                              d|          |d<   d}~t          |t                    r~|D ]{}t          |t                    rd|                    d          }t          |t                    r:t                              |          r t                              d|          |d<   d}||S )zSanitize 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.
    Fcontentr   Tr   )rK   r   r   rL   r   r   r   list)r   foundmsgr   partr   s         rC   _sanitize_messages_surrogatesr   b  s    E % %#t$$ 	'')$$gs## 		%(<(<W(E(E 		%*..xAAC	NEE&& 	% % %dD)) %88F++D!$,, %1E1Ed1K1K %'4'8'84'H'HV $LrE   c                    | D ]}t          |t                    r|                    d          dk    r2|                    d          }t          |t                    rd|vrd|vre	 t	          j        |          }t          |t                    r!d|v r|d= t	          j        |d          |d<   n# t          j        t          f$ r Y nw xY wt          
                    d|                                          }||k    r||d<   d	S )
a  Remove budget pressure warnings from tool-result messages in-place.

    Budget warnings are turn-scoped signals that must not leak into replayed
    history.  They live in tool-result ``content`` either as a JSON key
    (``_budget_warning``) or appended plain text.
    roletoolr   _budget_warningz[BUDGETFensure_ascii N)rK   r   r   rL   r   r   dumpsJSONDecodeError	TypeError_BUDGET_WARNING_REr   r   )r   r   r   parsedcleaneds        rC   #_strip_budget_warnings_from_historyr   z  s9     % %#t$$ 	6(A(A'')$$'3'' 	+<G+K+KPYahPhPh	Z((F&$'' ,=,G,G,-!%F!G!G!GI$i0 	 	 	D	 %((W55;;==g$C	N)% %s   )A	B44CCc            a          e Zd ZdZedefd            Zej        deddfd            Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd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eef         d4eeeef                  d5ed6ed7ed8d9d:eeef         d;ed<e	d=ed>ef`d?Zd@ ZdA Zd
dBdCefdDZdEeddfdFZddedefdGZdefdHZdefdIZde	defdJZdKedefdLZdKedefdMZdNedOedPeeeef                  defdQZdee         fdRZdSee         dTe	dUeeeef                  dVeeeeef                           deeef         f
dWZdXeddfdYZ dZZ!d[Z"d\Z#	 	 dd]ee         d^ed_eddfd`Z$dPee         ddfdaZ%ddPee         dVee         fdbZ&ddPee         dVee         fdcZ'dPee         dee         fddZ(defdeZ)dPeeeef                  dfedgedeeeef                  fdhZ*dPeeeef                  dfedgefdiZ+e,dje-defdk            Z.dlee         dee         fdmZ/dnedefdoZ0ddpdqeeef         dredjee-         dee1         fdsZ2e,dKedefdt            Z3ddPeeeef                  fduZ4ddEeddfdvZ5ddwZ6ddPeddfdxZ7dyeeeef                  ddfdzZ8edefd{            Z9dd|edefd}Z:e,defd~            Z;e,dPeeeef                  deeeef                  fd            Z<e,dedefd            Z=e,dedefd            Z>dededz  fdZ?d Z@ddeeeeef                           deeeeef                           fdZAe,ddedede	defd            ZBe,dedeCee         ee         f         fd            ZD	 ddedee         defdZEdPeeeef                  deeeef                  fdZFdedeeeef                  fdZGd
ddqededeeef         fdZHdedefdZIdedefdZJdedeCeef         fdZKdefdZLdefdZMdeNjO        fdZPe,dedefd            ZQdedrededefdZRe,dede	fd            ZSdedrededdfdZTdredefdZUdredefdZVdefdZWdredefdZXdedreddfdZYddqededefdZZddqedefdZ[ddBdCedefdZ\ddBdCedefdZ]defdZ^deddfdZ_ddZ`dee	         dedeCeef         fdZadqefdZbdqefdZcdeddfdZddeddfdZededdfdZfdefdZgdddqedefdZhdefdZidefdZj ekh d£          Zlde-de	de	defdƄZme,dKedefdǄ            Zne,dedeCeee1         f         fdɄ            Zodededefd˄ZpdKededefd̄ZqdUedefd̈́Zrdefd΄ZsdUedefdτZtdefdЄZudedz  fdфZvdSedefd҄Zwe,dedefdԄ            ZxddPede	fdքZyddd؜dPed|edTe	dXedeCf
dلZzddPedede	ddfd܄Z{dedededefd߄Z|ddPedede	ddfdZ}ddPedede	ddfdZ~de	dee         fdZde
ddfdZdPede	defdZ	 	 	 	 	 ddNed|edVeeeef                  dXedee         dee         deeef         fdZddEede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.
    ra   c                     | j         S rP   )	_base_urlrR   s    rC   base_urlzAIAgent.base_url  s
    ~rE   valueNc                 N    || _         |r|                                nd| _        d S Nr   )r   lower_base_url_lowerrA   r   s     rC   r   zAIAgent.base_url  s(    05=u{{}}}2rE   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tool_gen_callbackstatus_callback
max_tokensreasoning_configprefill_messagesplatformskip_context_filesskip_memoryiteration_budgetrk   fallback_modelcheckpoints_enabledcheckpoint_max_snapshotspass_session_idpersist_sessionc3                 3   t                       |	| _        |
| _        |,pt          |
          | _        || _        || _        || _        || _        || _	        |(| _
        d| _        d| _        |)| _        |1| _        |2| _        |.| _        || _        |r| dnd| _        |pd| _        t)          |t*                    r:|                                r&|                                                                nd}3|3pd| _        |p|| _        t5          |p|pg           | _        |dv r|| _        n| j        dk    rd| _        n{|3d| j        v rd| _        d| _        na| j        dk    s|3d	| j        v rd
| _        d| _        n<| j                            d                              d          rd
| _        nd| _        | j        dk    r|                                  rd| _        | j        dk    s| !                                r)tE          j#        d d          $                                 || _%        || _&        || _'        || _(        || _)        d| _*        | | _+        |!| _,        |"| _-        |$| _.        |#| _/        d| _0        d| _1        d| _2        d| _3        tE          j4                    | _5        d| _6        g | _7        tE          j8                    | _9        || _:        || _;        || _<        || _=        || _>        || _?        || _@        || _A        |%| _B        |&| _C        |'pg | _D        | !                                }4d| j                                        v }5| j        d
k    }6|4r|5p|6| _E        d| _F        d| _G        d| _H        d| _I        d| _J        ddlKmL t          jN                    }7t          dz  }8|8dz  }9|9P                                t          fd|7jR        D                       }:ddlSmT}; |:sw|8U                    dd            |9dd           }<|<V                    t          jW                   |<X                     |;d!                     |7Y                    |<           | j        rbt          jZ        t          j[        d"d#$           t          jN                    jR        D ]"}=|=X                     |;d"d#%                     #t          jN        d&          V                    t          jW                   t          jN        d'          V                    t          jW                   t          jN        d(          V                    t          jW                   t          jN        d)          V                    t          jW                   t          jN        d*          V                    t          jW                   t          jN        d+          V                    t          jW                   t          jN        d,          V                    t          jW                   t          jN        d-          V                    t          jW                   t          jN        d.          V                    t          jW                   t          jN        d/          V                    t          j\                   t          ^                    d0           n"t          jZ        t          j\        d1d#$           t          jN        d&          V                    t          j_                   t          jN        d'          V                    t          j_                   t          jN        d(          V                    t          j_                   t          jN        d)          V                    t          j_                   | j        r6d2D ]3}>t          jN        |>          V                    t          j_                   4d| _`        d| _a        d| _b        d| _c        i | _d        d| _e        d| _f        | j        d
k    rdd3lgmh}?mi}@ | j        dk    }A|Ar|p |@            pdn|pd}B|B| _j        |B| _k        || _l        dd4lgmm}C  |C|B          | _f         |?|B|          | _e        d| _n        i | _o        | j        sRt          d5| j         d6           |Br8t          |B          d7k    r%t          d8|Bdd9          d:|Bd;d                     n/|r|r||d<}D| j        d=k    r| j        |Dd><   | j        |Dd?<   |}Ed|E                                v rd@dAdBdC|DdD<   n6dE|E                                v rddFlrms}F  |F            |DdD<   ndG|E                                v rdHdIi|DdD<   nddJltmu}G  |G| j        pdK| j        dL          \  }H}I|HK|Hjj        t+          |Hj                  d<}Dt          |HdM          r|Hjw        rt          |Hjw                  |DdD<   n}| j        pd                                                                }J|Jr,|JdNvr(t          dO|J dP|Jz                                 dQ          t          j|        dRd          t          d@dAdBdCdS}D|D| _o        t+          |D~                    dTd                                                    }Kd|Kv rgd| j        pd                                v rJ|D~                    dD          pi }L|L~                    dUd          }MdV}N|N|Mvr|Mr|M dW|N |LdU<   n|N|LdU<   |L|DdD<   |D~                    dXd          | _j        	 |                     |DdYdZ          | _n        | j        st          d5| j                    |rt          d[|            |D~                    dXd\          }O|Or?|Od]k    r9t          |O          d7k    r&t          d^|Odd9          d:|Od;d                     nt          d_|Or
|Odd`         nd\ da           n%# t           $ r}Pt          db|P           d}P~Pww xY wt)          |-t4                    rdc |-D             | _        nOt)          |-t                    r3|-~                    dd          r|-~                    de          r	|-g| _        ng | _        d| _        d| _        | j        r| j        d         nd| _        | j        r| j        st          | j                  dfk    r0| j        d         }Qt          dg|Qde          dh|Qdd          di           nJt          djt          | j                   dkdl                    dm | j        D                       z              t          ||| j        n          | _        t                      | _        | j        rdo | j        D             | _        t          | j                  }R| j        st          dpt          | j                   dqdr                    |R                      |r%t          dsdr                    |                      |r%t          dtdr                    |                      n| j        st          du           | j        rH| j        sAt                      }Sdv |S                                D             }T|Trt          dw|T            | j        r| j        st          dx           | j	        rK| j        sDt          | j	                  dyk    r| j	        ddy         d:z   n| j	        }Ut          dz|U d{           | jE        r(| j        s!|6rd|nd}}Vt          d~|V dr| jF         d           t          j                    | _        |r|| _        nG| j                            d          }Wt%          j                    j        dd         }X|W d|X | _        t+                      }Y|Ydz  | _        | j        U                    dd           | j        d| j         dz  | _        g | _        d| _        ddlm}Z  |Z|/|0          | _        |+| _        d| _        | j        r	 | j                            | j        | j
        pt          j        ~                    dd          | j        | j        |&|%dd           n3# t           $ r%}Pt                              d|P           Y d}P~Pnd}P~Pww xY wddlm}[  |[            | _        	 ddlm}\  |\            }]n# t           $ r i }]Y nw xY wd| _        d| _        d| _        d| _        d| _        d| _        d| _        |*s	 |]~                    di           }^|^~                    dd          | _        |^~                    dd          | _        t]          |^~                    dd                    | _        t]          |^~                    dd                    | _        | j        s| j        rYddlm}_  |_|^~                    dd          |^~                    dd                    | _        | j                                         n# t           $ r Y nw xY wd| _        |*s	 |^r|^~                    ddd          nd}`|`s	 ddlm}a |a                                }b|bj        r~|bjj        s|bj        rpd}`	 ddlm}cm}d  |c            }ed|e                    di           dd<    |d|e           n# t           $ r Y nw xY w| j        st          d           t          d           n# t           $ r Y nw xY w|`rddlm}f ddlm}g  |f            | _         |g|`          }h|hr.|h                                r| j                            |h           | j        j        rddlm}i | j        |(pdt+           |i                      dd}j	 ddlm}k  |k            }l|l|jd<   d|jd<   n# t           $ r Y nw xY w | j        j        di |j t          ^                    d|`           n"t                              d|`           d| _        n:# t           $ r,}mt                              d|m           d| _        Y d}m~mnd}m~mww xY w| j        rt| j        m| j                                        D ]S}nd|nd}o| j                            |o           |n~                    dd          }p|pr| j                            |p           Td| _        	 |]~                    di           }qt]          |q~                    dd                    | _        n# t           $ r Y nw xY w|]~                    di           }rt)          |rt                    si }r|r~                    ddK          | _        |]~                    di           }st)          |st                    si }st          |s~                    dd                    }tt+          |s~                    dd                                                    dv }u|s~                    d          pd}vt          |s~                    dd                    }wt]          |s~                    dd`                    }x|]~                    dei           }yt)          |yt                    r|y~                    d          }znd}z|z-	 t]          |z          }zn# t          t          f$ r d}zY nw xY w|z1|]~                    d          }{t)          |{t4                    r|{D ]}|t)          ||t                    s||~                    dT          pd                    d          }}|}r|}| j                            d          k    r||~                    di           }~t)          |~t                    rr|~~                    | j        i           }t)          |t                    rB|~                    d          }|+	 t]          |          }zn# t          t          f$ r Y nw xY w nt          | j        |td|x|w|v| j        | j        t          | dXd          |z| j                  | _        |u| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d\| _        | j        sa|urAt          d| j        j        dWdĐt]          |tdz             d| j        j        dWdi           nt          d| j        j        dWdǝ           | j        }| j        | j        | j        | j        t          | dXd          t          | jo                  | jE        |j        |j        t          |dXd          |j        |j        |j        dȜ| _        | j        d
k    r/| j                            | jk        | jl        | jf        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!"}]
            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chat_completionsanthropic_messagesopenai-codexr(  zchatgpt.com/backend-api/codex	anthropicapi.anthropic.comr*  /
/anthropicr)  
openrouterc                      t                      S rP   )r   r`   rE   rC   <lambda>z"AIAgent.__init__.<locals>.<lambda>A  s    355 rE   TtargetdaemonFr   claude5mffffff?g?)RotatingFileHandlerlogsz
errors.logc              3      K   | ]H}t          |          o3t          t          |d d                                                    k    V  IdS )baseFilenamer   N)rK   r
   rX   resolve)r   handlerr9  resolved_error_log_paths     rC   r   z#AIAgent.__init__.<locals>.<genexpr>  ss       %
 %
  w 344 `WWnb99::BBDDH__%
 %
 %
 %
 %
 %
rE   )RedactingFormatter)parentsexist_oki       )maxBytesbackupCountz/%(asctime)s %(levelname)s %(name)s: %(message)sz4%(asctime)s - %(name)s - %(levelname)s - %(message)sz%H:%M:%S)levelformatdatefmt)rH  openaizopenai._base_clienthttpxhttpcoreasynciohpackzhpack.hpackgrpcmodalz
rex-deployz=Verbose logging enabled (third-party library logs suppressed)z)%(asctime)s - %(levelname)s - %(message)s)tools	run_agenttrajectory_compressorcron
hermes_cli)build_anthropic_clientresolve_anthropic_token_is_oauth_tokenu&   🤖 AI Agent initialized with model: z (Anthropic native)   u   🔑 Using token: r   ...r   r   copilot-acpr   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.com
User-AgentKimiCLI/1.3resolve_provider_clientautor   	raw_codex_default_headers)rg  r0  customz
Provider 'z:' is set in config.yaml but no API key was found. Set the zU_API_KEY environment variable, or switch to a different provider with `hermes model`.OPENROUTER_API_KEY)r   r   r^  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   rK   r   r   r   fs     rC   r   z$AIAgent.__init__.<locals>.<listcomp>e  s^     $ $ $a&&$+,55+<+<$ABw$$ $ $rE   r   r   rs   u   🔄 Fallback model:  ()u   🔄 Fallback chain (z providers):     → c              3   >   K   | ]}|d           d|d          dV  dS )r   rx  r   ry  Nr`   rv  s     rC   r   z#AIAgent.__init__.<locals>.<genexpr>w  s;      "c"caj#D#DAjM#D#D#D"c"c"c"c"c"crE   )r  r  r  c                 *    h | ]}|d          d         S r   r`   )r   r   s     rC   	<setcomp>z#AIAgent.__init__.<locals>.<setcomp>  s"    $U$U$U$T*%5f%=$U$U$UrE   u   🛠️  Loaded z tools: , u      ✅ Enabled toolsets: u      ❌ Disabled toolsets: u@   🛠️  No tools loaded (all tools filtered out or unavailable)c                     g | ]	\  }}||
S r`   r`   )r   rY   	availables      rC   r   z$AIAgent.__init__.<locals>.<listcomp>  s"    ^^^_T9T]^D^^^rE   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session_.json)CheckpointManager)enabledmax_snapshotsHERMES_SESSION_SOURCEcli)r   r  r  )r  sourcer   model_configuser_idzESession DB create_session failed (session_search still available): %s)	TodoStore)load_config
   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)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: %sr   )r   r   rY   skillscreation_nudge_intervalagenttool_use_enforcementcompression	threshold      ?r  )true1yessummary_modeltarget_ratio皙?protect_last_ncontext_lengthcustom_providersmodels   )r   threshold_percentprotect_first_nr  summary_target_ratiosummary_model_overrider  r   r   config_context_lengthr           unknownu   📊 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_oauthr`   )ri   r   r   rk   r   r   r  r  r  r  r  	_print_fnbackground_review_callbackr  r$  r%  _credential_poolr  r  r   rK   rL   r   r   r   r   r   r   r   r   rstripendswith_is_direct_openai_url_is_openrouter_urlro   Threadstartr  r  r  r  r  _reasoning_deltas_firedr  r  r  r  r  _last_reported_tool_executing_tools_interrupt_requested_interrupt_messageRLock_client_lock_delegate_depth_active_childrenrp   _active_children_lockr	  r
  r  r  r  r  r  r  r  r  r  _use_prompt_caching
_cache_ttl_budget_caution_threshold_budget_warning_threshold_budget_pressure_enabled_context_pressure_warnedlogging.handlersr9  r   	getLogger_hermes_homer=  r   handlersagent.redactr@  mkdirsetLevelWARNINGsetFormatter
addHandlerbasicConfigDEBUGINFOloggerinfoERROR_stream_callback_stream_needs_break_persist_user_message_idx_persist_user_message_override_anthropic_image_fallback_cache_anthropic_client_is_anthropic_oauthagent.anthropic_adapterrU  rV  r   _anthropic_api_key_anthropic_base_urlrX  client_client_kwargsprintrM   hermes_cli.modelsra  agent.auxiliary_clientrf  hasattrrj  r   RuntimeErrorupperr   getenvr   r   _create_openai_clientr   _fallback_chain_fallback_index_fallback_activated_fallback_modeljoinr   rP  setvalid_tool_namessortedr   itemsr	   nowsession_startr  strftimeuuiduuid4hexr   logs_dirsession_log_file_session_messages_cached_system_prompttools.checkpoint_managerr  _checkpoint_mgr_session_db_last_flushed_db_idxcreate_sessionenvironwarningtools.todo_toolr  _todo_storehermes_cli.configr  _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hermes_cli.profilesr  initialize_allr   get_all_tool_schemasr   add_skill_nudge_interval_tool_use_enforcementfloatr   rJ   r&   rX   context_compressorcompression_enabled_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_sourcer  threshold_tokens_primary_runtimeupdate)rA   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  
session_dbr   r!  credential_poolr"  r#  r$  r%  provider_nameis_openrouter	is_claudeis_native_anthropicroot_loggererror_log_direrror_log_pathhas_errors_log_handlerr@  error_file_handlerr>  quiet_loggerrU  rV  _is_native_anthropiceffective_key_is_oatr  effective_basera  rf  _routed_clientr  	_explicit_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_kwargsr  _profile_mpe_schema_wrapped_tnameskills_config_agent_section_compression_cfgcompression_thresholdr?  compression_summary_modelcompression_target_ratiocompression_protect_last
_model_cfg_config_context_length_custom_providers	_cp_entry_cp_url
_cp_models_cp_model_cfg_cp_ctx_ccr9  r?  s                                                                                                                                     @@rC   rD   zAIAgent.__init__  s   x 	
, !1 SON4S4S$!2.$'>$ 
 *.'"4.. / 0.8@Z****b B4>x4M4MlRZR`R`RbRbl((..000hl%+&1'X3344TTT$DMM]n,,-DMM#)HDL`)`)`-DM*DMM]k))m.CH[_c_sHsHs0DM'DMM!((--66|DD 	/ 1DMM.DM
 =...43M3M3O3O.-DM
 =L((D,C,C,E,E(55   eggg&<##6 &<#!2"4',$ 0*%:".!2#'  !& %*!"&%O--  ! "%.^%5%5" "3!2.*+F((@% !1!2 % 0 0 6B
 //11
 0 0 2 22	"m/CC$1$?i#WDW 
 *-&),&(,%
 ).% 	988888'))$v-&5"0"8"8":":!$ %
 %
 %
 %
 %
 '/%
 %
 %
 "
 "

 	433333% 		7t<<<!4!4a" " " ''888++,>,>A- -    ""#5666 1	LmM"   
 #,..7  $$%7%7J&& & &     h''00AAA344==goNNNg&&//@@@j))227?CCCi((11'/BBBg&&//@@@m,,55goFFFf%%..w???g&&//@@@l++44W\BBBKKWXXXX lB"    h''00???344==gmLLLg&&//>>>j))227=AAA L% L LL %l33<<W]KKKK !% $) 
 *.&.2+
 @B, "&#( =000________ $(=K#? L`uWG(?(?(A(AGRgngtrtM(DL&3D#'/D$JJJJJJ'.w}'='=D$%;%;M8%T%TD"DK"$D? [^tz^^^___  [S%7%7"%<%<Y}RaR/@YY]SUSVSVEWYYZZZ 78 7 -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#~';';'='===$m8M"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*` ` `2;//2C2C` ` `   $&9-A2#F#F$7,S2@7O, ,% %M #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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 
  
  
 &$%! 	 //#=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     $ ;	,:,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	( (!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'+$$$$$$,
  	6DJ$:/DDFF 6 6$.GDD
!!(+++ VR00 6)--f555 &("	&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$4$8$8$I$I$QT!#()9)=)=nd)S)S#T#T #&'7';';<Lb'Q'Q#R#R   ^^GR00
j$'' 	*%/^^4D%E%E""%)"!-.),-C)D)D&&z* . . .)-&&&. ") */A B B+T22 !2  I%i66 ! (}}Z88>BFFsKKG 7dm.B.B3.G.G#G#G%.]]8R%@%@
%j$77 -,6NN4:r,J,JM)->> -*7*;*;<L*M*M#*#6%-ADW(>(>,5z+B %- %- %-(,%-"3*33!9#<]D)R00"8]#
 #
 #
 $7  ! &'")*&$%!!"$%!%&")*&*+'()%*-'#, #)  	|" |  ~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{{{ %ZtY33!$"566"&": #	#&<")#y""="=#&<),);+.+?!
 !
  =000!((%)%<&*&>&*&>* *      10se  <Cp p$pp$AAAB' B'ACB2ACCACC0AD DADDADE	DAI IAIIAII+AQ J1AL( J:6AK1 K0AL( K1AK?K<AL( K>AK?K?(AL( L'AQ L(AL6L3AQ L5AL6L6BAQ OAO# O"AQ O#AO1O.AQ O0AO1O1AAQ QAQ<Q"AQ7Q7AQ<T?AU UAUUAU[A[ [A[1[0A[1_:A``A`!` A`!c                    d| _         d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        d| _        t          | d          r]| j        rXd| j        _        d| j        _        d| j        _        d| j        _        d| j        _        d| j        _        d| 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  rr  r>  FN)rC  rE  rF  rA  rB  rG  rH  rI  rD  rJ  rK  rL  r@  r  r>  last_prompt_tokenslast_completion_tokenslast_total_tokenscompression_count_context_probed_context_probe_persistable_previous_summaryrR   s    rC   reset_session_statezAIAgent.reset_session_state  s    & %&!$%!%&"%&")*&)*&*+'()%!"*-'#, #)  !" 4-.. 	=43J 	=9:D#6=>D#:89D#589D#56;D#3AFD#>8<D#555	= 	= 	= 	=rE   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  r  rI   rJ   )rA   r   kwargsfns       rC   _safe_printzAIAgent._safe_print  sU    	(5BB$ 	 	 	DD	s    //forcer  c                    |st          | dd          rdS |s|                                 r	| j        sdS  | j        |i | dS )uO  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.
        _mute_post_responseFN)rX   _has_stream_consumersr  r  )rA   r  r   r  s       rC   _vprintzAIAgent._vprint	  sm      	'<eDD 	F 	3355 	d>S 	F$)&)))))rE   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  r  r   r  r  r   )rA   r  s     rC   _emit_statuszAIAgent._emit_status  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                 H    |p| j                                         }d|v od|vS )z8Return True when a base URL targets OpenAI's native API.zapi.openai.comr0  )r   r   )rA   r   urls      rC   r  zAIAgent._is_direct_openai_url1  s0    /4/66883&B<s+BBrE   c                     d| j         v S )z1Return True when the base URL targets OpenRouter.r0  )r   rR   s    rC   r  zAIAgent._is_openrouter_url6  s    t333rE   c                 n    d| j         v p,| j                             d                              d          S )zRReturn True when the base URL targets Anthropic (native or /anthropic proxy path).r-  r.  r/  )r   r  r  rR   s    rC   _is_anthropic_urlzAIAgent._is_anthropic_url:  s6    "d&::ud>R>Y>YZ]>^>^>g>ght>u>uurE   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_tokensr  )r  r   s     rC   _max_tokens_paramzAIAgent._max_tokens_param>  s.     %%'' 	4+U33e$$rE   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   )rA   r   r   s      rC   _has_content_after_think_blockz&AIAgent._has_content_after_think_blockI  s>      	5 **733 GMMOO$$$rE   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                  }|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>z8</?(?:think|thinking|reasoning|REASONING_SCRATCHPAD)>\s*)rer   DOTALL
IGNORECASE)rA   r   s     rC   r  zAIAgent._strip_think_blocks`  s     	2 &.G29MMM&4b'UWUbIbccc&6G29UUU&LbRYacajkkk&TVXZaikivwwwrE   user_messageassistant_contentr   c                 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 )r   r   Nru  r   r   s     rC   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>t  s@      WWsz#t$$BF)BWWWWWWrE   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 rP   r`   )r   marker	user_texts     rC   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s(      DD)#DDDDDDrE   z~/r.  c              3       K   | ]}|v V  	d S rP   r`   r   r  assistant_texts     rC   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s(      '^'^V.(@'^'^'^'^'^'^rE   c              3       K   | ]}|v V  	d S rP   r`   r  s     rC   r   z=AIAgent._looks_like_codex_intermediate_ack.<locals>.<genexpr>  s9       *
 *
)/Fn$*
 *
 *
 *
 *
 *
rE   )r   r  r   r   rM   r~   r  r   )rA   r  r  r   has_future_ackaction_markersworkspace_markersuser_targets_workspaceassistant_mentions_actionassistant_targets_workspacer  r  s             @@rC   "_looks_like_codex_intermediate_ackz*AIAgent._looks_like_codex_intermediate_ackm  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drE   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<reasoning>(.*?)</reasoning>z2<REASONING_SCRATCHPAD>(.*?)</REASONING_SCRATCHPAD>r  

)r  r  r   r  r  rK   r   r   rX   rL   r  r  r  findallr   r  )rA   assistant_messagereasoning_partsdetailr  r   inline_patternspatternr  blockr   s              rC   _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;;///trE   finish_reasonapprox_tokensapi_messagesconversation_historyc          	      t   |                      |          }t          t          |dd          p!t          |dd          pt          |dd                    }t          |dd          pd}|                     |                                          }	||pdt          |          |pdf}
|
t          | dd          k    }t          | dd          }t          |d	d
          pd
}t          |dd
          pd
}t          |r$|t          t          |dz            |          k    pt          |          dk              }t          t          | dd          pd          }t          |          }t          |dk    t          |dd          ||g          }t          | j
        o|o|o|	           }|
| _        |||||||dS )a  Classify think-only/empty responses so we can retry, compress, or salvage.

        We intentionally do NOT short-circuit all structured-reasoning responses.
        Prior discussion/PR history shows some models recover on retry. Instead we:
        - compress immediately when the pattern looks like implicit context pressure
        - salvage reasoning early when the same reasoning-only payload repeats
        - otherwise preserve the normal retry path
        r  Nr  r  r   r   _last_empty_content_signaturer>  r  r   rM  皙?P   r   lengthr  F)reasoning_texthas_structured_reasoningrepeated_signatureshould_compressis_local_customis_large_session
is_resumed)r  r~   rX   r  r   rz   r}   rM   r%   r   r?  r  )rA   r  r  r  r  r  r  r  r   stripped_content	signaturer  
compressorctx_lenrM  r  r  r  context_pressure_signalsr   s                       rC    _classify_empty_content_responsez(AIAgent._classify_empty_content_response  s-   " 001BCC#'%{D99 E(*=tDDE(*=tDD$
 $
 
 +Y==C33G<<BBDD b)**R	
	 ''$8WY]*^*^^T#7>>
*&6::?a":/A1EEJS#c'C-.@.@BR*S*SS &<  2%
 
 ,GD*b,I,I,ORPP.//
#&)
$5u== 	$
 $
  $ %%(% %$	
 
 .7*,(@"4.. 0$
 
 	
rE   task_idc                 6   	 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)z3Clean up VM and browser resources for a given task.zFailed to cleanup VM for task : Nz#Failed to cleanup browser for task )r   r   r  r   r   r   )rA   r
  rg  s      rC   _cleanup_task_resourceszAIAgent._cleanup_task_resources;  s   	Qw 	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!AAA 
B&!BB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|Ft!          |d d           }|5	 |!                    |d!d"           d |_"        d S # t<          $ r Y d S w xY wd S d S # |Dt!          |d d           }|2	 |!                    |d!d"           d |_"        w # t<          $ r Y w w xY ww w xY w)#Nr   wr   T)r   r   r  r  r   )r  r  r  r   r   r   {}successr  r   r4  createdupdatedaddedr:  r  MemoryuserzUser profilez updatedzEntry addedremovedreplacedu    · u     💾 u   💾 z)Background memory/skill review failed: %sr  bg_review_donero  )#
contextlibr   r  devnullredirect_stdoutredirect_stderrr   r   r  r   r$  r%  r&  r'  r;  run_conversationrX   rK   r   r   r   r   r   r   r   r   r  fromkeysr  r  r   r  r   _close_openai_clientr  )r  _osreview_agent_devnullactionsr   rN   r  r4  labelr  _bg_cbrg  r  r  promptrA   s                 rC   _run_reviewz5AIAgent._spawn_background_review.<locals>._run_review  s   ((((((((LK!#+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  +$\8TBBF)!(== &/? >    37L///( ! ! ! DD! ,+))  +$\8TBBF)!(== &/? >    37L//( ! ! ! D! ,)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O7 9
N(N#O7 #N((O7 O" "
O0/O07Q P.-Q .
P;8Q :P;;Q Tz	bg-review)r4  r5  rY   )ro   _COMBINED_REVIEW_PROMPT_MEMORY_REVIEW_PROMPT_SKILL_REVIEW_PROMPTr  r  )rA   r  r  r  ro   r,  tr+  s   ``     @rC   _spawn_background_reviewz AIAgent._spawn_background_reviewo  s     	  	/] 	/1FF 	//FF.FN	! N	! N	! N	! N	! N	! N	!` IK;OOO						rE   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   )rX   rM   rK   r   r   )rA   r   idxoverrider   s        rC   $_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)BrE   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)r%  r5  r  _save_session_log_flush_messages_to_session_db)rA   r   r  s      rC   _persist_sessionzAIAgent._persist_session  sa     # 	F11(;;;!)x(((**85IJJJJJrE   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 )rY   r   )r   rY   r   r   s     rC   r   z9AIAgent._flush_messages_to_session_db.<locals>.<listcomp>  s:     ' ' ' "$!1@UVV' ' 'rE   r   tool_call_idr  	assistantr  r  codex_reasoning_items)
r  r   r   r   r   r=  r  r  r  r?  z$Session DB append_message failed: %s)r  r5  ensure_sessionr  r  r   rM   rz   r  r   r  r   rK   r   append_messager   r  r   )
rA   r   r  	start_idx
flush_fromr   r   r   tool_calls_datarg  s
             rC   r8  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)
        Nrs   r   r>  )rangerM   r   copy)rA   r   last_assistant_idxis       rC   "_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 %==??" +++,,rE   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   rY   descriptionr   
parametersN)rY   rM  rN  requiredFr   )rP  r   r   r   r   )rA   formatted_toolsr   funcformatted_tools        rC    _format_tools_for_system_messagez(AIAgent._format_tools_for_system_messageG  s     z 	4 J 	3 	3D
#DV#xxr::"hh|R88 	 N "">2222z/>>>>rE   
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>system)fromr   humanrs   r   r>  r   r   r  z<think>
z

</think>
r   
r   r   z2Unexpected invalid JSON in trajectory conversion: Nr   rY   r<  z<tool_call>
Fr   z
</tool_call>
<think>z<think>
</think>
gptr   z<tool_response>
){[r  r=  )r=  rY   r   z
</tool_response>r  )rS  r   rM   r   r   r6   rK   r   rL   r   r   r   r   r   r   r  
startswithAttributeErrorr  )rA   r   rT  rU  
trajectory
system_msgrJ  r   r   r   r   tool_call_jsontool_responsesjtool_msgtool_responsetool_content
tool_indexr   raw_contents                       rC   _convert_to_trajectory_formatz%AIAgent._convert_to_trajectory_format_  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)r  rk  _save_trajectory_to_filer   )rA   r   rT  rU  ra  s        rC   _save_trajectoryzAIAgent._save_trajectory  sE     % 	F77*iXX
 TZCCCCCrE   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>rs   z!HTML error page (title not found)z2Cloudflare Ray ID:\s*<strong[^>]*>([^<]+)</strong>status_codezHTTP zRay u    — bodyro  r  r  r   ,    )r  rL   r   r  groupr   rX   r   r  rK   r   r   )ro  _rerawmtitlerayray_idrr  r   rs  r   prefixs               rC   _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)%%%rE   keyc                 b    |sd S t          |          dk    rdS |d d          d|dd           S )NrY  z***r   rZ  r[  )rM   )rA   r  s     rC   _mask_api_key_for_logszAIAgent._mask_api_key_for_logs<  sG     	4s88r>>5bqb'((c"##h(((rE   	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 htmlrq  z:Service temporarily unavailable (HTML error page returned)r'     NrZ  )r   r_  r  splitrM   )rA   r  r   s      rC   _clean_error_messagezAIAgent._clean_error_messageC  s      	#"? ??''(899 	PW	=Q=QOO ((9??,,-- w<<#dsdme+GrE   )ro  
api_kwargsrp  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 rP   r`   r   kvs      rC   
<dictcomp>z3AIAgent._dump_api_request_debug.<locals>.<dictcomp>n  s    CCCTQQ]Aq]]]rE   r   z,Could not extract API key for debug dump: %sPOSTr.  r(  z
/responsesz/chat/completionszBearer zapplication/json)AuthorizationzContent-Type)methodr  rc  rs  )	timestampr  rp  request)r   r  )rr  
request_idcodeparamr   rs  responserr  response_statusresponse_textz,Could not extract error response details: %sro  z%Y%m%d_%H%M%S_%frequest_dump_r  r  FrC  )r   indentdefaultutf-8encodingu$   🧾 Request debug dump written to: HERMES_DUMP_REQUEST_STDOUTz*Failed to dump API request debug payload: )!rH  deepcopypopr  rX   r  r   r  r   r	   r  	isoformatr  r   r  r   r  r   r[   rL   r   r  r  
write_textr   r   r  r  r:   r  r  r   r   )rA   r  rp  ro  rs  r   rg  dump_payload
error_info	attr_name
attr_value	body_attrresponse_objr  	dump_file
dump_errors                   rC   _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)r6   r  r   r   )r   s    rC   _clean_session_contentzAIAgent._clean_session_content  sS      	N-g66&'7;;&)7G<<}}rE   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   r  r  message_countr   zHSkipping session log overwrite: existing has %d messages, current has %dr   )
r  r   r   r  r  last_updatedsystem_promptrP  r  r   rC  )r  r  zFailed to save session log: )r  r   r   r  r   r  existsr   r   	read_textrM   r   r   r   r  r   r   r  r  r  r	   r  r  rP  r9   rL   r  r   )rA   r   r   r   r   existing_countentryrg  s           rC   r7  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| _         || _        t          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)
        TNz0Failed to propagate interrupt to child agent: %su   
⚡ Interrupt requested(   z: 'z...''r   )r  r  _set_interruptr  r   r  	interruptr   r  r   r  r  rM   )rA   r  children_copychildrg  s        rC   r  zAIAgent.interrupt  s   0 %)!")t' 	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
A,,
B6BBc                 @    d| _         d| _        t          d           dS )zIClear any pending interrupt request and the global tool interrupt signal.FN)r  r  r  rR   s    rC   clear_interruptzAIAgent.clear_interrupt"	  s&    $)!"&urE   c                     | j         r[	 | j                             |pg            n# t          $ r Y nw xY w	 | j                                          dS # t          $ r Y dS w xY wdS )u   Shut down the memory provider — call at actual session boundaries.

        This calls on_session_end() then shutdown_all() on the memory
        manager. NOT called per-turn — only at CLI exit, /reset, gateway
        session expiry, etc.
        N)r-  on_session_endr   shutdown_all)rA   r   s     rC   shutdown_memory_providerz AIAgent.shutdown_memory_provider(	  s      	$33HNCCCC   $1133333   	 	s   & 
33A 
A A 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   rK   r   r   r   r"  rH   r  r  r  rM   r  )rA   r  last_todo_responser   r   rN   s         rC   _hydrate_todo_storezAIAgent._hydrate_todo_store9	  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  rR   s    rC   is_interruptedzAIAgent.is_interruptedY	  s     ((rE   system_messagec                 Z
    d} j         st                      }|r|g}d}|s*	 	 d}|rt          j        dd| d          }nt          }|g}g }d j        v r|                    t                     d j        v r|                    t                     d	 j        v r|                    t                     |r(|                    d
	                    |                     t           j                  }|r|                    |            j        rM 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                       }
|
rW|                    t&                      j        pd                                }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&            j'        pd                                (                                }|tR          v r |                    tR          |                    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.
        FTNzYou are Hermes AgentzYou are rs   r  r   skill_manager'  )r  alwaysr  on)falsenevernooffr   c              3   n   K   | ]/}t          |t                    |                                v V  0d S rP   )rK   rL   r   r   pmodel_lowers     rC   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>	  sA      __1JWXZ]L^L^_aggii;6______rE   c              3       K   | ]}|v V  	d S rP   r`   r  s     rC   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>	  s(      TT1a;.TTTTTTrE   geminigemmar  c              3   *   K   | ]}|j         v V  d S rP   )r  )r   rY   rA   s     rC   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>	  s+      wwtt'<<wwwwwwrE   )r   r   r  c                     h | ]}||S r`   r`   )r   toolsets     rC   r}  z/AIAgent._build_system_prompt.<locals>.<setcomp>	  s0          rE   c              3   4   K   | ]}t          |          V  d S rP   )r   )r   r   s     rC   r   z/AIAgent._build_system_prompt.<locals>.<genexpr>	  s<          8A(33           rE   )available_toolsavailable_toolsetsTERMINAL_CWD)r   	skip_soulr   )r  zConversation started: z%A, %B %d, %Y %I:%M %pz
Session ID: z
Model: z
Provider: alibabar.  rF  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  )*r  r*   r   replacer  r   r   r   r   r  r   r<  rK   rL   r   r   r   r   r,   r+   r.   r$  r%  format_for_system_promptr&  r-  build_system_promptr   r(   r   r  r)   hermes_timer  r  r$  r  r   r  r  r   r   )rA   r  _soul_loaded_soul_contentprompt_parts_ai_peer_name	_identity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_nowr  timestamp_line_model_shortplatform_keyr  s   `                        @rC   _build_system_promptzAIAgent._build_system_promptg	  sT   $ & 	$(NNM $ -# 	'  
  32:*.}.. 		 3	%;L 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   	K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 K##$ABBB !%
 0b7799|++w,/F/F ''(IJJJ %/// 		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::<<>))| <==={{<(((s   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).idr   )rK   r   r   rX   )r   s    rC   _get_tool_call_id_staticz AIAgent._get_tool_call_id_static
  sF     b$ 	*66$##)r)r4$$**rE   c                    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   r>  r   r   r=  c                 t    g | ]4}|                     d           dk    r|                     d          v 2|5S r   r   r=  )r   )r   ry  orphaned_resultss     rC   r   z2AIAgent._sanitize_api_messages.<locals>.<listcomp>6
  sO       f//AEE.4I4IM]4]4] 4]4]4]rE   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   r   r  r:  r  r   rM   r   )	r   surviving_call_idsr   r   cidresult_call_idsmissing_resultspatchedr  s	           @rC   _sanitize_api_messageszAIAgent._sanitize_api_messages
  s.    #&%% 	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$$   rE   r   c                 0   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   )MAX_CONCURRENT_CHILDRENc              3   :   K   | ]}|j         j        d k    dV  dS )delegate_taskrs   Nr   r   s     rC   r   z3AIAgent._cap_delegate_task_calls.<locals>.<genexpr>`
  s1      [[2r{7G?7Z7ZQ7Z7Z7Z7Z[[rE   r  rs   zUTruncated %d excess delegate_task call(s) to enforce MAX_CONCURRENT_CHILDREN=%d limit)tools.delegate_toolr  sumr   rY   r   r  r   )r   r  delegate_countkept_delegates	truncatedr   s         rC   _cap_delegate_task_callsz AIAgent._cap_delegate_task_callsU
  s     	@?????[[[[[[[444	 	% 	%B{?22!$;;;$$R((("a'N  $$$$/446M	
 	
 	

 rE   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)	r  r   rY   r   r:  r   r  r   rM   )r   seenuniquer   r  s        rC   _deduplicate_tool_callszAIAgent._deduplicate_tool_callss
  s     EE 	T 	TB;#R[%:;C$b!!!!@"+BRSSSSVs:66vvJFrE   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  r'  rs   r8  )ncutoffN)difflibr  r   r  r  )rA   r   r  lowered
normalizedmatchess         rC   _repair_tool_callzAIAgent._repair_tool_call
  s     	.----- //##d+++N __S#..66sC@@
... $#GT-BaPSTTT 	1:trE   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)r  r$  r,  rR   s    rC   _invalidate_system_promptz!AIAgent._invalidate_system_prompt
  s<     &*" 	0--/////	0 	0rE   rP  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   rY   rM  r   FrN  r?   )r   
propertiesr   rY   rM  strictrN  )rP  rK   r   r   rL   r   r   )rA   rP  source_tools	converteditemr  rY   s          rC   _responses_toolszAIAgent._responses_tools
  s     % 1uutz 	4*,	  	 	D-7d-C-CK*b)))B66&>>DdC(( 

 "!vvmR88 ff\HTV3W3WXX       D rE   r   fn_namer   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:r  r  )errorsrY  call_)hashlibsha256encode	hexdigest)r2  r   r3  r8  seeddigests         rC   _deterministic_call_idzAIAgent._deterministic_call_id
  so     	//I////GI F FGGQQSSTWUWTWXvrE   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|rs   Nfc_)rK   rL   r   r  r_  )r?  r   call_idresponse_item_ids       rC   _split_responses_tool_idz AIAgent._split_responses_tool_id
  s     &#&& 	: 	:%<<(-C(;(;%G%mmoo-G/5577?4,,,E"" 	;d{rE   rD  rE  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_`).rC  r   r7  Nz[^A-Za-z0-9_-]0   r     )rK   rL   r   r_  rM   r  r   r  r  r  r8  sha1r:  r;  )rA   rD  rE  	candidater  	sanitizedr<  r=  s           rC   "_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~~rE   c                 	   g }|D ]}t          |t                    s|                    d          }|dk    r5|dv r|                    dd          }|t          |          nd}|dk    rB|                    d          }d	}t          |t                    rF|D ]C}	t          |	t                    r,|	                    d
          r|                    |	           d}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   rW  >   r  r>  r   r   Nr>  r?  Fencrypted_contentTr   r   r   r   rY   r  rD  rC  r7  r   r  r   function_callr   rD  rY   r   r   r=  function_call_outputr   rD  output)rK   r   r   rL   r   r   r   rF  r_  rM   r>  r   r   )rA   r   r  r   r   r   content_textcodex_reasoninghas_codex_reasoningrir   r   r  r2  embedded_call_idembedded_response_item_idrD  	_raw_argsr   raw_tool_call_idr  s                        rC   !_chat_messages_to_responses_inputz)AIAgent._chat_messages_to_responses_input
  s   &( Z	 Z	Cc4(( 776??Dx,,,'')R00/6/Bs7|||;&& '*gg.E&F&FO*/'!/488 ;"1 ; ;B)"d33 ;?R8S8S ; %R 0 0 06: 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??     rE   	raw_itemsc           
         t          |t                    st          d          g }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|
rd|
d}|                    d          }t          |t                    r|r||d<   |                    d          }t          |t                    r||d<   ng |d<   |
                    |           |                    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   rQ  rD  rY   z#] function_call is missing call_id.z ] function_call is missing name.r   r  Fr   rR  rS  z*] function_call_output is missing call_id.rU  r   rT  r  rO  r   rO  r  r  r   >   r  r>  r   rP  z#] has unsupported item shape (type=z, role=).)rK   r   rJ   	enumerater   r   rL   r   r   r   r   )rA   r_  r%  r3  r0  	item_typerD  rY   r   rU  	encryptedreasoning_itemitem_idr  r   r   s                   rC   _preflight_codex_input_itemsz$AIAgent._preflight_codex_input_items^  s   )T** 	USTTT+-
"9-- M	 M	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.9PY%Z%ZN"hhtnnG!'3// 7G 7/6t,"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   rE   allow_streamrk  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          t          f          r|d"k    rt          |          |d!<                       d#          }t          |t          t          f          rt          |          |d#<   d$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 r`   r`   )r   r  r  s     rC   r   z7AIAgent._preflight_codex_api_kwargs.<locals>.<listcomp>  s#    DDD3c.C.C3.C.C.CrE   z3Codex Responses request missing required field(s): r~  .r   z;Codex Responses request 'model' must be a non-empty string.rn  r   rm  rP  z=Codex Responses request 'tools' must be a list when provided.zCodex Responses tools[ra  r   r   z] has unsupported type rY   rN  z] is missing a valid name.z] is missing valid parameters.rM  r-  Fr,  storez6Codex Responses contract requires 'store' to be false.>   rm  r   rq  rP  includer  temperaturetool_choicern  prompt_cache_keymax_output_tokensparallel_tool_calls)r   rn  rm  rq  r  rr  rv  r   rs  )rt  rw  ru  rh   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 rP   r`   )r   r  allowed_keyss     rC   r   z6AIAgent._preflight_codex_api_kwargs.<locals>.<genexpr>)  s-      XXC<@W@WC@W@W@W@WXXrE   z2Codex Responses request has unsupported field(s): )rK   r   rJ   r  r  r   rL   r   r   ri  r   rd  r~   r   r}   r=  r:  keys)rA   r  rk  rO  missingr   rn  normalized_inputrP  normalized_toolsr3  r   rY   rN  rM  r-  rq  r%  r  rr  rv  rs  passthrough_keyvalrh   
unexpectedry  s    `                        @rC   _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! '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
?+ 	l^^H--F!fD&8&8 !RSSS~~'+
8$X&&&&##jkkkXXXX:??+<+<XXXXX
 	]TYYzEZEZ]]]   rE   r0  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   rX   rK   r   rL   r   r  r   )rA   r0  r   chunksr   ptyper   s          rC   _extract_responses_message_textz'AIAgent._extract_responses_message_text1  s    $	400'4(( 	2 	$ 	$DD&$//E3334..D$$$ $ $d###wwv$$&&&rE   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   rZ  r   r  )rA   r0  r  r  r   r   s         rC   !_extract_responses_reasoning_textz)AIAgent._extract_responses_reasoning_textA  s    $	400gt$$ 	1 "F ( (tVT22dC(( (T (MM$''' 1yy((..000tVT**dC   	 T 	 ::<<rrE   r  c                    t          |dd          }t          |t                    r|s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d,}&|%|&fS )-zENormalize a Responses API object to an assistant_message-like object.rU  Nz&Responses API returned no output itemsstatus>   failed	cancelledro  r  zResponses API returned status 'r  >   queued
incompletein_progressFr   Tphase>   analysis
commentary>   finalfinal_answerr  rO  rb  r  r  r   summary_text)r   r   rQ  rY   r   r   r  r   rD  r   r<  r  rD  rE  r   r   custom_tool_callrm  rZ  c                     g | ]}||S r`   r`   )r   r  s     rC   r   z5AIAgent._normalize_codex_response.<locals>.<listcomp>  s    >>>aA>>>>rE   r  r  )r   r   r  r  r  r?  r   r  stop)rX   rK   r   r  rL   r   r   r   r   r  r   r  r   r   rF  r>  rM   rM  r   r  r  )'rA   r  rU  r  	error_objr  content_partsr  reasoning_items_rawr   has_incomplete_itemssaw_commentary_phasesaw_final_answer_phaser0  re  item_status
item_phasenormalized_phasemessage_textr  rf  raw_itemrh  r  raw_summaryr   r   r2  r   raw_call_idraw_item_idrZ  r  rD  rE  
final_textout_textr  r  s'                                          rC   _normalize_codex_responsez!AIAgent._normalize_codex_responseQ  s   8T22&$'' 	Iv 	IGHHH!(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 -//rE   c                 J    t          j                    }|j         d|j         S )Nr5  )ro   current_threadrY   ident)rA   threads     rC   _thread_identityzAIAgent._thread_identity  s(    )+++.....rE   c                     t          | dd          }t          | dd          }t          | dd          }d|                                  d| d| d| S )	Nr   r  r   r   zthread=z
 provider=z
 base_url=z model=)rX   r  )rA   r   r   r   s       rC   _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	
rE   c                 `    t          | dd           }|t          j                    }|| _        |S )Nr  )rX   ro   r  r  )rA   locks     rC   _openai_client_lockzAIAgent._openai_client_lock  s2    t^T22<?$$D $DrE   r  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  rK   rX   callabler~   )r  r  is_closed_attrhttp_clients       rC   _is_openai_client_closedz AIAgent._is_openai_client_closed  s     	'&&&&&fd## 	5 d;;%'' !>##  4 n%% tfi66"[%@@AAAurE   r  rq  c                |   | j         dk    s6t          |                    dd                                        d          r?ddlm}  |d	i |}t                              d|||                                            |S t          d	i |}t                              d|||                                            |S )
Nr]  r   r   zacp://copilotr   )CopilotACPClientz-Copilot ACP client created (%s, shared=%s) %sz(OpenAI client created (%s, shared=%s) %sr`   )
r   rL   r   r_  agent.copilot_acp_clientr  r  r  r  r   )rA   r  rp  rq  r  r  s         rC   r  zAIAgent._create_openai_client  s    =M))S1B1B:r1R1R-S-S-^-^_n-o-o)AAAAAA%%6666FKK?((**	   M((-((6$$&&		
 	
 	
 rE   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_sockrh   rs   z'Force-close TCP sockets sweep error: %s)
socketrX   r   shutdown	SHUT_RDWRrI   closer   r  r   )r  _socketclosedr  	transportpoolconnectionsconnrh   sockexcs              rC   _force_close_tcp_socketsz AIAgent._force_close_tcp_sockets-  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  r  r  r  r   r   )rA   r  rp  rq  force_closedr  s         rC   r$  zAIAgent._close_openai_clienth  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 )Nr  Tro  z7Failed to rebuild shared OpenAI client (%s) %s error=%sFzreplace:)
r  rX   r  r  r   r  r   r  r  r$  )rA   rp  
old_client
new_clientr  s        rC   _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 )Nr  zCDetected closed shared OpenAI client; recreating before use (%s) %szrecreate_closed:rp  z'Failed to recreate closed OpenAI client)	r  rX   r  r  r   r  r  r  r  )rA   rp  r  s      rC   _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.
        r  NFr  r  r  r  r   r  r  r  rh   rs   rE   Tu@   Found %d dead connection(s) in client pool — rebuilding clientdead_connection_cleanupr  zDead connection check error: %s)rX   r   r  setblockingrecvMSG_PEEKMSG_DONTWAITBlockingIOErrorrI   r  r   r  r   r   )rA   r  r  r  r  r  
dead_countr  rh   r  r  rN   r  s                rC   _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  Fro  )r  r  r  rK   r  r   r  r  )rA   rp  r  primary_clientrequest_kwargss        rC   _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 )NFro  )r$  )rA   r  rp  s      rC   _close_request_openai_clientz$AIAgent._close_request_openai_client  s#    !!&!FFFFFrE   on_first_deltac           	      (   ddl }|p|                     d          }d}d}d}d| _        t          |dz             D ]T}		  |j        j        di |5 }
|
D ]}| j        r nt          |dd          }d	|v s|d
k    rMt          |dd          }|r9|s7|s d}|r	  |             n# t          $ r Y nw xY w| 	                    |           sd|v rd}zd|v r,d|v r(t          |dd          }|r| 
                    |           |
                                cddd           c S # 1 swxY w Y   # |j        |j        |j        t          f$ r}|	|k     r<t                               d|	dz   |dz   |                                 |           Y d}~Qt                               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  rs   Fr   r   zoutput_text.deltazresponse.output_text.deltadeltaTrQ  r  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)r  response.completedzGResponses stream closed before completion (attempt %s/%s); retrying. %szYResponses stream did not emit response.completed; falling back to create(stream=True). %sr`   )rJ  r  r  rG  	responsesrh   r  rX   r   _fire_stream_delta_fire_reasoning_deltaget_final_responseRemoteProtocolErrorReadTimeoutConnectErrorConnectionErrorr  r   r  !_run_codex_create_stream_fallbackr  rL   )rA   r  r  r  _httpxactive_clientmax_stream_retrieshas_tool_callsfirst_delta_firedattemptrh   event
event_type
delta_textr  r  err_textmissing_completeds                     rC   _run_codex_streamzAIAgent._run_codex_stream  s   b$"D"DLa"D"b"b!',$/!344 =	 =	G<3],3AAjAA 7V!' K K4 "!E%,UFB%?%?
.*<<
Nj@j@j)0)D)DJ) 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!446637 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 74 .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=	 =	s    D.AD"
B"!D""
B/	,D".B/	/A$D"D."D&	&D.)D&	*D..J<GAGJJ&AJ
<AJ
J	J

Jc                    |p|                      d          }t          |          }d|d<   |                     |d          } |j        j        di |}t          |d          r|S t          |d          s|S d}	 |D ]}t          |d	d          }|s*t          |t                    r|                    d	          }|d
vrDt          |dd          }|*t          |t                    r|                    d          }|@|c t          |dd          }	t          |	          r	  |	             S # t          $ r Y S w xY wS 	 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  Trh   rj  rU  __iter__Nr   >   response.failedresponse.incompleter  r  r  zHResponses create(stream=True) fallback did not emit a terminal response.r`   )r  r   r  r  creater  rX   rK   r   r  r   r  )
rA   r  r  r  fallback_kwargsstream_or_responseterminal_responser  r  close_fns
             rC   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 	&%% 	+ - -$UFD99
! 3j&=&= 3!&6!2!2J%eee$+E:t$D$D!$,E41H1H,(-		*(=(=%$0,,,17DAAH!! HJJJJ    D	 1- 17DAAH!! HJJJJ    D 17DAAH!! HJJJJ    D ($$efffs[   =BF &
D11
D>=D>F %
E0 0
E=<E=!F?#
F.-F?.
F;8F?:F;;F?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 )Nr(  r+  Fr   )!resolve_codex_runtime_credentials)force_refreshz#Codex credential refresh failed: %sr   r   r.  codex_credential_refreshr  T)r   r   hermes_cli.authr  r   r  r   r   rK   rL   r   r   r  r   r  r  )rA   r  r  credsr  r   r   s          rC   %_try_refresh_codex_client_credentialsz-AIAgent._try_refresh_codex_client_credentialsd  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   r.  r^  nous_credential_refreshr  T)r   r   r  r  rz   r}   r   r  r=  r   r  r   r   rK   rL   r   r   r  r   r  r  r  )rA   r  r  r  r  r   r   s          rC   $_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*  r  Fr,  r   )rV  rU  z'Anthropic credential refresh failed: %sr  z?Failed to rebuild Anthropic client after credential refresh: %srW  T)r   r  r   r  rV  rU  r   r  r   rK   rL   r   r  r  r  rX   r   rX  r  )rA   rV  rU  	new_tokenr  rX  s         rC   )_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                    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 | j                            dd            d S )Nr   )_OR_HEADERSr   r0  r^  r_  r`  rb  rc  rd  )r  r*  r   r   r  r   ra  r  )rA   r   r*  r%  ra  s        rC   "_apply_client_headers_for_base_urlz*AIAgent._apply_client_headers_for_base_url  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))6BM5RD 1222##$5t<<<<<rE   c                    t          |dd           pt          |dd          }t          |dd           pt          |dd           p| j        }| j        dk    rddlm}m} 	 | j                                         n# t          $ r Y nw xY w|| _	        || _
         |||          | _        | j        d	k    r ||          nd
| _        || _        || _        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   )rU  rX  r,  Fr.  r   credential_rotationr  )rX   r   r   r  rU  rX  r  r  r   r  r  r   r  r   rK   rL   r  r  r+  r  )rA   r  runtime_keyruntime_baserU  rX  s         rC   _swap_credentialzAIAgent._swap_credential  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"GK}XcGcGc{'C'C'CinD$&DL(DMF"4>|S4Q4Qc++C000Wc)-I&*.-J'//>>>++3H+IIIIIs    A: :
BBrr  has_retried_429c                8   | j         }||d|fS |dk    r_|                    d          }|Ct                              dt	          |dd                      |                     |           dS d|fS |d	k    ra|sd
S |                    d	          }|Ct                              dt	          |dd                      |                     |           dS d
S |dk    r|                                }|Et                              dt	          |dd                      |                     |           d|fS |                    d          }|Ct                              dt	          |dd                      |                     |           dS d|fS )a  Attempt credential recovery via pool rotation.

        Returns (recovered, has_retried_429).
        On 429: first occurrence retries same credential (sets flag True).
                second consecutive 429 rotates to next credential (resets flag).
        On 402: immediately rotates (billing exhaustion won't resolve with retry).
        On 401: attempts token refresh before rotating.
        NFi  )rr  u3   Credential 402 (billing) — rotated to pool entry r  ?)TF  )FTu6   Credential 429 (rate limit) — rotated to pool entry   u(   Credential 401 — refreshed pool entry Tu:   Credential 401 (refresh failed) — rotated to pool entry )r  mark_exhausted_and_rotater  r  rX   r3  try_refresh_current)rA   rr  r4  r  
next_entry	refresheds         rC   _recover_with_credential_poolz%AIAgent._recover_with_credential_pool  s    $<;./))#77C7HHJ%rRYZdfjloRpRprrsss%%j111"{/))#" #"{77C7HHJ%uU\]gimorUsUsuuvvv%%j111"{;#0022I$fwyZ^`cGdGdffggg%%i000_,, 77C7HHJ%yY`akmqsvYwYwyyzzz%%j111"{o%%rE   c                 n    | j         dk    r|                                   | j        j        j        di |S )Nr*  r`   )r   r(  r  r   r  )rA   r  s     rC   _anthropic_messages_createz"AIAgent._anthropic_messages_create)  sA    =000::<<<5t%.5CC
CCCrE   c                 x    dddddi fd}t          j        |d          }|                                 |                                r|                    d            j        r	  j        d	k    rEd
dlm}  j	        
                                  | j        t           dd                     _	        n.                    d          }|                     |d           n# t          $ r Y nw xY wt!          d          |                                Љd         d         d         S )ad  
        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.
        Nr  ro  r  c            	      p   	 j         dk    rJ                    d          d<                       d         t          dd                     d<   n]j         dk    r                              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)Nr(  codex_stream_requestr  r  _codex_on_first_delta)r  r  r  r*  chat_completion_requestro  request_completer`   )r   r  r  rX   r?  chatcompletionsr  r   r   r  )rg  request_clientr  request_client_holderresultrA   s     rC   _callz.AIAgent._interruptible_api_call.<locals>._call:  s   a=$5556:6X6X`v6X6w6w)(3)-)?)?"4X>'.t5Ld'S'S *@ * *F:&&
 ]&:::)-)H)H)T)TF:&&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   B2B6 5D 6
C C
D 
CD 1D5Tr3  333333?r  r*  r   rU  r  interrupt_abortr  z!Agent interrupted during API callro  r  )ro   r  r  is_aliver  r  r   r  rU  r  r  r  rX   r   r  r   InterruptedError)rA   r  rL  r0  rU  rI  rJ  rK  s   ``    @@rC   _interruptible_api_callzAIAgent._interruptible_api_call.  s    #T22!)4 0	a 	a 	a 	a 	a 	a 	a 	a* E$777				jjll 	LFF3F( 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K+ jjll 	L, '?&/!j!!s   2A>C1 1
C>=C>r   c                     t          | dd          r"|r |                                rd| _        d|z   }| j        | j        fD ]!}|	  ||           # t
          $ r Y w xY w"dS )z;Fire all registered stream delta callbacks (display + TTS).r  Fr  N)rX   r   r  r  r  r   rA   r   cbs      rC   r  zAIAgent._fire_stream_deltam  s     4.66 	!4 	!DJJLL 	!',D$D=D-t/DE 	 	B~BtHHHH    D 	 	s   A
A A c                 d    d| _         | j        }|	  ||           dS # t          $ r Y dS w xY wdS )z&Fire reasoning callback if registered.TN)r  r  r   rU  s      rC   r  zAIAgent._fire_reasoning_delta}  sV    '+$$>4    >s    
--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)r  r   )rA   r   rV  s      rC   _fire_tool_gen_startedzAIAgent._fire_tool_gen_started  sP     #>9    >s    
&&c                 :    | j         dupt          | dd          duS )z4Return True if any streaming consumer is registered.Nr  )r  rX   rR   s    rC   r  zAIAgent._has_stream_consumers  s/     &d2 Ct/66dB	
rE   r  c                     j         dk    r0 _        	                                d _        S # d _        w xY w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                    }t          d                     dg           D                       dz  }|dk    rt          |d          }n|dk    rt          |d          }n|}t          j        |d          }|                                 |                                r|                    d           t          j                    d         z
  |k    rt                              d|           	                     d          }|                     |d           n# t$          $ r Y nw xY w	                      d           n# t$          $ r Y nw xY wt          j                    d<    j        r	  j         dk    rEdd lm}	  j                                          |	 j        t5           d!d                     _        n.                    d          }
|
                     |
d"           n# t$          $ r Y nw xY wt7          d#          |                                d$         d$         d%         S )&u  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.
        r(  NrA  r  doneFr  r0  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   rC   _fire_first_deltazDAIAgent._interruptible_streaming_api_call.<locals>._fire_first_delta  sq    $V,  ,0!&)"N$$$$$    DD	   s   
 
,,c                  
   ddl } t          t          j        dd                    }t          t          j        dd                    }i !dddi|                     d	||d	
          d}%                    d          $d<   t          j                    #d<    $d         j        j        j	        d+i |}g }i }t                      }i }i }	d}
d}d}g }d}d%_        |D ]h}t          j                    #d<   %j        r nG|j        s=t          |d          r|j        r|j        }t          |d          r|j        r|j        }g|j        d         j        }t          |d          r|j        r|j        }t%          |dd          pt%          |dd          }|r4|                    |                          %                    |           |r|j        ry|                    |j                   |s*               %                    |j                   d"d<   n3%j        r,	 %                    |j                   n# t0          $ 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t9          |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        }jd&                    |          pd}d}|rg }tO          |          D ]v}||         }|                    tQ          |d         |d$         |!                    d!          tQ          |d         d         |d         d                    %                     wd&                    |          pd}tQ          ||||&          }tQ          d||
pd'(          }tQ          d)tS          tU          j+                              z   ||g|*          S ),z#Stream a chat completions response.r   NHERMES_API_TIMEOUT      @HERMES_STREAM_READ_TIMEOUTg      N@Tinclude_usage      >@)connectr  rH   r  )rh   stream_optionsr  chat_completion_stream_requestr  r  r0  r>  Fr   usager  r  r  r   rF  )r  rs   r   r<  )r  r   r   extra_contentr  rY   r   rj  model_extra
model_dumpr   )r  r   rj  r   )r   r   r   r  r  )r3  r  r  zstream-)r  r   choicesri  r`   ),rJ  r=  r   r  Timeoutr  timerG  rH  r  r  r  r  rm  r  r   ri  r  rX   r   r  r   r  r  r   r   r3  r  rz   r   rY   r   rk  r   rl  r:  rY  r  r  r  r   rL   r  r  )&r  _base_timeout_stream_read_timeoutstream_kwargsrh   r  tool_calls_acctool_gen_notified_last_id_at_idx_active_slot_by_idxr  
model_namer   r  	usage_objchunkr  r  tc_deltaraw_idxdelta_idnew_slotr3  r  extrarY   full_contentmock_tool_callsr   full_reasoningmock_messagemock_choicer_  r  deltas_were_sentlast_chunk_timerJ  rA   s&                                   rC   _call_chat_completionszIAIAgent._interruptible_streaming_api_call.<locals>._call_chat_completions  s   """"!"),@&"I"IJJM#(3OQU)V)V#W#W 

#2D"9!>> -'	 *  	
 
 
M /3.P.P7 /Q / /!(+
 $(9;;OC L*849EL]]}]]F"$M#%N%(UU
 %'O(* MJD$&OI ,1D( i, i,'+y{{$, 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 I#, % % % $%  />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#**?d8Z&(ff_&=&=!0!#J!7&(n[&A" " "	, , ,      WW_55=N*$*"0	  L *$+5v  K
 #s4:<<000 $	   s   (I
IIc                     d} d_         t          j                    d<    j        j        j        di 5 }|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    r5t          |dd          }|r!| s 
                                 |           |dk    r2t          |dd          }	|	r 
             	                    |	            |
                                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.
            Fr0  r   Ncontent_block_startcontent_blocktool_useTrY   content_block_deltar  
text_deltar   r   thinking_deltar  r`   )r  ro  r  r   rh   r  rX   rY  r  r  get_final_message)has_tool_userh   r  r  r  r   r  
delta_typer   thinking_textr_  r  r  rA   s             rC   _call_anthropiczBAIAgent._interruptible_streaming_api_call.<locals>._call_anthropic  s9    !L+0D( $(9;;OC 7'07EE*EE  2# N N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#' !B !B$5$5$7$7$7$($;$;D$A$A$A!+/?!?!?07z20N0N#0 !N$5$5$7$7$7$($>$>}$M$M$M //11A 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2s   D6E;;E?E?c                  T   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|r||k     rt                              d|dz   |dz   t5          |          j        |                               dt5          |          j         d|dz    d|dz    d                               d          }
|
                    |
d	           d d<   	                     d	           n# t          $ r Y nw xY wY d }~e                    d|dz    d           t                              d|dz   |           n[t-          |                                          }d|v od|v }|r                    d           t                              d|           	 t?          j                    d <                                  d<   n# t          $ r}|d<   Y d }~nd }~ww xY w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_RETRIESrC  rs   r*  r  r  stream_request_completer  r  z9Streaming failed after partial delivery, not retrying: %sro  F)APIErrorrr  )
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 rP   r`   )r   phrase_err_lower_sses     rC   r   zKAIAgent._interruptible_streaming_api_call.<locals>._call.<locals>.<genexpr>  s<       7" 7"(. %+n$<7" 7" 7" 7" 7" 7"rE   zJStreaming attempt %s/%s failed (%s: %s), retrying with fresh connection...u'   ⚠️ Connection to provider dropped (u   ). Reconnecting… (attempt r.  ry  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.zTStreaming exhausted %s retries on transient error, falling back to non-streaming: %srh   znot supportedu   
⚠  Streaming is not supported for this model/provider. Falling back to non-streaming.
   To avoid this delay, set display.streaming: false in config.yaml
zCStreaming failed before delivery, falling back to non-streaming: %sr0  )!rJ  r}   r   r  rG  r   r(  r   r  r   r  r   rK   r  ConnectTimeoutPoolTimeoutr  r  r  rI  r  rX   rL   r   r   r  r   r[   r  r  r  ro  rS  )r  _max_stream_retries_stream_attemptrI  rg  _is_timeout_is_conn_err_is_sse_conn_err	_APIError_SSE_CONN_PHRASESstale
_err_lower_is_stream_unsupportedfallback_errr  r  r  r  r  r  rJ  rK  rA   s                 @rC   rL  z8AIAgent._interruptible_streaming_api_call.<locals>._call  s    """""%bi0G&K&K"L"LDh',-@1-D'E'E  O~=,@@@ JJLLL1@1B1BF:..1G1G1I1IF:.t "7!:!:8!D!D!-55nMf5ggggg .-u % w w w+E2 # #NN []^   /0F7O"FFFF` "7!:!:8!D!D!-55nMf5ggggg .-_ '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
 ' =, =:J =  /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!" !" !" )>(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!D 3a 7 !	    *-QJ (J 6 !B$3z$A 3  6 " $ 0 0%7!" !" !" #KK e !  
; 489;;OC0151M1Mj1Y1YF:..( ; ; ;.:F7OOOOOO;!6!:!:8!D!D!-55nMf5ggggg .-uwB "7!:!:8!D!D!-55nMf5ggggg .- "7!:!:8!D!D!-55nMf5gggg .s   O6  :B-:O6 -O 8(N; O6 EN;4J
N;
JN;JN;O6 !BN;9.M('N;(
N2M<7N;<NN;O6 ;O  O6 61P'HERMES_STREAM_STALE_TIMEOUTg     f@c              3   N   K   | ] }t          t          |                    V  !d S rP   rM   rL   )r   r  s     rC   r   z<AIAgent._interruptible_streaming_api_call.<locals>.<genexpr>E  s.      NN!#c!ff++NNNNNNrE   r      順 g     r@P  g      n@Tr3  rM  rN  uB   Stream stale for %.0fs — no chunks received. Killing connection.stale_stream_killr  stale_stream_pool_cleanupr*  r   rO  r  stream_interrupt_abortz+Agent interrupted during streaming API callro  r  )r   rD  rS  ro  r=  r   r  r  r   rz   ro   r  r  rQ  r  r  r   r  r   r  r  r  rU  r  r  r  rX   rR  )rA   r  r  rL  _stream_stale_timeout_base_est_tokens_stream_stale_timeoutr0  rcrU  rI  r  r  r_  r  r  r  rJ  rK  s   ```        @@@@@@@@rC   !_interruptible_streaming_api_callz)AIAgent._interruptible_streaming_api_call  sA   $ =---
 *8D&233J??-1**T*1111"T22!)4 0#UO!5> 	,	 	 	 	 	 	w	 w	 w	 w	 w	 w	 w	 w	 w	 w	r.	2 .	2 .	2 .	2 .	2 .	2 .	2 .	2`I	h I	h I	h I	h I	h I	h I	h I	h I	h I	h I	h I	hV &+295RTY+Z+Z%[%[" NNz~~j"/M/MNNNNNRSS  $'(BE$J$J!!6!!$'(BE$J$J!!$>!E$777				jjll +	VFF3F
 y{{_S114IIIX)  .228<<B~99"EX9YYY    D77?Z7[[[[    D (,y{{$( 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UW jjll +	VX '?&/!j!!s@   ; 	A$.G 
G G $G; ;
HH)A>J( (
J54J5c                 j   | 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	          \  }}|)t          j
        d|           |                                 S d}t          |j                  }|dk    rd}nZ|dk    s:|                    d                                                              d          rd}n|                     |          rd}| j        }	|| _        || _        || _        || _        d| _        |dk    rddlm}
m}m} |dk    r|j        p |            pdn|j        pd}|| _        || _        t5          |dd
          | _         |
|| j                  | _         ||          | _        d
| _        i | _        n"|j        | _        || _        |j        |d| _        |dk    }d|                                v rd|                                v p|| _         tC          | d          r| j"        rddl#m$}  || j        | j        | j        | j                  }| j        | j"        _        | j        | j"        _        | j        | j"        _        | j        | j"        _        || j"        _%        tM          || j"        j'        z            | j"        _(        | )                    d| d|            t          j*        d|	||           dS # tV          $ 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.
        Frs   r   r   r   r   re  Trh  Nz.Fallback to %s failed: provider not configuredr)  r+  r(  r,  r.  r/  r*  )rU  rV  rX  r   r\  r0  r6  r>  )get_model_context_length)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)-r  rM   r  r   r   r   _try_activate_fallbackr  rf  r   r   rL   r   r  r  r  r   r   r   r	  r  rU  rV  rX  r   r  rX   r  r  r  r  r  r  r  r>  agent.model_metadatar  r  r}   r  rM  r  r  r   ro  )rA   rh  fb_providerfb_modelrf  	fb_clientr  fb_api_modefb_base_url	old_modelrU  rV  rX  r]  rU  r  fb_context_lengthrg  s                     rC   r  zAIAgent._try_activate_fallback  s    3t';#<#<<<5!$"67!vvj))/R6688>>@@FF7OO)r0022 	1( 	1..000
T	1FFFFFF228t= = =LIq D! ! ! 22444 -Ki011Kn,,/++{/A/A#/F/F/L/L/N/N/W/WXd/e/e+2++K88 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'+29j$+O+O()?)?tOg)h)h&+:?=+I+I("&(##  )0'(0 +' '# #.1E"E!2!2!4!44UX^^EUEU9U '& $ t122 t7N IIIIII$<$<J L4=% % %! 15
'-37='026,'/37='09J'6;>%(?(QQ< <'8 00 0"-0 0   L48[   4 	1 	1 	1M>!LLL..00000000	1s&   ?AM4 I1M4 4
N2>)N-'N2-N2c                 r   | 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| _         d
| _        t-          j        d| j        | j                   dS # t0          $ 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 creates a fresh agent per message so this is a no-op
        there (``_fallback_activated`` is always False at turn start).
        Fr   r   r   r   r   r  r  r*  r   rO  r  r  r  Nrestore_primaryTro  r  r  r  r  r  r  z.Primary runtime restored for new turn: %s (%s)z%Failed to restore primary runtime: %s)r	  rN  r   r   r   r   r   r   r  r  r  rU  r  r  r  r  r  r  r>  r  rM  r  r   r  r   r   )rA   rtrU  ccrg  s        rC   _restore_primary_runtimez AIAgent._restore_primary_runtime  s    ' 	5"/	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,-BH23BK01BJ23BK "#> ?B"$%B"CB (-D$#$D L@
DM   4 	 	 	OCQGGG55555	s   E8F 
F6F11F6>   r  r  r  r  r  	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-researchr  Nprimary_recoveryTro  r  r   r   r   r   r   r*  r   rO  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)!r	  r   r[   _TRANSIENT_TRANSPORT_ERRORSr  r   r   r   rX   r$  r  r   rN  r   r  r   r   r   r   r  rU  r  r  r  r  r  r   r  r  ro  sleepr   r   )
rA   r  r  r  
error_typeprovider_lowerr  rU  	wait_timerg  s
             rC   _try_recover_primary_transportz&AIAgent._try_recover_primary_transport9  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)rK   r   r   r   )r   r   s     rC   _content_has_image_partsz AIAgent._content_has_image_parts  s^    '4(( 	5 	 	D$%% $((6*:*:>Z*Z*ZtturE   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   rm  
image/jpegdata:;rs   r   zimage/z.pngz.gifz.webpz.jpg)z	image/pngz	image/gifz
image/webpr  z	image/jpganthropic_image_F)r}  suffixdelete)rL   	partitionr_  rM   r  r   r   tempfileNamedTemporaryFilerH   base64	b64decoder
   rY   )	r  headerr  rN   mime	mime_partr  tmpr   s	            rC    _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   r  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_promptr  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: )r8  r9  rL   r:  r;  r  r   r_  r  tools.vision_toolsr  rL  r  rK   r   r   r   r   r  unlinkrI   )rA   r  r   	cache_keycached
role_labelanalysis_promptvision_sourcecleanup_pathrM  r  result_jsonrK  rg  notes                  rC   &_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 rP   r`   )r   r  s     rC   r   z8AIAgent._preprocess_anthropic_content.<locals>.<genexpr>  s'      BBdTBTBBBBBBrE   rZ  c              3      K   | ]}||V  	d S rP   r`   )r   r   s     rC   r   z8AIAgent._preprocess_anthropic_content.<locals>.<genexpr>  s'      ??D$?4??????rE   zI[A multimodal message was converted to text for Anthropic compatibility.])	r  rK   rL   r   r   r   r   r  r  )rA   r   r   
text_partsimage_notesr   r  r   
image_datar  r}  r  s               rC   _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ZrE   c           
      >    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)rK   r   r  r   )r   r   rA   s     rC   r   z>AIAgent._prepare_anthropic_messages_for_api.<locals>.<genexpr>  s`       
 
 sD!!Wd&C&CCGGIDVDV&W&W
 
 
 
 
 
rE   r   r   r  )r   rH  r  rK   r   r  r   rL   )rA   r  transformedr   s   `   rC   #_prepare_anthropic_messages_for_apiz+AIAgent._prepare_anthropic_messages_for_api  s     
 
 
 
#
 
 
 
 
 	   mL11 	 	Cc4(( !??	""CGGFF++5v66 C	NN rE   c                     t          | dd          pd                                dk    rdS t          | dd          pd                                }d|v pd|v S )zkTrue when using Alibaba/DashScope anthropic-compatible endpoint (model names keep dots, e.g. qwen3.5-plus).r   r   r  Tr   	dashscopealiyuncs)rX   r   )rA   bases     rC   _anthropic_preserve_dotsz AIAgent._anthropic_preserve_dots  sf    D*b))/R6688IEE4j"--3::<<d"8jD&88rE   c           
         | j         dk    ruddlm} |                     |          }t	          | dd          }|r|j        nd} || j        || j        | j        | j	        | j
        |                                 |          S | j         dk    rd}|}|re|d                             d	          d
k    rFt          |d                             d          pd                                          }|dd         }|st          }d| j                                        v pd| j                                        v }d}d}	| j	        r`t%          | j	        t&                    rF| j	                            d          du rd}	n'| j	                            d          r| j	        d         }| j        ||                     |          |                                 dddd}
|s
| j        |
d<   |	r-|r|                                 }|||
d<   n|dd|
d<   dg|
d<   n|sg |
d<   | j        
| j        |
d<   |
S |}d}|D ]u}t%          |t&                    sd|v rd} nV|                    d          }t%          |t0                    r+|D ]$}t%          |t&                    sd|v sd|v rd} n%|r nv|rt3          j        |          }|D ]}t%          |t&                    s|                    dd           |                    d          }t%          |t0                    rF|D ]C}t%          |t&                    r,|                    dd           |                    dd           D| j        pd                                |r_|d                             d	          d
k    r@t9          fd t:          D                       r t1          |          }i |d         d	d!i|d<   i }| j        r
| j        |d"<   | j        r
| j        |d#<   | j         r
| j         |d$<   | j!        r
| j!        |d%<   | j"        rd|d&<   | j#        r
| j#        |d'<   | j        |tI          tK          j&        d(d)                    d*}| j        r
| j        |d+<   | j        .|'                    | (                    | j                             n^| )                                rJd,| j        pd                                v r-	 dd-lm*}  || j                  }||d.<   n# tV          $ r Y nw xY wi }| )                                }d| j,        v pd| j,        v }|r|r||d/<   d0| j,        v }| -                                ra|r|                                 }|||d<   nC| j	        4t'          | j	                  }|r|                    d          du rn||d<   nddd1|d<   |rd2g|d3<   |r||d4<   |S )5z9Build the keyword arguments dict for the active API mode.r*  r   build_anthropic_kwargsr>  N)r   r   rP  r  r  is_oauthpreserve_dotsr  r(  r   r   rW  r   rs   models.github.air_  mediumTr  Feffortrg  )r   rn  rm  rP  rt  rw  rq  ru  r  )r  r  zreasoning.encrypted_contentrr  rv  r?  r   rD  rE  c              3       K   | ]}|v V  	d S rP   r`   )r   r  r  s     rC   r   z,AIAgent._build_api_kwargs.<locals>.<genexpr>  s(      EE!A%EEEEEErE   	developeronlyignoreordersortrequire_parametersdata_collectionra  rb  )r   r   r  rP  r6  )_get_anthropic_max_outputr  r   nousresearchr  r  product=hermes-agenttags
extra_body).r   r  r  r  rX   r  r   rP  r  r  r  r  r   rL   r   r   r   r   rK   r   r^  r1  r  #_github_models_reasoning_extra_bodyr   rH  r  r  r   r-   r	  r
  r  r  r  r  r=  r   r  rO  r  r  r  r   r   _supports_reasoning_extra_body)rA   r  r  r*  r  rn  payload_messagesis_github_responsesreasoning_effortreasoning_enabledr  github_reasoningsanitized_messagesneeds_sanitizationr   r   r   provider_preferencesr  r  _model_output_limitr"  _is_openrouter_is_github_models_is_nousr  r  s                             @rC   _build_api_kwargszAIAgent._build_api_kwargs  s   =000FFFFFF!%!I!I,!W!W d$8$??G07Ag,,TG))j+j?!%!61";;==&	 	 	 	 =---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    ( $$ GD4I4)P)P G(,,Y775@@(-%%*..x88 G'+'<X'F$  ,??@PQQ..00%'+ F ' =-1_)*  '& 	H (,'O'O'Q'Q$'3.>{+5ERX*Y*YF;')F(GF9%%( '$&y!*.2o*+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
 
(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
 


 : 	-"&*Jw?&d44T_EEFFFF$$&& 	8
8Hb7O7O7Q7Q+Q+Q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 	2'1J|$s   !S= =
T
	T
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.
        r  Tzai-gateway.vercel.shr  r_  r   github_model_reasoning_effortsFr0  api.mistral.air   )z	deepseek/z
anthropic/zopenai/zx-ai/zgoogle/gemini-2z
qwen/qwen3c              3   B   K   | ]}                     |          V  d S rP   )r_  )r   r}  r   s     rC   r   z9AIAgent._supports_reasoning_extra_body.<locals>.<genexpr>  s1      SS5##F++SSSSSSrE   )r   r   r4  r~   r   r   r   r   )rA   r4  reasoning_model_prefixesr   s      @rC   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   r3  Nr  Fr  r  xhighhighminimallow)r   r4  r   r   r  rK   r   r   rL   r   r   )rA   r4  supported_effortsrequested_efforts       rC   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d	|j        p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!          |t.                    r|                                s|                     |          \  }}|}t!          |t.                    r|                                st!          |t.                    r)|                                r|                                }n_t+          |dd          }|rt+          |dd          nd}|rt+          |dd          nd}|                     ||t          |                    }|                                }t+          |dd          }t!          |t.                    r|                                s|                     |          \  }}|}|                     |t!          |t.                    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  r  r  c              3   f   K   | ],}|                                 |                                 V  -d S rP   r   )r   bs     rC   r   z3AIAgent._build_assistant_message.<locals>.<genexpr>?  s7      &T&TQ!''))&Tqwwyy&T&T&T&T&T&TrE   NzCaptured reasoning (	 chars): r>  r   r   r  r  r  __dict__rl  r?  r  rD  r   rY   r   r  rE  r<  r  rj  r   ) r  r~   r   r  r  r  r  r  r   r   rM   r  r  r   r  r  rK   r   r   rE  rl  rX   r   rL   r   rF  r>  rM  r   r   rY   r   )rA   r  r  r  _from_structuredr   think_blockscombinedr   raw_details	preserveddcodex_itemsr   r   r?  rD  rZ  r  _fn_fn_name_fn_argsrE  r[  tc_dictr~  s                             rC   _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'*	
 
 $&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 )ub  Strip Codex Responses API fields from tool_calls for strict providers.

        Providers like Mistral strictly validate the Chat Completions schema
        and reject unknown fields (call_id, response_item_id) with 422.
        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).
        r   rD  rE  c                 ~    g | ]9}t          |t                    r fd |                                D             n|:S )c                 $    i | ]\  }}|v	||S r`   r`   )r   r  r  _STRIP_KEYSs      rC   r  zJAIAgent._sanitize_tool_calls_for_strict_api.<locals>.<listcomp>.<dictcomp>  s)    AAAdaA[,@,@Q,@,@,@rE   )rK   r   r  )r   r   rV  s     rC   r   z?AIAgent._sanitize_tool_calls_for_strict_api.<locals>.<listcomp>  s_     !
 !
 !
  "d##,AAAAbhhjjAAAA)+!
 !
 !
rE   )r   rK   r   )rR  r   rV  s     @rC   #_sanitize_tool_calls_for_strict_apiz+AIAgent._sanitize_tool_calls_for_strict_api  sn     [[..
*d++ 	N "45!
 !
 !
 !
 !!
 !
 !

 rE   	min_turnsc           	      H   | 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
}|	                    |           	 d| j
        v }g }|D ]}	|	                                }
|	                    d          dk    r|	                    d          }|r||
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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|                                 %          }|                     |          }nS|sQ| j        ||gdd&|                     d          } |                     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#        }n7tM          |d+          r'|j'        r |j'        d         j(        }|j#        r|j#        }|D ]}|j)        j*        dk    r	 tW          j,        |j)        j-                  }|                    d,d          }dd-l.m/}  ||                    d.          ||                    d/          |                    d0          | j        1          }| j0        s&tc          d2|                    d,d                      # td          $ r%} tf          4                    d3|            Y d} ~ d} ~ ww xY wn2# td          $ r%} tf          4                    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  r  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_sentinelr5  r   r>  r  r  r  r[  rW  rP  r   rY   rF  )call_llmTflush_memoriesrM  i   re  )taskr   rP  rs  r  r  Fr(  rP  rs  rv  r*  r  )r   r   rP  r  r  r  )r   r   rP  rs  r  r  normalize_anthropic_responsestrip_tool_prefixrm  r4  memory_toolactionr   old_textre  r4  r   rf  rq  u     🧠 Memory flush: saved to z!Memory flush tool call failed: %sz Memory flush API call failed: %sr`   )5r(  r  r$  r@  rX   rM   r  ro  	monotonicr   r   rH  r   r  rW  r  rP  r  r\  r  r   r1  r1  r  r  r  r   r  r?  r  r  rG  rH  r  r  r   r`  r  r  rm  r  r   rY   r   r   r   r+  rd  r  r  r   r  r   )!rA   r   rX  effective_minflush_content	_sentinel	flush_msg_is_strict_apir  r   rR  r  memory_tool_defr0  	_call_llm_aux_availabler  codex_kwargs_build_ant_kwargs
ant_kwargsr  r   assistant_msgr  
_nar_flush
_flush_msgr  r   r   flush_target_memory_toolrK  rg  s!                                    rC   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[\\		"""w	-1EENL - -((**776??k11 # 4 4I  A7@ 34K...OT222-t444! 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 # j  x|//0ABBiOO   x|//0ABBiOO  HRL,,->??9LL LLk EDDDDD!N $9))*+ ##           !&  " Kdm7H&H&H#55lCC(,(=(=>O(P(PW%.1]+&,668<L!4511,??# K9M(M(M______..*|*+%)"&"?"?"A"A	  
  :::FF# K!Z ,-.#&	 
 ,,T22
 o4==EU=VV[gn  K  Kq{  K  K  FJ  K  K  K 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   (D1U	 .U	 7J
 	U	 
JU	 JGU	 B5TU	 
UT?:U	 ?UU	 X 	
U8U3.X 3U88X BZ!r  r  r
  c                N   |                      |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t'          j                    j        d	d
          | _        | j        d| j         dz  | _        | j                            | j        | j        pt4          j                            dd          | j        |	           |ru	 | j                            |          }
| j                            | j        |
           n9# t@          t          f$ r%}tB          "                    d|           Y d	}~nd	}~ww xY w| j        #                    | j        |           d| _$        n2# t          $ r%}tB          %                    d|           Y d	}~nd	}~ww xY wtM          |          tO          |          z   }|| j        _(        d| j        _)        | j        j*        dk    r|| j        j*        z  }|dk     rd| _+        	 ddl,m-}  ||           n# t          $ r Y nw xY w||fS )zCompress conversation context and split the session in SQLite.

        Returns:
            (compressed_messages, new_system_prompt) tuple
        r   )rX  )current_tokensr  rP  r  r  r  Nr  r  r  r  r  )r  r  r   parent_session_idz,Could not propagate title on compression: %suK   Session DB compression split failed — new session will NOT be indexed: %s333333?F)reset_file_dedup).r]  r-  on_pre_compressr   r>  compressr"  format_for_injectionr   r)  r  r  r  get_session_titler  end_sessionr	   r  r  r  r  r  r  r  r  r  r   r  r   r   get_next_title_in_lineageset_session_titlerJ   r  r   update_system_promptr  r   r   r    r  r  rM  r  tools.file_toolsr~  )rA   r   r  r  r
  
compressedtodo_snapshotnew_system_prompt	old_titleold_session_id	new_titlerg  _compressed_est_post_progressr~  s                  rC   _compress_contextzAIAgent._compress_context[  s    	H222  	$44X>>>>    ,55h}5]]
(==?? 	Jv-HHIII&&((( 55nEE%6" 	qq ,>>tOO	 ,,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 ""344,Z889 	 6E29:6 "3a77,t/F/WWN$$05-
	999999W%%%% 	 	 	D	 ,,,sd   ; 
AAC;I+ :H
 	I+ 
I H;6I+ ;I  *I+ +
J5JJL 
L L effective_task_idapi_call_countc                     |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)rA   r  r   r  r  r   s         rC   _execute_tool_callszAIAgent._execute_tool_calls  s     '1
 !%
	*1*== ::%x1BN  %*D!!	 66!8->  %*D!!ED!))))s   &A A 	A&function_namer   c           	         |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 t/          |||| j        rt3          | j                  n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.
        todor   	todo_toolr  r  Fr  r  rq  r   Session database not available.r  ro  r   queryr   role_filterlimitr  r  r  r  dbcurrent_session_idr  r4  rc  re  r   rf  rg  )r:  r  r   clarify_toolquestionrm  r  rm  callbackr  r  goalcontexttoolsetstasksr   r  r  r  r  r   parent_agentNenabled_tools)r!  r  r   r"  r  r   r   tools.session_search_toolr   r  r+  rd  r$  r-  on_memory_writer   has_toolhandle_tool_calltools.clarify_toolr  r  r  r  r   r  r   )rA   r  r   r  
_todo_tool_session_searchr4  rx  rK  _clarify_tool_delegate_tasks              rC   _invoke_toolzAIAgent._invoke_tool  s    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!    (}.?=A=R\d4#8999X\   s   AF 
F'&F'c                 ,   0 |j         }t          |          } j        rMt           j         d| d           |D ].}|                    dd|j        j         d|j        d           /dS g }|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|                    |	|
|f           d                    d |D                       } j        st          d| d|            t;          |d          D ]\  }\  }}}t          j        |d          } j        rKt          d| d| dtA          |!                                           d           t          d |            qt          |           j"        k    r|d j"                 d!z   n|}t          d| d| dtA          |!                                           d"|            |D ]d\  }}} j#        rW	 tI          ||          } #                    |||           6# t,          $ r!}tK          j&        d#|            Y d}~\d}~ww xY we|D ]Y\  }}} j'        rL	  '                    |j        ||           +# t,          $ r!}tK          j&        d$|            Y d}~Qd}~ww xY wZdg|z  00 fd%}d} j        rV j#        sOtQ          j)        tT          j+                  }tU          | d&| d'd( j,        )          }|-                                 	 t]          |t^                    }t`          j1        2                    |*          5 }g }t;          |          D ]7\  }\  }}}|3                    |||||          }|                    |           8t`          j1        4                    |           ddd           n# 1 swxY w Y   |rRtk          d+ 0D                       }tk          d, 0D                       } |6                    d-| d.| d/| d0d1           nZ# |rStk          d+ 0D                       }tk          d, 0D                       } |6                    d-| d.| d/| d0d1           w w xY wt;          |          D ]\  }\  }}}0|         }!|!	d2| d3}"d4}#n|!\  }
}}"}#}$|$r<t          |"          d5k    r
|"dd5         n|"}%tn          8                    d6|
|#|%            j        rCtK          j&        d7|
 d8|#d9d:           tK          j&        d;t          |"           d<|"             j        r,ts          |||#|"=          }& :                    d>|&            n j        s| j        r-t          d?|dz    d8|#d9d:           t          d@|"            nHt          |"           j"        k    r|"d j"                 d!z   n|"}'t          d?|dz    d8|#d9dA|'             j;        rM	  ;                    |j        |||"           n.# t,          $ r!}tK          j&        dB|            Y d}~nd}~ww xY wdC}(t          |"          |(k    r%t          |"          })|"d|(         dD|)dEdF|(dEdGz   }"d|"|j        d}*|                    |*            <                    |          }+|+r|r|dH                             dI          dk    r|dH         dJ         },	 t          j        |,          }-t          |-t                     r%|+|-dK<   t          j        |-d          |dH         dJ<   n|,dL|+ z   |dH         dJ<   n-# t          j        tz          f$ r |,dL|+ z   |dH         dJ<   Y nw xY w j        s@ j>        |z
  }.|. j>        dMz  k    rdNndO}/t           j         |/ d|. dP           dS dS dS dS dS )QzExecute 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 rP   r`   )r   r  rY   s      rC   r   z9AIAgent._execute_tool_calls_concurrent.<locals>.<genexpr>L  s(      "G"GJAtQ4"G"G"G"G"G"GrE   u     ⚡ Concurrent: u    tool calls — rs   Fr        📞 Tool r  (ry       Args: rZ  ) - Tool progress callback error: Tool start callback error: c                 @   t          j                     }	                     ||
          }n=# t          $ r0}d| d| }t                              d||d           Y d}~nd}~ww xY wt          j                     |z
  }t          ||          \  }}	|||||f| <   dS )z%Worker function executed in a thread.Error executing tool '': z_invoke_tool raised for %s: %sTr  N)ro  r  r   r  ro  r4   )r3  r   r  r   r  rK  
tool_errordurationis_errorr  r  resultsrA   s             rC   	_run_toolz9AIAgent._execute_tool_calls_concurrent.<locals>._run_toolk  s    IKKEi**=-IZ[[ i i iP-PPJPP=}jcghhhhhhhhi y{{U*H.}fEEKHa+]FHhWGENNNs   . 
A(&A##A(u    ⚡ running z tools concurrentlydotsspinner_typeprint_fn)max_workersc              3      K   | ]}|dV  	d S )Nrs   r`   r   rs     rC   r   z9AIAgent._execute_tool_calls_concurrent.<locals>.<genexpr>  s"      DDaammmmmDDrE   c              3   *   K   | ]}||d         V  d S )Nr  r`   r  s     rC   r   z9AIAgent._execute_tool_calls_concurrent.<locals>.<genexpr>  s&      GG!GGrE   u   ⚡ r.  z tools completed in .1fzs totalr  z!': thread did not return a resultr  r   "Tool %s returned error (%.2fs): %sTool  completed in .2fsTool result (rC  rK         ✅ Tool      Result: s - Tool complete callback error: r   

[Truncated: tool response was rm   chars, exceeding the  char limit]rF  r   r   r   r  皙?   ⚠️  WARNING   💡 CAUTION iterations remaining)?r   rM   r  r  r  r   r   rY   r  r)  r*  r   r   r   r   rK   r   r  r  r   get_working_dir_for_pathensure_checkpointr   r   r   r  getcwdr  r  rd  r   r  r   rz  r  r  _build_tool_previewr   r   r  randomchoicer1   KAWAII_WAITINGr  r  r   _MAX_TOOL_WORKERS
concurrentfuturesThreadPoolExecutorsubmitwaitr  r  r  r   _get_cute_tool_message_implr  r  _get_budget_warningr   r   )1rA   r  r   r  r  r   	num_toolsr   parsed_callsr   r  r   	file_pathwork_dirr   r   tool_names_strrJ  rY   r   args_strargs_previewpreviewcb_errr  spinnerfacer  executorr  rw  rU  	total_durr  function_resulttool_durationr  result_previewcute_msgresponse_previewMAX_TOOL_RESULT_CHARSoriginal_lenrf  budget_warninglast_contentr   r{   tierr  s1   `  `                                            @rC   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2223333ORS[}}_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DDDD  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$
	X 
	X 
	X 
	X 
	X 
	X 
	X ? 	4#> 	=!=>>D#t$X$X)$X$X$Xgmx|  yG  H  H  HGMMOOO	gi):;;K#66;6OO 1S[+4\+B+B & &'A'D$ 	1b$EEANN1%%%% "''0001 1 1 1 1 1 1 1 1 1 1 1 1 1 1  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 $-\#:#: 3	& 3	&AD$
Ay"b4"b"b"b #YZV}o}h w>A/>R>RUX>X>X_TcT%:%:^mNNN#GXeguvvv' dM"[-"["[}"["["["[\\\M"b#o2F2F"b"bQ`"b"bccc  	f6tT=Yhiii  h1111_ f' fO!OO=OOOOPPP;/;;<<<<Z]^mZnZnqu  rG  [G  [G7M8M7M'NQV'V'V  M\$d!dd=dddRbddeee* MM//tT?SSSS  M M MM"K6"K"KLLLLLLLLM %,!?##&;;;"?33#$:%:$:;K<S K K%:JK K KK   * " H
 OOH%%%% 11.AA 	Th 	T8B<+;+;F+C+Cv+M+M#B<	2LQL11fd++ U0>F,-.2je.T.T.THRL++.:=TN=T=T.THRL+()4 Q Q Q*69P9P9P*PY'''Q? T /.@	,59Ls9R,R,R((XfR$RR)RRRSSSSS	T 	T 	T 	T+M+MT Ts   B<<CC;AE
EE/BG66
HH'M;;
N&N!!N&:O
P!O==P35U= (A)TU= T!!U= $T!%U= =AW]//
^9^^ Ab   'c
	c
c                    t          |j        d          D ]U\  }}| 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        }|dk    rd| _
        n|dk    rd| _        	 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 }| j        st          j        |d          }| j        rKt/          d| d| dt1          |                                           d           t/          d|            nft          |          | j        k    r|d| j                 dz   n|}t/          d| d| dt1          |                                           d|            | j        rW	 t9          ||          }|                     |||           n.# t:          $ r!}t!          j        d|            Y d}~nd}~ww xY w| j        rL	 |                     |j        ||           n.# t:          $ r!}t!          j        d|            Y d}~nd}~ww xY w|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          }tK          |          ra|"                    d           p%tM          j'        d!tM          j(                              }| j         $                    |d"|dd#                     n# t:          $ r Y nw xY wtS          j)                    }|d$k    rdd%l*m+}  ||"                    d&          |"                    d'd          | j,        (          }tS          j)                    |z
  }| j        r)|                     d)t[          d$|||*                      nP|d+k    r| j.        st          j        dd,d-          }n[dd.l/m0}  ||"                    d/d          |"                    d0          |"                    d1d2          | j.        | j1        3          }tS          j)                    |z
  }| j        r)|                     d)t[          d+|||*                      n|dk    r|"                    d4d          }dd5l2m3}  ||"                    d6          ||"                    d7          |"                    d8          | j4        9          }tS          j)                    |z
  }| j        r)|                     d)t[          d|||*                      n|d:k    rdd;l5m6}  ||"                    d<d          |"                    d=          | j7        >          }tS          j)                    |z
  }| j        r)|                     d)t[          d:|||*                      nB|d?k    rdd@l8m9} |"                    dA          }|r)t%          |t0                    rdBt          |           dC} n(|"                    dD          pdddE         }!|!rdF|! ndG} d}"| j        rU| j        sNtu          j;        tx          j=                  }#ty          |# dH|  dI| j>        J          }"|"?                                 |"| _@        d}$	  ||"                    dD          |"                    dK          |"                    dL          ||"                    dM          | N          }|}$d| _@        tS          j)                    |z
  }t[          d?|||$*          }%|"r|"A                    |%           n| j        r|                     d)|%            n# d| _@        tS          j)                    |z
  }t[          d?|||$*          }%|"r|"A                    |%           w | j        r|                     d)|%            w w xY w| j        rd}"| j        srtu          j;        tx          j=                  }#t          |          }&t9          ||          p|}ty          |# dH|& dH| dI| j>        J          }"|"?                                 d}'	 t          |||| jD        rt1          | jD                  ndO          }|}'n=# t:          $ r0}(dP| dQ|( }t          F                    dR||(dS           Y d}(~(nd}(~(ww xY wtS          j)                    |z
  }t[          ||||'*          }%|"r|"A                    |%           n|                     d)|%            n# tS          j)                    |z
  }t[          ||||'*          }%|"r|"A                    |%           w |                     d)|%            w xY w	 t          |||| jD        rt1          | jD                  ndO          }n=# t:          $ r0}(dP| dQ|( }t          F                    dR||(dS           Y d}(~(nd}(~(ww xY wtS          j)                    |z
  }| j        r|nt          |          dTk    r
|ddT         n|})t          ||          \  }*}+|*rt                              dU|||)           | j        rCt!          j        dV| dW|dXdY           t!          j        dZt          |           d[|            | jH        rM	 | H                    |j        |||           n.# t:          $ r!}t!          j        d\|            Y d}~nd}~ww xY wd]},t          |          |,k    r%t          |          }-|d|,         d^|-d_d`|,d_daz   }d||j        d
}.|	                    |.           | j        sv| j        r*t/          db| dW|dXdY           t/          dc|            nEt          |          | j        k    r|d| j                 dz   n|}/t/          db| dW|dXdd|/            | j        r|t          |j                  k     r}t          |j                  |z
  }0|                     | j         d|0 ded           |j        |d         D ]2}|j        j        }	ddf|	 dg|j        d
}
|	                    |
           3 n>| jI        dk    r1|t          |j                  k     rtS          jJ        | jI                   W| K                    |          }1|1r|r|dh         "                    di          dk    r|dh         d7         }2	 t          j        |2          }3t%          |3t&                    r%|1|3dj<   t          j        |3d          |dh         d7<   n|2dk|1 z   |dh         d7<   n-# t          j        t          f$ r |2dk|1 z   |dh         d7<   Y nw xY w| j        s@| jM        |z
  }0|0| jM        dlz  k    rdmndn}4t/          | j         |4 d|0 do           dS dS dS dS dS )pz`Execute tool calls sequentially (original behavior). Used for single calls or interactive tools.rs   Nr  r  Tr  r   r  r  r	  r  r   r  z(Unexpected JSON error after validation: Fr   r  r  r  ry  r  rZ  r  r  r  r  r   r   r  r  r   r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r4  rc  re  r   rf  rg  r   r  r  rm  r  r  r  r  u   🔀 delegating z tasksr     u   🔀 u   🔀 delegatingr'  r  r  r  r  r   r  r  r  r  z&handle_function_call raised for %s: %sr  r   r  r  r  r  r  r  rC  r  r  r  rm  r  r  r  r  r  z remaining tool call(s)u   [Tool execution skipped — z* was not started. User sent a new message]rF  r   r   r  r  r  r  r  )Nrd  r   r  r  r  rM   r   rY   r  r   r)  r*  r   r   r   r   r   r   rK   r   r  r   r  r  r   rz  r  r  r  r   r   r  r  r  r   r  r  r   r   r  r  ro  r!  r  r"  r  r  r  r   r  r+  rd  r$  r  r  r  r  r  r  r  r1   r  r  r  _delegate_spinnerr  _get_tool_emojir   r  r  ro  r4   r  r   r  r  r   r   )5rA   r  r   r  r  rJ  r   remaining_calls
skipped_tcskipped_nameskip_msgr  r   rg  r  r	  r
  r  r  r  r   r   tool_start_timer  r  r  r  r4  rx  r  r  	tasks_argspinner_labelgoal_previewr  r  _delegate_resultr  emoji_spinner_resultr  r  _is_error_resultr  r  r  rf  r  r{   r  r  r   r  s5                                                        rC   r  z&AIAgent._execute_tool_calls_sequential  s   %&7&BAFF E	, E	,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 ((+,((.00*+'# $
9+=+G H H' # # # N1 N NOOO "# mT22 # "? n:m%HHH' n[[[m[[d=CUCUCWCW>X>X[[[\\\2223333ORS[}}_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* MM1-OOG//wVVVV  M M MM"K6"K"KLLLLLLLLM ' JJ,,Y\=-XXXX  J J JM"H"H"HIIIIIIIIJ  777D<P<X7 - 1 1&" = =I  #'#7#P#PQZ#[#[,>>$&?&?&?   !   D 
**t/C/K*'++Ir::C.s33 +//	::dbiXZXaXcXc>d>d,>>!?S"X!?!?   !   D #ikkO&&CCCCCC",*'++G44'++GU;;*# # #
 !%	o =? CLL  "B&A&-Yfo~&&&  "B  "B  C  C  C"222' 
&*jUMn1o1o&p&pOO[[[[[[&5o+//<<$1$5$5m$D$D+//;;++/?' ' 'O !%	o =? 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::,# # # !%	o =? 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 =? 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? $4+F $!=)EFFD+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 ">2 $!=)EFFD+M::E1-OO`S`G+t,G,Ge,G,Gg,G,GV\gkguvvvGMMOOO"&6&:%}6GEIEZ&dd4+@&A&A&A`d' ' '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...._(__5555 %)IKK/$AM:=-Yfo~H 6X...._(__5555u&:%}6GEIEZ&dd4+@&A&A&A`d' ' '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 sC]Tacqrrr# `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 %,!?##&;;;"?33#$:%:$:;K<S K K%:JK K KK   * ) H
 OOH%%%? d' dMMMMMMMNNN;/;;<<<<Z]^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?+++ 11.AA 	Th 	T8B<+;+;F+C+Cv+M+M#B<	2LQL11fd++ U0>F,-.2je.T.T.THRL++.:=TN=T=T.THRL+()4 Q Q Q*69P9P9P*PY'''Q? T /.@	,59Ls9R,R,R((XfR$RR)RRRSSSSS	T 	T 	T 	T+M+MT Ts   C%%D4DD'H66
I! II!,J		
J4J//J4AL
L&%L&<BO
OOA`((A*b0eg#
f&f<g#fg##Ah>.i11
j+;&j&&j+0n
n9n44n94Ax 'x>=x>c                     | j         r| j        dk    rdS || j        z  }| j        |z
  }|| j        k    rd| d| j         d| dS || j        k    rd| d| j         d| d	S dS )
zReturn a budget pressure string, or None if not yet needed.

        Two-tier system:
          - Caution (70%): nudge to consolidate work
          - Warning (90%): urgent, must respond now
        r   Nz[BUDGET WARNING: Iteration r.  z. Only zd iteration(s) left. Provide your final response NOW. No more tool calls unless absolutely critical.]z[BUDGET: Iteration z. z1 iterations left. Start consolidating your work.])r  r   r  r  )rA   r  progressr{   s       rC   r  zAIAgent._get_budget_warning  s     , 	0Cq0H0H4!D$77'.8	t555cn c ct?R c c!c c c
 t555Pn P Pt7J P PP P P trE   compaction_progressc                 t   ddl m}m} |j        r|j        |j        z  nd}| j        dv r. |||j        || j                  }|                     |           | j        rY	  |||| j                  }|                     d|           dS # t          $ r  t                              dd	
           Y dS w xY wdS )u  Notify the user that context is approaching the compaction threshold.

        Args:
            compaction_progress: How close to compaction (0.0–1.0, where 1.0 = fires).
            compressor: The ContextCompressor instance (for threshold/context info).

        Purely user-facing — does NOT modify the message stream.
        For CLI: prints a formatted line with a progress bar.
        For gateway: fires status_callback so the platform can send a chat message.
        r   )format_context_pressureformat_context_pressure_gatewayr  )Nr  )r,  rM  r  r?  )r,  r  r?  context_pressurez)status_callback error in context pressureTr  N)agent.displayr.  r/  r  rM  r  r?  r  r  r   r  r   )rA   r,  r  r.  r/  threshold_pctliner   s           rC   _emit_context_pressurezAIAgent._emit_context_pressure  s+    	[ZZZZZZZS]Slu
3j6OOOru
 =M))**$7!+!<"/$($<	  D T"""  		YY55(;&3(,(@  
 $$%7===== Y Y YHSWXXXXXXY		Y 		Ys    )B &B54B5c           
      d   t          d| j         d           d}|                    d|d           	 d| j        v }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 r4tQ          j)        d%d	|tP          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 r4tQ          j)        d%d	|tP          j*        &          	                                }|r|                    d'|d           nd(}nd(}nH# tV          $ r;} tY          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  rP  r5  )r  r  Nr   r  rW  rs   r   r  r  Tr  r  r   r!  r(  rP  )r   r   r  r  r  r  r   r"  r*  )r  r`  )r   r   rP  r  r  r  r  ra  iteration_limit_summaryr  r[  z<think>.*?</think>\s*r  r>  z>I reached the iteration limit and couldn't generate a summary.)r   r   rP  r  r  r  r  iteration_limit_summary_retryz Failed to get summary response: z"I reached the maximum iterations (z!) but couldn't summarize. Error: r`   )/r  r   r   r   rH  r  rW  r  r  r   r  rd  insertr$  r  r   r1  r  r  r   r   r  rO  r  r	  r
  r  r  r  r  r`  r  r  r?  r  rG  rH  r  rm  r  r  r   r  r   r   r   rL   )!rA   r   r  summary_requestrm  r  r   rR  internal_fieldeffective_system
sys_offsetr3  pfmsummary_extra_bodyr0  rq  summary_responser  r  final_responsesummary_kwargsr,  _bak_nar_ant_kw_msgretry_response	retry_msg_bak2_nar2_ant_kw2
_retry_msgrg  s!                                    rC   _handle_max_iterationszAIAgent._handle_max_iterations4  s   bT5Hbbbccc. 	
 	ODDEEEH	A .1EENL - -((**&D 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   V3W( (
X-21X((X-stream_callbackpersist_user_messagec                    ɇʇˇ̗ t                                                         t          |t                    rt	          |          }t          |t                    rt	          |          }| _        d _        | _        |pt          t          j	                              }d _
        d _        d _        d _        d _        d _        d _        d _         j        dk    r;	                                  r                     d           n# t*          $ r Y nw xY wt-           j                   _        |rt3          |          ng }|rt5          |           |r. j                                        s                     |            xj        dz  c_        ||n|}	d}
 j        dk    r9d j         v r0 j!        r) xj"        dz  c_"         j"         j        k    r	d}
d _"        d	|d
}|#                    |           tI          |          dz
  }| _         j%        s8 &                    d|dd          tI          |          dk    rdnd d            j'        =d}|rQ j(        rJ	  j(        )                     j*                  }|r|+                    d          pd}n# t*          $ r Y nw xY w|r| _'        nމ ,                    |           _'        	 ddl-m.}  |d j*         j/        ta           dd          pd           n2# t*          $ r%}tb          2                    d|           Y d}~nd}~ww xY w j(        rY	  j(        3                     j*         j'                   n2# t*          $ r%}tb          4                    d|           Y d}~nd}~ww xY w j'        } j5        rFtI          |           j6        j7         j6        j8        z   dz   k    rts          ||pd j:        pd          }| j6        j;        k    rtb          <                    d|d j6        j;        d j/         j6        j=        d            j%        s( &                    d|dd j6        j;        dd           t}          d          D ]q}tI          |          } ?                    ||||          \  }}tI          |          |k    r n0d}ts          ||pd j:        pd          }| j6        j;        k     r nrd}	 ddl-m.}  |d j*        |	t3          |          t          |            j/        ta           dd          pd           }g }|D ]}t          |t                    r>|+                    d!          r)|#                    t          |d!                              Ut          |t                    r)|B                                r|#                    |           |rd"C                    |          }n2# t*          $ r%}tb          2                    d#|           Y d}~nd}~ww xY wd}d}d}d}d}d}d}  D                                 d}! jE        rG	 t          |t                    r|nd}" jE        F                    |"          pd}!n# t*          $ r Y nw xY w| j        k     @r j        jG        dk    @r~ jH        I                                  jJ        r d} j%        s &                    d$           @n>|dz  } j        K                                s9 j%        s0 &                    d% j        jL         d& j        jM         d'           ?n jN        	 g }#t          |          D ]D}$|$+                    d(          d)k    r)|$+                    d*          rd+ |$d*         D             }# nE N                    ||#           n3# t*          $ r&}%tb          4                    d,||%           Y d}%~%nd}%~%ww xY w jP        dk    rd- j         v r xjQ        dz  c_Q        g }&t          |          D ]\  }'}(|(S                                })|'|k    rQ|(+                    d(          d	k    r8|!r6|)+                    d.d          }*t          |*t                    r|*d"z   |!z   |)d.<   |(+                    d(          d)k    r|(+                    d/          }+|+r|+|)d0<   d/|)v r|)T                    d/           d1|)v r|)T                    d1           d2 jU        v r V                    |)           |&#                    |)           |pd}, jW        r|,d"z    jW        z   B                                },|r|,d"z   |z   B                                },|,r	d3|,d
g|&z   }& jX        rK|,rdnd}-t           jX                  D ]0\  }'}.|&Y                    |-|'z   |.S                                           1 jZ        r t          |& j\         j        dk    4          }& ]                    |&          }&t          d5 |&D                       }/|/d6z  }0d̉ j%        s _                    d7 j`         d8| d& j         d            _                     j`         d9tI          |&           d:|0dd;|/dd<            _                     j`         d= j:        rtI           j:                  nd            nt          jb        t          jd                  }1t          jb        t          je                  }2 jf        r f                    |1 d>|2 d           n[ g                                sGt          jb        g d?          }3t          |1 d>|2 d|3 jh        @          ̠̉i                                  jj        rt          j4        dA j/         dBtI          |           dC j:        rtI           j:                  nd            t          j4        dD|r|dE         d(         ndF            t          j4        dG|0ddH           t          jl                    }4d}5d}6d}7d}8d}9d}:d};d}<d}=d}>dI}?d}@|5|6k     "r	  m                    |&          }A j        dJk    r n                    |AdK          }At          dL          r p                    |AdMN            fdO}Bd}C g                                s'ddPlqmr}D t          ta           dQd          |D          rd}C|Cr s                    |A|BR          }@n t                    |A          }@t          jl                    |4z
  }Er̠u                    d           d̉ jf        r f                    d            j%        s! _                     j`         dS|EdTdU            jj        rF|@rta          |@dVdW          ndW}Ft          j4        dX|F dYt          |@dZ          r|@jw        ndW            d}Gg }H j        dJk    r|@ta          |@d[d          nd}I|@d}G|H#                    d\           nt          |It2                    sd}G|H#                    d]           natI          |I          dk    rd}G|H#                    d^           n5 j        dk    r|@ta          |@d.d          nd}J|@d}G|H#                    d\           nt          |Jt2                    sd}G|H#                    d_           ntI          |J          dk    rd}G|H#                    d`           n|@/t          |@da          r|@jx        tI          |@jx                  dk    rrd}G|@|H#                    d\           nXt          |@da          s|H#                    db           n2|@jx        |H#                    dc           n|H#                    dd           |Grr̠u                    de           d̉ jf        r f                    d           |5dz  }5 jy        tI           jz                  k     r                     df            {                                rd}5dgdg}K|@rmt          |@dh          r]|@j|        rVt          |@j|                  t          |@j|        di          r,|@j|        j}        r |@j|        j}        +                    djdg          }Kn-|@r+t          |@dk          r|@j~        rt          |@j~                  |Kdgk    r#|@r!t          |@dV          r|@j/        r
dl|@j/         }K|Kdgk    rK|@rIdm t          |@                                          D             }L jj        rt          j4        dn|L             _                     j`         do|5 d&|6 dpdqC                    |H           dr            _                     j`         ds|K dr                                ʦ          }M _                     j`         dt|M dr            _                     j`         du|EdTdvdr           |5|6k    r                     dw|6 dx            {                                rd}5                     dy|6 dz           t          j|         j`         d{|6 d|                                ||           |d|d}dd~S t          dd|5dz
  z  z  d          }N _                     j`         d|N ddr           t          j2        d|5 d&|6 dpdqC                    |H           d|K            t          jl                    |Nz   }Ot          jl                    |Ok     r jJ        rX _                     j`         ddr                                ||            D                                 d|5 d&|6 d||dddS t          j        d           t          jl                    |Ok     o j        dJk    rpta          |@dd          }Pta          |@dd          }Qd}Rt          |Qt                    r|Q+                    d          }Rnta          |Qdd          }R|Pdk    r|Rdv rd}?nCdI}?n@ j        dk    r#dId*ddId}S|S+                    |@j        dI          }?n|@jx        d         j        }?|?dk    r1 _                     j`         ddr           d}T j        dk    rAt          |@da          r|@jx        r|@jx        d         j~        nd}U|Urta          |Ud.d          nd}Tns j        dk    rhg }Vta          |@d.g           D ];}Wta          |Wdd          dk    r$|V#                    ta          |Wdd                     <|Vrd7C                    |V          nd}T|Tduo                     |T           p|Tdu }X|XrWd}Y _                     j`         ddr           d}Z                     |                                ||           |Z||dd|YdS  j        dk    r|@jx        d         j~        }[|[j        s|dz  }                     |[|?          }\|#                    |\           |[j        r
||[j        z  }|dk     rZ _                     j`         d| d           d	dd
}]|#                    |]           | _                             |           d}>nS                     |          B                                }^                     |                                ||           |^pd||ddddS tI          |          dk    rf _                     j`         d                                |          }_                     |                                ||           d|_|ddddS  _                     j`         ddr                                ||           d||ddddS t          |@dZ          r|@jw        rt!          |@jw         j         j                  }`|`j        }a|`j        }b|`j        }c|a|b|cd}d j6                            |d            j6        j        r~ j6        j=        }eta           j6        dd          rDt/           j/         j        |e            &                     j`         d|edd j/                    d j6        _        d j6        _         xj        |az  c_         xj        |bz  c_         xj        |cz  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_        tO           j/        |` j         j        ta           dd                    }f|fj        # xj        tU          |fj                  z  c_        |fj         _        |fj         _         j(        r j*        r	  j(                             j*        |`j        |`j        |`j        |`j        |`j        |fj        tU          |fj                  nd|fj        |fj         j         j        |fj        dk    rdnd j/                   n# t*          $ r Y nw xY w jj        r2t          j4        d|dd         dd|dd         dd|dd         d            jZ        r̉ j        dk    r1ta          |@jw        dd          pd}gta          |@jw        dd          pd}hnDta          |@jw        dd          }i|irta          |idd          pdnd}g|irta          |idd          pdnd}h|dd         }j|jdk    r|g|jz  dz  nd}k j%        s- _                     j`         d|gdd&|jdd|kdd|hdd
           d}<np# t`          $ r r̠u                    d           d̉ jf        r f                    d           t          jl                    |4z
  }l _                     j`         ddr                                ||           d}d|ldd}Y nt*          $ r}mr̠u                    d¦           d̉ jf        r f                    d           t          |mtb                    rMta           dd          s<d _        te          |          r% _                     j`         dĝdr           Y d}m~mjta          |mdd          }n                     |n|<Ʀ          \  }o}<|orY d}m~m j        dJk    rN j        dk    rC|ndk    r=|9s;d}9                     dr          r# _                     j`         dɝ           Y d}m~m j        dk    rI j        dk    r>|ndk    r8|;s6d};                     dr          rtm           j`         d˝           Y d}m~mJ j        dk    r|ndk    rt           d̦          r|:sd}:ddlm}p                                  rtm           j`         dΝ           Y d}m~m j        }q |p|q          rdnd}rtm           j`         dѝ           tm           j`         d|r            tm          |qr(tI          |q          dk    r j`         d|qddӅ          dn	 j`         d՝           tm           j`         d֝           ddlm}s  |s            }ttm           j`         d|t dٝ           tm           j`         d|t d۝           tm           j`         dܝ           tm           j`         dݝ           tm           j`         dޝ           tm           j`         dߝ           |5dz  }5t          jl                    |4z
  }ut{          |m          j        }vt          |m                                          ʉ                     |m          }wtb          2                    d|5|6|v                                 |w           ta           dd          }xta           dd          }*ta           dVd          }y|nrd|n dnd}z _                     j`         d|5 d&|6 dp|v |z dr            _                     j`         d|x d|y dr            _                     j`         d|* dr            _                     j`         d|w dr           |nrU|ndk     rOta          |mdd          }{|{rt          |{          dd         nd}|||r! _                     j`         d|| dr            _                     j`         d|udTdtI          |&           d|0ddH            jJ        r} _                     j`         ddr                                ||            D                                 d|v d                     t          |m                     d||dddcY d}m~mS ta          |mdd          }n|ndk    pdv pdv pdv pdv pdv }}|}ro jy        tI           jz                  k     rR j        }~|~duo|~                                }|s1                     d            {                                rd}5Y d}m~m|ndk    pdv pdv pdv }|r| dz  } | |8k    r _                     j`         d |8 ddr            _                     j`         ddr           t          j|         j`         d|8 d                                ||           |d|d|8 dddcY d}m~mS                      d|  d&|8 d           tI          |          } ?                    |||0|          \  }}tI          |          |k     rH                     d	| d
tI          |           d           t          j        d           d}=Y d}m~mnM _                     j`         ddr            _                     j`         ddr           t          j|         j`         d                                ||           |d|dddcY d}m~mS t          fddD                       }|s|ndk    rta          ta           dd          dd          }|0|dz  k    ptI          |&          dk    }tI          ʠB                                          dk     }|r:|r8d} _                     j`         d|0ddtI          |&           ddr           |r j6        }|j=        }t          ʦ          }|r3||k     r-|} _                     j`         d|dd|dddr           nt          |          }|ru||k     ro||_=        t          ||j        z            |_;        d|_        t          |o||k              |_         _                     j`         d|dd
|ddHdr           n  _                     j`         ddr           | dz  } | |8k    r _                     j`         d |8 ddr            _                     j`         ddr           t          j|         j`         d |8 d                                ||           |d|d!|8 dddcY d}m~mS  _                     j`         d"|  d&|8 d           tI          |          } ?                    |||0|          \  }}tI          |          |k     s|ra||k     r[tI          |          |k     r,                     d	| d
tI          |           d           t          j        d           d}=Y d}m~mn _                     j`         d#dr            _                     j`         d$dr           t          j|         j`         d%|0dd&                                ||           |d|d'|0dd(ddcY d}m~mS h d)}t          |mt          t          f          ot          |mtb                     }ta          |mdd          pi }{t          |{t                    r*|{+                    dhi           +                    dkd          nd}|ndk    o(|B                                                                d*v }t          |nt                    od|ncxk    odk     nc o|n|vo| }|s |st          fd+d,D                       o| }|r*                     d-|n d.            {                                rd}5Y d}m~mԉ p                    |Ad/|m0            _                     j`         d1|n d2dr            _                     j`         d|x d|y dr            _                     j`         d|* dr           |nd3v sd4v s
d5v sd6v r _                     j`         d7dr            _                     j`         d8dr            _                     j`         d9|y d:dr           d;t          |*                                          v r  _                     j`         d<dr           n  _                     j`         d=dr           t          j|         j`         d>|m            |ndk    r<|0d?k    stI          |&          dk    r! _                     j`         d@dr           n                     ||           d||ddt          |m          dcY d}m~mS |5|6k    r|7s#                     |m|5|6A          r
d}7d}5Y d}m~m                     dw|6 dB            {                                rd}5Y d}m~m)                     |m          }|}r% _                     j`         dC|6 dDdr           n# _                     j`         dy|6 dEdr            _                     j`         dF| dr           ta          |mdd           ot          fdGdHD                       }|r@ _                     j`         dIdr            _                     j`         dJdr           t          j|        dK j`        |6||x|ytI          |&          |0d            p                    |AdL|m0                                ||           dM|6 dN| }|r|dOz  }|||dd|dcY d}m~mS d}|}rta          ta          |mdPd          dQd          }|ryt          |dR          rh|+                    dS          p|+                    dT          }|r:	 t          t          |          d          }n# t          t          f$ r Y nw xY w|r|nt          d|5z  d          }N|}r&                     dU|N dV|5dz    d&|6 dW           n!                     d|N dX|5 d&|6 dW           tb          2                    dY|N|5|6                                 |m           t          jl                    |Nz   }Ot          jl                    |Ok     r jJ        r^ _                     j`         ddr                                ||            D                                 dZ|5 d&|6 d||dddcY d}m~mS t          j        d           t          jl                    |Ok     Y d}m~mnd}m~mww xY w|5|6k     "|rnC|=r'|dz  } j                                         |5dz  }5d}=(|>r(|@1tm           j`         d[                                ||           n	  j        dJk    r                     |@          \  }[}?n; j        dk    rdd\lm}  ||@ j        ]          \  }[}?n|@jx        d         j~        }[|[j        t          |[j        t                    ss|[j        }t          |t                    rH|+                    dd          p*|+                    d.d          pt          j        |          |[_        nt          |t2                    rg }|D ]}t          |t                    r|#                    |           -t          |t                    rC|+                    d          dk    r*|#                    |+                    dd                     t          |t                    r,d|v r(|#                    t          |d                              d7C                    |          |[_        nt          |          |[_        |[j        r} j%        sv jj        r& _                     j`         d^|[j                    nI _                     j`         d^|[j        dd          tI          |[j                  dk    rdnd            |[j        r j        rta           d_d          dk    r|[j        B                                }t          j        d`d|          B                                }|r$|                    d7          d         dd         nd}|r)	                      da|           n# t*          $ r Y nw xY wt          |[j        pd          rt           db          sd _         xj        dz  c_         _                     j`         dc            j        dk    r) _                     j`         dd j         de           ,} _                     j`         dfdr           d _                             |          }_                     |                                ||           d|_|dddgdS t           db          rd _         j        dJk    r|?dk    rt           dh          sd _         xj        dz  c_                             |[|?          }\t          |\+                    d.          pdB                                          }t          |\+                    d/          t                    r5t          |\+                    d/d          B                                          nd}t          |\+                    di                    }|s|s|r|r|dE         nd}t          |t                    r|+                    di          nd}|\+                    di          }t          |t                    o|+                    d(          d)k    o~|+                    d1          dk    oe|+                    d.          pd|\+                    d.          pdk    o5|+                    d/          pd|\+                    d/          pdk    o||k    }|s|#                    |\            j        dk     rL j%        s' _                     j`         dj j         dk           | _                             |           /d _                             ||           d||dddldS t           dh          rd _        |[j        r^ j%        s4 _                     j`         dmtI          |[j                   dn            jj        rD|[j        D ]<t          j4        doj        j         dpj        j        ddq          d           =|[j        D ]lˉj        j         j         vrW                     j        j                  }|r6tm           j`         drj        j         ds| d           |j        _        m fdt|[j        D             }|r~t           du          sd _
         xj
        dz  c_
        dqC                    t           j                             }|d         }tI          |          dk    r|dd         dz   n|} _                     j`         dv| dw j
         dk            j
        dk    rJ _                     j`         dxdr           d _
                             ||           d||dddy| dS                      |[|?          }|#                    |           |[j        D ]Mˉj        j         j         vrdzj        j         d{| }nd|}|#                    d}j        |d~           N2Vt           du          rd _
        g }|[j        D ]ˉj        j        }t          |t          t2          f          r t          j        |          j        _        K|:t          |t                    s%t          |          j        _        j        j        }|r|B                                sdj        _        	 t          j        |           # t          j        $ r9}|#                    j        j        t          |          f           Y d}~d}~ww xY w|r2 xj        dz  c_        |d         \  }ʉ _                     j`         d| dʛ             j        dk     r( _                     j`         dd j         d           3 _                     j`         d           d _                             |[|?          }|#                    |           d |D             }|[j        D ]Yˉj        j        |v r&t          fd|D                       }d| d}nd}|#                    d}j        |d~           Z4d _                             |[j                  |[_                             |[j                  |[_                             |[|?          }|[j        pd}|r                     |          r| _        t          h d          ɐt          fd|[j        D                       }|r g                                rd _        nI j%        rB                     |          B                                }|r _                    d|            |#                    |            j        r'	                      d           n# t*          $ r Y nw xY w                     |[|||           d _        d |[j        D             }|dhk    r j                                          j6        }|j        |j        z   }|j;        dk    r5||j;        z  }|dk    r$ j        sd _                             ||            j5        r=|                    |          r( ?                    || j6        j        |          \  }}d}| _                             |           7%|[j        pd}                     |          s=ta           dd          }|rQtb          4                    d           d _        d _        t}          tI          |          dz
  dEdE          D ]}||         }(|(+                    d(          d)k    r|(+                    d*          rg }|(d*         D ][ˉrt          t                    sˠ+                    di           }|#                    |+                    dd                     \ddqC                    |           dtI          |          dk    rdUnd d|(d.<    n׉                     |          B                                }d _        nt           d          sd _         xj        dz  c_                             |[|?|0|&|          }|d         }+ _                     j`         d           |+rCtI          |+          dk    r|+dd         dz   n|+} _                     j`         d|            nEtI          |          dk    r|dd         dz   n|} _                     j`         d| d           |d         r:| dz  } | |8k    rE _                     j`         d |8 ddr            _                     j`         ddr           n _                     j`         d|  d&|8 dWdr           tI          |          } ?                    |||0|          \  }}tI          |          |k     rgd}                     d	| d
tI          |           d           t          j        d           |dz  } j                                         |5dz  }5:ĉ _                     j`         d           |+rZ|d         rQ|d         rH _                     j`         ddr           d _        |+}d)||+|?d}|#                    |           n] j        dk     r( _                     j`         dd j         d           ;q _                     j`         ddr           d _        ta           dd          }|r/d _        t}          tI          |          dz
  dEdE          D ]}||         }(|(+                    d(          d)k    r|(+                    d*          rg }|(d*         D ][ˉrt          t                    sˠ+                    di           }|#                    |+                    dd                     \ddqC                    |           dtI          |          dk    rdUnd d|(d.<    n׉                     |          B                                }d _        n|+rA _                     j`         ddr           |+}d)||+|?d}|#                    |           n|d)||+|?d}|#                    |                                |                                ||           d}|d         rd}|pd||dd|dS t           d          rd _        d _         j        dJk    r j         r|dk     r                     |||          ri|dz  }                     |[d          }\|#                    |\           d	dd
}]|#                    |]           | _                             |           >:d}|r	||z   }d}d}                     |          B                                }                     |[|?          }|#                    |            j%        s &                    d| d           n# t*          $ r}d| dt          |           	 tm          dʛ            n3# t          t          f$ r tb          |                    ʦ           Y nw xY w jj        rt          j        d           d}t}          tI          |          dz
  dEdE          D ]}'||'         }(t          |(t                    s n|(+                    d(          d}k    r<|(+                    d(          d)k    r|(+                    d*          rpd ||'dz   d         D             }|(d*         D ]Mˉrt          t                    sːd         |vr(d}ːd         dʛ d~}|#                    |Ħ           Nd} | j        dz
  k    r#dʛ }|#                    d)|d
           Y d}~n)Y d}~nd}~ww xY w| j        k     r j        jG        dk    @~|s| j        k    s j        jG        dk    rX j        jG        dk    r2 j%        s+tm          d% j        jL         d& j        jM         d'                                ||          }|duo
| j        k     }ŉ                     |||Ŧ                                |                                ||           |ry|sw	 ddl-m.}  |d j*        |	|t3          |           j/        ta           dd          pd           n3# t*          $ r&}tb          2                    d|           Y d}~nd}~ww xY wd}t          |          D ]:}(|(+                    d(          d)k    r|(+                    d/          r
|(d/         } n;i d|d|Ɠd|d|d|œddd|dta           dd          dV j/        d j        d j        d j        d j        d j        d j        d j        d j         j         j        ta           j6        dd          pd j         j         j        dĜ}d _        |r j        r j        |ǐd<    D                                 d _        d}ȉ jP        dk    r" jQ         jP        k    rd- j         v r	d}d _Q         jE        rK|rI|rG	  jE                            ||            jE                            |           n# t*          $ r Y nw xY w|r>|s<|
s|r8	                      t3          |          |
|ȐƦ           n# t*          $ r Y nw xY w	 ddl-m.}  |dǉ j*        || j/        ta           dd          pdȦ           n3# t*          $ r&}tb          2                    d|           Y d}~nd}~ww xY w|S (  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
        Nr   Fr*  u~   🔌 Detected stale connections from a previous provider issue — cleaned up automatically. Proceeding with fresh connection.rs   r  Tr  rP  u   💬 Starting conversation: 'r  rZ  r   r  r  )invoke_hookon_session_startr  )r  r   r  z on_session_start hook failed: %sz*Session DB update_system_prompt failed: %s)r  rP  zDPreflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)rm  u   📦 Preflight compression: ~z tokens >= z
 thresholdr  ry  pre_llm_call)r  r  r  is_first_turnr   r  r  r  zpre_llm_call hook failed: %su2   
⚡ Breaking out of tool loop due to interrupt...u%   
⚠️  Iteration budget exhausted (r.  z iterations used)r   r>  r   c                 T    g | ]%}t          |t                    |d          d         &S r   )rK   r   r   s     rC   r   z,AIAgent.run_conversation.<locals>.<listcomp>  sA     * * *$&#-b$#7#7* ":v 6* * *rE   z&step_callback error (iteration %s): %sr  r   r  r  r  r5  rW  )	cache_ttlnative_anthropicc              3   N   K   | ] }t          t          |                    V  !d S rP   r  r  s     rC   r   z+AIAgent.run_conversation.<locals>.<genexpr>_  s.      DDc#c((mmDDDDDDrE   r  rZ  u   🔄 Making API call #u      📊 Request size: z messages, ~z
 tokens (~z chars)u      🔧 Available tools: r'  )brainsparklepulsemoonstarr  zAPI Request - Model: z, Messages: z	, Tools: zLast message role: rF  rr  zTotal message size: ~z tokensr  r(  rj  HERMES_DUMP_REQUESTS	preflightr  c                  v    r                     d           d  j        r                     d           d S d S r   )r  r  )rA   thinking_spinners   rC   _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 7rE   r  r  r[  u   ⏱️  API call completed in r  r  r   zN/AzAPI Response received - Model: z	, Usage: ri  rU  zresponse is Nonezresponse.output is not a listzresponse.output is emptyzresponse.content is not a listzresponse.content is emptyrm  z#response has no 'choices' attributezresponse.choices is Nonezresponse.choices is emptyu   (´;ω;`) oops, retrying...u<   ⚠️ Empty/malformed response — switching to fallback...Unknownro  metadatarR  r  zmodel=c                 n    i | ]2\  }}|                     d           |t          |          dd         3S )r  Nr   )r_  rL   r  s      rC   r  z,AIAgent.run_conversation.<locals>.<dictcomp>  sA    )v)v)vdadedpdpqtdudu)v!SVVDSD\)v)v)vrE   z*Response attributes for invalid response: u&   ⚠️  Invalid API response (attempt z): r~  r  u      🏢 Provider: u      📝 Provider message: u      ⏱️  Response time: z/s (fast response often indicates rate limiting)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.zOInvalid API response shape. Likely rate limited or malformed provider response.)r   rU  	api_callsro  r     rC  x   u   ⏳ Retrying in z/s (extended backoff for possible rate limit)...zInvalid API response (retry z | Provider: u3   ⚡ Interrupt detected during retry wait, aborting.zAOperation interrupted: retrying API call after rate limit (retry rc  )r@  r   re  rU  interruptedr  r  incomplete_detailsrp  r  >   r  rv  r  )end_turnr  r  stop_sequenceuQ   ⚠️  Response truncated (finish_reason='length') - model hit max output tokensr)  r   r   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   re  rU  partialro  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 attemptsu3      ⏪ Rolling back to last complete assistant turnz-Response truncated due to output length limitu-   ❌ First response truncated - cannot recoverz3First response truncated due to output length limit)r@  r   re  rU  r  ro  )r   r   )prompt_tokenscompletion_tokenstotal_tokensr  u   💾 Cached context length: z tokens for r   )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=rm  z, completion=rn  z, total=ro  cache_read_input_tokenscache_creation_input_tokensprompt_tokens_detailscached_tokensru  r   u      💾 Cache: z	 tokens (z.0fz% hit, z	 written)u    ⚡ Interrupted during API call.z3Operation interrupted: waiting for model response (r  zs elapsed).u   (╥_╥) error, retrying..._surrogate_sanitizeduH   ⚠️  Stripped invalid surrogate characters from messages. Retrying...rr  )rr  r4  r+  r8  u8   🔐 Codex auth refreshed after 401. Retrying request...r  u<   🔐 Nous agent key refreshed after 401. Retrying request...r  rW  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: rY  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?        • Clear stale keys: hermes config set ANTHROPIC_TOKEN ""u?        • Legacy cleanup: hermes config set ANTHROPIC_API_KEY ""z;API call failed (attempt %s/%s) error_type=%s %s summary=%sr   r  r   z [HTTP r  u!   ⚠️  API call failed (attempt u      🔌 Provider: z	  Model: u      🌐 Endpoint: u      📝 Error: ru  rs  rt  u      📋 Details: u      ⏱️  Elapsed: zs  Context: z msgs, ~u?   ⚡ Interrupt detected during error handling, aborting retries.z+Operation interrupted: handling API error (r  r7  z
rate limitztoo many requests
rate_limitzusage limitquotau9   ⚠️ Rate limited — switching to fallback provider...  request entity too largezpayload too largezerror code: 413u   ❌ 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   rU  re  ro  rl  u@   ⚠️  Request payload too large (413) — compression attempt u   🗜️ Compressed rz  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.c              3       K   | ]}|v V  	d S rP   r`   r   r  r  s     rC   r   z+AIAgent.run_conversation.<locals>.<genexpr>  s8       2 2&&I2E 2 2 2 2 2 2rE   )zcontext lengthzcontext sizezmaximum contextztoken limitztoo many tokenszreduce the lengthzexceeds the limitzcontext windowr  zprompt is too longzprompt exceeds max lengthi  r>  r  i@ r  r  r  u)   ⚠️  Generic 400 with large session (~z	 tokens, u1    msgs) — treating as probable context overflow.u)   ⚠️  Context limit detected from API: z tokens (was ry  u3   ⚠️  Context length exceeded — stepping down: uM   ⚠️  Context length exceeded at minimum tier — attempting compression...z!Context compression failed after z3Context length exceeded: max compression attempts (u(      🗜️  Context compression attempt 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.>     r  r7  )ro  r   c              3       K   | ]}|v V  	d S rP   r`   r  s     rC   r   z+AIAgent.run_conversation.<locals>.<genexpr>  sG       b b  {Abhlubu b b b b b brE   )zerror code: 401zerror code: 403zerror code: 404zerror code: 422zis not a valid modelzinvalid modelzmodel not foundzinvalid api keyinvalid_api_keyauthenticationunauthorized	forbiddenz	not foundu!   ⚠️ Non-retryable error (HTTP u   ) — trying fallback...non_retryable_client_error)rp  ro  u%   ❌ Non-retryable client error (HTTP z). Aborting.)r8  i  r  r  
permissionu9      💡 Your API key was rejected by the provider. Check:u-         • Is the key valid? Run: hermes setupu+         • Does your account have access to r6  r0  u?         • Check credits: https://openrouter.ai/settings/creditsu6      💡 This type of error won't be fixed by retrying.zNon-retryable client error: r  uU   ⚠️  Skipping session persistence for large failed session to prevent growth loop.)r  r  u"   ) exhausted — trying fallback...u   ❌ Rate limit persisted after z! retries. Please try again later.z) exceeded. Giving up.u      💀 Final error: c              3       K   | ]}|v V  	d S rP   r`   )r   r  r  s     rC   r   z+AIAgent.run_conversation.<locals>.<genexpr>  s7       $ $qAN $ $ $ $ $ $rE   )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 z
 retries: 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  rc  r   zretry-afterzRetry-Afteru#   ⏱️ Rate limit reached. Waiting zs before retry (attempt z)...zs (attempt z4Retrying API call in %ss (attempt %s/%s) %s error=%sz<Operation interrupted: retrying API call after error (retry u:   ❌ All API retries exhausted with no successful response.r_  ra  u   🤖 Assistant: r  z,</?(?:REASONING_SCRATCHPAD|think|reasoning)>	_thinking_incomplete_scratchpad_retriesuL   ⚠️  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 retries_codex_incomplete_retriesr?  u0   ↻ Codex response incomplete; continuing turn (z/3)z@Codex response remained incomplete after 3 continuation attemptsu   🔧 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 r`   )r   rY   r  )r   r   rA   s     rC   r   z,AIAgent.run_conversation.<locals>.<listcomp>  s;     * * *-/;+43HHH (HHHrE   _invalid_tool_retriesu   ⚠️  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   r  u1   ⚠️  Invalid JSON in tool call arguments for 'r  u;   ⚠️  Injecting recovery tool results for invalid JSON...c                     h | ]\  }}|S r`   r`   )r   rY   r  s      rC   r}  z+AIAgent.run_conversation.<locals>.<setcomp>P  s    ,S,S,SgdAT,S,S,SrE   c              3   B   K   | ]\  }}|j         j        k    |V  d S rP   r   )r   r!  rg  r   s      rC   r   z+AIAgent.run_conversation.<locals>.<genexpr>S  s9      .h.hTQRSWYWbWgRgRgqRgRgRgRg.h.hrE   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 rP   r   )r   r   _HOUSEKEEPING_TOOLSs     rC   r   z+AIAgent.run_conversation.<locals>.<genexpr>~  sB       0 0 " K,0CC0 0 0 0 0 0rE   u     ┊ 💬 c                 &    h | ]}|j         j        S r`   r   r   s     rC   r}  z+AIAgent.run_conversation.<locals>.<setcomp>  s     Y Y Yb!1 Y Y YrE   execute_coder}  _last_content_with_toolsuO   Empty follow-up after tool calls — using prior turn content as final responser   rY   zCalling the z tool_empty_content_retries)r  r  r  r  r  uC   ⚠️  Response only contains think block with no content after itz   Reasoning: z   Content: 'r   u      💡 Local/custom backend returned reasoning-only output with no visible content. This often means the resumed/large session exceeds the runtime context window. Try /new or lower model.context_length to the actual runtime limit.ub   🗜️  Reasoning-only response looks like implicit context pressure — attempting compression (z4 messages after reasoning-only response, retrying...zQ   Compression could not shrink the session; falling back to retry/salvage logic.r  r  u`   ℹ️  Structured reasoning-only response repeated unchanged — using reasoning text directly.rD  u/   ❌ Max retries (3) for empty content exceeded.zRUsing reasoning as response content (model wrapped entire response in think tags).zIModel generated only think blocks with no actual response after 3 retriesr  zLocal/custom backend returned reasoning-only output with no visible response after 3 retries. Likely causes: wrong /v1 endpoint, runtime context window smaller than Hermes expects, or a resumed/large session exceeding the backend's actual context limit.)r  r  r   zr[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]u"   🎉 Conversation completed after z OpenAI-compatible API call(s)z)Error during OpenAI-compatible API call #u   ❌ zDetailed error information:c                 z    h | ]8}t          |t                    r!|                    d           dk    0|d         9S r  ru  )r   ry  s     rC   r}  z+AIAgent.run_conversation.<locals>.<setcomp>   sP     ( ( ( !)!T22( 89uuV}}7N7N n-7N7N7NrE   r  zError executing tool: z0I apologize, but I encountered repeated errors: post_llm_call)r  r  assistant_responser  r   r  zpost_llm_call hook failed: %sr@  last_reasoningr   re  rU  rl  rh  response_previewed_response_was_previewedrr  rs  rt  rv  r  )rn  ro  r  rw  rx  ry  interrupt_message)r  r  r  r  )r  rU  rh  r   r  zon_session_end hook failed: %s)ri   r  rK   rL   r   r  r  r  r  r  r  _invalid_json_retriesr  r  r  r  r  r  r   r  r  r   rk   r   r   r   r   r"  	has_itemsr  r@  r'  r  r$  r)  r   rM   r  r  r  r  get_sessionr  r   r  hermes_cli.pluginsrP  r   rX   r  r   r  r   r?  r>  r  r  r!   rP  rM  r  r  rG  r  r~   r   r   r  r  r-  prefetch_allr{   r  new_turnr  rt   rx   rl   r  r  r;  r*  rd  rH  r  r   rW  r  r  r8  r  r'   r  r  r  r  r  r  r  r1   KAWAII_THINKINGTHINKING_VERBSr  r  r  r  r  r   ro  r1  r  r:   r  r  r  r  rS  r  r  ri  rm  r  r  r  ro  rc  r  varsr  r  r9  r   r  stop_reasonr  r  r  r   rQ  r   r  r7  r  rK  r0   r   rm  rs  ro  update_from_responser  r$   r   r  rA  rB  rC  rD  rE  rr  rF  rG  rt  rH  ru  rI  rv  r/   
amount_usdrJ  r=  r  rK  r  rL  update_token_countsrR  UnicodeEncodeErrorr   r=  r  r%  r  r  rX  r(  r  r6  r  r   r[   r   r~  r  r  has_availabler   r#   r"   r}   r  rJ   r   r  rv   r  r`  r  r   r   r  r  r   r  r7   r   rY   r   r'  r  r  r   r   nextr  r  	frozensetallr  r  r  r  r  r  r4  r   r  r	  r  r  rI   	exceptionrL  rn  r  sync_allqueue_prefetch_allr1  )rA   r  r  r  r
  rM  rN  r  r   original_user_message_should_review_memoryuser_msgcurrent_turn_user_idxstored_promptsession_row_invoke_hookr  rg  active_system_prompt_preflight_tokens_pass	_orig_len_plugin_turn_context_pre_results
_ctx_partsr  r  r@  rh  codex_ack_continuationslength_continue_retriestruncated_response_prefixcompression_attempts_ext_prefetch_cache_query
prev_tools_m	_step_errr  r3  r   rR  _baser  r;  r<  r=  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_attemptedr4   restart_with_compressed_messages restart_with_length_continuationr  r  r  ra  _use_streamingr  api_duration
resp_modelresponse_invaliderror_detailsoutput_itemscontent_blocksrR  
resp_attrscleaned_provider_errorr  	sleep_endr  ri  incomplete_reasonstop_reason_map_trunc_content
_trunc_msg_text_parts_blk_thinking_exhausted_exhaust_error_exhaust_responser  interim_msgcontinue_msgpartial_responserolled_back_messagescanonical_usagerm  rn  ro  
usage_dictctxcost_resultr  writtendetailsr+  hit_pctapi_elapsedr  rr  recovered_with_poolrX  r  auth_method_dhh_fn_dhhelapsed_timer  _error_summary	_provider_model_status_code_str	_err_body_err_body_stris_rate_limitedr  pool_may_recoveris_payload_too_larger  is_context_length_errorr  r  is_generic_errorr  old_ctxparsed_limitnew_ctx_RETRYABLE_STATUS_CODESis_local_validation_error_err_message_is_generic_400is_client_status_erroris_client_error_final_summary_is_stream_drop_final_response_retry_after_resp_headers_ra_rawr`  rx  r   r   _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_previewrt  r   invalid_json_argsr   r   recovery_assistantinvalid_nameserrtool_resultturn_content_all_housekeepingclean	_tc_names_compressor_real_tokens_compaction_progressfallbackrJ  r   r  empty_response_inforeasoning_previewcontent_preview	empty_msgerror_message	final_msgpending_handledanswered_idserr_msgrU  r  rK  _should_review_skillsr  r  r   r`  s   `                                                                                                                                                                                                        @@@@rC   r"  zAIAgent.run_conversation  sf   < 	
 	%%'''
 lC(( 	>/==L*C00 	N#78L#M#M  !0)-&.B+#8s4:<<'8'8 &'"%&"&'#./+)*&(,%#( $)!
 =0001133 %%&  
    
 !00C D D 2FM4,---2  	:/999
   	;(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 $1	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((E &:&@b"j0D) ) )%
 )4+B+SSS T  "	@FFFFFF'<?2%)(^^#'(<#=#==j z488>B  L J! ) )a&& )155+;+; )%%c!I,&7&788883'' )AGGII )%%a((( ?'-{{:'>'>$ 	@ 	@ 	@NN93????????	@ "#"#$&!  	
 ! 	)3L#)F)FNB&*&:&G&G&O&O&USU##    t222t7L7VYZ7Z7Z ))+++ ( " \$$%Z[[[aN(0022  _$$  &^dNcNh  &^  &^ko  lA  lK  &^  &^  &^  _  _  _ !-f!#J&x00 " "66&>>[88RVVL=Q=Q8* **,\*:* * *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((** ///CGGFOOv4M4MRe4M#KK	266E!%-- R-2V^>Q-Q	* 776??k11%(WW[%9%9N% F7E 34 '))KK,,,"g--KK000
 $t';;;<<WEEE ##G,,,,  49r+ f$4v$=@\$\#c#c#e#e # ^$4v$=@T$T#[#[#]#]  `)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 DD|DDDDDK'1,M  $? -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 }]%BCC}]%ABB) 	- **d+>+>T+>+>+>????3355 - $*=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*&+%#O/4,/4,"MH++p(!%!7!7!E!EJ}(999%)%E%Ej_d%E%e%e
&'=>> U44Z4TTT7 7 7 7 7 7 &*N5577 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$!?!? M/3,)001PQQQQ ..!33/3,)001KLLL*>>>OWOc9d)K)K)Kim#+/3,)001CDDDD!+ND!A!A N/3,)001QRRRR 00A55/3,)001LMMM#+78Y3O3O+S[ScSkors{  tD  pE  pE  IJ  pJ  pJ/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' U!+ 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 %*+K$ %.	(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  &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  &U  &US_  &U  &U  &U  &U  ]a  b  b  b&+55 --  /A[  /A  /A  /A  B  B  B#::<< )./ ( --.{+.{.{.{|||#MT_*o*oYd*o*o*oppp 11(<PQQQ,4-2-;)z*.$ $  %(Q;?-C(Dc$J$J	  &D  &D  &D  &D  &D  LP  Q  Q  Q  )\{  )\  )\U`  )\  )\eieneno|e}e}  )\  )\  MZ  )\  )\  ]  ]  ] %)IKK)$;	"ikkI55#8 
" $-t-t-t  }A  !B  !B  !B $ 5 5h@T U U U $ 4 4 6 6 6 7X  {F  7X  7X  IT  7X  7X  7X081?1637(" (" !" !JsOOO #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$00  &K  &K  &K  SW  X  X  X *.=,>>>IPQY[dIeIe  *Fjrjz  *F)9!)<)D)D  BFJU_-iWZD-Q-Q-QeiNN!].BBB*,K(/)R(H(H R R#*4#>#>&#H#H$/$6$6wtVR7P7P$Q$Q$QGR-\TYY{-C-C-CX\N +$6 X$($G$G$W$W W/4 ,t3 ,
 /  !9 +
 !LL#'? !E !E !E&* )   !H . !889JKKK 11(<PQQQ2C,4-;-2+/)7$ $   =,>>>080@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(" (" !" 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 _Xhn _X*9$N%)]%)]+ + +
 )8(E,;,I)'6'C-:1B,8& &

 /DDZPPP
  2B 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&9 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'   ' 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  r( r( r(' 0(--.LMMM+/(- 3..r222 ")-?@@ %QUWmotIuIu %4818BB % LL#'? | | |&* )    %HHHH #*)]D"I"IK;?;];]$/(7 <^ < <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ssstttsssttt1$K#'9;;#?L!%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  "[  "[  "[  "[  \  \  \ 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 $s* 0'940.);0 (940 )I5	0
 #i/ $ ' )4+?#dFZB[B[+[+[
  $4+/t+;+T@R@R@T@T(/ ) --.ijjj#::<< )./ ( $s* :5B:.);: -	9	 ) , &,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+/$ $       ))  +b  nB  +b  +b  E]  +b  +b  +b  c  c  c'*8}}9=9O9O$nM$5 :P : :6"6
 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+/$ $       /2 2 2 2 2 U 2 2 2 / /+" 3 {c7I7I")'$8Ld*S*SUegm"n"n+87S=+H+bCP\L]L]`bLb(+.y/@/@+A+AB+F(+ 0@ 6:3 LL#'? !J !J%2 ]!J !J?B<?P?P!J !J !J '+	 )    / D%)%<
","; (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'88?J5:=g
Hd>d:e:eJ79=J6 EI , H1HE EJA !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+/$ $         &V  &Vau  &V  &V  yQ  &V  &V  &V  W  W  W'*8}}9=9O9O$nM$5 :P : :6"6
 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+/$ $      $ />oo+"9z9.EFF J *96H I II . !(	64 @ @ FBIU_`ikoUpUp$xIMM'2$>$>$B$B9b$Q$Q$QvxL'2c'9'kl>P>P>R>R>X>X>Z>Z^k>kO-7S-I-I  .ncU`NfNfNfNfcfNfNfNfNf  .nkv  V  lV  .n  _n  [n*'@ (DZ (^a b b b b E b b b _ _ '8 !87 $ ' + ))*sk*s*s*sttt6688 %*+K$HHHH44&/KS\ 5    %w%w^i%w%w%w  @D  E  E  E%g%g9%g%g_e%g%gosttt%R%R5%R%RZ^___&*44)8S8SWbfoWoWos  DM  tM  tM LLDO)v)v)v  CL  D  D  D LLDO)j)j)jrvLwww LLDO)q)qhn)q)q)qy}L~~~+s5zz/?/?/A/AAA $  .A  .A  .A  IM  !N  !N  !N 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 %*+K$HHHH)-)B)B9)M)M*  LLDO  *K  *K\g  *K  *K  *K  SWL  X  X  X  X LLDO)q)qk)q)q)qy}L~~~%^%^n%^%^fjkkk !(	=$ G GG  # $ $ $ $ = $ $ $ ! ! ( +  LL#'? !? !? !? '+ )    !LL#'? !- !- !- '+ )     n O[.%vs</@/@]BVBV  
 44&/Fi 5    --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< [#a;FVXZB[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 )++	11Mr( ++h  / !#%,,... q 380/ 
 dddeee%%h0DEEEB
=$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 %, 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 !#D*;Q??!CC"3";"A"A"C"CK"$&G[# #egg   EP!W!2!24!8!8!;CRC!@!@UWJ! !! 77ZPPPP( ! ! ! D!
 -->-F-L"MM "4)IJJ @>?;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     4!ABB <:;D7=$555-<:W:W"4)DEE ;9:6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`/* 9.C 9Gb 93;#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 9$OOK888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 %/ ? ~%|%|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* * *& * %!&t-DEE ;9:D6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- -    
 !t%<== 7562 )+%/: 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 ) &%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 - -) - D1K1K1M1M D7;D44!_ D$($<$<\$J$J$P$P$R$RE$ D $-B5-B-B C C COOM222 1 !! 66t<<<<( ! ! ! D! ,,->J[]klll 04D,
 !Z Y<M<X Y Y YI ^$444-44666 #'"9K#6%<= ! #3a77/;k>Z/Z,/477@]7<@D9 778LkZZZ/ 	4K4O4OP\4]4] 	49=9O9O$n*.*A*T$5 :P : :6"6 04, .6D***8444  &7%>%D"N  >>~NN ]
 $+41KT#R#R# ""LL)z{{{<@D9:;D7%*3x==1+<b"%E%E 	* 	*&.qk#&776??k#A#AcgglF[F[#A13J.1,.? %U %U/1(WB9M9M(Wx-/VVJ-C-C(2(9(9"&&:S:S(T(T(T(T 6HDIIjDYDY  6H  6Hgjkugvgvyzgzgz`c`c  AC  6H  6H  6HC	N$)E-1-E-Eh-O-O-U-U-W-WN;?D8!  't-EFF <:;D733q833.2.S.S-*7*7)51E /T / /+ *==M)N%|%|%|}}}) ^PSTbPcPcfiPiPitt0Du0L0Lo}- LLDO)^)^K\)^)^____MPQ_M`M`ceMeMenSbS.AE.I.IkyO LLDO)\)\/)\)\)\]]]./@A T0A5036NNN $  .D  .D_w  .D  .D  .D  LP  !Q  !Q  !Q $  .i  .i  .i  qu  !v  !v  !v  !v $  .Y  .Y  dx  .Y  .Y  {S  .Y  .Y  .Y  ae  !f  !f  !f/28}}AEAWAW$,nM,= BX B" B" >*> $'x==<#?#?;?$8$($5$5  7cL  7c  7c_bck_l_l  7c  7c  7c  %d  %d  %d$(JqMMM$2a$7N$($9$@$@$B$B$B$/1$4K$, $  .S  .S  .S  !T  !T  !T +" 34H I" !44N O"
 !LLDO  *^  *^  *^  fjL  k  k  k:;D7-;N(3+9-;1>	) )I %OOI666!6:: LLDO)x)xUYUp)x)x)xyyy$ LLDO)l)l)ltxLyyy:;D7
 (/t5OQU'V'VH' &@D =).s8}}q/@"b)I)I 	!. 	!.A*21+C'*wwv+'E'E#''R^J_J_'E57
25l2C )Y )YB35,[ZD=Q=Q,[S[13
B1G1GB,6,=,=bffVY>W>W,X,X,X,X :L		R\H]H]  :L  :Lknoykzkz}~k~k~dgdg  EG  :L  :L  :LI(-151I1I(1S1S1Y1Y1[1[?C < %  . 
& $  .T  .T  .T  \`  !a  !a  !a1?,7/=1?5B	-" -"	 !)	 : : : % )4+9-;1>	) )I %OOI666 889JKKK 11(<PQQQ,wM23DE "%o !. 3A2HD,4-;-2+/)6$ $  t%=>> 86739=D6 )::: 1 ;3a77 CC)5.<%- D   8 014/&*&C&CDUWc&d&d 444 %+!U( ( !55519...x888 ./+0 4)B^)S46123/ &*%=%=n%M%M%S%S%U%UN $ = =>OQ^ _ _IOOI...? ~(()|n)|)|)|}}} 2 2 2bbbZ]^_Z`Z`bb	,,,,----, , , ,LL+++++, ' E%&CDDD
 #( 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%<<<%cXa%c%cN OO[^$T$TUUUEEEE =<<<<[2w5 t222t7L7VYZ7Z7Z^7 !d111$.!33$.!33DO3  Ot?T?Y  O  O\`\q\{  O  O  O  P  P  P!88>RRN #$.W>DDW3W	 	hi@@@ 	$$%6777 	h(<===  	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 	| 	$--lNKKK$77EEEE   
  	+ 	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 sY  +)D 
D"!D"48J- -
J:9J:"0L 
ML==M%M3 3
N"=NN"=C=W; ;
X*X%%X*5Z 
ZZA,_ 
_8_33_8O"An @>HAn IAAn JC:An N+An OHAn WCAn Z AAn [=A8An ]6=An ^4H&An gBAi# i"An i#
Ai0i-An i/Ai0i0DAn nBB{)p
B{)p$BB{$r<-B{$s/AB{$uAB{$vAB{$w=N5B{$F2B{)F8BB{$IB)B{$K=B{)LBB{$N&A<B{$P"B{)P(IB{$ZB{)Z	B?B{$]BB{$_B{)_EB{$d&G-B{$lB{)l&B{$m0B{$m;E-B{$s(B{)s.A'B{$uBu6u5B{$u6Bvv	B{$vBvvD"B{$z.B{)z4+B{${$B{)}L
DU I#CI; I:DU I;
CJJDU JCJJBDU LA0DU NJDU X&DU YH,DU a3B DU c5CDU gCggDU gCh!g(.ChhDU hCh!h!A6DU jB>DU mD:DU rCr* r)DU r*
Cr7r4DU r6Cr7r7DDU wFDU }	HDU E#A8DU G1DU HE)DU M;ADU N>A!DU P B7DU SBDU UD\U'D\U>DVVD\V-DWW D\WDWWE	D\\D\`ADa a
Da8aDa3a3Da8g05Dh& h&
Dh3h2Dh3h?&Di& i&
Di3i2Di3i74Dj, j,
Dkj6DkkDk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
        )rM  r@  )r"  )rA   r  rM  rK  s       rC   rG  zAIAgent.chatg!  s(     &&w&PP&''rE   )2NNNNNNNNr   r   r   NNFFFNr   r   NNNNFNNNNNNNNNNNNNNNNFFNNNNFr   FTrP   )FFr|   )r   rA  )NNNNN)r[   r\   r]   r^   r   rL   r   setterr   r}   r=  r   r~   r  r   r   rD   r  r  r  r  r  r  r  r   r  r  r  r  r   r  r	  r  r.  r/  r-  r1  r5  r9  r8  rK  rS  rk  rn  staticmethodr   r~  r  r  r
   r  r  r7  r  r  r  r  r  r  r  r  r  r  r'  r)  r1  r>  tuplerF  rM  r^  ri  r  r  r  r  r  r  ro   r  r  r  r  r  r$  r  r  r  r  r  r  r  r  r%  r(  r+  r3  r=  r?  rS  r  r  rY  r  r  r  r  r  r  r  r  r  r  r  r  r  r1  r$  r#  rQ  rW  r]  r  r  r  r  r  r  r4  rL  r"  rG  r`   rE   rC   r   r     s         #    X _>c >d > > > _> %)!% &*'+"' % '+ #'+'+%)!,1(,+/(,+/&*'+%)"&*.&*$(+/15#(!.2)-$)(* % $g^ ^^ ^ 	^
 ^ ^ s)d"^ ^ 3i$^ ^ ^ ^ s)^  9^  ^  !^" #^$ "%%^& '^( )^*  9+^,  9-^. c/^0 1^2 &*3^4 #&5^6 7^8 !)9^: &;^< !)=^> $?^@ %A^B #C^D  E^F  (G^H $I^J "K^L M^N sCx.O^P tCH~.Q^R S^T !U^V W^Z ,[^\ S#X]^` "a^b #&c^d e^f g^ ^ ^ ^@,= ,= ,=\  $ ,1 * * *D * * * *(UC UD U U U U(C Cc CT C C C C
4D 4 4 4 4v4 v v v v	%s 	%t 	% 	% 	% 	%%c %d % % % %.3 3    EeEe Ee tCH~&	Ee
 
Ee Ee Ee EeP@x} @ @ @ @DB
  }	B

 B
 4S>*B
 'tDcN';<B
 
c3hB
 B
 B
 B
HVs Vt V V V V$	L 	L 
	G " $#	h h:h h 	h
 
h h h hT*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    > &*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N         "4S#X+? D    @ ) ) ) ) X)h) h)3 h)# h) h) h) h)\ + + + + \+ 6d38n)= 6$tCQTH~BV 6 6 6 \6p 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- 
	   :`$tCH~:N `SWX\]`be]eXfSg ` ` ` `DTc Td4S>>R T T T Tt #	{ { {{ 	{
 
c3h{ { { {z'C 'C ' ' ' ' c c     S0# S0%S/ S0 S0 S0 S0j/# / / / /
S 
 
 
 
Y_          \:4 C QU Z]    * 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F FD F# FV^ F F F FP&g &gD &g# &g &g &g &gP FJ   d d    : EI ! ! !T !T ! ! ! !F%4 % % % %N=3 =4 = = = =J J J J62& c]2& 	2&
 
tTz	2& 2& 2& 2&hDT D D D D
;"$ ;" ;" ;" ;"~s t     # $         
t 
 
 
 
 ?C`" `" `"`"3;`" `" `" `"Hm1 m1 m1 m1 m1b>$ > > > >D #,) - - - # #
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     "9$ 9 9 9 9Nd Nt N N N N` T  T  T  T  TD,TD[ , , , ,@t tQU t t t tl T d    \0[ [t [s [ [ [ [z ^br{ R- R- R-$ R- R-WZ R-lo R-  AF R- R- R- R-h* *t *X[ *mp *y} * * * *.E# Ed EWZ E_b E E E ENHT HT$ HTcf HTx{ HT  EI HT HT HT HTT\T \T$ \Tcf \Tx{ \T  EI \T \T \T \T|# (3-    0%Y% %YPT %Y %Y %Y %YNUt US US U U U Ut #59.2.2Z" Z"Z" Z" #4S>2	Z"
 Z" "(+Z" 'smZ" 
c3hZ" Z" Z" Z"xD( (C ((82D (PS ( ( ( ( ( (rE   r   r   r  Frs  r  r   r   r   	max_turnsr  r  
list_toolsr  save_sampleverboser  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(----------------------------------------)webr  visioncreativer  )researchdevelopmentr  content_creation
full_stacku   
📌 Basic Toolsets:resolved_toolsr~  rr  u     • r   z - rM  z    Tools: u5   
📂 Composite Toolsets (built from other toolsets):includesz    Includes: z    Total tools: 
tool_countu!   
🎭 Scenario-Specific Toolsets:20u3   
📦 Legacy Toolsets (for backward compatibility):r  u   ✅u   ❌r  r'  r  z    Requirements: ri  u   
🔧 Individual Tools (z available):u     📌 z (from ry  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 r`   rA  r   r0  s     rC   r   zmain.<locals>.<listcomp>!  s      P P Pq P P PrE   rm  u   🎯 Enabled toolsets: c                 6    g | ]}|                                 S r`   rA  rY  s     rC   r   zmain.<locals>.<listcomp>!  s     !R!R!R!''))!R!R!RrE   u   🚫 Disabled toolsets: u   💾 Trajectory saving: ENABLEDu:      - Successful conversations → trajectory_samples.jsonlu7      - Failed conversations → failed_trajectories.jsonl)	r   r   r   r   r  r  r  r  r  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: rU  u   📞 API Calls: re  u   💬 Messages: r   r@  u   
🎯 FINAL RESPONSE:z------------------------------r   sample_r  )conversationsr  r   rU  r  r  r  r  FrC  )r   r  u"   
💾 Sample trajectory saved to: u   
⚠️ Failed to save sample: u    
👋 Agent execution completed!)r  model_toolsrI  r   rJ  r  rK  rL  r  r   r  rM   r  r  r   r  r"  rL   r  r  rk  r	   r  r  r  rH   r   r   r   ))r  r   r   r   rD  r  r  rE  r  rF  rG  r  rI  r   rJ  rK  rL  all_toolsetsbasic_toolsetscomposite_toolsetsscenario_toolsetsrY   r  r  r  	tools_strincludes_strlegacy_toolsetsr  	all_toolsr   enabled_toolsets_listdisabled_toolsets_listr  rg  rT  rK  	sample_idsample_filenamera  rw  s)                                            rC   mainrj  v!  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  NNFFFFrs  )r^   atexitrL  r  concurrent.futuresr  rH  r8  r   r   r  r[   r  r   r  r  re   r  ro  ro   weakreftypesr   r  typingr   r   r   r   rI  r   firer	   pathlibr
   r6  r   hermes_cli.env_loaderr   r  __file__parent_project_env_loaded_env_paths	_env_pathr  r]  r   r   r   r   tools.terminal_toolr   tools.interruptr   r  tools.browser_toolr   r   agent.prompt_builderr   r   r   r   r   r   r  r   r   r    r!   r"   r#   r$   r%   agent.context_compressorr&   agent.prompt_cachingr'   r(   r)   r*   r+   r,   r-   r.   agent.usage_pricingr/   r0   r1  r1   r2   r  r3   r  r4   r5   r  agent.trajectoryr6   r7   r8   rm  utilsr9   r:   r<   ri   rk   r  r   r   r   r  compileVERBOSEr   r   rL   r~   r   r   r   r   r   r   r  r   r   r   r   r   r   r}   rj  Firer`   rE   rC   <module>r     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            + * * * * * ; ; ; ; ; ; . . . . . . 1 0 0 0 0 0               
                    7 6 6 6 6 6 > > > > > > \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \ 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 ? ? ? ? 
-..RZ<I  s s    D T    0%$ %4 % % % %<[( [( [( [( [( [( [( [(~~  !#S/ S/S/S/ S/ 	S/
 S/ S/ S/ S/ S/ S/ S/ S/ S/ S/ S/l zDIdOOOOO rE   