
    oq'j?                        d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	m
Z
mZmZ ddlmZ ddlmZ  ej        e          Ze G d d	                      ZddZdS )u  Per-turn setup for ``run_conversation`` (the turn prologue).

``run_conversation`` opened with ~470 lines of straight-line setup before the
tool-calling loop ever started: stdio guarding, runtime-main wiring, retry-counter
resets, user-message sanitization, todo/nudge-counter hydration, system-prompt
restore-or-build, crash-resilience persistence, preflight context compression, the
``pre_llm_call`` plugin hook, and external-memory prefetch.

All of that is *prologue* — it runs once per turn, has no back-references into the
loop, and produces a fixed set of values the loop then consumes. ``TurnContext``
captures those produced values; ``build_turn_context`` performs the setup work and
returns one. ``run_conversation`` is left to unpack the context and run the loop,
shrinking the orchestrator by the full prologue.

The builder still mutates ``agent`` heavily (counters, thread id, cached prompt,
session DB) exactly as the inline code did — those side effects are the point. The
``TurnContext`` it returns carries only the *locals* the loop reads back.

Behavior is identical to the original inline prologue; this is a pure
move-and-name refactor with no semantic change.
    )annotationsN)	dataclass)AnyDictListOptional)IterationBudget)estimate_request_tokens_roughc                      e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   dZded<   dZded<   dZded<   dS )TurnContextzCValues produced by the turn prologue and consumed by the turn loop.struser_messager   original_user_messagezList[Dict[str, Any]]messagesOptional[List[Dict[str, Any]]]conversation_historyOptional[str]active_system_prompteffective_task_idturn_idintcurrent_turn_user_idxFboolshould_review_memory plugin_user_contextext_prefetch_cacheN)__name__
