
    `gj                    <    d Z ddlmZ ddlZddlmZ  G d d      Zy)a  Agent-construction and session-resume display methods for ``HermesCLI``.

Extracted from ``cli.py`` as part of the god-file decomposition campaign
(``~/.hermes/plans/god-file-decomposition.md``, Phase 4 step 2). This mixin holds
the agent lifecycle/setup cluster: runtime-credential resolution, per-turn agent
config, first-use agent construction, and resumed-session preload + history recap.

Behavior-neutral: every method is lifted verbatim from ``HermesCLI``. ``self.*``
calls resolve unchanged via the MRO. Neutral dependencies are imported at module
top level; ``cli.py``-internal helpers/constants are imported lazily inside each
method (``from cli import ...`` resolves at call time, when ``cli`` is fully
loaded) so this module never imports ``cli`` at import time -> no import cycle.
    )annotationsN)escapec                  @    e Zd ZdZd	dZd
dZddddddZd	dZd Zy)CLIAgentSetupMixinzFAgent construction + session-resume display methods for ``HermesCLI``.c                   ddl m}m}m} ddlm}m} d}d}	  || j                  | j                  | j                        }||ddlm}	 t        ||	      rt        | j                  t              r| j                  ng }
|
D ]  }|j!                  d      xs dj#                         j%                         }|j!                  d	      xs dj#                         }|r|s\	 dd
lm} d|i}|j!                  d      r|d   |d<    ||      }|r||d<    |d&i |}|j+                  d|||        |d| d|        || _        || _        d} n |'|r ||      nd} |       j/                  d| d       y|j!                  d      }|j!                  d      }|j!                  dd      }|j!                  d| j0                        }|j!                  d      }t        |j!                  d      xs g       }|j!                  d      }t3        |      xr t        |t4               }|sbt        |t4              r|sP|j!                  dd      }t        |t4              xr |xr d|v}|rd}|j7                  d||       nt/        d        yt        |t4              r|st/        d!       y|| j8                  k7  xs || j:                  k7  }|| j<                  k7  xs1 || j0                  k7  xs  || j>                  k7  xs || j@                  k7  }|| _        || _        || _        || _         || _!        |j!                  d      | _"        || _        || _        |j!                  d	      }|rat        |t4              rQ| j,                   xs9 | j,                  | j<                  k(  xs | j,                  |j!                  d"      k(  }|r|| _        | j,                  s-|r+	 dd#l#m$}   | |      }!|!r|!| _        |jK                  d$|!|       | jM                  |      }"|s|s|"r| jN                  d| _'        d| _(        y%# t        $ r}|}Y d}~ d}~ww xY w# t        $ r Y w xY w# t        $ r Y fw xY w)'a  
        Ensure runtime credentials are resolved before agent use.
        Re-resolves provider credentials so key rotation and token refresh
        are picked up without restarting the CLI.
        Returns True if credentials are ready, False on auth failure.
        r   )ChatConsole_cprintlogger)resolve_runtime_providerformat_runtime_provider_errorN)	requestedexplicit_api_keyexplicit_base_url)	AuthErrorprovider model)resolve_entry_api_keyr   base_urlr   r   zEPrimary provider auth failed (%s). Falling through to fallback: %s/%su7   ⚠️  Primary auth failed — switching to fallback: z / zProvider resolution failed.z
[bold red][/]Fapi_key
openrouterapi_modecommandargscredential_poolsourcezopenrouter.aizno-key-requireduh   No API key for custom endpoint %s (source=%s), using placeholder — local servers typically ignore authua   
⚠️  Provider resolver returned an empty API key. Set OPENROUTER_API_KEY or run: hermes setupuf   
⚠️  Provider resolver returned an empty base URL. Check your provider config or run: hermes setupname)get_default_model_for_provideru8   No model configured — defaulting to %s for provider %sT ))clir   r	   r
   hermes_cli.runtime_providerr   r   requested_provider_explicit_api_key_explicit_base_url	Exceptionhermes_cli.authr   
isinstance_fallback_modellistgetstriplowerhermes_cli.fallback_configr   warningr   printr   callablestrdebugr   r   r   acp_commandacp_args_credential_pool_provider_sourcehermes_cli.modelsr   info_normalize_model_for_provideragent_active_agent_route_signature)#selfr   r	   r
   r   r   _primary_excruntimeexcr   	_fb_chain_fb_fb_provider	_fb_modelr   
_fb_kwargs_fb_api_keymessager   r   resolved_providerresolved_api_moderesolved_acp_commandresolved_acp_argsresolved_credential_pool_is_callable_provider_source_has_custom_basecredentials_changedrouting_changedruntime_modelshould_use_runtime_modelr   _defaultmodel_changeds#                                      S/root/.hermes/venv/lib/python3.12/site-packages/hermes_cli/cli_agent_setup_mixin.py_ensure_runtime_credentialsz.CLIAgentSetupMixin._ensure_runtime_credentials   s    	54	

 	.11!%!7!7"&"9"9G ?|71,	24>t?S?SUY4ZD00`b	$ !C$'GGJ$7$=2#D#D#F#L#L#NL!$!1!7R > > @I'y !T&1<%@
