
    (Gj]                    0    d Z ddlmZ ddlZddlmZ d ZdS )u  Post-loop turn finalization for ``run_conversation``.

Extracted from ``agent/conversation_loop.py`` as part of the god-file
decomposition campaign (``~/.hermes/plans/god-file-decomposition.md``, Phase 1
step 4 — the post-loop ``TurnFinalizer`` seam). ``run_conversation``'s tail
(everything after the main tool-calling ``while`` loop) is lifted here verbatim:
budget-exhaustion summary, trajectory save, session persist, turn diagnostics,
response transforms, result-dict assembly, steer drain, and the memory/skill
review trigger.

Behavior-neutral: the body is moved unchanged. All ``agent.*`` side effects fire
exactly as before; only the post-loop *locals* are passed in as keyword args, and
the assembled ``result`` dict is returned to ``run_conversation`` which returns it
to the caller. The function is synchronous with a single return — mirroring the
region it replaces (no awaits, no early returns).

Module ``logger`` is imported lazily inside the body (``from
agent.conversation_loop import logger``) so this module never imports
``agent.conversation_loop`` at import time -> no import cycle, and the log records
keep the exact logger name (``"agent.conversation_loop"``).
    )annotationsN)_summarize_user_message_for_logc                  ddl m} ||| j        k    s| j        j        dk    rpd| d| j         d}|                     d| d| j         d           | j        s!|                     d	| d| j         d
           |                     ||          }t          j
                            d          }|r	 ddlm} |                                }	 |                    ||d| d| j         dddd|| j        d           |                    d||| j                   	 |                                 n:# t$          $ r Y n.w xY w# 	 |                                 w # t$          $ r Y w w xY wxY wn(# t$          $ r |                    d|d           Y nw xY wt)          |                              d          }|duo| o|| j        k     p|}g }	 |                     |t/          |	          |           nG# t$          $ r:}|                    d|            |                    d|d           Y d}~nd}~ww xY w	 |                     |           nG# t$          $ r:}|                    d|            |                    d|d           Y d}~nd}~ww xY w	 |                     |           |rddlm}  |||           |rS|sQ	 |r|d                             d          nd}n# t$          $ r d}Y nw xY w|dk    r|                    d|d           |                     ||           nG# t$          $ r:}|                    d |            |                    d!|d           Y d}~nd}~ww xY w|r|d                             d          nd}d}|d"k    rt?          |          D ]}|                    d          dk    rk|                    d#          rV|d#         }|rJtA          |d         tB                    r/|d                             d$i                               d%          } ntE          d& |D                       }|rtG          |          nd}| j        r| j        j$        nd}| j        r| j        j%        nd} d'}!|| j&        || j        || |||| j'        pd(f
}"|d"k    r|s |j        d)|!z   d*z   g|"|R   n |j        |!g|"R   |r|s	 tQ          | d+d          pi }#|#rE| )                                r1| *                    |#          }$|$r|+                                d,z   |$z   }n-# t$          $ r }%|,                    d-|%           Y d}%~%nd}%~%ww xY w|s	 | -                                r|pd..                                }&|&d.k    p|&d/k    }'|' oAt)          |                              d0           otG          |&          d1k    o|&dd         d2v}(t)          |          d3k    })|'s|(s|)r$| /                    |          }*|*r|'r|*}n|&d,z   |*z   }n-# t$          $ r }+|,                    d4|+           Y d}+~+nd}+~+ww xY wd5},|r|s	 dd6l0m1}-  |-d7|| j'        pd.| j&        tQ          | d8d          pd.9          }.|.D ]}/tA          |/t(                    r|/r|/}d}, n n-# t$          $ r }0|                    d:|0           Y d}0~0nd}0~0ww xY w|rs|sq	 dd6l0m1}-  |-d;| j'        |||
|te          |          | j&        tQ          | d8d          pd.<	  	         n-# t$          $ r }0|                    d=|0           Y d}0~0nd}0~0ww xY wd}1t?          |          D ]U}2|2                    d          d>k    r n9|2                    d          dk    r|2                    d?          r
|2d?         }1 nVi d@|dA|1dB|dC|dD|dE|dF|dGd5dH|dI|,dJtQ          | dKd5          dL| j&        dM| j3        dN| j4        dO| j5        dP| j6        dQ| j7        | j8        | j9        | j:        | j;        | j<        tQ          | j=        dRd          pd| j>        | j?        | j@        | j'        dS
}3| jA        | jA        B                                |3dT<   |r||3dU<   | C                                }4|4r|4|3dV<   d5| _D        |r| jE        r
| jE        |3dW<   | F                                 d| _G        d5}5| jH        dk    r"| jI        | jH        k    rdX| jJ        v r	d}5d| _I        | K                    |
|||Y           |r=|s;|s|5r7	 | L                    te          |          ||5Z           n# t$          $ r Y nw xY w	 dd6l0m1}-  |-d[| j'        ||||| j&        tQ          | d8d          pd.\           n-# t$          $ r }0|                    d]|0           Y d}0~0nd}0~0ww xY w|3S )^zRun the post-loop finalization and return the turn ``result`` dict.

    Lifted verbatim from ``run_conversation`` (the region after the main agent
    loop). See module docstring.
    r   )loggerNzmax_iterations_reached(/)u#   ⚠️ Iteration budget exhausted (u   ) — asking model to summariseu%   