__module____qualname____doc____annotations__r   r   r        7/home/ubuntu/.hermes/hermes-agent/agent/turn_context.pyr   r   %   s         MM """"8888''''LLL!&&&&&!!!!!       r$   r   r   r   system_messager   r   r   task_idpersist_user_messagereturnc               >    |             |                                   	 ddlm}  |t          | dd          pdt          | dd          pdt          | dd          pdt          | dd          pdt          | dd          pd	           n# t          $ r Y nw xY w || j                    |t          | d
d                     |                                  t          |t                    r |	|          }t          |t                    r |	|          }|| _	        d| _
        || _        |pt          t          j                              }|| _        | j        pd d| dt          j                    j        dd          }|| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        | j                                         d| _        d| _         | j!        dk    r;	 | "                                r| #                    d           n# t          $ r Y nw xY w| j$        r| %                                 d| _$        tM          | j'                  | _(         |
|          }tS          |          dk    r|dd         dz   n|}|*                    dd          }tV          ,                    d| j        pd| j-        | j.        pd| j/        pdtS          |pg           |           |rta          |          ng }|r.| j1        2                                s| 3                    |           |rV| j4        dk    rKtk          d |D                       }|dk    r,|| _4        | j6        dk    r| j7        dk    r|| j6        z  | _7        | xj4        dz  c_4        t          | dd          }||8                                 t          | dd          }||8                                 ||n|}d}| j6        dk    r9d| j9        v r0| j:        r)| xj7        dz  c_7        | j7        | j6        k    r	d}d| _7        d |d!}|;                    |           tS          |          dz
  }|| _
        | j<        sC |
|          }| =                    d"|dd#          tS          |          d#k    rdnd d$           | j>         || ||           | j>        }	 | ?                    ||           n4# t          $ r' tV          @                    d%| j        pdd&           Y nw xY w| jA        rtS          |          | jB        jC        | jB        jD        z   dz   k    rt          ||pd| jF        pd'          }| jB        }t          |d(d)           } ||          } | s|jG        }!|!dk    r||!k    r||_G        | r/tV          ,                    d*|d+|jH        d+|jI        d+           n|J                    |          rtV          ,                    d,|d+|jH        d+| j-        |jK        d+           | #                    d-|d+d.|jH        d+d/           t          d0          D ]}"tS          |          }#| M                    ||||1          \  }}tS          |          |#k    r nXd}d| _        d| _        d| _        d| _        d| _        t          ||pd| jF        pd'          }|J                    |          s nd}$	 dd2lNmO}%  |%d3| j        |||ta          |          t          |           | j-        t          | d4d          pdt          | d5d          pd6
  
        }&g }'|&D ]}(t          |(t                    r>|(R                    d7          r)|';                    t          |(d7                              Ut          |(t                    r)|(S                                r|';                    |(           |'rd8T                    |'          }$n2# t          $ r%})tV          @                    d9|)           Y d})~)nd})~)ww xY wi | _U        t          jW                    jX        | _Y         |            Z                    d| jY                   | j[        r+ |            Z                    d| jY                   d| _\        nd| _]        d| _\        | j^        rK	 t          |t                    r|nd}*| j^        _                    | j4        |*           n# t          $ r Y nw xY wd}+| j^        rG	 t          |t                    r|nd},| j^        `                    |,          pd}+n# t          $ r Y nw xY wt          ||||||||||$|+:          S );a  Run the once-per-turn setup and return the loop's input context.

    The callables/helpers the original prologue referenced from the
    ``conversation_loop`` module are passed in explicitly to keep this module
    free of an import cycle with ``agent.conversation_loop``.
    r   )set_runtime_mainproviderr   modelbase_urlapi_keyapi_mode)r.   r/   r0   _memory_write_originassistant_toolNsession:   FTanthropic_messagesu~   🔌 Detected stale connections from a previous provider issue — cleaned up automatically. Proceeding with fresh connection.P   z...
 zPconversation turn: session=%s model=%s provider=%s platform=%s history=%d msg=%rnoneunknownc              3  L   K   | ]}|                     d           dk    dV   dS )roleuser   N)get).0ms     r%   	<genexpr>z%build_turn_context.<locals>.<genexpr>   s?       
 
quuV}}/F/FA/F/F/F/F
 
r$   r?   _stream_context_scrubber_stream_think_scrubbermemoryr>   )r=   contentu   💬 Starting conversation: '<   'z:Early turn-start session persistence failed for session=%s)exc_info)system_prompttools$should_defer_preflight_to_real_usagec                    dS )NFr#   )_tokenss    r%   <lambda>z$build_turn_context.<locals>.<lambda>  s    E r$   zpSkipping preflight compression: rough estimate ~%s >= %s, but last real provider prompt was %s after compression,zDPreflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)u   📦 Preflight compression: ~z tokens >= z# threshold. This may take a moment.   )approx_tokensr'   )invoke_hookpre_llm_callplatform_user_id)	
session_idr'   r   r   r   is_first_turnr-   rV   	sender_idcontextz

zpre_llm_call hook failed: %s)r   r   r   r   r   r   r   r   r   r   r   )b_ensure_db_sessionagent.auxiliary_clientr+   getattr	ExceptionrX   _restore_primary_runtime
isinstancer   _stream_callback_persist_user_message_idx_persist_user_message_overrideuuiduuid4_current_task_idhex_current_turn_id_current_api_request_id_invalid_tool_retries_invalid_json_retries_empty_content_retries_incomplete_scratchpad_retries_codex_incomplete_retries_thinking_prefill_retries_post_tool_empty_retried_last_content_with_tools$_last_content_tools_all_housekeeping_mute_post_response_unicode_sanitization_passes_tool_guardrailsreset_for_turn_tool_guardrail_halt_decision_vision_supportedr0   _cleanup_dead_connections_emit_status_compression_warning_replay_compression_warningr	   max_iterationsiteration_budgetlenreplaceloggerinfor-   r,   rV   list_todo_store	has_items_hydrate_todo_store_user_turn_countsum_memory_nudge_interval_turns_since_memoryresetvalid_tool_names_memory_storeappend
quiet_mode_safe_print_cached_system_prompt_persist_sessionwarningcompression_enabledcontext_compressorprotect_first_nprotect_last_nr
   rL   last_prompt_tokensthreshold_tokenslast_real_prompt_tokensshould_compresscontext_lengthrange_compress_contexthermes_cli.pluginsrT   r   dictr@   stripjoin_turn_failed_file_mutations	threadingcurrent_threadident_execution_thread_id_set_interrupt_interrupt_requested _interrupt_thread_signal_pending_interrupt_message_memory_manageron_turn_startprefetch_allr   )-agentr   r&   r   r'   stream_callbackr(   restore_or_build_system_promptinstall_safe_stdiosanitize_surrogatessummarize_user_message_for_logset_session_contextset_current_write_originrar+   r   r   _preview_text_msg_previewr   prior_user_turnsscrubberthink_scrubberr   r   user_msgr   _print_previewr   _preflight_tokens_compressor_defer_preflight_preflight_deferred_last_pass	_orig_lenr   _invoke_hook_pre_results
_ctx_partsrexc	_turn_msgr   _querys-                                                r%   build_turn_contextr   @   sx   0 	
;;;;;;E:r**0bE7B''-2UJ339rE9b117RUJ339r	
 	
 	
 	
 	
     ())) WU,BDTUUVVV 
""$$$ ,$$ 9**<88&,, I223GHH -E&*E#+?E(43tz||#4#4.E!.Y[[1B[[TZ\\EUVXWXVXEY[[G$E$&E! #$E"#E#$E +,E(&'E#&'E#%*E"%)E"16E. %E)*E&	))+++*.E'"E ~---	..00 """  
  	 	 	D	 ! *))+++%)" -U-ABBE 32<@@M36}3E3E3J3JM#2#&..P]L''c22L