77:.>A*oJ':;&;C&@&=HJ'9:":"HZ"Hc(,	  "YZfYggjktju vw2>/%.
'+/!6 ?EQ3LAWtGM*WIS 9:++i(;;z*#KK
LA#KK
DMMB&{{95 V!4!:;#*;;/@#A  !) 1 R*Wc:R6R$j#.Fg
 kk(B/G)(C8iXi/aiJi+Pg  D E(C( D E%5RT]]9R. 2 DMM12#t'7'772 !DMM1	 	 *)/) 8 'H 5   G,Zs; JJ 2

dmm+2

gkk&11 %
 (*

 zz/
L9:KL!)DJKKR "3 ::;LM  ?mI_DJ15D.M  	L	@ % ! !r  s<   )P0  A,Q	*Q 0	Q9QQ		QQ	Q%$Q%c                   ddl m} | j                  | j                  | j                  | j
                  | j                  t        | j                  xs g       t        | dd      d}| j                  || j                  |d   |d   |d   |d	   t        |d
         fd}t        | dd      }|sd|d<   |S 	  ||d         }||d<   |S # t        $ r d}Y w xY w)aL  Build the effective model/runtime config for a single user turn.

        Always uses the session's primary model/provider.  If the user has
        toggled `/fast` on and the current model supports Priority
        Processing / Anthropic fast mode, attach `request_overrides` so the
        API call is marked accordingly.
        r   )resolve_fast_mode_overridesr6   Nr   r   r   r   r   r   r   r   r   r   r   r   )r   r?   	signatureservice_tierrequest_overridesr   )r8   rY   r   r   r   r   r4   r*   r5   getattrr   tupler&   )r=   user_messagerY   r?   router\   	overridess          rV   _resolve_turn_agent_configz-CLIAgentSetupMixin._resolve_turn_agent_config   s     	B ||'',"-&t-?F
 ZZ


#
#
#	"gfo&
 t^T:)-E%&L	3E'NCI &/!"  	I	s   4C CCN)model_overrideruntime_overrider]   c                  ddl m}m}m}m}m}m}	m}
m} | j                  y |
        | j                          | j                          | j                         syddlm}  |        | j                  	 ddlm}  |       | _        | j(                  ro| j                  rb| j*                  sU| j                  j-                  | j.                        }t1        | d	d
      dk(  }|sk|rDt3        d| j.                   t4        j6                         t3        dt4        j6                         y |	d| j.                   |         |	| d|        y	 | j                  j9                  | j.                        }|rx|| j.                  k7  ri |       j3                  dt;        | j.                         dt;        |       d       || _        | j                  j-                  | j.                        }|r|}| j                  j=                  | j.                  d      }|r2|D cg c]  }|j?                  d      dk7  s| }}|| _        tA        |D cg c]  }|j?                  d      dk(  s| c}      }d}|j?                  d      r	d|d    d}|rEt3        d| j.                   | d| d|dk7  rdnd d tA        |       d!