⚠️  Iteration budget exhausted (u   ) — requesting summary...HERMES_KANBAN_TASK)	kanban_dbzIteration budget exhausted (u;   ) — task could not complete within the allowed iterations	timed_outT)budget_used
budget_max)erroroutcomerelease_claimend_runevent_payload_extraz5recorded budget-exhausted failure for task %s (%d/%d)z5Failed to record budget-exhausted failure for task %s)exc_infoztext_response(zsave_trajectory: z*finalize_turn: _save_trajectory failed: %szcleanup_task_resources: z1finalize_turn: _cleanup_task_resources failed: %s)close_interrupted_tool_sequencerole	assistant)r   contentzpersist_session: z*finalize_turn: _persist_session failed: %stool
tool_callsfunctionnamec              3     K   | ]I}t          |t                    r2|                    d           dk    0|                    d          EdV  JdS )r   r   r      N)
isinstancedictget).0ms     :/home/rurouni/.hermes/hermes-agent/agent/turn_finalizer.py	<genexpr>z finalize_turn.<locals>.<genexpr>   sf        a#$55==K#?#?AEE,DWDW#? 	
#?#?#?#?     zuTurn ended: reason=%s model=%s api_calls=%d/%d budget=%d/%d tool_turns=%d last_msg_role=%s response_len=%d session=%snonez>Turn ended with pending tool result (agent may appear stuck). z last_tool=%s_turn_failed_file_mutationsz

