
    sj                    P    d Z ddlmZ ddlZddlmZ ddlmZ  G d d          Z	dS )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)escape)base_url_host_matchesc                  \    e Zd ZdZddZddZddZdd
ZddddddZdddZ	ddZ
d ZdS )CLIAgentSetupMixinzFAgent construction + session-resume display methods for ``HermesCLI``.returnboolc                	   ddl m}m}m} ddlm}m} d}d}	  || j        | j        | j	                  }n# t          $ r}|}Y d}~nd}~ww xY w|:|7ddlm}	 t          ||	          r t          | j        t                    r| j        ng }
|
D ]}|                    d          pd                                                                }|                    d	          pd                                }|r|sk	 dd
lm} d|i}|                    d          r|d         |d<    ||          }|r||d<    |d*i |}|                    d|||            |d| d|            || _        || _        d} n# t          $ r Y w xY w|2|r ||          nd} |                                d| d           dS |                    d          }|                    d          }|                    dd          }|                    d| j                  }|                    d          }t          |                    d          pg           }|                    d          }t3          |          ot          |t4                     }|st          |t4                    r|s|                    dd          }t          |t4                    o|ot7          |d           }|rd}|                    d||           nY|p| j        pd                                }|r|d k    rt/          d!| d"           nt/          d#           t/          d$           dS t          |t4                    r|st/          d%           dS || j        k    p
|| j        k    }|| j        k    p || j        k    p|| j         k    p
|| j!        k    }|| _        || _        || _         || _!        || _"        |                    d          | _#        || _        || _        |                    d	          }|rTt          |t4                    r?| j         p-| j        | j        k    p| j        |                    d&          k    } | r|| _        | j        sE|rC	 dd'l$m%}!  |!|          }"|"r|"| _        |&                    d(|"|           n# t          $ r Y nw xY w| '                    |          }#|s|s|#r| j(        d| _(        d| _)        d)S )+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sourceopenrouter.aizno-key-requireduh   No API key for custom endpoint %s (source=%s), using placeholder — local servers typically ignore authautou(   
⚠️  No API key found for provider 'z'.u-   
⚠️  No inference provider is configured.zS   Run 'hermes model' to choose a provider, or 'hermes setup' for first-time setup.uf   
⚠️  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strr   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_provcredentials_changedrouting_changedruntime_modelshould_use_runtime_modelr%   _defaultmodel_changeds$                                       D/home/agent/.hermes/hermes-agent/hermes_cli/cli_agent_setup_mixin.py_ensure_runtime_credentialsz.CLIAgentSetupMixin._ensure_runtime_credentials   s    	5444444444	
 	
 	
 	
 	
 	
 	
 	

 	..1!%!7"&"9  GG
  	 	 	LLLLLL	 ?|7111111,	22 !4>t?SUY4Z4ZbD00`b	$ ! !C$'GGJ$7$7$=2#D#D#F#F#L#L#N#NL!$!1!1!7R > > @ @I' !y ! !TTTTTT&1<%@
77:.. N>A*oJ':;&;&;C&@&@& I=HJ'9:":":"H"HZ"H"Hc(,	     vZf v vkt v vwww2>/%.
'+$ ! ! ! ! ?EQt33LAAAWtGKMM 9W 9 9 9:::5++i((;;z**#KK
LAA#KK
DMBB&{{955 V!4!4!:;;#*;;/@#A#A  !) 1 1 R*Wc:R:R6R$ 	j#.F.F 	g 	
 kk(B//G8S)) II-hHHH 
   +Pg    +Kd.EKRRTT LUf__OeOOOPPPPJKKK = > > >u(C(( 	 	 D E E E5%5RT]9R. 2 DM12#t'772 !DM1	 	 *)/) 8 'H 5 5   G,, 	+Zs;; 	+ J 2
dm+2
gkk&111 %
 ( +*

 z 	/ 	
LLLLLL99:KLL !)DJKKR "3      
 ::;LMM   	6? 	6m 	6I_DJ15D.ts:   6 
A AA=A=E<<
F	F	1R6 6
SSc                   ddl m} 	  || j        | j        | j                  }n# t
          $ r Y dS w xY wt          |t                    sdS |                    d          }|                    d          }t          |          r$t          |t                    st          |          S t          |t                    r|rt          |          S t          t          |t                    o|ot          |d                     S )u  Silently probe whether any inference provider can be resolved.

        Unlike ``_ensure_runtime_credentials`` this never prints and never
        mutates CLI state — it exists so the interactive first-run path can
        detect a completely unconfigured install *before* the user types a
        message into a chat that cannot work (#62935-adjacent UX class:
        keyless first run must route into onboarding, not a broken chat).
        r   )r   r   Fr   r   r"   )r(   r   r)   r*   r+   r,   r.   dictr1   r7   r8   r	   r   )rC   r   rE   r   r   s        r]   _runtime_credentials_readyz-CLIAgentSetupMixin._runtime_credentials_ready   s4    	IHHHHH	..1!%!7"&"9  GG
  	 	 	55	'4(( 	5++i((;;z**G 	"Z%=%= 	">>!gs## 	" 	">>!x%% EE)(ODDD
 
 	
s   & 
44c                   ddl m}m}  |d            |d            |d           	 t          d                                                                          }n'# t          t          f$ r t                       d}Y nw xY w|dv r |d	           d
S 	 ddl	m
}  |             ny# t          t          t          f$ r t                        |d           Y d
S t          $ r:}|                    d|            |d|             |d           Y d}~d
S d}~ww xY w	 ddlm}  |                                d          pi }t#          |t$                    ry|                    d          pd                                }|r|| _        |                    d          p|                    d          pd                                }	|	r|	| _        n-# t          $ r }|                    d|           Y d}~nd}~ww xY wd| _        d| _        |                                 r |d           dS  |d           d
S )a  Offer the provider picker when no provider is configured at all.

        Called from the interactive startup path when
        ``_runtime_credentials_ready()`` is False and stdin is a TTY. Runs the
        exact same flow as ``hermes model`` (which fronts Quick Setup / Nous
        Portal OAuth as the first, recommended option) so there is a single
        source of truth for provider onboarding. Returns True when a provider
        was configured.
        r   )r   r   r   u?   ⚕ No inference provider is configured yet — let's fix that.z[  You'll pick a provider (Nous Portal OAuth is the fastest; no API key needed) and a model.z   Set up a provider now? [Y/n]: n>   rc   noz9  Skipped. Run 'hermes model' or 'hermes setup' any time.F)select_provider_and_modelz/  Setup cancelled. Run 'hermes model' any time.z#first-run provider setup failed: %su!     ⚠️  Provider setup failed: z"  Run 'hermes model' to try again.N)load_configr   r   defaultz#first-run config re-sync failed: %su3     ✓ Provider configured — you're ready to chat.Tz>  Provider setup didn't complete. Run 'hermes model' to retry.)r'   r   r   inputr2   r3   KeyboardInterruptEOFErrorr6   hermes_cli.mainre   
SystemExitr,   r9   hermes_cli.configrf   r1   r.   r`   r)   r   rA   rB   ra   )
rC   r   r   answerre   rF   rf   
_model_cfg_new_provider
_new_models
             r]   _offer_first_run_setupz)CLIAgentSetupMixin._offer_first_run_setup   s    	('''''''QRRR 2 	3 	3 	3	=>>DDFFLLNNFF!8, 	 	 	GGGFFF	 [  GOPPP5	AAAAAA%%''''!8Z8 	 	 	GGGGEFFF55 	 	 	LL>DDDG===>>>G899955555			E555555%+--++G44:J*d++ ,!+
!;!;!Ar H H J J  <.;D+NN9--N1H1HNB%''   ,!+DJ 	E 	E 	ELL>DDDDDDDD	E 
-1***,, 	GIJJJ4PQQQusH   3A !BBB) )0D	D%/DD#B3G 
H!G<<Huser_messager8   r`   c                   ddl m} | j        | j        | j        t          | d| j                  | j        | j        t          | j	        pg           t          | dd          d}| j
        || j
        |d         |d         |d         |d	         |d
         t          |d                   fd}t          | dd          }|sd|d<   |S 	  ||d                   }n# t          $ r d}Y nw xY w||d<   |S )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_overridesr)   r<   Nr   r   r   r)   r   r   r   r    r   r   r   r   r   )r   rE   	signatureservice_tierrequest_overridesr   )r>   ru   r   r   r   getattrr   r:   r0   r;   r   tupler,   )rC   rs   ru   rE   routerx   	overridess          r]   _resolve_turn_agent_configz-CLIAgentSetupMixin._resolve_turn_agent_config#  sL    	BAAAAA |")*DM# # ',"--&t-?FF
 
 Z

#,-
#
#	"gfo&&
 
 t^T:: 	)-E%&L	33E'NCCII 	 	 	III	%.!"s   C C&%C&N)model_overrideruntime_overridery   r   r   ry   dict | Nonec                  ddl m}m}m}m}m}m}	m}
m} | j	        dS | 
                                  |
             |                                  |                                  |                                 sdS ddlm}  ||t!          | dd                     | j        D	 dd	lm}  |            | _        n-# t(          $ r }|                    d
|           Y d}~nd}~ww xY w| j        r| j        r| j        s| j                            | j                  }t!          | dd          dk    }|sh|r?t5          d| j         t6          j                   t5          dt6          j                   n% |	d| j         |             |	| d|            dS 	 | j                            | j                  }n# t(          $ r
 | j        }Y nw xY w|rx|| j        k    rm |                                dt=          | j                   dt=          |           d           || _        | j                            | j                  }|r|}t!          | dd          }|rdS |                     d          }|rW|| _         |rt5          d| t6          j                   n- |                                dt=          |                      dS | j        !                    | j        d          }|rSd |D             }|| _        tE          d |D                       }d}|#                    d          rd|d          d}|rEt5          d | j         | d!| d"|d#k    rd$nd d%tE          |           d&
t6          j                   nw |                                d' |             d(t=          | j                   d) |             d*t=          |           d+| d"|d#k    rd$nd d%tE          |           d&           | $                    ||,           | %                    ||,           | &                    ||,           ne|r%t5          d-| j         d.t6          j                   n> |                                d' |             d/t=          | j                   d0           	 | j        '                    | j                   n# t(          $ r Y nw xY w	 |pZ| j(        | j)        | j*        t!          | d1| j*                  | j+        | j,        t[          | j.        pg           t!          | d2d          d3}|p| j/        } |dji d4|d5|#                    d5          d6|#                    d6          d7|#                    d7          d1|#                    d1          d8|#                    d8          d9|#                    d:          d;|#                    d<          d=|#                    d=          d>| j0        d?| j1        d@t!          | d@d          dA| j2        dB| j3        dC| j4        dD| j4         dt!          | ddE          dF| j5        r| j5        nddG| j6        pddH| j7        dI| j8        dJ|dK| j9        dL| j:        dM| j;        dN| j<        dO| j=        dP| j>        dQ| j?        dR| j        dSdTdU| j        dV| j@        dW| A                                dX| jB        dY| jC        dZ| jD        d[| jE        d\| jF        d]| jG        d^| jH        d_| jI        d`| jI        da| jJ        db| jK        r| jL        nddc| jK        r| jM        nddd| jN        r| jO        ndde| jN        r| jP        nddf| jQ        dg| jR        dh| jS        | _	        ddl }| j	        |_T        |	| j	        _U        	 ddilVmW}  || j	                   n# t(          $ r Y nw xY w||#                    d7          |#                    d1          |#                    d6          |#                    d8          |#                    d:          t          |#                    d<          pdj          f| _Y        | jZ        r| j        r| j	        r	 | j	        [                                 | j	        j\        r?| j        ]                    | j        | jZ                    |	dk| jZ                    d| _Z        n,# t          t(          f$ r} |	dl|            Y d}~nd}~ww xY wdS # t(          $ rW} |            }|                    dm| dn           ddol_m`}  ||          D ]}|                    |           Y d}~dS d}~ww xY w)pz
        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)'ensure_mcp_discovery_before_agent_build_single_query_mode)r   single_query)	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]_resume_history_error)tip_onlyzCannot resume session: $[bold red]Cannot resume session:[/] )repair_alternationc                D    g | ]}|                     d           dk    |S rolesession_metar1   .0ms     r]   
<listcomp>z2CLIAgentSetupMixin._init_agent.<locals>.<listcomp>  s,    SSS!155==N3R3RA3R3R3R    c                D    g | ]}|                     d           dk    |S )r   userr   r   s     r]   r   z2CLIAgentSetupMixin._init_agent.<locals>.<listcomp>  s,     P P Pqf8O8O8O8O8Or   r   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.[/]r)   r<   rv   r   r   r   r   r   r:   r   r;   r   r    
max_tokensmax_iterationsrun_budget_secondsenabled_toolsetsdisabled_toolsetsverbose_logging
quiet_modeallephemeral_system_promptprefill_messagesreasoning_configrx   ry   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   )partial_update_hint)ar'   r   r   r   r   r   r   r   r   rA   finalize_preloaded_skills_install_tool_callbacks_ensure_tirith_securityr^   hermes_cli.mcp_startupr   rz   _session_dbhermes_stater   r,   r5   _resumedconversation_historyget_sessionr   r6   sysstderrresolve_resume_session_id_escape_resume_history_limit_errorr   get_messages_as_conversationlenr1   _restore_session_cwd_restore_session_yolo_restore_session_modelreopen_sessionr   r   r   r   r:   r0   r;   r   r   	max_turnsr   r   verbosesystem_promptr   r   rx   _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{   rB   _pending_title_ensure_db_session_session_db_createdset_session_title
ValueErrorhermes_constantsr   )rC   r   r   ry   r   r   r   r   r   r   r   r   r   r   er   _quiet_moderesolved_idresolved_metaprior_resume_errorresume_limit_errorrestored	msg_count
title_partrE   effective_model_clir   consoler   lines                                  r]   _init_agentzCLIAgentSetupMixin._init_agentS  s    	xwwwwwwwwwwwwwwwwwww:!4
 	&&((('')))$$&&&$$&&&//11 	5RRRRRR// ';UCC	
 	
 	
 	
 #l222222#,9;;   l l lgijkkkkkkkkl = ]	T- ]	d6O ]	+77HHL "$(<fEENK 
 mAAA
SSSSZ Z    
 GSDOSTSSTTTGtkkeikklllu.".HHYY . . ."o. 	1{do==##)GDO$<$< ) ){++) ) )  
 #. $ 0 < <T_ M M  1#0L!(/F!M!M! u "&!A!A4!A!P!P! -?* H4FHHszZZZZZKMM''\wGY?Z?Z\\   u'DDD E  H  !SSxSSS,4) P PH P P PQQ	
##G,, A!@|G'<!@!@!@J ;t ;
 ; ;%; ;;D>>CCr; ;x==; ; ; !Z	      KMM''u u u!(!9!9u u!,u u181D1Du u &u u <E>>CCru u VYYaUbUbu u u   )),k)JJJ**<{*KKK++L+LLLL _4?___ Z    
  KMM'' B  B  B9Q9Q  B  B  B   //@@@@   z	& < M M&-.' ' !M+T]0b11#*41CT#J#J+ +G -:
O  5 5 5%o5I...5 !Z0005 !Z000	5
 $+;;/C#D#D#D5 !Z0005 $KK	2225 !V,,,5 !(,= > > >5  ??5  $~~5 $+41Et#L#L#L5 "&!6!65 #'"8"85 !%5   $|++!5" $+41Eu#M#M#M#5$ ?C>P(Z(:(:VZ%5& "&!6!>$'5( "&!6!6)5* "..+5, #4"3-5. #'"6"6/50 #'"8"8152 !% 5 5354 #11556 -1,I,I758 *.)G)G95: -1,M,M;5<  ??=5> ?5@  ++A5B "&!7!7C5D $(#C#C#E#E#EE5H  $33I5J #'"3"3K5L %)$<$<M5N *.)F)FO5P .2-N-NQ5R -1,L,LS5T !% 4 4U5V $(#4#4W5X !--Y5Z (,'='=[5\ <@;U$_D$7$7[_]5^ BFA['et'='=ae_5` =A<R&\d&8&8X\a5b >B=S"]$"9"9Y]c5d !%e5f '+&;&;g5h #'"3"3i5DJ~ %)ZD" $+DJ 
OOOOOO--dj9999     J''011J''J''I&&gkk&))/R002D. " 	Et'7 	EDJ 	EEJ11333z5 3(::4?DL_``` QD<O Q QRRR.2+"I. E E EGCCCDDDDDDDDE 4 	 	 	!kmmGMMI1IIIJJJ<<<<<<++A.. $ $d####55555	s   $B: :
C$CC$F> >GG0S 
SS!Kd 9_ d 
_d _B'd A$c* )d *d;d	d dd 
e9"Ae44e9Fr   c                (   | j         sdS ddlm}m}m} 	 |rnt          | j         dd          }t          |          sdS  |            }|dk    rdS 	  || j        |           nX# |$ r} ||j        |d          |d}~ww xY wt          | j         dd          }t          |          sdS  || j                   nU# |$ r}t          |          cY d}~S d}~wt          $ r,}t                              d	| j        |           Y d}~dS d}~ww xY wdS )
u  Return a safe-resume error without materializing transcript rows.

        ``tip_only`` matches call sites that load only the tip session's rows
        (``get_messages_as_conversation`` without ancestors) — counting the
        full lineage there would over-reject heavily-compressed sessions
        whose tip is small. Generic guard failures fail OPEN (resume
        proceeds) — only a genuine over-limit result blocks.
        Nr   )SessionExportTooLargeErrorSessionResumeTooLargeErrorresolved_max_resume_messagesassert_export_safe)max_messageszin its tip segment)scopeassert_resume_safez@Resume safety check failed for %s (proceeding without guard): %s)r   r   r  r  r  rz   r7   r   message_countr8   r,   r   r5   )	rC   r   r  r  r  	tip_checklimitrF   safety_checks	            r]   r   z.CLIAgentSetupMixin._resume_history_limit_errorY  s     	4	
 	
 	
 	
 	
 	
 	
 	
 	
 	
	 .#D$46JDQQ		**  44466A::4IdoEBBBBB1   44)58L  
  't'79MtTT--  4T_---) 	 	 	s88OOOOOO 	 	 	NNR   44444	 tsX   'B= B= A$ #B= $B)A==B(B= ,B= =DCDD#!D

Dc                h   ddl m} | j        r| j        sdS | j                            | j                  }|s5|                     d| j         d           |                     d           dS 	 | j                            | j                  }n# t          $ r
 | j        }Y nw xY w|rV|| j        k    rK|                     d| j         d| d	           || _        | j                            | j                  }|r|}| 	                                }|r!|| _
        |                     d
|            dS | j                            | j                  \  }}|}|rd |D             }|| _        d |D             | _        ddlm t!          fd| j        D                       }	d}
|                    d          rd|d          d}
 |            }|                     d| d| j         d|
 d|	 d|	dk    rdnd dt!          |           d           |                     |           |                     |           |                     |           n- |            }|                     d| d| j         d           dS 	 | j                            | j                   n# t          $ r Y nw xY wdS )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   )r   Fz[bold red]Session not found: r   zH[dim]Use a session ID from a previous CLI run (hermes sessions list).[/]r   r   z2; resuming the descendant with your transcript.[/]r   c                D    g | ]}|                     d           dk    |S r   r   r   s     r]   r   z?CLIAgentSetupMixin._preload_resumed_session.<locals>.<listcomp>  s,    OOOaquuV}}/N/N/N/N/Nr   c                D    g | ]}|                     d           dk    |S r   r   r   s     r]   r   z?CLIAgentSetupMixin._preload_resumed_session.<locals>.<listcomp>  s3     , , ,aeeFmm~.M.M.M.M.Mr   )is_user_originated_turnc                *    g | ]} |          |S r&   r&   )r   r   r*  s     r]   r   z?CLIAgentSetupMixin._preload_resumed_session.<locals>.<listcomp>  s:       ..q11  r   r   r   r   r   [u   ]↻ Resumed session [bold]z[/bold]r   r   r   r   r   z total messages)[/]r   r   T)r'   r   r   r   r   r   _console_printr   r,   r   r   get_resume_conversationsr   _resume_display_historyagent.context_compressorr*  r   r1   r   r   r   r   )rC   r   r   r  r  r  model_historydisplay_historyr  r  r  accent_colorr*  s               @r]   _preload_resumed_sessionz+CLIAgentSetupMixin._preload_resumed_session  s    	$#####} 	D$4 	5'33DODD 	DDDD   -   5	**DDT_UUKK 	* 	* 	*/KKK	* 	-;$/99S S SS S S   *DO ,88IIM -,!==?? 	);D&K7IKK   5)-)9)R)RSWSb)c)c&  $	OO8OOOH(0D%, ,*, , ,D( IHHHHH    !9   I J(( ;:,w"7:::
&;==L6L 6 6T_ 6 66 66 63<>>CCr6 6 x==6 6 6   %%l333&&|444''5555&;==L0L 0 04? 0 0 0   5	++DO<<<< 	 	 	D	 ts$   /B B#"B#J" "
J/.J/c                   0 ddl m}m}m}m} ddlm} t           d j                  }|sdS  j	        dk    rdS |
                    di           }t          |
                    dd	                    }t          |
                    d
d                    }	t          |
                    dd                    }
t          |
                    dd                    }|
                    dd          }g }d}d}|D ]}|
                    dd          }|
                    d          }|
                    d          }|
                    d          pg }|dk    ra|dk    r|                    d           }|dk    r|                    d           |dk    r|                    d           |dk    r|dk    r|d k    r#|dnt          |          }t          |t                    rg }|D ]}t          |t                     rC|
                    d!          d"k    r*|                    |
                    d"d                     Zt          |t                     r.|
                    d!          d#k    r|                    d$           d%                    |          } ||          }t%          |          |	k    r|d|	         d&z   }|                    d |f           |d'k    r|dnt          |          } | ||                    }g }g }|r|                    |           |                                }t%          |          |k    r d(                    |d|                   d)z   }t%          |          |
k    r|d|
         d&z   }|                    |           |rt%          |          }g }|D ]^}|
                    d*i           }t          |t                     r|
                    d+d,          nd,}||vr|                    |           _d-                    |dd.                   }t%          |          d.k    r|d/z  }|d0k    rd1nd2} d3| d4|  d5| d6}!|                    |!           |                    |!           |st)          |          }"|r|"s|r|                    d'd%                    |          f           t%          |          d0z
  }d%                    |          }	|sdS d}#t%          |          |d7z  k    rt%          |          |d7z  z
  }#||#d         }|+|r)||#z
  }$d|$cxk    rt%          |          k     r
n nd8|f||$<   dd9lm}% dd:lm}& 	 dd;lm}'  |'            }(|(                    d<d=          })|(                    d>d?          }*|(                    d@dA          }+|(                    dBdC          },n# t8          $ r d=})d?}*dA}+dC},Y nw xY w |&            }|#r|                    dD|# dEdFG           t;          |          D ]\  }-\  }}|dHk    r|                    dI| d(dFG           np|d k    rw|                    dJdK|* G           |                                }.|                    |.d         d(z   dLG           |.d0d         D ]}/|                    dM|/ d(dLG           n|d8k    rw|                    dNdO|, G           |                                }.|                    |.d         d(z   dG           |.d0d         D ]}/|                    dP|/ d(dG           nv|                    dNdK|, G           |                                }.|                    |.d         d(z   dLG           |.d0d         D ]}/|                    dP|/ d(dLG           |-t%          |          d0z
  k     r|                    d            |%|dQ|* dRdS|+ dT|)U          0 |0 fdV            |            5                       0           ddd           dS # 1 swxY w Y   dS )WaP  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_textr/  Nminimaldisplayresume_exchanges
   resume_max_user_charsi,  resume_max_assistant_chars   resume_max_assistant_lines   resume_skip_tool_onlyTr   r   display_kindcontent
tool_callshiddenmodel_switch)eventzmodel changedasync_delegation_complete)rJ  zbackground delegation completedauto_continue)rJ  zresumed interrupted turnsystemtoolr   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)stylerJ  u     ◈ u     ● You: z	dim bold dimz	         u     ◆ Hermes: zbold z            z[dim z]Previous Conversation[/]zdim )r   r   )r   border_stylepaddingrc  c                 .                                    S )N)"_render_resume_history_panel_lines)panelrC   s   r]   <lambda>z=CLIAgentSetupMixin._display_resumed_history.<locals>.<lambda>  s    T-T-TUZ-[-[ r   )r'   r6  r7  r8  r9  tools.ansi_stripr:  rz   r   resume_displayr1   intappendr8   r.   r0   r`   joinr   
splitlinesr	   
rich.panelr\  	rich.textr]  hermes_cli.skin_enginer^  	get_colorr,   	enumerater-  )1rC   r6  r7  r8  r9  _sanitize_display_textr2  _dispMAX_DISPLAY_EXCHANGESMAX_USER_LENMAX_ASST_LENMAX_ASST_LINESSKIP_TOOL_ONLYentries_last_asst_idx_last_asst_fullmsgr   rE  rF  rG  rP  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mlri  s1   `                                               @r]   _display_resumed_historyz+CLIAgentSetupMixin._display_resumed_history  sR
    	qpppppppppppTTTTTT!$(A4C\]] 	F )++F y"-- #EII.@"$E$E F F599%<cBBCC599%A3GGHHUYY'CQGGHH#:DAA " Q	7 Q	7C7762&&D77>22Lggi((G..4"Jx''~--9::::::KLLL..DEEExv~~v~~$_rr#g,,gt,, +E ' 4 4%dD11 4dhhv6F6F&6P6P!LL&")=)=>>>>'d33 48H8HK8W8W!LL33388E??D
 .-d33t99|++.6D~....$$$_rr#g,,--.C.CD.I.IJJ
 '%%d+++ OO--E5zzN22#yy)?@@6I4yy<//#M\M2U:LL&&& 2":HE( / /VVJ33<Fr4<P<P_rvvfi888V_u,,!LL... $		%) 4 4I5zzA~~!W,	%-]]66D!IX!I!IT!I!IY!I!I!IJLL,,,%%j111 ::! ( z SXXe__=>>>!$W!1"%((:"6"6 	F w<</!333'll%:Q%>>Gghh'G %/%$w.GG****c'll*****$4o#F  	%$$$$$""""""	+>>>>>>#O%%E#oomYGGO$	JJ %0@) L L!&)!D!D 	+ 	+ 	+'O( )!*		+  	LL;;;;"    
  )11 	! 	!OA|dw.d...lCCCC]2P>N2P2PQQQ OO--	Yq\D0>>>#ABB- B BBLL!3R!3!3!35LAAAAB)))-5Q=O5Q5QRRR OO--	Yq\D0;;;#ABB- B BBLL!6!6!6!6bLAAAAB -5UAS5U5UVVV OO--	Yq\D0>>>#ABB- E EBLL!6!6!6!6eLDDDD3w<<!###R   E*EEE3 133!
 
 
 	%$%[%[%[%[%[\\\$$&& 	' 	'&&&	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's%   :A(W# #W87W8*aaa)r   r	   )rs   r8   r   r`   )r   r8   r   r`   ry   r   r   r	   )F)r   r	   )__name__
__module____qualname____doc__r^   ra   rr   r~   r  r   r4  r  r&   r   r]   r   r      s        PPd d d dL 
  
  
  
D> > > >@. . . .` 48RVy} D D D D D DL, , , , ,\` ` ` `D|' |' |' |' |'r   r   )
r  
__future__r   r   rich.markupr   r   utilsr   r   r&   r   r]   <module>r     s     # " " " " " 



 ) ) ) ) ) ) ' ' ' ' ' 'M' M' M' M' M' M' M' M' M' M'r   