t4        j6                         nb |       j3                  d" |        d#t;        | j.                         d$ |        d%t;        |       d&| d|dk7  rdnd d tA        |       d!       | jC                  ||'       na|r*t3        d(| j.                   d)t4        j6                         n5 |       j3                  d" |        d*t;        | j.                         d+       	 | j                  jD                  jG                  d,| j.                  f       | j                  jD                  jI                          	 |xs^ | jJ                  | jL                  | jN                  | jP                  | jR                  tU        | jV                  xs g       t1        | d-d      d.}|xs | jX                  } |ddi d/|d0|j?                  d0      d1|j?                  d1      d2|j?                  d2      d3|j?                  d3      d4|j?                  d5      d6|j?                  d7      d8|j?                  d8      d9| jZ                  d:| j\                  d;| j^                  d<| j`                  d=| jb                  d>| jb                   d	t1        | d	d?      d@| jd                  r| jd                  nddA| jf                  xs ddB| jh                  dC| jj                  dD|dE| jl                  dF| jn                  dG| jp                  dH| jr                  dI| jt                  dJ| jv                  dK| jx                  dL| j.                  dMdNdO| j                  dP| jz                  dQ| j}                         dR| j~                  dS| j                  dT| j                  dU| j                  dV| j                  dW| j                  dX| j                  dY| j                  dZ| j                  d[| j                  d\| j                  r| j                  ndd]| j                  r| j                  ndd^| j                  r| j                  ndd_| j                  r| j                  ndd`| j                  da| j                  db| j                  | _	        ddl }| j                  |_Q        |	| j                  _R        	 ddclSmT}  || j                         ||j?                  d2      |j?                  d1      |j?                  d3      |j?                  d5      t        |j?                  d7      xs dd      f| _V        | j                  r| j                  r| j                  r~	 | j                  j                          | j                  j                  rL| j                  j                  | j.                  | j                          |	de| j                          d| _W        yy# t$        $ r}|j'                  d|       Y d}~4d}~ww xY w# t$        $ r | j.                  }Y ew xY wc c}w c c}w # t$        $ r Y w xY w# t$        $ r Y sw xY w# t        t$        f$ r} |	df|        Y d}~yd}~ww xY w# t$        $ r$} |       j3                  dg| dh       Y d}~yd}~ww xY w)iz
        Initialize the agent on first use.
        When resuming a session, restores conversation history from SQLite.
        
        Returns:
            bool: True if successful, False otherwise
        r   )AIAgentr   _DIM_RST_accent_hexr	   _prepare_deferred_agent_startupr
   NTF)wait_for_mcp_discovery)	SessionDBuF   SQLite session store not available — session will NOT be indexed: %stool_progress_modefulloffzSession not found: )filez@Use a session ID from a previous CLI run (hermes sessions list).z[1;31mSession not found: [dim]Session  was compressed into z5; resuming the descendant with your transcript.[/dim]repair_alternationrolesession_metauserr   title ""u   ↻ Resumed session  ( user message   s, z total messages)z[bold u   ]↻ Resumed session[/] [bold]z	[/][bold ]z[/] ()quietzSession z+ found but has no messages. Starting fresh.	]Session . found but has no messages. Starting fresh.[/]CUPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?r6   rZ   r   r   r   r   r   r4   r   r5   r   r   
max_tokensmax_iterationsenabled_toolsetsdisabled_toolsetsverbose_logging
quiet_modeallephemeral_system_promptprefill_messagesreasoning_configr\   r]   providers_allowedproviders_ignoredproviders_orderprovider_sortprovider_require_parametersprovider_data_collectionopenrouter_min_coding_score
session_idplatformr!   
session_dbclarify_callbackreasoning_callbackfallback_modelthinking_callbackcheckpoints_enabledcheckpoint_max_snapshotscheckpoint_max_total_size_mbcheckpoint_max_file_size_mbpass_session_idskip_context_filesskip_memorytool_progress_callbacktool_start_callbacktool_complete_callbackstream_delta_callbacktool_gen_callbacknotice_callbacknotice_clear_callbackreaction_callback)seed_credits_at_session_startr    z  Session title applied: z!  Could not apply pending title: z&[bold red]Failed to initialize agent: r   )\r!   rg   r   rh   ri   rj   r	   rk   r
   r;   _install_tool_callbacks_ensure_tirith_securityrW   hermes_cli.mcp_startuprl   _session_dbhermes_staterm   r&   r/   _resumedconversation_historyget_sessionr   r^   r0   sysstderrresolve_resume_session_id_escapeget_messages_as_conversationr+   len_restore_session_cwd_connexecutecommitr   r   r   r   r4   r*   r5   r   r   	max_turnsr   r   verbosesystem_promptr   r   r\   _providers_only_providers_ignore_providers_order_provider_sort_provider_require_params_provider_data_collection_openrouter_min_coding_score_clarify_callback_current_reasoning_callbackr)   _on_thinkingr   r   r   r   r   ignore_rules_on_tool_progress_inline_diffs_enabled_on_tool_start_on_tool_completestreaming_enabled_stream_delta_on_tool_gen_start