z(file-mutation verifier footer failed: %s z(empty)text_response   >      。   ！   ？?!r   .`partial_stream_recoveryz$turn-completion explainer failed: %sF)invoke_hooktransform_llm_outputplatform)response_text
session_idmodelr6   z$transform_llm_output hook failed: %spost_llm_call)r8   task_idturn_iduser_messageassistant_responseconversation_historyr9   r6   zpost_llm_call hook failed: %suser	reasoningfinal_responselast_reasoningmessages	api_calls	completedturn_exit_reasonfailedpartialinterruptedresponse_transformedresponse_previewed_response_was_previewedr9   providerbase_urlinput_tokensoutput_tokenscache_read_tokenslast_prompt_tokens)
cache_write_tokensreasoning_tokensprompt_tokenscompletion_tokenstotal_tokensrS   estimated_cost_usdcost_statuscost_sourcer8   	guardrailcleanup_errorspending_steerinterrupt_messageskill_manage)original_user_messagerB   rJ   rD   )messages_snapshotreview_memoryreview_skillson_session_end)r8   r;   r<   rF   rJ   r9   r6   zon_session_end hook failed: %s)Magent.conversation_loopr   max_iterationsiteration_budget	remaining_emit_status
quiet_mode_safe_print_handle_max_iterationsosenvironr!   
hermes_clir
   connect_record_task_failureinfoclose	Exceptionwarningstr
startswith_save_trajectoryr   appendr   _cleanup_task_resources)_drop_trailing_empty_response_scaffoldingagent.message_sanitizationr   _persist_sessionreversedr   r    sumlenused	max_totalr9   r8   getattr_file_mutation_verifier_enabled$_format_file_mutation_failure_footerrstripdebug"_turn_completion_explainer_enabledstrip#_format_turn_completion_explanationhermes_cli.pluginsr4   listrN   rO   session_input_tokenssession_output_tokenssession_cache_read_tokenssession_cache_write_tokenssession_reasoning_tokenssession_prompt_tokenssession_completion_tokenssession_total_tokenscontext_compressorsession_estimated_cost_usdsession_cost_statussession_cost_source_tool_guardrail_halt_decisionto_metadata_drain_pending_steerrM   _interrupt_messageclear_interrupt_stream_callback_skill_nudge_interval_iters_since_skillvalid_tool_names_sync_external_memory_for_turn_spawn_background_review)6agentrB   api_call_countrJ   rH   rD   r?   effective_task_idr<   r=   ra   _should_review_memory_turn_exit_reasonr   _kanban_task_kb_connnormal_text_responserF   _cleanup_errors	_save_err_cleanup_errr   
_tail_role_persist_err_last_msg_role_last_tool_name_m_tcs_turn_tool_count	_resp_len_budget_used_budget_max	_diag_msg
_diag_args_failedfooter_ver_err	_stripped_is_empty_terminal_is_partial_fragment_is_partial_stream_recovery_explanation_exp_err_response_transformed_invoke_hook_transform_results_hook_resultexcrC   msgresult_leftover_steer_should_review_skillss6                                                         r$   finalize_turnr      s&   * /.....%...!+q00
 _n^^uG[^^^,. , ,5CW , , ,	
 	
 	
  	, , ,%J^ , , ,   55hOO z~~&:;; $	#777777,,$) .) )161E) ) )
 !,&* $+9*/*>- - -   " KKO$ne6J  
$   $      K !       011<<=MNNd" 	
J	
 U11 $# ( O]x)H)V)VXabbbb ] ] ]>9>>???A9W[\\\\\\\\]
g%%&78888 g g gH,HHIIIH,aeffffffffg+`77AAA   	FRRRRRR++HnEEE  	R+ 	R"9AKXb\--f555t

 " " "!


"[(( P PQQQx)=>>>> ` ` `A<AABBBA<Z^________` 2:CXb\%%f---tNO8$$ 	 	Bvvf~~,,1E1E,,' OJtAw55 O&*2hll:r&B&B&F&Fv&N&NO       (6<N###1I272HO5)..aL6;6LS%(22RSK	D 
 	5;8Lk.)"F	J L)*	
 	
 )	
 	
 	
 	
 	
 	I+
++++"  Ok O	Oe%BDIIORG O5@@BB OCCGLL O%3%:%:%<%<v%E%NN 	O 	O 	OLLCXNNNNNNNN	O&  &K%	K7799 "+1r88::	%."_%N	Y8N"
 +* ] 122==oNNN]I",] ""##.\\	 % )**.GG , '+ 3
 $)#L#L)$ $L $ - 
 .:NN !*F 2\ A +  	K 	K 	KLL?JJJJJJJJ	K "  Hk H	HFFFFFF!-&, +1rk 
D99?R" " " !3  lC00 \ %1N,0)E 	H 	H 	HNNA3GGGGGGGG	H  Ak A	AFFFFFFL +)2#1%)(^^k 
D99?R
 
 
 
 
  	A 	A 	ANN:C@@@@@@@@	A N!!  776??f$$E776??k))cggk.B.B) -NE.. 	H 	^	
 	Y 	- 	& 	5 	{ 	 5 	ge-FNN 	 	EN 	EN 	2  	4!" 	U<#$ $>!:4"<2%e&>@TVWXX]\]#>00&7  F: *6#AMMOO{  3#2  0022O 2"1$)E!  ?u/ ?&+&>"# 
 "E "#a''(E,GGG%"888 $#$  
((3%	 )     k /D H] 	**"&x..33 +    
  	 	 	D	>BBBBBB'%#+UJ55;		
 		
 		
 		
 		
  > > >7========> Msg  5E. AE D3 2E. 3
E =E. ?E  E. E*EE*
E'$E*&E''E**E. ."FF$G4 4
H8>0H33H8<I 
J0JJ-L/ K( 'L/ (K74L/ 6K777L/ /
M390M..M3AT5 5
U?UU%B8X 
Y(YYAZ( (
[2[[A\ 
]']].%e 
e! e!%4f 
g$f??g)__doc__
__future__r   rn   agent.codex_responses_adapterr   r    r&   r$   <module>r      s\    , # " " " " " 				 I I I I I I] ] ] ] ]r&   