KKZ"FEK1L9#)S)=)C%D%D	   .BIt()))rH  8E$5$?$?$A$A 8!!"6777  \ 6! ; ; 
 
+
 
 
 
 
 a%5E"+a//E4MQR4R4R,<u?[,[) 
a u8$??HU$<dCCN! 5I4T00Zf !$q((E222# 3!!Q&!!$(DDD#' ()E% <88HOOHMMA-&;E# 
77EE<N3B3,? <N++b00uub< < <	
 	
 	
 "*&&un>RSSS 6
x)=>>>> 
 
 
H& 	 	
 	
 	
 	
 	

 	!AMME4D#6EFHIJ J J :.4"+%
 
 

 ."2!!
 

 /./@AA" 	C2Ezz/%771B. )	KKI$((/336::    (():;; !	KKV$((/33-11   *0AM * *!2B* * *  
 q  MM	161H1Hn<M- 2I 2 2.. x==I--E'+$/0,23/15.=B:,1)$A"6"<"+-% % %!
 #223DEE E <BBBBBB#|'%.!%h#$8999+UJ55;eZ66<"
 
 
 !#
 	% 	%A!T"" %quuY'7'7 %!!#a	l"3"34444As## %		 %!!!$$$ 	:"(++j"9"9 < < <5s;;;;;;;;< )+E% "+!9!;!;!AE BDDu9:::! 7
D%"<===16..#' 16.  	1;<QSV1W1W_--]_I!//0F	RRRR 	 	 	D	  	.89NPS.T.T\**Z\F!&!6!C!CF!K!K!Qr 	 	 	D	 !311+31/-   ss   A+B 
BB)H? ?
II4T .T<;T<D`* *
a4aa+9d% %
d21d2?5e5 5
ff)r   r   r&   r   r   r   r'   r   r(   r   r)   r   )r!   
__future__r   loggingr   re   dataclassesr   typingr   r   r   r   agent.iteration_budgetr	   agent.model_metadatar
   	getLoggerr   r   r   r   r#   r$   r%   <module>r      s   , # " " " " "       ! ! ! ! ! ! , , , , , , , , , , , , 2 2 2 2 2 2 > > > > > >		8	$	$ ! ! ! ! ! ! ! !4D D D D D Dr$   