_on_notice_on_notice_clear_on_reaction_active_agent_ref	_print_fnagent.credits_trackerr   r_   r<   _pending_title_ensure_db_session_session_db_createdset_session_title
ValueError)r=   rd   re   r]   rg   r   rh   ri   rj   r	   rk   r
   rl   rm   erw   _quiet_moderesolved_idresolved_metarestoredm	msg_count
title_partr?   effective_model_clir   s                              rV   _init_agentzCLIAgentSetupMixin._init_agent   s	    	xww::!')$$&$$&//1A  #l2#,;  ==T--d6O6O++77HL "$(<fENK//@A

SZ ZZ  ;DOO;LTFSTtf$deidjkl."..HHY {doo=###GDOO$<#==R{+, -()
 #. $ 0 0 < <T__ M #0L''DDD E H '/S!155=N3RASS,4)H Pqf8O PQ	
##G,#&|G'<&=R!@J.t.?
| L%;m9>Cr3RRTx=/)9; !ZZ	  M''  0!!(!9 : ;!!,q1D0E F%;m9>Cr3RRTUXYaUbTccsu )),k)J"4??"33^_ ZZ
  M'' y9Q8R  SA  B  &&..Y__&   &&--/o	& << MM MM MM++T]]0b1#*41CT#J+G -:

O  3%3I.3 !Z03 !Z0	3
 !Z03 $KK	23 !V,3 !(,= >3  ??3  $~~3 "&!6!63 #'"8"83 !%3  $||+3 $+41Eu#M3  ?C>P>P(:(:VZ!3" "&!6!6!>$#3$ "&!6!6%3& "..'3( #4)3* #'"6"6+3, #'"8"8-3. !% 5 5/30 #11132 -1,I,I334 *.)G)G536 -1,M,M738  ??93: ;3<  ++=3> "&!7!7?3@ $(#C#C#EA3D  $33E3F #'"3"3G3H %)$<$<I3J *.)F)FK3L .2-N-NM3N -1,L,LO3P !% 4 4Q3R $(#4#4S3T !--U3V (,'='=W3X <@;U;UD$7$7[_Y3Z BFA[A[t'='=ae[3\ =A<R<Rd&8&8X\]3^ >B=S=S$"9"9Y]_3` !%a3b '+&;&;c3d #'"3"3e3DJz %)ZZD" $+DJJ 
O-djj9  J'J'J'I&gkk&)/R02D. ""t'7'7DJJEJJ113zz55((::4??DL_L_`";D<O<O;P QR.2+
 I  lgijkkl>  ."oo.  T PH  p  ( #I. E?sCDDE  	M"H3 OP	s   4b %c c7cc#'c#-Ac( M5d/ 9c8 B	d/ A<d 	b?"b::b?cc(	c54c58	dd/ dd/ d,d'"d/ 'd,,d/ /	e8eec                X   ddl m} | j                  r| j                  sy| j                  j	                  | j
                        }|s1| j                  d| j
                   d       | j                  d       y	 | j                  j                  | j
                        }|ra|| j
                  k7  rR| j                  d| j
                   d| d	       || _        | j                  j	                  | j
                        }|r|}| j                  j                  | j
                  d
      }|r|D cg c]  }|j                  d      dk7  s| }}|| _        t        |D cg c]  }|j                  d      dk(  s| c}      }d}|j                  d      r	d|d    d} |       }	| j                  d|	 d| j
                   d| d| d|dk7  rdnd dt        |       d       | j                  |       n* |       }	| j                  d|	 d| j
                   d       y	 | j                  j                  j                  d| j
                  f       | j                  j                  j!                          y
# t        $ r | j
                  }Y w xY wc c}w c c}w # t        $ r Y y
w xY w)a  Load a resumed session's history from the DB early (before first chat).

        Called from run() so the conversation history is available for display
        before the user sends their first message.  Sets
        ``self.conversation_history`` and prints the one-liner status.  Returns
        True if history was loaded, False otherwise.

        The corresponding block in ``_init_agent()`` checks whether history is
        already populated and skips the DB round-trip.
        r   )rj   Fz[bold red]Session not found: r   zH[dim]Use a session ID from a previous CLI run (hermes sessions list).[/]rr   rs   z2; resuming the descendant with your transcript.[/]Trt   rv   rw   rx   r   ry   rz   r{   [u   ]↻ Resumed session [bold]z[/bold]r|   r}   r~   r   r   z total messages)[/]r   r   r   )r!   rj   r   r   r   r   _console_printr   r&   r   r+   r   r   r   r   r   r   )
r=   rj   rw   r   r   r   r   r   r   accent_colors
             rV   _preload_resumed_sessionz+CLIAgentSetupMixin._preload_resumed_session  s    	$}}D$4$4''33DOOD//@D - 	***DDT__UK ;$//900E-QS *DO ,,88IM,##@@OO A 
 #+OaquuV}/NOHO(0D%L1AEE&MV4KQLMIJ(!,w"7!8:
&=LL>!<T__<MW, ;m9>Cr+J"x=/!46 %%l3&=LL>4??*; </ 0 	""**"
 ""))+ c  	*//K	*  PL8  		s=   9%I7 .JJJ8J!AJ 7JJ	J)(J)c                   . ddl m}m}m}m} ddlm}  j                  sy j                  dk(  ry|j                  di       }t        |j                  dd            }t        |j                  d	d
            }t        |j                  dd            }	t        |j                  dd            }
|j                  dd      }g }d}d} j                  D ]  }|j                  dd      }|j                  d      }|j                  d      xs g }|dk(  rB|dk(  rH|dk(  r|dn
t        |      }t        |t              rg }|D ]  }t        |t              r6|j                  d      dk(  r"|j                  |j                  dd             It        |t              sZ|j                  d      dk(  so|j                  d        dj!                  |      } ||      }t#        |      |kD  r|d| dz   }|j                  d|f       6|dk(  s=|dn
t        |      } | ||            }g }g }|rm|j                  |       |j%                         }t#        |      |
kD  rdj!                  |d|
       d z   }t#        |      |	kD  r|d|	 dz   }|j                  |       |rt#        |      }g }|D ]N  }|j                  d!i       }t        |t              r|j                  d"d#      nd#}||vs>|j                  |       P d$j!                  |dd%       }t#        |      d%kD  r|d&z  }|d'k(  rd(nd)}d*| d+| d,| d-}|j                  |       |j                  |       |st'        |      } |r| s|r|j                  ddj!                  |      f       t#        |      d'z
  }dj!                  |      } |syd}!t#        |      |d.z  kD  rt#        |      |d.z  z
  }!||!d }|%|r#||!z
  }"d|"cxk  rt#        |      k  r
n nd/|f||"<   dd0lm}# dd1lm}$ 	 dd2lm}%  |%       }&|&j5                  d3d4      }'|&j5                  d5d6      }(|&j5                  d7d8      })|&j5                  d9d:      }* |$       }|!r|j                  d;|! d<d=>       t9        |      D ]Y  \  }+\  }}|dk(  ra|j                  d?d@|( >       |j%                         },|j                  |,d   dz   dA>       |,d'd D ]  }-|j                  dB|- ddA>        n|d/k(  ra|j                  dCdD|* >       |j%                         },|j                  |,d   dz   d>       |,d'd D ]  }-|j                  dE|- dd>        n`|j                  dCd@|* >       |j%                         },|j                  |,d   dz   dA>       |,d'd D ]  }-|j                  dE|- ddA>        |+t#        |      d'z
  k  sI|j                  d       \  |#|dF|( dGdH|) dI|'J      . |. fdK        |       5   j;                  .       ddd       y# t6        $ r d4}'d6}(d8})d:}*Y w xY w# 1 sw Y   yxY w)LaP  Render a compact recap of previous conversation messages.

        Uses Rich markup with dim/muted styling so the recap is visually
        distinct from the active conversation.  Caps the display at the
        last ``MAX_DISPLAY_EXCHANGES`` user/assistant exchanges and shows
        an indicator for earlier hidden messages.
        r   )
CLI_CONFIG_record_output_history_entry_strip_reasoning_tags_suspend_output_history)sanitize_display_textNminimaldisplayresume_exchanges
   resume_max_user_charsi,  resume_max_assistant_chars   resume_max_assistant_lines   resume_skip_tool_onlyTrv   r   content
tool_callssystemtoolrx   typetext	image_urlz[image] z...	assistant
z ...functionr   unknownr      z, ...r~   callcallsr   z tool z: r      assistant_last)Panel)Text)get_active_skinbanner_textz#FFF8DCsession_labelz#DAA520session_borderz#8B8682ui_okz#8FBC8Fz  ... z earlier messages ...

z
dim italic)styleu     ● You: z	dim bold dimz	         u     ◆ Hermes: zbold z            z[dim z]Previous Conversation[/]zdim )r   r~   )ry   border_stylepaddingr  c                 &    j                         S )N)"_render_resume_history_panel_lines)panelr=   s   rV   <lambda>z=CLIAgentSetupMixin._display_resumed_history.<locals>.<lambda>  s    T-T-TUZ-[     )r!   r   r   r   r   tools.ansi_stripr   r   resume_displayr+   intr2   r(   r*   dictappendjoinr   
splitlinesbool
rich.panelr  	rich.textr  hermes_cli.skin_enginer  	get_colorr&   	enumerater   )/r=   r   r   r   r   _sanitize_display_text_dispMAX_DISPLAY_EXCHANGESMAX_USER_LENMAX_ASST_LENMAX_ASST_LINESSKIP_TOOL_ONLYentries_last_asst_idx_last_asst_fullmsgrv   r   r  r  partspart
full_partslinestc_countnamestcfnr   	names_strnoun
tc_summaryhas_textskippedadj_idxr  r  r  _skin_history_text_c_session_label_c_session_border_c_assistant_label_ci	msg_linesmlr  s/   `                                             @rV   _display_resumed_historyz+CLIAgentSetupMixin._display_resumed_history  s    	qpT(( )+ y"- #EII.@"$E F599%<cBC599%A3GHUYY'CQGH#:DA ,, D	7C7762&Dggi(G.4"Jxv~v~$_r#g,gt,E ' 4%dD1dhhv6F&6P!LL&")=>'d38HK8W!LL3	4
 88E?D
 .d3t9|+.6D~.$$_r#g,-.CD.IJ
%%d+ OO-E5zN2#yy)?@6I4y</#M\2U:LL&":HE( /VVJ3<Fr4<Prvvfi8V_u,!LL.	/
 !%		%) 4I5zA~!W,	%-]6D#$XJfTF"YKq!IJLL,%%j1:!(zSXXe_=>!$W!1"%((:"6ID	7L  w</!33'l%:Q%>>Ggh'G %/$w.GG*c'l*$4o#F  	%"	+>#%E#oomYGO$	J %0@) L!&)!D LL	!:;"  
  )1 	!OA|dv~]I>N=O2PQ OO-	Yq\D0>#AB- BBLL9RD!35LAB))-u=O<P5QR OO-	Yq\D0;#AB- BBLL<t2!6bLAB -yAS@T5UV OO-	Yq\D0>#AB- EBLL<t2!6eLDE3w<!##R -	!0 *++DE 123!
 	%%[\$& 	'&	' 	'[  	+'O( )!*		+Z	' 	's   AX;  Y;YYY)returnr(  )r`   r2   rP  r$  )rd   r2   re   r$  r]   zdict | NonerP  r(  )	__name__
__module____qualname____doc__rW   rc   r   r   rO  r    r   rV   r   r      s1    P[z*X 48RVy} cJObl'r   r   )rT  
__future__r   r   rich.markupr   r   r   r    r   rV   <module>rW     s!    # 
 )n
' n
'r   