
    |+j                    V+   U d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZ d dlmZmZ d dlmZmZmZmZ d dlmZ d dlmZ d dlm Z m!Z!m"Z"m#Z#m$Z$  ej%        e&          Z' e            Z( ee( ee)          j*        j*        d	z  
           e	j+        ,                    e(dd          Z-d Z.e.e_/        d Z0e0e_/        	 d dl1m2Z2  e2             n# e3$ r Y nw xY wd dl4m5Z5m6Z6m7Z7 i Z8e9e:e9f         e;d<   i Z<e9e:e=f         e;d<   i Z>e9e:e?e:ej@        f         f         e;d<   i ZAe9e:e?e:e9f         f         e;d<   i ZBe9e:e:f         e;d<   daCdaDe:dz  e;d<    ejE                    ZF ejE                    ZG ejH                    ZI ejE                    ZJdaKe9dz  e;d<   daLeMdz  e;d<   daN ejE                    ZO	  eMe	jP        Q                    d          pd          ZRn# eSeTf$ r dZRY nw xY w eUdeR          ZV	  eMe	jP        Q                    d          pd          ZWn# eSeTf$ r dZWY nw xY w eUd eW          ZXd!ZY eZh d"          Z[ eZh d#          Z\	  eUd$ e]e	jP        Q                    d%          pd&                    Z^n# eSeTf$ r d'Z^Y nw xY wej_        `                    e^d()          Za e jb        d*            ejc        Zdeje        e_c         G d+ d,          Zf e d- eF          Zg ef            Zh G d. d/          Zid0e:fd1Zjd2e:d3e:dz  d0dfd4Zkd5d6d7e:d8e:d9e:d0e?ee:dz  f         fd:Zld;e9dz  d0dfd<Zmdd;e9dz  d>e:d0dfd?Znd=d@d;e9dz  d>e:d0dfdAZodBe:d;e9d0dfdCZpd=d@dBe:d>e:d0eqfdDZrd;e9dz  d0eqfdEZsdBe:d0dfdFZtdGd@d>e:d0e?e]e]f         fdHZuddIZv	  eMe	jP        Q                    dJ          pdK          Zwn# eTeSf$ r  eMdK          ZwY nw xY w eUd ew          ZwdLZxd0eqfdMZydBe:d;e9dNeMd0eqfdOZzddPZ{ddQZ| e jb        ev            e|             dR Z}dSe]fdTZ~dUe:dz  d0edz  fdVZh dWZdXedz  d0e:dz  fdYZdZe9d0eqfd[Zd d\e:dBe:d]e9dz  fd^Zd dBe:d_e:d`e:dz  fdaZdbe]dce]d0e]fddZdeed0e9fdfZdge9d0e9fdhZdSe]die:d0e9fdjZdke:fdlZdmed0e?ee:e9f         e9z  fdnZdme9d0e9dz  fdoZd dme9dpee!         d0e9dz  fdqZd!d;e9dse:dteMd0e9dz  fduZdBe:d;e9d0dfdvZdw Zdx Zdye:d0e:fdzZd d{e9dz  d0e:fd|Zd;e9dz  d0e:fd}Zd~e:d0e:fdZd;e9dz  d0e:fdZd;e9dz  d0dfdZd;e9d0dfdZej        d;e9fd            Zd;e9d~e:d0e:fdZdZe?e:df         e;d<   dZd0e9fdZde9fdZd7e:d0e:fdZd d7e:d~e:dz  d0efdZded0dfdZddZd"d\e:dBe:d]e9dte]d0e:f
dZd dBe:dz  d0dfdZd0e9fdZd0e:fdZd0e?e:e:dz  f         fdZde9dz  d0e9fdZd de9dz  d0e9fdZd;e9dz  d0dfdZde:fdZ eZh d          Zd0e:fdZi ddddddddddddddddddddddddddddddddZde9d0e:fdZd0e9dz  fdZd0e:dz  fdZd0eqfdZd0e:fdZd0ee:         dz  fdZdBe:d0e:fdZdBe:d0eqfdZdBe:d0eqfdZdBe:d;e9fdZddZdddBe:d;e9de:deqd0e9f
dZ	 	 	 	 d#d;e9de:dz  de]dz  dedz  de]dz  d0e?e]e9f         fdńZdddǜdBe:d;e9deqdeqd0df
dʄZd0e9fd˄Zd0e:fd̄Zde9d0e:fd̈́Zd0e:fd΄Zd$Zd d;e9dz  d0e9fdτZdke:de9d0e:fdфZdZdZd`e:d0e:fdԄZd`e:d0e:fdՄZde9d0e:fdքZdged0e:fdׄZdeMdz  d0e:fdلZdZedee:d0e]dz  fdڄZdke:dge:deMdz  d0e:dz  fd܄ZdBe:de:dke:de9fdބZdBe:de:dke:de9dge:f
d߄Z	 	 	 d$dBe:d2e:dke:dz  de:dz  de9dz  f
dZdBe:d0e9fdZdBe:fdZd0e:fdZԐd de9dz  d0e9fdZՐd de:de9dz  d0e?e:e:f         fdZd0e:fdZ	 d%dBe:d;e9de:de:d0e?eqe9dz  f         f
dZde9de]d0e]fdZd0ee:         fdZd Zd Zde:d0e9fdZde:d0e9fdZސd&d;e9de]de]d0ee9         fdZdke:dge:d0e:fdZde:de:d0e9fdZdBe:d;e9d0e9fdZ	 	 	 	 	 	 d'dBe:de:d3e:dz  d e9e:z  dz  de:dz  de9dz  de:dz  fdZd(dBe:de:dede]fdZd0e:fd	Zd
 Zd~e:de:d0e:fdZde:dee:         d0e:fdZded0e:fdZded0e:fdZdee9         d0ee9         fdZded0ee9         fdZded0e:fdZded0e:fdZd;e9d`ed0dfdZd;e9ded0dfdZd;e9d0dfdZd;e9d0e9dz  fdZ ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed           d{e9d0e9fd!            Z ed"          d{e9d0e9fd#            Z ed$          d{e9d0e9fd%            ZdBe:d0e:fd&ZdBe:d;e9d0e:fd'Zded0e:fd(Zd;e9de:d0e:fd)Zd%dBe:d;e9d*e:d0e9fd+Zd7e:d0e?e:e9f         dz  fd,Zd;e9d0e9fd-Zdddd.dBe:d;e9de]dz  d/eqdpe!dz  d0e9fd0Z ed1          d{e9d0e9fd2            Z ed3          d{e9d0e9fd4            Z ed5          d{e9d0e9fd6            Z ed7          d{e9d0e9fd8            Z ed9          d{e9d0e9fd:            Z ed;          d{e9d0e9fd<            Z ed=          d{e9d0e9fd>            Z ed?          d{e9d0e9fd@            Z edA          d{e9d0e9fdB            Z edC          d{e9d0e9fdD            Z edE          d{e9d0e9fdF            Z edG          d{e9d0e9fdH            Z edI          d{e9d0e9fdJ            Z edK          d{e9d0e9fdL            Z edM          d{e9d0e9fdN            Z edO          d{e9d0e9fdP            Z edQ          d{e9d0e9fdR            Z edS          d{e9d0e9fdT            Z edU          d{e9d0e9fdV            ZdW Zd3e:fdXZdYZdZe9d0dfd[Zd0ee9         fd\Z ed]          d{e9d0e9fd^            Z ed_          d{e9d0e9fd`            Z eda          d{e9d0e9fdb            Z edc          d{e9d0e9fdd            Z ede          d{e9d0e9fdf            Z edg          d{e9d0e9fdh            Zd;e9die9d0eqfdjZ die9d0e?fdkZdlej@        dBe:d;e9d0dfdmZdBe:d;e9d0ej@        fdnZdBe:d;e9d`ed0dfdoZ edp          d{e9d0e9fdq            Z edr          d{e9d0e9fds            ZdtZduZdvZdwZe?e?e	e:f         df         e;dx<   dye:dze:d0e	dz  fd{Z
d%d|e	d}e:d0e:fd~Zd0eZe:         fdZd;e9d|e	de:de:d0ef
dZ ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Zdade:d0e:fdZd;e9ded0e:fdZd;e9d0efdZdke:d0e:fdZded}e:d0efdZdye:d0edz  fdZde:d0e	fdZd;e9de:de:dke:d0e?eeqf         f
dZ ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Zd Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z eZh d          ZeZe:         e;d<   g dZee?e:e:e:f                  e;d<    eZh d          ZeZe:         e;d<    eZddh          ZeZe:         e;d<    ed          d{e9d0e9fd            Zdee:         d0e:dz  fdZ edæ          d{e9d0e9fdĄ            Z edŦ          d{e9d0e9fdƄ            Zdke:d0e:fdǄZ edȦ          d{e9d0e9fdɄ            Zd a edʦ          d{e9d0e9fd˄            ZdZd̐Z  eZh dͣ          Z! ejE                    Z"i Z#e9e:e?eMee:         f         f         e;d<   de:d0ee:         fdτZ$dke:de:d0e?e]e]f         dz  fdфZ% edҦ          d{e9d0e9fdӄ            Zd%de:de:d0e9fdՄZ&de:de:deqd0e9fdׄZ'd`e:d0ee9         dz  fd؄Z( ed٦          d{e9d0e9fdڄ            Z edۦ          d{e9d0e9fd܄            Z edݦ          d{e9d0e9fdބ            Z edߦ          d{e9d0e9fd            ZdBe:d;e9de:d0e:fdZ) ed          d{e9d0e9fd            Z ejE                    Z*da+e:e;d<   d d\e:d]e9dz  d0dfdZ,d0eqfdZ-d0eqfdZ.d0e9fdZ/d0e:fdZ0 ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Zd0e:fdZ1d0eqfdZ2de:dteMd0eqfdZ3d0ee:         fdZ4d0e:fdZ5de:de]d e:d0ee:         fdZ6 ed          d{e9d0e9fd            Zd{e9d0e9fdZ7d0e9fdZ8 ed          d{e9d0e9fd            Z ed          d{e9d0e9fd	            Z ed
          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            Z ed          d{e9d0e9fd            ZdS ()      NdatetimePath)AnyOptional)get_hermes_homeget_hermes_home_overridereset_hermes_home_overrideset_hermes_home_override)load_hermes_dotenv)is_truthy_value)StdioTransport	Transportbind_transportcurrent_transportreset_transportz.env)hermes_homeproject_envlogsztui_gateway_crash.logc                    dd l }d                    |                    | ||                    }	 t          j        t          j                            t                    d           t          t          dd          5 }|	                    dt          j        d	           d
           |	                    |           d d d            n# 1 swxY w Y   n# t          $ r Y nw xY wt          |                                          r9t          |                                                                          d         n| j        }t#          d| j         d| t$          j        d           t%          j        | ||           d S )Nr    Texist_okautf-8encodingu   
=== unhandled exception · %Y-%m-%d %H:%M:%S ===
z[gateway-crash] : fileflush)	tracebackjoinformat_exceptionosmakedirspathdirname
_CRASH_LOGopenwritetimestrftime	Exceptionstrstrip
splitlines__name__printsysstderr__excepthook__)exc_type	exc_valueexc_tbr%   traceffirsts          1/usr/local/lib/hermes-agent/tui_gateway/server.py_panic_hookrA   8   s   GGI..xFKKLLE
BGOOJ//$????*cG444 	GGZ>Q0R0RZZZ   GGENNN		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
     y>>!!	I))++A.. 

 

9X.
9
9%
9
9
RVWWWWxF33333s7   AC ?AC C CC CC 
C%$C%c                 ^   dd l }d                    |                    | j        | j        | j                            }	 t          j        t          j        	                    t                    d           t          t          dd          5 }|                    dt          j        d	           d
| j        j         d           |                    |           d d d            n# 1 swxY w Y   n# t"          $ r Y nw xY wt%          | j                                                  r>t%          | j                                                                                  d         n| j        j        }t-          d| j        j         d| j        j         d| t.          j        d           d S )Nr   r   Tr   r   r   r   u   
=== thread exception · r   u    · thread=r    z[gateway-crash] thread z raised r!   r"   )r%   r&   r'   r:   r;   exc_tracebackr(   r)   r*   r+   r,   r-   r.   r/   r0   threadnamer1   r2   r3   r4   r5   r6   r7   r8   )argsr%   r=   r>   
first_lines        r@   _thread_panic_hookrH   U   s   GG""4=$.$BTUU E	
BGOOJ//$????*cG444 	GG6T];N-O-O 6 6![-6 6 6   GGENNN	 	 	 	 	 	 	 	 	 	 	 	 	 	 	     t~$$&&	$DN!!##..0033]# 
 
b$+"2bbDM<RbbV`bbZ     s7   AC4 AC(C4 (C,,C4 /C,0C4 4
D D)prefetch_update_check)make_stream_rendererrender_diffrender_message	_sessions_methods_pending_pending_prompt_payloads_answers	_db_error
_cfg_cache
_cfg_mtimeHERMES_TUI_SLASH_TIMEOUT_S45g     F@g      @!HERMES_TUI_WS_ORPHAN_REAP_GRACE_S20g      4@        thinkingtools	subagentsactivity>   hiddenexpanded	collapsed>	   cli.exec
shell.exec
slash.execskills.managebrowser.manageplugins.managesession.branchsession.resumesession.compress   HERMES_TUI_RPC_POOL_WORKERS4   ztui-rpc)max_workersthread_name_prefixc                  :    t                               dd          S )NFT)waitcancel_futures)_poolshutdown     r@   <lambda>rx      s    E$GG rw   c                   *    e Zd ZdZdedefdZddZdS )_DropTransportzGDetached WS sink: keep sessions resumable without writing stale frames.objreturnc                     dS NFrv   )selfr{   s     r@   r.   z_DropTransport.write   s    urw   Nc                     d S Nrv   )r   s    r@   closez_DropTransport.close   s    trw   r|   N)r5   
__module____qualname____doc__dictboolr.   r   rv   rw   r@   rz   rz      sP        QQ $         rw   rz   c                      t           S r   )_real_stdoutrv   rw   r@   rx   rx      s    , rw   c                   D    e Zd ZdZdedefdZd Zd Zdedefd	Zd
 Z	dS )_SlashWorkerz3Persistent HermesCLI subprocess for slash commands.session_keymodelc                 P   t          j                    | _        d| _        g | _        t          j                    | _        t          j	        ddd|g}|r|d|gz  }d| _
        t          j        |t          j        t          j        t          j        ddt          j                    t          j                                        	          | _        t          j        | j        d
                                           t          j        | j        d
                                           d S )Nr   -mztui_gateway.slash_workerz--session-keyz--modelFT   )stdinstdoutr8   textbufsizecwdenvtargetdaemon)	threadingLock_lock_seqstderr_tailqueueQueuestdout_queuer7   
executable_closed
subprocessPopenPIPEr(   getcwdenvironcopyprocThread_drain_stdoutstart_drain_stderr)r   r   r   argvs       r@   __init__z_SlashWorker.__init__   s   ^%%
	&(6;kmm N&
  	'Y&&D$/??	
!!	
 	
 	
	 	 24@@@FFHHH 24@@@FFHHHHHrw   c                     | j         j        pg D ]D}	 | j                            t	          j        |                     0# t          j        $ r Y Aw xY w| j                            d            d S r   )r   r   r   putjsonloadsJSONDecodeError)r   lines     r@   r   z_SlashWorker._drain_stdout  s    I$* 	 	D!%%dj&6&67777'   d#####s   ,?AAc                     | j         j        pg D ]1}|                    d          x}r| j        |gz   dd          | _        2d S )N
i)r   r8   rstripr   )r   r   r   s      r@   r   z_SlashWorker._drain_stderr  s_    I$* 	E 	ED{{4(((t E$($4v$=stt#D 	E 	Erw   commandr|   c           
         | j                                         t          d          | j        5  | xj        dz  c_        | j        }| j         j                            t          j        ||d          dz              | j         j        	                                 	 	 | j
                            t                    }n"# t          j        $ r t          d          w xY w|n|                    d          |k    rb|                    d	          s#t          |                    d
d                    t          |                    dd                                                    cd d d            S t          d| j        r2dt%          d                              | j        dd                    z   nd           # 1 swxY w Y   d S )Nzslash worker exitedr   )idr   r   Ttimeoutzslash worker timed outr   okerrorzslash worker failedoutputr   zslash worker closed piper!   
   i)r   pollRuntimeErrorr   r   r   r.   r   dumpsr$   r   get_SLASH_WORKER_TIMEOUT_Sr   Emptyr2   r   r   chrr&   )r   r   ridmsgs       r@   runz_SlashWorker.run  s   9>>'4555Z 	 	IINII)CIO!!$*CG-L-L"M"MPT"TUUUIO!!###;A+//8O/PPCC{ A A A&'?@@@A;774==C''wwt}} P&swww8M'N'NOOO3778R001188::#	 	 	 	 	 	 	 	& sY]Yi+q4#b'',,t?OPRPSPS?T2U2U+U+Uoqss  '	 	 	 	 	 	 	 	 	 	s2   A.G C ?G CBG8AGG
Gc                    t          | dd          rd S d| _        | j        }	 |                                x|                                 	 |                    d           nL# t          $ r? |                                 	 |                    d           n# t          $ r Y nw xY wY nw xY wnL# t          $ r? 	 |                                 |                    d           n# t          $ r Y nw xY wY nw xY w|j        |j	        |j
        fD ]'}	 |                                 # t          $ r Y $w xY wd S # |j        |j	        |j
        fD ]'}	 |                                 # t          $ r Y $w xY ww xY w)Nr   FTr   r   )getattrr   r   r   	terminaterr   r1   killr   r   r8   r   )r   r   streams      r@   r   z_SlashWorker.close.  s   4E** 	Fy	yy{{"   IIaI((((    IIKKK		!	,,,,$   	  	 	 					!	$$$$   		  :t{DK@  LLNNNN    D 4:t{DK@  LLNNNN    Ds   (B0 A# "B0 #B,BB,
B&#B,%B&&B,)B0 +B,,B0 /D: 0
C9;*C&%C9&
C30C92C33C96D: 8C99D: D((
D54D5:E8E'&E8'
E4	1E83E4	4E8N)
r5   r   r   r   r2   r   r   r   r   r   rv   rw   r@   r   r      s        ==IC I I I I I<$ $ $E E E
3 3    6    rw   r   r|   c                     t                                          d          } t          | t                    si } t	          |                     dd          pd                                                                          }|dv r|ndS )Ndisplaybusy_input_moder   >   r   steer	interruptr   )	_load_cfgr   
isinstancer   r2   r3   lowerr   raws     r@   _load_busy_input_moder   L  s|    kkooi((Ggt$$ 
gkk+R006B
7
7
=
=
?
?
E
E
G
GC88833kIrw   
event_type
session_idc                 R    	 ddl m}  || |d           dS # t          $ r Y dS w xY w)z-Fire session lifecycle hooks with CLI parity.r   )invoke_hooktui)r   platformN)hermes_cli.pluginsr   r1   )r   r   _invoke_hooks      r@   _notify_session_boundaryr   T  sX    BBBBBBZJGGGGGG   s    
&&r   )surfacer   live_session_idr   c                    	 ddl m}  || |t                      d|i          S # t          $ r&}t                              d|           Y d }~dS d }~ww xY w)Nr   )try_acquire_active_sessionr   )r   r   configmetadataz'Failed to claim active session slot: %sNN)hermes_cli.active_sessionsr   r   r1   loggerwarning)r   r   r   r   excs        r@   _claim_active_session_slotr   ^  s    IIIIII))";;'9	
 
 
 	
    @#FFFzzzzzs   "% 
AAAsessionc                     | sd S |                      dd           }|d S 	 |                                 d S # t          $ r  t                              dd           Y d S w xY w)Nactive_session_leasez%Failed to release active session slotTexc_info)popreleaser1   r   debug)r   leases     r@   _release_active_session_slotr   r  s     KK.55E}M M M M<tLLLLLLMs   6 &A A 	tui_close
end_reasonc                    | r|                      d          rdS d| d<   t          |            |                      d          }||                                 |                      d          }|                      d          }|>|5  t          |                      dg                     }ddd           n# 1 swxY w Y   n#t          |                      dg                     }|9|r7t	          |d          r'	 |                    |           n# t          $ r Y nw xY w|                      d	          }t          |d
d          p|}t          d|           |r8	 t                      }||
                    ||           n# t          $ r Y nw xY w	 |                      d          }	|	r|	                                 dS dS # t          $ r Y dS w xY w)z8Best-effort finalize hook + memory commit for a session.
_finalizedNT_notif_stopagenthistory_lockhistorycommit_memory_sessionr   r   on_session_finalizeslash_worker)r   r   setlisthasattrr  r1   r   r   _get_dbend_sessionr   )
r   r   
stop_eventr  lockr  r   r   dbworkers
             r@   _finalize_sessionr  ~  s[    gkk,//  GL )))]++JKK  E;;~&&D 	7 	77;;y"5566G	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 w{{9b1122W8O)P)P	''0000 	 	 	D	 ++m,,Kd33B{J2J???  	B~z:666 	 	 	D	^,, 	LLNNNNN	 	   sH   $B77B;>B;;D 
DD&F 
FF+G 
GGr   c                F   | sdS t          | |           	 ddlm} |                     d          x}r ||           n# t          $ r Y nw xY w	 |                     d          }|&t          |d          r|                                 dS dS dS # t          $ r Y dS w xY w)a  Fully tear down a session: finalize, unregister, close agent + worker.

    Shared by ``session.close`` and the orphaned-WS-session reaper. The
    slash-worker subprocess is closed inside ``_finalize_session`` (the single
    finalize chokepoint); this still unregisters the approval notifier and
    closes the in-process agent. Idempotent: the ``_finalized`` guard in
    ``_finalize_session`` and the ``poll()`` guard in ``_SlashWorker.close``
    make repeat calls harmless.
    Nr  r   unregister_gateway_notifyr   r  r   )r  tools.approvalr  r   r1   r
  r   )r   r   r  keyr  s        r@   _teardown_sessionr    s      g*5555<<<<<<++m,,,3 	+%%c***   G$$!8!8KKMMMMM    s#   (A   
AA;B 
B B sidc                     t           5  t                              |           |u r||d<   	 ddd           dS 	 ddd           n# 1 swxY w Y   |                                 dS )u   Store worker on session iff sid still maps to it, else close it — a
    concurrent teardown already popped the session and would orphan the
    worker. Closes the create/close race at every slash-worker spawn site.r  N)_sessions_lockrM   r   r   )r  r   r  s      r@   _attach_workerr    s     
  ==((&,GN#       (               LLNNNNNs   #AA	A	c                    t           5  t                              | d          }ddd           n# 1 swxY w Y   |dS t          ||           dS )ax  Single idempotent teardown for one session: pop it under the sessions
    lock, then finalize, unregister notify, close agent + slash worker via the
    shared ``_teardown_session`` path. Returns True iff it closed a live
    session. The ``_finalized`` / worker ``_closed`` guards make concurrent or
    repeat calls (e.g. session.close racing the WS-orphan reaper) harmless.NFr  T)r  rM   r   r  )r  r   r   s      r@   _close_session_by_idr    s     
 + +--T**+ + + + + + + + + + + + + + +ug*55554s   044c                     | r|                      d          rdS |                      d          rdS |                      d          t          u S )a  True if a WS session has no live transport and no in-flight turn.

    After ``handle_ws`` detaches a disconnected client it points the session at
    ``_detached_ws_transport``. A session left on that transport (and not
    mid-turn) is genuinely orphaned and safe to reap.
    r   Frunning	transport)r   _detached_ws_transportr   s    r@   _ws_session_is_orphanedr$    sU      gkk,// u{{9 u;;{##'===rw   c                      t           dk    rdS d fd}t          j        t           |          }d|_        |                                 dS )a+  After a grace window, reap session ``sid`` iff it's still orphaned.

    Called from the WS-disconnect path. The grace window lets a transient
    reconnect (or a ``session.resume`` that reattaches the transport) cancel
    the reap by re-binding a live transport. Disabled when the grace is 0.
    r   Nr|   c                      t           5  t          t                                                   s	 d d d            d S t	           d           d d d            d S # 1 swxY w Y   d S )Nws_orphan_reapr  )_session_resume_lockr$  rM   r   r  r  s   r@   _reapz'_schedule_ws_orphan_reap.<locals>._reap  s     " 	C 	C*9==+=+=>> 	C 	C 	C 	C 	C 	C 	C 	C !1ABBBB	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	Cs   )AAA!$A!Tr   )_WS_ORPHAN_REAP_GRACE_Sr   Timerr   r   )r  r*  timers   `  r@   _schedule_ws_orphan_reapr.    se     !##C C C C C C O3U;;EEL	KKMMMMMrw   ws_disconnectc                b    t           5   fdt                                          D             }ddd           n# 1 swxY w Y   d}d}|D ]`\  }}|                    d          rt	          ||           |dz  }1t
          |d<   |dz  }	 t          |           Q# t          $ r Y ]w xY w||fS )u  On transport disconnect, reap the sessions that opted into
    close_on_disconnect (sidecar/dashboard) immediately via the unified
    ``_close_session_by_id`` path, and re-point the rest back to stdio so later
    emits don't hit a dead socket.

    Non-flagged detached sessions are handed to the grace-windowed WS-orphan
    reaper (``_schedule_ws_orphan_reap``): a quick reconnect / session.resume
    that re-binds a live transport cancels the reap, otherwise the orphan is
    torn down through the same idempotent ``_teardown_session`` path. This is
    the single WS-disconnect teardown entry point — there is no second
    independent reap loop in ``handle_ws``.

    Returns ``(reaped, detached)`` counts for disconnect-path observability.c                 L    g | ] \  }}|                     d           u ||f!S r!  r   ).0r  sr!  s      r@   
<listcomp>z1_close_sessions_for_transport.<locals>.<listcomp>,  s8    ]]]fc1QUU;=O=OS\=\=\#q=\=\=\rw   Nr   close_on_disconnectr  r   r!  )r  rM   itemsr   r  r"  r.  r1   )r!  r   ownedreapeddetachedr  r   s   `      r@   _close_sessions_for_transportr<    s:     
 ^ ^]]]]	(9(9]]]^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^FH  W;;,-- 	 <<<<aKFF
 $:GK MH(----   8s   &;??B
B*)B*c                      t           5  t          t                    } d d d            n# 1 swxY w Y   | D ]}t          |d           d S )Ntui_shutdownr  )r  r	  rM   r  )sidsr  s     r@   _shutdown_sessionsr@  @  s    	  I               = =S^<<<<<= =s   )--HERMES_TUI_SESSION_TTL_Si`T  g     r@c                 >    | t           u rdS t          | dd           du S )NTr   )r"  r   r2  s    r@   _transport_is_deadrC  R  s,    
 ***t9i..$66rw   nowc                    |                     d          st          |           rdS |                     d          }||                                sdS t          |                     d                    sdS t	          |                     d          pd          }t	          |                     d          pd          }||z
  t
          k    o||z
  t
          k    S )Nr   Fagent_readyr!  last_activerY   
created_at)r   _session_pending_kindis_setrC  float_SESSION_TTL_S)r  r   rD  readyrG  rH  s         r@   _session_is_evictablerN  \  s    {{9 !6s!;!; uKK&&Eugkk+6677 uM229c::Kw{{<007C88J+/WS:5E4WWrw   c                      t          j                     t          5  fdt                                          D             } d d d            n# 1 swxY w Y   | D ]}t	          |d           d S )Nc                 <    g | ]\  }}t          ||          |S rv   )rN  )r4  r  r5  rD  s      r@   r6  z'_reap_idle_sessions.<locals>.<listcomp>l  s2    ]]]63:OPSUVX[:\:\]3]]]rw   idle_timeoutr  )r/   r  rM   r8  r  )victimsr  rD  s     @r@   _reap_idle_sessionsrS  i  s    
)++C	 ^ ^]]]]Y__%6%6]]]^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ = =S^<<<<<= =s   &AAAc                  \    d } t          j        | d                                           d S )Nc                  x    	 t          j        t                     	 t                       n# t          $ r Y nw xY w:r   )r/   sleep_REAPER_SCAN_SrS  r1   rv   rw   r@   _loopz!_start_idle_reaper.<locals>._loopr  sP    	J~&&&#%%%%   		s   + 
88Tr   )r   r   r   )rX  s    r@   _start_idle_reaperrY  q  s;       E$///5577777rw   c                      t           Vddlm}  	  |             a d anB# t          $ r5}t          |          at                              d|           Y d }~d S d }~ww xY wt           S )Nr   	SessionDBuJ   TUI session store unavailable — continuing without state.db features: %s)_dbhermes_stater\  rR   r1   r2   r   r   )r\  r   s     r@   r  r    s    
{******		)++CII 	 	 	CINN\   44444	 Js    
A*AAcodec                <    t           pd}t          | |d|           S )Nzstate.db unavailablezstate.db unavailable: )rR   _err)r   r_  details      r@   _db_unavailable_errorrc    s(    00FT<F<<===rw   profilec                    | pd                                 }|sdS 	 ddlm} t          |                    |                    }n# t
          $ r Y dS w xY w|                                t          t                                                    k    rdS |dz                                  s|                                r|ndS )zLResolve a named profile's home on THIS host, or None for the launch profile.r   Nr   )profilesstate.db)	r3   
hermes_clirf  r   get_profile_dirr1   resolve_hermes_homeexists)rd  rE   profiles_modhomes       r@   _profile_homero    s    Mr  ""D t777777L006677   tt ||~~l++335555t:%--//J4;;==J44dJs   (A 
AA>   r   auto.profile_homec                 t   | dS 	 ddl }t          |           dz  }|                                sdS t          |d          5 }|                    |          pi }ddd           n# 1 swxY w Y   t          |                    d          pi                     d          pd                                          }|r	|t          v rdS t          j
                            t          j
                            |                    }t          j
                            |          r|ndS # t          $ r Y dS w xY w)	a  Resolve a non-launch profile's ``terminal.cwd`` from its own config.yaml.

    The desktop's app-global remote mode serves every profile from one backend,
    so the process-global ``TERMINAL_CWD`` belongs to the *launch* profile. A new
    session bound to another profile must take its workspace from THAT profile's
    config, not the stale env var (issue #40334). Returns an absolute, existing
    directory, or None for placeholders / missing / invalid paths.
    Nr   config.yamlr   r   terminalr   r   )yamlr   rl  r-   	safe_loadr2   r   r3   _CWD_PLACEHOLDERSr(   r*   abspath
expanduserisdirr1   )rr  rv  pr>   datar   resolveds          r@   _profile_configured_cwdr    sv    t.xxzz 	4!g&&& 	+!>>!$$*D	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+488J''-222599?R@@FFHH 	c...47??27#5#5c#:#:;;7==22<xx<   ttsB   *D) D) A'D) 'A++D) .A+/AD) 
AD) )
D76D7r{   c                 l   |                      d          dk    rt|                      d          pi                      d          pd}|rFt                               |          pi                      d          x}|                    |           S t                      pt                              |           S )uA  Emit one JSON frame. Routes via the most-specific transport available.

    Precedence:

    1. Event frames with a session id → the transport stored on that session,
       so async events land with the client that owns the session even if
       the emitting thread has no contextvar binding.
    2. Otherwise the transport bound on the current context (set by
       :func:`dispatch` for the lifetime of a request).
    3. Otherwise the module-level stdio transport, matching the historical
       behaviour and keeping tests that monkey-patch ``_real_stdout`` green.
    methodeventparamsr   r   r!  )r   rM   r.   r   _stdio_transport)r{   r  ts      r@   
write_jsonr    s     wwxG##!!'R,,\::Ar 	 )--,,277DDDAQ773<<3#3::3???rw   r  payloadc                 D    | |d}|||d<   t          dd|d           d S )N)typer   r  2.0r  )jsonrpcr  r  )r  )r  r  r  r  s       r@   _emitr    s=    3//F#y5GvFFGGGGGrw   kindr   c                 n    ||n|                                 }|sd S t          d| ||nd|d           d S )Nstatus.updatestatusr  r   )r3   r  )r  r  r   bodys       r@   _status_updater    s_    $DD$5577D 	)xFF    rw   widthheightc                 ~    | dk    s|dk    rdS t          d| dz   dz            t          d|dz   dz            z  dz  S )zVery rough UI estimate for image prompt cost.

    Uses 512px tiles at ~85 tokens/tile as a lightweight cross-provider hint.
    This is intentionally approximate and only used for attachment display.
    r   r   i  i   U   )max)r  r  s     r@   _estimate_image_tokensr    sP     zzVq[[qq53;3&''#a&3,31F*G*GG"LLrw   r*   c                 X   d| j         i}	 ddlm} |                    |           5 }|j        \  }}d d d            n# 1 swxY w Y   t          |          |d<   t          |          |d<   t          t          |          t          |                    |d<   n# t          $ r Y nw xY w|S )NrE   r   )Imager  r  token_estimate)rE   PILr  r-   sizeintr  r1   )r*   metar  imgr  r  s         r@   _image_metar    s    DID	ZZ 	%HME6	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%E

WVX!7E

CKK!P!P   Ks2   B =B AB AAB 
B'&B'resultc                     d| |dS )Nr  )r  r   r  rv   )r   r  s     r@   _okr    s    C6:::rw   r   c                     d| ||ddS )Nr  )r_  message)r  r   r   rv   )r   r_  r   s      r@   ra  ra    s    C4C2P2PQQQrw   rE   c                       fd}|S )Nc                     | t           <   | S r   )rN   )fnrE   s    r@   deczmethod.<locals>.dec   s    	rw   rv   )rE   r  s   ` r@   r  r    s#         Jrw   reqc                 ~   t          | t                    st          ddd          S |                     d          }|                     d          }t          |t                    r|st          |dd          S |                     di           }|i }n&t          |t                    st          |dd	          S |||fS )
z;Validate a JSON-RPC request enough for safe local dispatch.Niz#invalid request: expected an objectr   r  z2invalid request: method must be a non-empty stringr  iz"invalid params: expected an object)r   r   ra  r   r2   )r  r   r  r  s       r@   _normalize_requestr  '  s    c4   ID&"GHHH
''$--CWWXFfc"" W& WC!UVVVWWXr""F~%% GC!EFFFrw   c                     t          |           }t          |t                    r|S |\  }}}t                              |          }|st          |dd|           S  |||          S )Nizunknown method: )r  r   r   rN   r   ra  )r  
normalizedr   r  r  r  s         r@   handle_requestr  :  sw    #C((J*d## $C	f		B >C!<F!<!<===2c6??rw   r!  c                    	 |pt           	t          	          }	 t                     }t          |t                    r|t          |           S |\  }}}|t          vrt                     t          |           S t          j	                     	fdt                              fd           	 t          |           dS # t          |           w xY w)u  Route inbound RPCs — long handlers to the pool, everything else inline.

    Returns a response dict when handled inline. Returns None when the
    handler was scheduled on the pool; the worker writes its own response
    via the bound transport when done.

    *transport* (optional): pins every write produced by this request —
    including any events emitted by the handler — to the given transport.
    Omitting it falls back to the module-level stdio transport, preserving
    the original behaviour for ``tui_gateway.entry``.
    c                      	 t                    } n># t          $ r1}t                              d          dd|           } Y d }~nd }~ww xY w|                     |            d S d S )Nr   i zhandler error: )r  r1   ra  r   r.   )respr   r  r  s     r@   r   zdispatch.<locals>.run`  s    L%c** L L LCGGDMM63JS3J3JKKL  s    
A'A		Ac                  .                                    S r   )r   )ctxr   s   r@   rx   zdispatch.<locals>.<lambda>h  s    SWWS\\ rw   N)r  r   r  r   r   r   _LONG_HANDLERSr  contextvarscopy_contextrt   submit)
r  r!  tokenr  _ridr  _paramsr  r   r  s
   `      @@@r@   dispatchr  F  s    	%%A1E',,
j$'' 	* 	' !+fg''!#&&" 	 &((	 	 	 	 	 	 	)))))***s   %C	 C	  7C	 	C      >@r   r   c                     |                      d          }|'|                    |          st          |dd          S |                      d          }|rt          |d|          nd S )NrF  r     zagent initialization timed outagent_error)r   rr   ra  )r   r   r   rM  errs        r@   _wait_agentr  o  sl    KK&&EG!<!<C?@@@
++m
$
$C#&04T3D0rw   c                     |                     d          dS |                    dt          j                              }|5                                  s|                     d          r	 ddd           dS d|d<   ddd           n# 1 swxY w Y   |d         d
 fd}t          j        |d	                                           dS )a  Start building the real AIAgent for a TUI session, once.

    Classic `hermes` shows the prompt before constructing AIAgent; the TUI used
    to eagerly build it during session.create, making startup feel blocked on
    tool discovery/model metadata even though the composer was visible.  Keep
    the shell responsive by deferring this work until the first prompt (or any
    command that actually needs the agent), while retaining the same ready/error
    event contract for the frontend.
    rF  Nagent_build_lockagent_build_startedTr   r|   c            	         t           5  t                                        } d d d            n# 1 swxY w Y   |                                  d S d }d}d }|                     d          }	 t	                    }d }|rEt          |          }	 ddlm}  |t          |          dz            }n# t          $ r d }Y nw xY w	 t          |          }t          |           n# t          |           w xY w|| d<   	 t          t          |d	t                                          }t          | |           n# t          $ r Y nw xY w	 dd
lm}	m}
  |	fd           d} |
             n# t          $ r Y nw xY wt'                     	 ddlm}  ||           n# t          $ r Y nw xY wt           5  t          v r)t-          t                             t                   d<   d d d            n# 1 swxY w Y   t/          d           t1          ||           }t3          t5                                }|r||d<   t6                              |           t;          d|           n?# t          $ r2}t=          |          | d<   t;          ddd| i           Y d }~nd }~ww xY w|t?          |           t           5  t                                        | u}d d d            n# 1 swxY w Y   |r%|r#	 ddlm }  |           n# t          $ r Y nw xY w                                 d S # |t?          |           t           5  t                                        | u}d d d            n# 1 swxY w Y   |r%|r#	 ddlm }  |           n# t          $ r Y nw xY w                                 w xY w)NFrr  r   r[  rg  db_path)
session_dbr  r   register_gateway_notifyload_permanent_allowlistc                 &    t          d|           S Nzapproval.requestr  r}  r  s    r@   rx   z4_start_agent_build.<locals>._build.<locals>.<lambda>  s    e,>T&J&J rw   T)seed_credits_at_session_startr  on_session_resetconfig_warningsession.infor  r   r  zagent init failed: r  )!r  rM   r   r  _set_session_contextr   r^  r\  r   r1   _make_agent_clear_session_contextr   r   _resolve_modelr  r  r  r  _wire_callbacksagent.credits_trackerr  _start_notification_pollerr   _session_info_probe_config_healthr   r   r   r  r2   r   r  )currentr  notify_registered
home_tokenrr  tokensr  r\  r  r  r  r  infocfg_warnereplacedr  r  rM  r  s                    r@   _buildz"_start_agent_build.<locals>._build  s    	) 	)mmC((G	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)?IIKKKF!
{{>22R	)#..F J &5lCC
&666666!*43E3E
3R!S!S!SJJ  & & &!%JJJ&/#CDDD&v....&v....  %GG%c75'>CSCS+T+TUUsGV4444          
 ('JJJJ   %)!((****    C   OOOOOO--e4444    d d)##4NsT]^aTb4c4cIcN=1d d d d d d d d d d d d d d d %%7=== 00D+IKK88H ))1%&x(((.#t,,,, 	H 	H 	H%(VVGM"'3,E!,E,E FGGGGGGGG	H %*:666   = =$==--W<= = = = = = = = = = = = = = = - HHHHHH--c2222    DIIKKKKK %*:666   = =$==--W<= = = = = = = = = = = = = = = - HHHHHH--c2222    DIIKKKKsu  044/"I7 "B5 4I7 5CI7 CI7 C* I7 *C;;I7 <E  I7 
EI7 EI7 #E6 5I7 6
F I7 FI7 F( 'I7 (
F52I7 4F55
I7 ?3G>2I7 >HI7 HA0I7 6L? 7
J3(J.)L? .J33L? K77K;>K;L 
L&%L&?ON5ONON	ON#"O#
N0-O/N00Or   r   )r   
setdefaultr   r   rJ  r   r   )r  r   r  r  r  rM  s   `   @@r@   _start_agent_buildr  w  s^    KK&&E}0).2B2BCCD	 . .<<>> 	W[[)>?? 	. . . . . . . . *.%&. . . . . . . . . . . . . . . -
 C] ] ] ] ] ] ] ]~ F40006688888s   +B>BBBc                     t                               |                     d          pd          }|r|d fnd t          |dd          fS )Nr   r     session not found)rM   r   ra  )r  r   r5  s      r@   _sess_nowaitr    sI    fjj..4"55AKAt99d36I&J&JKKrw   c                     t          | |          \  }}|rd |fS t          |                     d          pd|           |t          ||          fS )Nr   r   )r  r  r   r  )r  r   r5  r  s       r@   _sessr    s]    &#&&FAs
 c{vzz,//52q999{1c""##rw   	path_partc                 j   t           j                            |           }t           j        dk    r|                    dd          }t          |          dk    rZ|d         dk    rN|d         dk    rB|d                                         r(d	|d                                          d|dd           S |S )
Nnt\/   r   :rk   r   z/mnt/)r(   r*   rz  rE   replacelenisalphar   )r  r`   r  s      r@   _normalize_completion_pathr    s    w!!),,H	w$%%dC00

OOq  1$$1$$1%%'' % D:a=..00CC:abb>CCCOrw   r  c                    | pi } |                      d          pt                               |                      d          pdi                                d          p`t          t          |                      d                              p1t          j                             d          pt	          j                    }	 t          j                            t          j        	                    t          |                              }t          j                            |          r|S n# t          $ r Y nw xY wt	          j                    S )Nr   r   r   rd  TERMINAL_CWD)r   rM   r  ro  r(   r   r   r*   ry  rz  r2   r{  r1   )r  r   r~  s      r@   _completion_cwdr    s   \rF

5 	==L117R<<@@GG	 #=I1F1F#G#GHH		
 :>>.))	 9;; 7??27#5#5c#hh#?#?@@7=="" 	O	   9;;s   ?A)D* *
D76D7c                 4   t           j                            d          pd                                                                }|r|dk    rt           j                            dd                                          }|s	 t                                          di           }t          |t                    r6t          |                    d          pd                                          }n# t          $ r d}Y nw xY w|r|dvr|S t          |           S )a  Return the cwd that terminal_tool should use for this TUI session.

    ``_completion_cwd`` validates paths on the host so file completion does not
    point at nonsense.  Non-local terminal backends are different: their cwd is
    inside the target environment, so an SSH path like /home/user/workspace may
    not exist on the local macOS host but is still the correct execution cwd.
    TERMINAL_ENVr   localr  ru  r   >   r   rp  rq  )r(   r   r   r3   r   r   r   r   r2   r1   _session_cwd)r   backendr   terminal_cfgs       r@   _terminal_task_cwdr    s    z~~n--3::<<BBDDG 
7g%%jnn^R006688 	({{z2>>lD11 El..u55;<<BBDDC    	3222J   s   A-C1 1D ?D r   c                 h   	 t          j        dd| ddgddddt           j                  }|j        d	k    r|j                                        }|r|S t          j        dd| d
ddgddddt           j                  }|j        d	k    r|j                                        ndS # t          $ r Y dS w xY w)Ngit-Cbranchz--show-currentTg      ?F)capture_outputr   r   checkr   r   	rev-parsez--shortHEADr   )r   r   DEVNULL
returncoder   r3   r1   )r   r  r	  heads       r@   _git_branch_for_cwdr  4  s    D#x)9:$
 
 
 !!]((**F ~D#{Iv>$
 
 
 '+o&:&:t{  """B   rrs   AB# AB# #
B10B1c                 v    | r*|                      d          rt          | d                   S t                      S )Nr   )r   r2   r  r#  s    r@   r  r  O  s;     #7;;u%% #75>"""rw   c                     | sd S 	 ddl m}  || d         dt          |           i           d S # t          $ r Y d S w xY w)Nr   register_task_env_overridesr   r   )tools.terminal_toolr  r  r1   )r   r  s     r@   _register_session_cwdr  U  s     CCCCCC##M"U,>w,G,G$H	
 	
 	
 	
 	
    s   '/ 
==c                    |                      d          }|sdS |                      d          }|rTddlm} 	  |t          |          dz            }n-# t          $ r  t
                              dd	
           Y dS w xY wd	}nt                      }d}|dS 	 |                    |dt                      |                      d          rt          |           nd           n,# t          $ r t
                              dd	
           Y nw xY w|r(	 |                                 dS # t          $ r Y dS w xY wdS # |r&	 |                                 w # t          $ r Y w w xY ww xY w)u
  Idempotently persist the session's DB row on first real activity.

    Called from prompt.submit so a row only exists once the user actually sends
    a message — abandoned drafts never leave an empty "Untitled" session behind.
    Uses INSERT OR IGNORE under the hood, so re-calls (and the AIAgent's own
    lazy create) are no-ops.

    Only an *explicitly chosen* workspace is persisted as the session's cwd.
    The agent still runs in the auto-detected directory (session["cwd"]), but
    we don't stamp that onto the row — otherwise every session the user never
    picked a folder for gets grouped under whatever directory the desktop
    happened to launch in (e.g. "desktop"). Leaving it null groups them under
    "No workspace", which is the desired default.
    r   Nrr  r   r[  rg  r  z)failed to open profile db for session rowTr   Fr   explicit_cwd)sourcer   r   z%failed to persist desktop session row)r   r^  r\  r   r1   r   r   r  create_sessionr  r  r   )r   r  rr  r\  r  close_dbs         r@   _ensure_session_db_rowr  b  s    ++m
$
$C  ;;~..L ******	4#5#5
#BCCCBB 	 	 	LLDtLTTTFF	 YY	z
 "")0^)D)DNW%%%$	 	 	
 	
 	
 	
  M M M<tLLLLLM  	




   	 	8 	



   	sr   A &A?>A?A	C$ #D< $&D
D< DD< D) )
D76D7<E& EE&
E"E&!E""E&c              #   H  K   d\  }}|                      d          }|rRddlm} 	  |t          |          dz            d}}n:# t          $ r t
                              dd	           Y nw xY wt                      }	 |V  |rJ|Jt          j	        t                    5  |
                                 d
d
d
           d
S # 1 swxY w Y   d
S d
S d
S # |rH|Gt          j	        t                    5  |
                                 d
d
d
           w # 1 swxY w Y   w w w xY w)aU  Yield the SessionDB that owns this session's row (profile-aware).

    Mirrors :func:`_ensure_session_db_row`: a remote/profile session persists
    into its own profile's ``state.db`` (a fresh handle we close on exit);
    everything else borrows the shared ``_get_db()`` handle (left open). Yields
    None when the db is unavailable.
    r~   rr  r   r[  rg  r  Tz%failed to open profile db for sessionr   N)r   r^  r\  r   r1   r   r   r  
contextlibsuppressr   )r   r  r  rr  r\  s        r@   _session_dbr!    s      LB;;~..L ******	Q$9T,-?-?*-LMMMtBB 	Q 	Q 	QLL@4LPPPPP	Q YY 	$Y//  


                 	 	8 	$Y//  


               	sS   A &A.-A. C !CC
CD!2DD!DD!DD!c                 N   t           j                            t           j                            t	          |                              }t           j                            |          st          d|           || d<   d| d<   t          |            t                      }|X	 |	                    | 
                    dd          |           n,# t          $ r t                              dd           Y nw xY w	 d	d
lm}  || d                    n# t          $ r Y nw xY w|S )N"working directory does not exist: r   Tr  r   r   zfailed to persist session cwdr   r   )
cleanup_vm)r(   r*   ry  rz  r2   r{  
ValueErrorr  r  update_session_cwdr   r1   r   r   r  r$  )r   r   r~  r  r$  s        r@   _set_session_cwdr'    sG   wrw11#c((;;<<H7=="" ECcCCDDDGEN #GN'"""	B	~	I!!'++mR"@"@(KKKK 	I 	I 	ILL84LHHHHH	I222222
7=)****   Os$   %*C &C98C9=D 
D"!D")asciiemojikaomojiunicode._INDICATOR_STYLESr*  c                     	 dd l } t                      }t          |t                    r|r|nt          }t          |          dz  }|                                r|                                j        nd }t          5  t          ;t          |k    r0t          |k    r%t          j        t                    cd d d            S d d d            n# 1 swxY w Y   |                                rAt          |d          5 }|                     |          pi }d d d            n# 1 swxY w Y   ni }t          5  t          j        |          a
|a|ad d d            n# 1 swxY w Y   |S # t"          $ r Y nw xY wi S )Nr   rt  r   r   )rv  r
   r   r2   rk  r   rl  statst_mtime	_cfg_lockrS   rT   	_cfg_pathr   deepcopyr-   rw  r1   )rv  overridern  r|  mtimer>   r}  s          r@   r   r     sI    ,--%h44SSxx|JJ&%&XXZZ9!!T 	1 	1%**=*=)q..}Z00	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 88:: 	a'*** /a~~a((.B/ / / / / / / / / / / / / / / D 	 	t,,JJI	 	 	 	 	 	 	 	 	 	 	 	 	 	 	    Is   A:E& <6C2E& ?E& CE& C(E& ;DE& D##E& &D#'E& 4EE& EE&  E!E& &
E32E3cfgc                 h   dd l }t          dz  }t          |dd          5 }|                    | |           d d d            n# 1 swxY w Y   t          5  t          j        |           a|a	 |	                                j
        an# t          $ r d aY nw xY wd d d            d S # 1 swxY w Y   d S )Nr   rt  wr   r   )rv  rk  r-   	safe_dumpr0  r   r2  rS   r1  r.  r/  rT   r1   )r5  rv  r*   r>   s       r@   	_save_cfgr9    sI   KKK-'D	dC'	*	*	* asA              	  ]3''
		-JJ 	 	 	JJJ	                 sG   AAAB'.BB'BB'BB''B+.B+c                 6   | sdS t           5  t          t                                                    D ]M}|                    d          | k    r2t          |                    d          pd          c cddd           S N	 ddd           n# 1 swxY w Y   dS )zReverse-map session_key to the session's logical cwd.

    Snapshots ``_sessions`` first: concurrent RPC handlers mutate it from the
    thread pool, so iterating the live view risks ``RuntimeError: dictionary
    changed size during iteration``.
    r   r   r   N)r  r	  rM   valuesr   r2   )r   sesss     r@   _cwd_for_session_keyr=    s      r	 2 2))++,, 	2 	2Dxx&&+55488E??0b11112 2 2 2 2 2 2 25	22 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2s   A'B BBBc                 t    	 ddl m} ||nt          |           } || |          S # t          $ r g cY S w xY w)Nr   )set_session_vars)r   r   )gateway.session_contextr?  r=  r1   )r   r   r?  r~  s       r@   r  r    sk    
<<<<<< /33/CK/P/PKXFFFF   			s   %( 77r  c                 T    | sd S 	 ddl m}  ||            d S # t          $ r Y d S w xY w)Nr   )clear_session_vars)r@  rB  r1   )r  rB  s     r@   r  r  "  s_     >>>>>>6"""""   s    
''c                  `    dt           j        d<   dt           j        d<   dt           j        d<   dS )zARoute approvals through gateway callbacks instead of CLI input().1HERMES_GATEWAY_SESSIONHERMES_EXEC_ASKHERMES_INTERACTIVEN)r(   r   rv   rw   r@   _enable_gateway_promptsrH  -  s/    +.BJ'($'BJ !'*BJ#$$$rw   ,  c                 "   t          j                    j        d d         }t          j                    }t
          5  ||ft          |<   ||d<   | t          |          ft          |<   d d d            n# 1 swxY w Y   	 t          | ||           |
                    |           t
          5  t                              |d            t                              |d            d d d            n# 1 swxY w Y   nZ# t
          5  t                              |d            t                              |d            d d d            w # 1 swxY w Y   w xY wt
          5  t                              |d          cd d d            S # 1 swxY w Y   d S )N   
request_idr   r   )uuiduuid4hexr   Event_prompt_lockrO   r   rP   r  rr   r   rQ   )r  r  r  r   r   evs         r@   _blockrS  7  si   
*,,
2A2
C			B	 ? ?b	 #).W(> %? ? ? ? ? ? ? ? ? ? ? ? ? ? ?4eS'"""
    	4 	4LLd###$((d333	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4\ 	4 	4LLd###$((d333	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 
 % %||C$$% % % % % % % % % % % % % % % % % %se   +A22A69A6>'C; ,7C//C36C3;E7E:EE

EE
EFFFc                     t           5  t          t                                                    D ].\  }\  }}| || k    rdt          |<   |                                 /	 ddd           dS # 1 swxY w Y   dS )u|  Release pending prompts with an empty answer.

    When *sid* is provided, only prompts owned by that session are
    released — critical for session.interrupt, which must not
    collaterally cancel clarify/sudo/secret prompts on unrelated
    sessions sharing the same tui_gateway process.  When *sid* is
    None, every pending prompt is released (used during shutdown).
    Nr   )rQ  r	  rO   r8  rQ   r  )r  r   	owner_sidrR  s       r@   _clear_pendingrV  I  s     
  $()9)9$:$: 	 	 C)R{i3.. "	                 s   AA,,A03A0c            
          	 ddl m} m}  | t                                  |            }|j        |j        |j        |j        |j        |j	        |j        pi 
                    dd          dS # t          $ r i cY S w xY w)Nr   )init_skin_from_configget_active_skinhelp_headerr   )rE   colorsbrandingbanner_logobanner_herotool_prefixrZ  )hermes_cli.skin_enginerX  rY  r   rE   r[  r\  r]  r^  r_  r   r1   )rX  rY  skins      r@   resolve_skinrb  \  s    QQQQQQQQikk***  Ik+++ M/R44]BGG
 
 	
    			s   A+A. .A=<A=c                     t           j                            dd          pt           j                            dd                                          } | r| S t	                                          dd          }t          |t                    r7t          |                    dd          pd                                          S t          |t                    r|r|                                S dS )NHERMES_MODELr   HERMES_INFERENCE_MODELr   defaultzanthropic/claude-sonnet-4)r(   r   r   r3   r   r   r   r2   )r   ms     r@   r  r  o  s    

~r** 	8:>>2B77egg   
$$A!T 7155B''-2..44666!S a wwyy&&rw   c                  4   t                      } t          j                            dd                                          }|r| |fS t          j                            dd          pt          j                            dd                                          }|s| d fS 	 ddlm} t                                          d          pi }t          |t                    rHt          |                    d          pd                                                                          ndpEt          j                            d	d                                                                          pd
} |||          }|r	|\  }}||fS n# t          $ r Y nw xY w| d fS )NHERMES_TUI_PROVIDERr   rd  re  r   ) detect_static_provider_for_modelr   providerHERMES_INFERENCE_PROVIDERrp  )r  r(   r   r   r3   hermes_cli.modelsrj  r   r   r   r2   r   r1   )	r   explicit_providerexplicit_modelrj  r5  current_providerdetectedrk  detected_models	            r@   _resolve_startup_runtimers  ~  s   E
'<bAAGGII (''' 	
~r** 	8:>>2B77egg   d{FFFFFFkkoog&&," c4((CGGJ''-2..4466<<>>>
 z~~92>>DDFFLLNN  	 43NDTUU 	,'/$Hn!8++	,    $;s    C$F 
FFrowc                    | si S |                      d          }i }t          |t                    r|}nt          |t                    rm|                                rY	 t          j        |          }t          |t                    r|}n,# t          $ r t          	                    dd           Y nw xY wi }t          |                      d          p|                     d          pd                                          }t          |                     d          p+|                     d          p|                      d          pd                                          }t          |                     d	          pd                                          }t          |                     d
          pd                                          }|                     d          }	t          |                     d          pd                                          }
|r||pd|pd|pdd|d<   |r||d<   t          |	t                    r|	|d<   |
r|
|d<   |S )a  Return runtime fields persisted with a stored session.

    ``session.resume`` is a session-scoped operation: reopening an older chat
    must restore the model/provider/reasoning state that chat actually used,
    not whatever global model the user most recently selected in another chat.
    The durable session row stores the model directly, the billing provider in
    ``billing_provider``, and richer runtime knobs in JSON ``model_config``.
    model_configz+failed to parse stored session model_configTr   r   r   rk  billing_providerbase_urlapi_modereasoning_configservice_tierN)r   rk  rx  ry  model_overrideprovider_overridereasoning_config_overrideservice_tier_override)
r   r   r   r2   r3   r   r   r1   r   r   )rt  
raw_configrv  parsed	overridesr   rk  rx  ry  rz  r{  s              r@   !_stored_session_runtime_overridesr    s     	((JL*d## W!	J	$	$ W)9)9);); W	WZ
++F&$'' &% 	W 	W 	WLLFQULVVVVV	W I  CL$4$4W$=$=CDDJJLLE$$ 	.//	77%&&	 	 
 egg  <##J//5266<<>>H<##J//5266<<>>H#''(:;;|''77=2>>DDFFL 
  (D (D (D	'
 '
	"#  2)1	%&"D)) B1A	-. :-9	)*s   +B
 
&B32B3existingc                 .   t          |pi           }t          t          | dd          pd                                          }t          t          | dd          pd                                          }t          t          | dd          pd                                          }t          t          | dd          pd                                          }t          | dd           }t          | dd           }|r||d<   |r||d<   |r||d<   n|                    dd            |r||d<   n|                    dd            t          |t                     r||d<   n|                    dd            |r||d<   n|                    dd            |S )Nr   r   rk  rx  ry  rz  r{  )r   r2   r   r3   r   r   )	r  r  r   r   rk  rx  ry  rz  r{  s	            r@   _runtime_model_configr    s   (.b!!Fw++1r2288::E75*b117R88>>@@H75*b117R88>>@@H75*b117R88>>@@Hu&8$??5.$77L  w &%z %%z

:t$$$ %%z

:t$$$"D)) -%5!""

%t,,, )!-~

>4(((Mrw   c                    | sdS |                      d          }t          |                      d          pd                                          }||sdS t          |dd          pt	                      }|dS 	 |                    |          pi }|                     d          }i }t          |t                    r|}nTt          |t                    r?|                                r+t          j	        |          }t          |t                    r|}t          ||          }t          t          |dd          pd                                          }	t          |d          r-|                    |t          j        |          |	pd           dS |	r(t          |d	          r|                    ||	           dS dS dS # t          $ r  t                               d
d           Y dS w xY w)zIPersist active session runtime so future resumes restore the same footer.Nr  r   r   r!  rv  r   update_session_metaupdate_session_modelz&failed to persist live session runtimeTr   )r   r2   r3   r   r  get_sessionr   r   r   r   r  r
  r  r   r  r1   r   r   )
r   r  r   r  rt  r  existing_configr  rv  r   s
             r@   _persist_live_session_runtimer    s    KK  Egkk-006B77==??K}K}	t	,	,	9		B	zNnn[))/RWW^,,
j$'' 	)(OO
C(( 	)Z-=-=-?-? 	)Z
++F&$'' )"(,UODDGE7B//5266<<>>2,-- 	8"";
<0H0H%-SWXXXXX 	8wr#9:: 	8##K77777	8 	8 	8 	8 N N N=MMMMMMNs   :DG (G &G+*G+key_pathc                    t                      }|}|                     d          }|d d         D ];}||vs(t          |                    |          t                    si ||<   ||         }<|||d         <   t          |           d S )Nrq  )r   splitr   r   r   r9  )r  valuer5  r  keysr  s         r@   _write_config_keyr    s    
++CG>>#DCRCy  gZC0@0@$%G%GGCL#,GDHcNNNNNrw   >   offtopbottomc                     | du rdS t          | t                    r1|                                                                 x}t          v r|S dS )NFr  r  )r   r2   r3   r   _STATUSBAR_MODES)r   r5  s     r@   _coerce_statusbarr  -  sP    
e||u#s ciikk&7&7&9&9!9>N N N5rw   0r  rD  allanybuttonbuttonsclickfalsefullnoonscrollwheeltrueyesr   c                    t          | t                    sdS d| v r|                     d          }n|                     dd          }|du s|dk    rdS |du s|dS t          |t          t          f          rdS t          |t
                    r?t                              |                                                                d          S dS )u  Resolve display.mouse_tracking to one of ``off|wheel|buttons|all``.

    Boolean values keep their legacy meaning (``True`` → ``all``, ``False`` →
    ``off``). The ``wheel`` preset (DEC 1000+1006) is the tmux-friendly
    subset — wheel + click only, no hover events to trigger prompt-row
    clipboard probes. Legacy ``tui_mouse`` is honored only when
    ``mouse_tracking`` is absent.
    r  mouse_tracking	tui_mouseTFr   r  )	r   r   r   r  rK  r2   _MOUSE_TRACKING_ALIASESr3   r   r   s     r@   _display_mouse_trackingr  I  s     gt$$ u7""kk*++kk+t,,
e||saxxu
d{{cku#U|$$ u#s G&**399;;+<+<+>+>FFF5rw   c                      ddl m}  t          t                                          d          pi                     dd          pd                                          } | |          S )Nr   parse_reasoning_effortr  reasoning_effortr   )hermes_constantsr  r2   r   r   r3   )r  efforts     r@   _load_reasoning_configr  c  sp    777777		!	!	'R,,-?DDJ egg  "!&)))rw   c                      t          t                                          d          pi                     dd          pd                                                                          } | r| dv rd S | dv rdS d S )Nr  r{  r   >   r  nonenormalrf  standard>   r  fastpriorityr  )r2   r   r   r3   r   )r   s    r@   _load_service_tierr  l  s~    Y[[__W%%+00DDJKK		 
  #IIIt
(((z4rw   c                      t          t                                          d          pi                     dd                    S )Nr   show_reasoningF)r   r   r   rv   rw   r@   _load_show_reasoningr  y  s6    ++1r667GOOPPPrw   c                     t           j                            dd                                                                          } | dv r| S t                                          d          pi                     dd          }|du rdS |d	u rdS t          |pd                                                                          }|dv r|ndS )
NHERMES_TUI_TOOL_PROGRESSr   >   r  newr  verboser   tool_progressr  Fr  T)r(   r   r   r3   r   r   r2   )r   r   modes      r@   _load_tool_progress_moder  }  s    
*..3R
8
8
>
>
@
@
F
F
H
HC
...
;;??9%%+
0
0%
H
HC
e||u
d{{us|e""$$**,,D;;;44Frw   c                  ~   d t           j                            dd                              d          D             } d }d }| s(	 ddlm}  |d          }||S n# t          $ r Y nw xY w	 dd	lm n# t          $ r d Y nw xY w| rfd
| D             fd| D             }|rW	 ddl	m
}  |             fd|D             n# t          $ r g Y nw xY wr#                               fd|D             }t          d D                       rBd | D             }|r2t          dd                    |           t          j        d           d S |sS t#                      t#                      	 ddlm} ddlm}	  |            }
t-          |
                    d          t.                    r|
                    d          ni }|                                D ]\  }}t-          |t.                    s |	|                    dd          d          r#                    t5          |                     _                    t5          |                     n,# t          $ r t#                      t#                      Y nw xY wfd|D             }fd|D             }fd|D             }|z   }|r2t          dd                    |           t          j        d           |r2t          dd                    |           t          j        d           |r|S d}	 dd lm} dd!lm} ||n	 |            }t;           ||d"d#                    }|t          |t          j        d           |pd S # t          $ r" |t          d$t          j        d           Y d S w xY w)%Nc                 ^    g | ]*}|                                 |                                 +S rv   )r3   r4  items     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s>       ::<<

  rw   HERMES_TUI_TOOLSETSr   ,r   )coding_selectionr   )r   )validate_toolsetc                 *    g | ]} |          |S rv   rv   r4  rE   r  s     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s*    HHHT1A1A$1G1GHDHHHrw   c                     g | ]}|v|	S rv   rv   )r4  rE   built_ins     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s#    HHHt4x3G3Gd3G3G3Grw   )discover_pluginsc                 *    g | ]} |          |S rv   rv   r  s     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s+    VVV?O?OPT?U?UVVVVrw   c                     g | ]}|v|	S rv   rv   )r4  rE   plugin_valids     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s#    VVVtT=U=Ud=U=U=Urw   c              3      K   | ]}|d v V  	dS )>   *r  Nrv   r4  rE   s     r@   	<genexpr>z)_load_enabled_toolsets.<locals>.<genexpr>  s'      99t|#999999rw   c                     g | ]}|d v|	S )>   r  r  rv   r  s     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s"    MMMD4L4Lt4L4L4Lrw   zR[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: , Tr"   read_raw_config)_parse_enabled_flagmcp_serversenabled)rf  c                     g | ]}|v |	S rv   rv   )r4  rE   	mcp_namess     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s#    FFFdDI4E4ET4E4E4Erw   c                     g | ]}|v |	S rv   rv   )r4  rE   mcp_disableds     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s#    HHHT4<3G3GD3G3G3Grw   c                 $    g | ]}|v|v
|S rv   rv   )r4  rE   r  r  s     r@   r6  z*_load_enabled_toolsets.<locals>.<listcomp>  s8     
 
 
9$$\)A)A )A)A)Arw   z4[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: zf[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS (set enabled: true in config.yaml to use): zI[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsetsload_config)_get_platform_toolscliinclude_default_mcp_serverszq[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets)r(   r   r   r  agent.coding_contextr  r1   toolsetsr  r   r  extendr  r6   r&   r7   r8   r  hermes_cli.configr  hermes_cli.tools_configr  r   r   r8  addr2   r  r  sorted)explicitr5  fallback_noticer  	selection
unresolvedr  ignoredr  r  raw_cfgr  rE   
server_cfg	mcp_validdisabledunknownvalidr  r  r  r  r  r  r  r  s                        @@@@@r@   _load_enabled_toolsetsr    s    JNN#8"==CCCHH  H
 CO  	======((%888I$   % 	 	 	D	 -------         S
$0HHHHXHHHHHHHxHHH
 	W"??????  """VVVVVVV " " "!"  W---VVVVzVVV
9999999 		MMMMMG I48IIg4F4FI I	    4 	O!ee	!$	!999999CCCCCC%o''G gkk-88$??M*** 
 %0$5$5$7$7 0 0 j!*d33 &&z~~i'F'FPTUUU 0MM#d)),,,, $$SYY////0  	! 	! 	!I55LLL	! GFFFjFFF	HHHHZHHH
 
 
 
 
"
 
 

 9$ 	[tyyQXGYGY[[Z   
  	)99X&&) ) Z     	L X 	111111??????_cc++-- UMMM
 
 &/
$????$   & DZ   
 tts\   
A! !
A.-A.2A9 9BB0C CCC+I. .&JJ9AN (N<;N<c                 ~    t          t                              | i                               dd          pd          S )Ntool_progress_moder  )r2   rM   r   r)  s    r@   _session_tool_progress_moder     s4    y}}S"%%))*>FFO%PPPrw   c                 (    t          |           dk    S )Nr  r   r)  s    r@   _session_verboser    s    &s++y88rw   c                 (    t          |           dk    S )Nr  r  r)  s    r@   _tool_progress_enabledr  !  s    &s++u44rw   c           	      Z   |                     d          }|r&	 |                                 n# t          $ r Y nw xY w	 t          |d         t	          |                     d          dt                                          }n# t          $ r	 d |d<   Y d S w xY wt          | ||           d S )Nr  r   r  r   )r   r   r1   r   r   r  r  )r  r   r  
new_workers       r@   _restart_slash_workerr  %  s    [[((F 	LLNNNN 	 	 	D	!M"GKK(('>3C3CDD
 


    "& 3,,,,,s   . 
;;AB BBc                    ddl m} t                      }|                    d          }t	          |t
                    si }||d<   | j        |d<   | j        |d<   | j        r| j        |d<   n|	                    dd             ||           d S )Nr   )save_configr   rf  rk  rx  )
r  r
  r   r   r   r   	new_modeltarget_providerrx  r   )r  r
  r5  	model_cfgs       r@   _persist_model_switchr  ;  s    ------
++C  Ii&& !	 G!+Ii"2Ij ( &	*j$'''Krw   Fconfirm_expensive_model	raw_inputr  c                   ddl m}m} ddlm}  ||          \  }}}	}
|st          d          |                    d          }|rMt          |dd          pd}t          |dd          pd}t          |d	d          pd}t          |d
d          pd}n |d           }t          |                    dd          pd          }t                      }t          |                    d	d          pd          }|                    d
d          }t          |          rt          |t                    s|}nt          |pd          }d }d }	 ddlm}m}  |            }|                    d          } ||          }n# t          $ r Y nw xY w |||||||	|||	  	        }|j        st          |j        pd          |s_	 ddlm}  ||j        |j        |j        p||j        p||j                  }n# t          $ r d }Y nw xY w||j        |j        d|j        dS |rq|                    |j        |j        |j        |j        |j                   t7          | |           t9          |           t;          d| t=          ||                     t          |t>                    r$|j        |j        |j        |j        |j        d|d<   |	rtA          |           |j        |j!        pdddS )Nr   )parse_model_flagsswitch_modelresolve_runtime_providermodel value requiredr  rk  r   r   rx  api_key	requested)get_compatible_custom_providersr  	providers)	r  rp  current_modelcurrent_base_urlcurrent_api_key	is_globalrn  user_providerscustom_providerszmodel switch failed)expensive_model_warning)rk  rx  r  
model_infoT)r  r   confirm_requiredconfirm_message)r  new_providerr  rx  ry  r  )r   rk  rx  r  ry  r|  F)r  r   r%  )"hermes_cli.model_switchr  r  hermes_cli.runtime_providerr  r%  r   r   r2   r  callabler   r  r  r  r1   successerror_messagehermes_cli.model_cost_guardr#  r  r  rx  r  r$  r  ry  r  r  r  r  r   r  warning_message)r  r   r  r  r  r  r  model_inputrn  persist_global_force_refreshr  rp  r  r  r  runtime_runtime_key
user_provscustom_provsr  r  r5  r  r#  r   s                             r@   _apply_model_switchr6  M  s    HGGGGGGGDDDDDDEVEVW`EaEaBK"NN 1/000KK  E 6"5*b99?Rw339r"5*b99?R!%B77=2**T:::w{{:r::@bAA&((w{{:r::@bAA {{9b11L!! 	6*\3*G*G 	6*OO!,"4"55O JLRRRRRRRRkmmWW[))
66s;;    \)#)' +!%
 
 
F > H-F1FGGG" 	KKKKKK-- /<,<9/!,  GG  	 	 	GGG	)"?$(#*?	    
B&/N__ 	 	
 	
 	
 	c7+++%g...nc=#@#@AAA '4   
%.~%
 %
 !  &f%%%!)/R!  s$   2E> >
F
F3G6 6HHfocus_topicapprox_tokensbefore_messageshistory_versionc                 0   ddl m} | d         }||f| d         5  t          |                     dg                     }t	          |                     dd                    }d d d            n# 1 swxY w Y   |}t          |          dk     rt          |          }d|fS |4t          |dd	          pd	}	t          |d
d           pd }
 |||	|
          }|                    |d ||pd           \  }}| d         5  t	          |                     dd                    |k    rt          |          }d|fcd d d            S || d<   |dz   | d<   d d d            n# 1 swxY w Y   t          |          }t          |          t          |          z
  |fS )Nr   estimate_request_tokens_roughr  r  r  r:  rn   _cached_system_promptr   r\   system_promptr\   )r8  r7  r   )	agent.model_metadatar=  r	  r   r  r  
_get_usager   _compress_context)r   r7  r8  r9  r:  r=  r  r  usage_sys_prompt_tools
compressed_s                r@   _compress_session_historyrI    s    CBBBBBGE
 /"9^$ 	E 	E"7;;y"#=#=>>O!'++.?"C"CDDO	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E G
7||a5!!%x e%<bAAGR..6$55;f
 
 
 ++#'4	 ,  MJ 
	  9 9w{{,a0011_DD u%%Ee89 9 9 9 9 9 9 9 (	%4q%8!"9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 uEw<<#j//)500s*   AA..A25A2=:EEE!$E!Tclear_pending_titlerestart_slash_workerrK  rL  c                X    |                     d          }t          |dd          pd}|                     dd          pd}|r||k    rdS 	 ddlm}m}m}	m}
m} 	  ||           n# t          $ r Y nw xY w||d<   	  |	|          }n# t          $ r d}Y nw xY w|r(	  ||            ||           n# t          $ r Y nw xY w	  |
| fd	           n# t          $ r Y nw xY wn# t          $ r ||d<   Y nw xY w|rd|d
<   |r$	 t           |           dS # t          $ r Y dS w xY wdS )a  Re-anchor session_key when AIAgent._compress_context rotates session_id.

    AIAgent._compress_context ends the current SessionDB session and creates
    a new continuation session, rotating ``agent.session_id``.  The TUI
    gateway keeps the gateway-side ``session_key`` separate (used for
    approval routing, slash worker init, DB title/history lookups, yolo
    state).  Without this sync, those operations would target the ended
    parent session while the agent writes to the new continuation session.

    Policy flags:
        clear_pending_title: True for manual /compress (title belongs to old
            session). False for post-turn auto-compression (preserve user
            intent so pending_title can be applied to the continuation).
        restart_slash_worker: True for manual /compress and post-turn
            auto-compression (worker holds stale session key). False only
            if the caller manages the worker lifecycle separately.
    r  r   Nr   r   r   )disable_session_yoloenable_session_yolois_session_yolo_enabledr  r  Fc                 &    t          d|           S r  r  r  s    r@   rx   z2_sync_session_key_after_compress.<locals>.<lambda>9  s    U#5sDAA rw   pending_title)
r   r   r  rN  rO  rP  r  r  r1   r  )r  r   rK  rL  r  new_session_idold_keyrN  rO  rP  r  r  yolo_was_ons   `            r@    _sync_session_key_after_compressrV     sW   0 KK  EUL$77=2Nkk-,,2G ^w66#0	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
	%%g.... 	 	 	D	!/	 11'::KK 	  	  	 KKK	  	##N333$$W----   	##AAAA     	 	 	D	 0 0 0 "0	0  (#'  	!#w///// 	 	 	DD	 s   C( A( 'C( (
A52C( 4A55C( >B
 	C( 
BC( BC( B6 5C( 6
C C( CC( C C( 
C$!C( #C$$C( (C:9C:D 
D'&D'c                 $    d& fd	}t           dd          pd |dd           |dd           |d           |d	           |d
           |d           |d           |d           |d          d
}t           dd           }|rt          |dd          p	|d         pd}t          |dd          pd}|r>||d<   ||d<   t          dt          dt          ||z  dz                                |d<   t          |dd          pd|d<   	 ddlm}m}  ||d          ||d         |d         |d         |d                   t           dd           t           d d           !          }|j        |d"<   |j        t          |j                  |d#<   n# t          $ r Y nw xY wt          t          j                            d$                    r:	                                  }	|	t!          |	          |d%<   n# t          $ r Y nw xY w|S )'Nc                 P    t          | d          p|rt          |d          ndS )Nr   r   )kfbr  s     r@   rx   z_get_usage.<locals>.<lambda>M  s/    75!Q//WR4VGE2q4I4I4IUV rw   r   r   session_input_tokenssession_prompt_tokenssession_output_tokenssession_completion_tokenssession_cache_read_tokenssession_cache_write_tokenssession_reasoning_tokenssession_total_tokenssession_api_calls)
r   inputr   
cache_readcache_write	reasoningprompt
completiontotalcallscontext_compressorlast_prompt_tokensr   rk  context_lengthcontext_usedcontext_maxd   context_percentcompression_countcompressions)CanonicalUsageestimate_usage_costre  r   rf  rg  )input_tokensoutput_tokenscache_read_tokenscache_write_tokensrk  rx  )rk  rx  cost_statuscost_usdHERMES_DEV_CREDITSdev_credits_spent_microsr   )r   r  minroundagent.usage_pricingrv  rw  r  
amount_usdrK  r1   r   r(   r   r   get_credits_spent_microsr  )
r  grD  compctx_usedctx_maxrv  rw  costspents
   `         r@   rB  rB  L  s   WWWWWA,,2)+BCC!+-HIIa344q566Q122!+,,a344)**&'' E 5.55D K4!5q99PU7^Pq$ 0!449 	Y$,E.!#*E- '*1c#uX=ORU=U7V7V.W.W'X'XE#$ '.A1 E E JnKKKKKKKK""'NN"7^#Ho"'"5#(#7	   UJ55UJ55

 

 

  ${m?& %do 6 6E*    rz~~&:;;<< 	2244E 47JJ01 	 	 	D	Ls%   BF 
F'&F'(H   
HHc                     	 t          | dd          pd}t          | dd          pd}|r|dk    rd| dS n# t          $ r Y nw xY wdS )uE   Light credential check at session creation — returns warning or ''.r  r   rk  no-key-requiredz$No API key configured for provider 'z'. First message will fail.)r   r1   )r  r  rk  s      r@   _probe_credentialsr    s    eY++1r5*b117R 	`c..._(____ /   2s   37 
AAc                    t          | t                    sdS g }t          d |                                 D                       }|sn8d                    d |D                       }|                    d| d           |                     d          }|                     d          }t          |t                    rt          |                    d	d          pd                                          	                                }|rC|d
vr?t          |t                    r*|                    d          |                    d           d                    |                                          S )ut   Flag bare YAML keys (`agent:` with no value → None) that silently
    drop nested settings. Returns warning or ''.r   c              3   $   K   | ]\  }}||V  d S r   rv   r4  rZ  vs      r@   r  z'_probe_config_health.<locals>.<genexpr>  s&      >>TQAIqIIII>>rw   r  c              3   "   K   | ]
}d | d V  dS `Nrv   )r4  rZ  s     r@   r  z'_probe_config_health.<locals>.<genexpr>  s*      55aQ555555rw   z"config.yaml has empty section(s): uZ   . Remove the line(s) or set them to `{}` — empty sections silently drop nested settings.r   r  personality>   r  rf  neutralpersonalitiesNzj`display.personality` is set but `agent.personalities` is empty/null; personality overlay will be skipped. )
r   r   r  r8  r&   appendr   r2   r3   r   )r5  warnings	null_keysr  display_cfg	agent_cfgr  s          r@   r  r    s}    c4   rH>>SYY[[>>>>>I 
yy55955555= = = =	
 	
 	

 '')$$K  I+t$$ +//-<<BCCIIKKQQSS		#AAA9d++ Bo..6OO7   88H##%%%rw   c                  J    	 ddl m}   |             pdS # t          $ r Y dS w xY w)Nr   get_active_profile_namerf  )hermes_cli.profilesr  r1   r  s    r@   _current_profile_namer    sO    ??????&&((5I5   yys    
""c                 :   |7t                                           D ]}|                    d          | u r|} nt          |          }t	                                          d          pi                     d          pd}|pi                     d|          }t          | dd           }d}t          |t                    r<|                    d          dur%t          |                    dd          pd          }t          | d	d           pd}d}		 d
dl	m
}
m}m} |pi                     d          }|rt           ||                    nd}t          |
          p|p |            dk    }	n# t          $ r d}	Y nw xY wi dt          | dd          dt          | dd          d|d	|d|dk    d|	di di d|dt          |          dt          |pd          dt          |pi                     d                    dt           dddddd ddt#          |           t%                      d}	 d
dlm}m} ||d<   ||d<   n# t          $ r Y nw xY w	 d
d lm} t          | dg           pg D ]J}|d!         d"         }|d                              ||          pd#g                               |           Kn# t          $ r Y nw xY w	 d
d$lm}  |            |d<   n# t          $ r Y nw xY w	 d
d%lm}  |            |d&<   n# t          $ r g |d&<   Y nw xY w	 t          | d'd          pd|d(<   n# t          $ r Y nw xY w	 d
d)lm} d
d*lm }  |d+,          |d<    |            |d<   n# t          $ r Y nw xY wtC          |           }|r||d-<   |S ).Nr  r   r  r   rz  r  Fr  r{  r   )_YOLO_MODE_FROZEN_get_approval_moderP  r   r  r   rk  r  r  r  yolor\   skillsr   r	  r   desktop_contractversionrelease_dateupdate_behindupdate_command)rD  profile_name)__version____release_date__)get_toolset_for_toolfunctionrE   otherget_available_skills)get_mcp_statusr  r>  r@  )get_update_result)recommended_update_command      ?r   credential_warning)"rM   r;  r   r  r   r   r   r   r2   r  r  r  rP  r   r1   r  DESKTOP_BACKEND_CONTRACTrB  r  rh  r  r  model_toolsr  r  r  hermes_cli.bannerr  tools.mcp_toolr  r  r  r  r  )r  r   	candidater   cfg_personalityr  rz  r  r{  r  r  r  rP  r   session_yolor  r  r  r  r  rE   r  r  r  r  warns                             r@   r  r    s   "))++ 	 	I}}W%%..# / w

C!	228b==mLLRPRO=b%%m_EEKu&8$??#T**I  ++588/33HbAAGRHH5.$77=2L D	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 }"))-88EP[t33K@@AAAV[%&&W,W:L:L:N:NRW:W   ,,GE:r22 	, 		
 	
* 	 	 	" 	s 	%c** 	s;,"-- 	4B++I6677 	4 	2 	  	!" 	"#$ E""-//'  D*<<<<<<<<%Y/^   	444444,,2 	 	AZ=(DM$$%9%9$%?%?%J7BOOVV   	
    ::::::--//X   !111111,n..] ! ! ! ]! '/F K K Qr_   777777@@@@@@ 1 1# > > >_!;!;!=!=   e$$D *%)!"Ks   AE0 0E?>E?;I 
IIA$K 
KKK) )
K65K6:L L L $L; ;
MM(M5 5
NNrF   c                 R    	 ddl m}  || |d          pdS # t          $ r Y dS w xY w)Nr   )build_tool_previewP   )max_lenr   )agent.displayr  r1   )rE   rF   r  s      r@   	_tool_ctxr  (	  sX    444444!!$b999?R?   rrs    
&&     c                    t          |           t          k    r |                     d          t          k     r| S t          |           }d}t	          t                    D ](}|                     dd|          }|dk     rd} n|dz   })|}t          |t          |           t          z
            }||k    r;|                     d|          }d|cxk    rt          |           dz
  k     rn n|dz   }| |d                                          }t          dt          |           t          |          z
            }| d |                             d          }|r
d| d| d}	nd| d}	|	 | S )Nr   r   r   z[showing verbose tail; omitted z	 lines / z chars]
)	r  _TUI_VERBOSE_TEXT_MAX_CHARScount_TUI_VERBOSE_TEXT_MAX_LINESrangerfindr  findlstrip)
r   idxr   rH  
line_start
next_breaktailomitted_charsomitted_lineslabels
             r@   _cap_tui_verbose_textr  <	  s   D		000JJt:::
d))CE.//  jjq#&&77EEaJ
CII(CCDDEzYYtU++

****SYY]*****NE<  D3t99s4yy011M%L&&t,,M K@@ @'4@ @ @ 	
 K-JJJTrw   c                     	 ddl m}  |t          |           d          }n# t          $ r Y dS w xY wt	          |          S )Nr   )redact_sensitive_textT)forcer   )agent.redactr  r2   r1   r  )r   r  redacteds      r@   _redact_tui_verbose_textr  `	  sf    666666((T$???   rr ***s    # 
11c                     	 t          j        | pi ddt                    }n!# t          $ r t          | pi           }Y nw xY wt	          |          S )Nrk   F)indentensure_asciirf  )r   r   r2   r1   r  )rF   r   s     r@   _tool_args_textr  j	  sa    jAE3OOO   $*"oo#C(((s   " A A c                     	 ddl m}  ||           }n# t          $ r t          |           }Y nw xY wt	          |          S )Nr   )_multimodal_text_summary)agent.tool_dispatch_helpersr  r1   r2   r  )r  r  r   s      r@   _tool_result_textr  r	  sc    HHHHHH&&v..   &kk#C(((s    00secondsc                     | dS | dk     r| ddS | dk     rt          |            dS t          t          t          |                     d          \  }}|r| d| dn| dS )Nr   r   z.1fr5  <   zm rg  )r  divmodr  )r  minssecss      r@   _fmt_tool_durationr  |	  s    r||     ||..####E'NN++R00JD$!%5ddd:::5rw   c                     | }|D ]/}t          |t                    s d S |                    |          }0t          |t                    rt	          |          nd S r   )r   r   r   r	  r  )r{   r*   curr  s       r@   _count_listr  	  s_    
C  #t$$ 	44ggcll!#t,,63s888$6rw   
duration_sc                    	 t          j        |          }n# t          $ r d }Y nw xY wt          |          }|rd| nd}d }| dk    r9t	          |t
                    r$t          |dd          }|d| d|dk    rd	nd
 }nN| dk    rHt	          |t
                    r3t          |d          pt          |dd          }|d| d|dk    rdnd }t	          |t
                    rS|                    d          r>t          |                    d          pd          	                                }|r| | S |r| | nd S )N in r   
web_searchr}  webzDid r  r   searchsearchesweb_extractresultsz
Extracted pagepagesfallback_warning)
r   r   r1   r  r   r   r  r   r2   r3   )	rE   r  r  r}  dursuffixr   nr   s	            r@   _tool_summaryr  	  s   z&!!    Z
(
(C (\C\\\bFD|
4 6 6fe,,=B!BB!q&&hhjBBD			:dD#9#9	i((PKfi,P,P=CCCa1ffFF'CCD$ ($((+=">"> (dhh1228b99??AA 	('v''' $.dF$.s    &&tool_call_idc                    t                               |           }|i	 ddlm}  |||          }|||                    di           |<   n# t
          $ r Y nw xY wt          j                    |                    di           |<   t          |           rL||t          ||          d}t          |           rt          |          }|r||d<   t          d| |           d S d S )Nr   )capture_local_edit_snapshotedit_snapshotstool_started_at)tool_idrE   context	args_textz
tool.start)rM   r   r  r  r  r1   r/   r  r  r  r  r  )	r  r  rE   rF   r   r  snapshotr  r	  s	            r@   _on_tool_startr  	  s)   mmC  G	AAAAAA224>>H#IQ""#3R88F 	 	 	D	BF)++,b11,?c"" *# t,,
 

 C   	1'--I 1'0$ 	lC)))))* *s   -A 
AAc                    |||d}t                               |           }d }d }|T|                    di                               |d           }|                    di                               |d           }|rt	          j                    |z
  nd }	|	|	|d<   	 t          j        |          |d<   n# t          $ r ||d<   Y nw xY wt          |||	          }
|
r|
|d<   t          |           rt          |          }|r||d<   |dk    r{	 t          j        |          }t          |t                    r@t          |                    d	          t                    r|                    d	          |d	<   n# t          $ r Y nw xY w	 d
dlm} g } ||||||j                  rd                    |          |d<   n# t          $ r Y nw xY wt%          |           s|                    d          rt'          d| |           d S d S )N)r  rE   rF   r  r  r  r  summaryresult_texttodotodosr   )render_edit_diff_with_delta)function_argsr
  print_fnr   inline_diffztool.complete)rM   r   r  r   r/   r   r   r1   r  r  r  r   r   r	  r  r  r  r&   r  r  )r  r  rE   rF   r  r  r   r
  
started_atr  r  r  r}  r  rendereds                  r@   _on_tool_completer  	  s   &dCCGmmC  GHJ%%&6;;??dSS''(92>>BB<QUVV
-7Az))TJ *# Jv.. # # #"#D&*55G %$	 1'// 	1%0GM"v~~	:f%%D$%% 5*TXXg5F5F*M*M 5#'88G#4#4  	 	 	D	====== &&_
 
 
 	9 &*YYx%8%8GM"   c"" -gkk-&@&@ -osG,,,,,- -s7   B5 5CCA)E8 8
FF	5F? ?
GGpreview_argsc                    t          |           sd S |dk    r|rd S |dk    r:|r8dt          |          i}t          |           rd|d<   t          d| |           d S |                    d          rst          |                    d          pd          t          |                    d	          pd
          t          |                    d          pd          d}|                    d          rt          |d                   |d<   |                    d          rt          |d                   |d<   |                    d          t          |d                   |d<   |                    d          rt          |d                   |d<   |                    d          t          |d                   |d<   |                    d          rd |d         D             |d<   dD ]D}|                    |          }|+	 t          |          ||<   -# t          t          f$ r Y @w xY wE|                    d          1	 t          |d                   |d<   n# t          t          f$ r Y nw xY w|                    d          rd |d         D             |d<   |                    d          rd |d         D             |d<   |                    d          rt          |d                   |d<   |rt          |          |d<   |rt          |          |d<   |                    d          rt          |d                   |d<   |                    d          rt          |d                   |d<   |                    d          t          |d                   |d<   |r*|d k    r$t          |          |d!<   t          |          |d<   t          || |           d S d S )"Nztool.startedzreasoning.availabler   Tr  z	subagent.goalr   
task_countr   
task_indexr   )r  r  r  subagent_id	parent_iddepthr   
tool_countr  c                 ,    g | ]}t          |          S rv   r2   r4  r  s     r@   r6  z%_on_tool_progress.<locals>.<listcomp>
  s    "G"G"Ga3q66"G"G"Grw   )rx  ry  reasoning_tokens	api_callsr}  
files_readc                 ,    g | ]}t          |          S rv   r#  r4  r|  s     r@   r6  z%_on_tool_progress.<locals>.<listcomp>2
  s    $K$K$KSVV$K$K$Krw   files_writtenc                 ,    g | ]}t          |          S rv   r#  r)  s     r@   r6  z%_on_tool_progress.<locals>.<listcomp>4
  s    'Q'Q'Q1A'Q'Q'Qrw   output_tail	tool_namer  r  duration_secondszsubagent.tooltool_preview)r  r2   r  r  
startswithr   r  	TypeErrorr%  rK  r	  )	r  r   rE   r  r  _kwargsr  int_keyvals	            r@   _on_tool_progressr5  	  sY    "#&& ^### 	***w*&,c'll%;C   	&!%GI#S'222[)) 9(F++1r22gkk,77<1==gkk,77<1==
 
 ;;}%% 	A%()?%@%@GM";;{## 	=#&w{';#<#<GK ;;w+"77#344GG;;w 	5"77#344GG;;|$$0$'(=$>$>GL!;;z"" 	H"G"G7:3F"G"G"GGJ
 	 	G ++g&&C'*3xxGG$$!:.   D 
 ;;z"".&+GJ,?&@&@
##z*   ;;|$$ 	L$K$KW\5J$K$K$KGL!;;'' 	R'Q'Q8P'Q'Q'QGO$;;}%% 	B%)'-*@%A%AGM" 	-#&t99GK  	+!'llGFO;;x   	7 #GH$5 6 6GH;;y!! 	9!$WY%7!8!8GI;;)**6*/8J0K*L*LG&' 	+z_44&)'llGN#!'llGFOj#w'''''s9( 9(s$   HH,+H,I I32I3c                 h      fd fdd fd	 fd fd fdd fd	 fd fd	 fd
d fd	dS )Nc                 (    t          | ||          S r   )r  )tc_idrE   rF   r  s      r@   rx   z_agent_cbs.<locals>.<lambda>I
  s    d:
 :
 rw   c                 *    t          | |||          S r   )r  )r8  rE   rF   r  r  s       r@   rx   z_agent_cbs.<locals>.<lambda>L
  s    DUdFE
 E
 rw   c                 &    t          | |||fi |S r   )r5  )r   rE   r  rF   kwargsr  s        r@   rx   z_agent_cbs.<locals>.<lambda>O
  s.    ctT7Dd
 d
4:d
 d
 rw   c                 H    t                    ot          dd| i          S )Nztool.generatingrE   )r  r  )rE   r  s    r@   rx   z_agent_cbs.<locals>.<lambda>R
  s,    *@*E*E +:#S64.99 rw   c                 *    t          dd| i          S )Nzthinking.deltar   r  r   r  s    r@   rx   z_agent_cbs.<locals>.<lambda>T
  s    %0@#PT~*V*V rw   c                 T    t          dd| it                    rddini           S )Nzreasoning.deltar   r  T)r  r  r>  s    r@   rx   z_agent_cbs.<locals>.<lambda>U
  s<    5TR3CC3H3HPy$//bR,
 ,
 rw   c                 b    t          t          |           |d nt          |                    S r   )r  r2   )r  r   r  s     r@   rx   z_agent_cbs.<locals>.<lambda>Z
  s,    >TDLDDc$ii4
 4
 rw   c                 p    t          d| j        | j        | j        | j        | j        | j        d          S )Nznotification.show)r   levelr  ttl_msr  r   )r  r   rB  r  rC  r  r   )r   r  s    r@   rx   z_agent_cbs.<locals>.<lambda>`
  s?    U(ud &
 &
 rw   c                 *    t          dd| i          S )Nznotification.clearr  r  )r  r  s    r@   rx   z_agent_cbs.<locals>.<lambda>l
  s    U #s|.
 .
 rw   c                 ,    t          d| |d          S )Nzclarify.request)questionchoicesrS  )qcr  s     r@   rx   z_agent_cbs.<locals>.<lambda>o
  s     sq$A$A*
 *
 rw   c                 J    t          dd d| fd|ffD             d          S )Nzterminal.read.requestc                     i | ]
\  }}|||S r   rv   r  s      r@   
<dictcomp>z0_agent_cbs.<locals>.<lambda>.<locals>.<dictcomp>w
  s    TTTdaamQmmmrw   r   r     r   rH  )r   r  r  s     r@   rx   z_agent_cbs.<locals>.<lambda>t
  sB    #TT/'51ABTTT	B
 B
 B
 rw   )tool_start_callbacktool_complete_callbacktool_progress_callbacktool_gen_callbackthinking_callbackreasoning_callbackstatus_callbacknotice_callbacknotice_clear_callbackclarify_callbackread_terminal_callbackNNNr   r   rv   r)  s   `r@   
_agent_cbsr[  G
  s     
  
  
  
#
 #
 #
 #
#
 #
 #
 #
 #
: : : :VVVV
 
 
 


 
 
 
 

 
 
 
"
 "
 "
 "

 
 
 

#
 #
 #
 #
 #
Y2 2 2rw   c                 ^     ddl m} ddlm}  | fd           d fd	} ||           d S )Nr   )set_sudo_password_callback)set_secret_capture_callbackc                  *    t          d i d          S )Nzsudo.requestx   r   rH  r)  s   r@   rx   z!_wire_callbacks.<locals>.<lambda>
  s    vnc2s'S'S'S rw   c                     || d}|r||d<   t          d|          }|sd| ddddS dd	lm} i  || |          dd
dS )N)ri  env_varr   zsecret.requestTFskipped)r+  	stored_as	validatedrc  r  r   )save_env_value_securer   )rc  r  )rS  r  rf  )rb  ri  r   plr4  rf  r  s         r@   	secret_cbz"_wire_callbacks.<locals>.secret_cb
  s    733 	&%BzN%sB// 	$"$   	<;;;;;
##GS11

 
 
 	
rw   r   )r  r]  tools.skills_toolr^  )r  r]  r^  rh  s   `   r@   r  r  }
  sy    >>>>>>======SSSSTTT
 
 
 
 
 
*  	*****rw   c                    t          | t                    r|                     dd          g}|                     d          r|                    d| d                     |                     d          r|                    d| d                     d                    d |D                       S t          |           S )	Nr@  r   tonezTone: stylezStyle: r   c              3      K   | ]}||V  	d S r   rv   r)  s     r@   r  z-_render_personality_prompt.<locals>.<genexpr>
  s'      //qQ///////rw   )r   r   r   r  r&   r2   )r  partss     r@   _render_personality_promptro  
  s    % 0?B//099V 	3LL1%-1122299W 	5LL35>33444yy//E//////u::rw   c                    	 ddl m}  |                                d          pi                     di           pi S # t          $ r 	 ddlm}  |                                d          pi                     di           pi cY S # t          $ rB | pt                      } |                     d          pi                     di           pi cY cY S w xY ww xY w)Nr   )load_cli_configr  r  r  )r  rq  r   r1   r  r  r   )r5  rq  _load_full_cfgs      r@   _available_personalitiesrs  
  s*   K''''''!!%%g..4"99/2NNTRTT K K K	KGGGGGG"N$$((117R<<_bQQWUWWWW 	K 	K 	K$CGGG$$*//DDJJJJJJ	KKs.   := 
C:BCACCCCr  c                 z   t          | pd                                          }|                                }|r|dv rdS t          |          }||vrSt	          |          }d                    d |D                       }d| d}|r	|d| z  }n|d	z  }t          |          |t          ||                   fS )
Nr   >   r  rf  r  )r   r   r  c              3   "   K   | ]
}d | d V  dS r  rv   )r4  r   s     r@   r  z(_validate_personality.<locals>.<genexpr>
  s*      661h!hhh666666rw   zUnknown personality: `z`.z

Available: `none`, z

No personalities configured.)r2   r3   r   rs  r  r&   r%  ro  )r  r5  r   rE   r  names	availablebases           r@   _validate_personalityry  
  s    
ekr


 
 
"
"C99;;D 4999v,S11M=  }%%II6666666	//// 	79i999DD66D+M$,?@@@@rw   c                    | dS t          | t                    r|                                 S t          | t                    rd                    d | D                       S t          |                                           S )zHNormalize config prompt values from YAML before handing them to AIAgent.Nr   r   c              3      K   | ]F}t          |                                          #t          |                                          V  Gd S r   r2   r3   r  s     r@   r  z_prompt_text.<locals>.<genexpr>
  sG      RRtD		@Q@QRT**RRRRRRrw   )r   r2   r3   r	  r&   r  s    r@   _prompt_textr~  
  sx    }r% {{}}% SyyRRuRRRRRRu::rw   r   
new_promptr  c                    |sdS ||d<   |                     d          }|r|pd|_        |rd| d}nd}|d         5  |d	                             d
|d           t          |                     dd                    dz   |d<   ddd           n# 1 swxY w Y   t	          |          }t          d| |           d|fS dS )u  Apply a personality change to an existing session without resetting history.

    Updates the agent's ephemeral system prompt in-place so the new personality
    takes effect on the next turn.  The cached base system prompt is left intact
    (ephemeral_system_prompt is appended at API-call time, not baked into the
    cache), which preserves prompt-cache hits.

    Also injects a system-role marker into the conversation history so the model
    knows to pivot its style from this point forward (without this, LLMs tend to
    continue the tone established by earlier messages in the transcript).

    Returns (history_reset, info) — history_reset is always False since we
    preserve the conversation.
    )FNr  r  Nz[System: The user has changed the assistant's personality. From this point forward, adopt the following persona and respond accordingly: ]zv[System: The user has cleared the personality overlay. From this point forward, respond in your normal default style.]r  r  userrolecontentr:  r   r   r  F)r   ephemeral_system_promptr  r  r  r  )r  r   r  r  r  markerr  s          r@   _apply_personality_to_sessionr  
  s`   "  {(GMKK  E (2(:d%  
	. *. . . FR  ^$ 	T 	TI%%v&&I&IJJJ),W[[9JA-N-N)O)ORS)SG%&	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T U##nc4(((d{;s   ABBBrf  c                 B   	 t          t          j                            dd          pd          }|dk    r|S n# t          t
          f$ r Y nw xY w|                     d          pi }t          |                    d          p|                     d          p|          S )NHERMES_TUI_MAX_TURNSr   r   r  	max_turns)r  r(   r   r   r1  r%  )r5  rf  env_maxr  s       r@   _cfg_max_turnsr    s    bjnn%;R@@EAFFQ;;N z"     &BIy}}[))LSWW[-A-ALWMMMs   6: AAc                  F   t           j                            dd          } g }t                      }|                     dd                              d          D ]F}|                                }|r.||vr*|                    |           |                    |           G|S )NHERMES_TUI_SKILLSr   r   r  )	r(   r   r   r  r  r  r3   r  r  )r   r  seenpartr  s        r@   _parse_tui_skills_envr    s    
*..,b
1
1CFUUDD#&&,,S11    zz|| 	 D$$HHTNNNMM$Mrw   c                  <    ddl m}   | t                                S )a  Return the configured fallback chain for TUI-created agents.

    Delegates to the shared ``get_fallback_chain`` helper so the TUI path
    stays in parity with ``HermesCLI.__init__`` and ``gateway/run.py``:
    ``fallback_providers`` is the primary source of truth and keeps its
    order, with legacy ``fallback_model`` entries merged in afterwards
    (deduped on provider/model/base_url).
    r   get_fallback_chain)hermes_cli.fallback_configr  r   r  s    r@   _load_fallback_modelr    s+     >=====ikk***rw   c                     t          | d          rt          | d          pg S t          | d          rt          | dd          S t                      S )zOReturn an agent's fallback chain without rehydrating deliberately empty chains._fallback_chain_fallback_modelN)r
  r   r  )r  s    r@   _agent_fallback_modelr  '  s]    u'(( 7u/006B6u'(( 7u/666!!!rw   task_idc                    t                      }i dt          | dd           pd dt          | dd           pd dt          | dd           pd dt          | dd           pd dt          | dd           pd dt          | dd           pd dt          | dd           pt                      dt          |d	          d
t          | d
d           pt	                      dddddt          | dd           pd dt          | dd           dt          | dd           dt          | dd           dt          | dd           dt          | dd          t          | dd           t          | dd           |t          | dd           pt                      t          | dd           pt                      t          t          | di           pi           dt                      t          |           d	S )Nrx  r  rk  ry  acp_commandacp_argsr   max_iterations   enabled_toolsets
quiet_modeTverbose_loggingFr  providers_allowedproviders_ignoredproviders_orderprovider_sortprovider_require_parametersprovider_data_collectionopenrouter_min_coding_scorerz  r{  request_overridesr   )	r  r  r   rz  r{  r  r   r  fallback_model)
r   r   r  r  r  r  r  r   r  r  )r  r  r5  s      r@   _background_agent_kwargsr  0  sy   
++C GE:t44< 75)T22:d  	GE:t44<  	GE:t44<	 
 	wumT::Bd  	GE:t44<  	..B.2B2B  	.b11  	GE+=tDD $!##  	d  	5  	"752KT#R#R $  	WU,?FF   	WU,?FF! " 	75*;TBB# $ 	>>% & 	&w0%(
 (
' , %,E3Mt$T$T'.u6SUY'Z'Z#E+=tDD $!##~t<<T@R@T@T!'%1Db"I"I"ORPPii/66?       rw   c                 \    t          | |          }|                    ddgd dd           |S )Nru  r#   T)r  r  skip_memory)r  update)r  r  r;  s      r@   _ephemeral_preview_agent_kwargsr  V  sF    %eW55F
MM!+V 4	
 	
   Mrw        max_messagesmax_tool_charsc                    	 | d         5  t          |                     dg           pg           }ddd           n# 1 swxY w Y   n5# t          $ r( t          |                     dg           pg           }Y nw xY w|sg S d}t          t	          |          dz
  dd          D ]%}||                             d          dk    r|} n&t          dt	          |          |z
            }|t          ||          }g }||d         D ]}t          |t                    s|                    d          }	|	d	vr2d
 |	                                D             }
|	dk    rY |
j        d          }t          |t                    r4t	          |          |k    r!|d|         dt	          |           dz   |
d<   |                    |
           |S )u  Distill the parent session's recent history into a context the
    ephemeral preview-restart agent can actually use.

    The restart agent has no idea what app the user was building, what
    server they ran, what cwd was active, or which port belongs to which
    project. Without this, it would take the bare URL + console logs and
    guess — usually starting the wrong thing.

    We keep the last ``max_messages`` messages from the parent session so
    the restart agent sees recent user prompts, assistant replies, and
    most importantly any terminal/tool calls. Tool result payloads are
    truncated so we don't blow the context window with file dumps.
    r  r  Nr   r  r  r  r   )r  	assistanttoolsystemc                 &    i | ]\  }}|d k    ||S )rh  rv   r  s      r@   rM  z,_preview_restart_history.<locals>.<dictcomp>  s(    AAAA[0@0@10@0@0@rw   r  r  z
... (truncated, original z chars))r	  r   r1   r  r  r  r  r   r   r8  r2   r  )r   r  r  r  last_user_idxr  r   trimmedr   r  r   r  s               r@   _preview_restart_historyr  b  sS   9^$ 	= 	=7;;y"55;<<G	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 9 9 9w{{9b117R889  	
 MS\\A%r2..  3<F##v--ME . 3w<<,.//E E=))Guvv  #t$$ 	wwv>>>AAAAA 6>>dhy))G'3'' CLL>,I,IO^O,ICLLIIIJ Y 	tNs1   A &<A A  A A A /A:9A:c                    	 t          j        |          }n# t          $ r Y dS w xY wt          |t                    sdS | dk    rt          |                    d          pd                                          }|                    d          }|r
|dd          S |                    d          rd|                    d           S |d| S t          |                    d	          pd                                          d d
         S )Nr   ru  r   	exit_codeiPr   zBackground process started: zterminal exited with code r   r  )r   r   r1   r   r   r2   r   r3   )rE   r  r}  r   r  s        r@   _preview_tool_result_previewr    s&   z&!!   rr dD!! rzTXXh''-2..4466HH[))	 	"%&&>!88L!! 	KJ$((<2H2HJJJ ;	;;;txx  &B''--//66s    
%%parentc           
      *    i ddt           dt           dd f fddt           dt           dt          dd ffd	}dt           dt           d
t          dt           dd f
fd}ddt           dt           d z  dt           d z  dd ffd}|||fddfd	dS )Nr  r  rB  r|   c                     t          | pd                                          }|rt          d||d           d S d S )Nr   preview.restart.progress)r  rB  r   )r2   r3   r  )r  rB  r   r  r  s      r@   progressz,_preview_restart_callbacks.<locals>.progress  sZ    7=b!!'')) 	j,f'TYcg6h6hiiiii	j 	jrw   r  rE   rF   c                     t          j                     | <   t          ||          } d| |rd| nd            d S )NzRunning r!   r   )r/   r  )r  rE   rF   r  r  r  s       r@   
tool_startz._preview_restart_callbacks.<locals>.tool_start  sU    #'9;;
< d##=D=";*s***==>>>>>rw   r  r  c                     t          j                                         | t          j                               z
  }t          |||          pd| |rdt          |           nd }t	          ||          } ||rd| ndz              d S )Nz	Finished r  r   r   )r/   r   r  r  r  )	r  rE   r  r  r  r  r   r  r  s	          r@   tool_completez1_preview_restart_callbacks.<locals>.tool_complete  s    Y[[:>>,	#L#LL
fj99  O  >O  >O  {E  PMOvVhisVtVtOvOvOv  KM  >O  >O-dF;;V;MMMM<=====rw   r   r  c                     |r t          |                     d S |r& |                     dd           d|            d S d S )Nrq  r  r!   )r2   r  )r   rE   r  r2  r  s       r@   r  z1_preview_restart_callbacks.<locals>.tool_progress  sq     	@HS\\""""" 	@H
**344>>>>?????	@ 	@rw   c                       d|            S )Nz
Preparing rv   )rE   r  s    r@   rx   z,_preview_restart_callbacks.<locals>.<lambda>  s    ((3F3F3F*G*G rw   c                 "     ||n|           S r   rv   )r  r   r  s     r@   rx   z,_preview_restart_callbacks.<locals>.<lambda>  s    88DDTDDZ^3_3_ rw   )rO  rP  rQ  rR  rU  )r  r   r   )r2   r   )r  r  r  r  r  r  r  s   ``   @@r@   _preview_restart_callbacksr    sa   #%Jj j# jc jt j j j j j j j
? ?C ?t ? ? ? ? ? ? ? ?
>C >s >4 > >QU > > > > > > >@ @# @S4Z @t @jn @ @ @ @ @ @  *"/"/GGGG_____  rw   c                 \   t          |d                   }	 t          | |d         |d         |                    d                    }t          |           n# t          |           w xY w||d<   g |d<   i |d<   d|d<   d	|d
<   t	                      |d<   t                      |d<   i |d<   |d         5  g |d<   t          |                    dd                    dz   |d<   d d d            n# 1 swxY w Y   t          ||          }t          d| |           t          | |           |S )Nr   r|  )r   r|  r  attached_imagesr  r   image_counterFr   r  r  r  r  r  r:  r   r  )
r  r  r   r  r  r  r  r  r  r  )r  r   r  	new_agentr  s        r@   _reset_session_agentr    s   !'-"899F'M"}-
 #;;'788	
 	
 	
	 	v&&&&v&&&& GG!#G "G GOGI 4 6 6G$<$>$>G !!#G		  P P	%(5F)J)J%K%Ka%O!"P P P P P P P P P P P P P P P G,,D	.#t$$$#w'''Ks   2A A*5/C00C47C4r  r|  r}  r~  r  c           
         ddl m} ddlm}	 	 ddlm}
  |
             n# t          $ r Y nw xY w	 ddlm}
  |
             n# t          $ r Y nw xY wt                      }|	                    d          pi }t          |	                    dd                    }t                      }|ruddlm}  |||p|	          \  }}}|r%t          d
d                    |                     |r3d                    d ||fD                                                       }t#          |t$                    r|	                    d          rt'          |	                    d          pd          }|	                    d          p|pd }|	                    d          }|	                    d          }|	                    d          } |	||pd           }|r||d<   |r||d<   |r||d<   n=t)                      \  }}t#          |t&                    r|r|}|r|} |	||pd           } |d/i d|dt+          |d          d|	                    d          d|	                    d          d|	                    d          d|	                    d          d|	                    d          d|	                    d          d|	                    d          ddddd||nt-                      d ||nt/                      d!t1                      d"d#d$|p|d%||nt3                      d&|pd d't5          t6          j        	                    d(                    d)t5          t6          j        	                    d*                    d+t5          t6          j        	                    d,                    d-t5          t6          j        	                    d,                    d.t;                      t=          |           S )0Nr   AIAgentr  )wait_for_mcp_discoveryr  r@  r   )build_preloaded_skills_promptr  zUnknown skill(s): r  

c              3      K   | ]}||V  	d S r   rv   )r4  r  s     r@   r  z_make_agent.<locals>.<genexpr>#  s;       ( (4(( ( ( ( ( (rw   r   rk  rx  r  ry  )r  target_modelr  Z   r  r   r  rF   credential_poolr  Tr  Frz  r{  r  r   r   r   r  r  checkpoints_enabledHERMES_TUI_CHECKPOINTSpass_session_idHERMES_TUI_PASS_SESSION_IDskip_context_filesHERMES_IGNORE_RULESr  r  rv   )	run_agentr  r)  r  hermes_cli.mcp_startupr  r1   tui_gateway.entryr   r   r~  r  agent.skill_commandsr  r%  r&   r3   r   r   r2   rs  r  r  r  r  r  r   r(   r   r  r[  )r  r  r   r  r|  r}  r~  r  r  r  r  r5  r  r@  startup_skillsr  skills_prompt_loaded_skillsmissing_skillsr   requested_provideroverride_base_urloverride_api_keyoverride_api_moder2  s                            r@   r  r    sg    "!!!!!DDDDDDAAAAAA       <<<<<<        ++C  &BI !C!CDDM*,,N FFFFFF8U8U%#9
 9
 9
5~~  	OM$))N2K2KMMNNN 	"KK ( ("/!?( ( (  egg  .$'' 
N,>,>w,G,G 
N&&w//5266+//
;;X?PXTX*..z::)--i88*..z::**($
 
 
  	4"3GJ 	2!1GI 	4"3GJ$<$>$>!!nc** 	#~ 	#"E 	3!2**($
 
 
 7 % % %e%%c2...% Z(((% Z(((	%
 I&&&% Z(((% KK	***% V$$$%  $5666% 4% %$ )4 &%'))'%. %0 "!#%%1%4 01115%6 7%8 $9%: ",!7::WYY;%< !. 5=%> ,BJNN;S,T,TUUU?%@ (
7S(T(TUUUA%B +2:>>:O+P+PQQQC%D $BJNN3H$I$IJJJE%F ,---
S//I% % %s    
,,A 
AAr  r  colsc                     t          j                     }t          5  i d|d|d|dt          j                    dddd d|d	|d
ddg dddt	                      d|dd dt                      dt                      di i d t                      pt          dt           <   d d d            n# 1 swxY w Y   t                      }||                    |          }|rT|                    d          r?t          5   t          v r|d         t                    d<   d d d            n# 1 swxY w Y   nU	 |                    |t                    d                    n,# t          $ r t                              dd           Y nw xY wt#          t                               	 t%           t                    t'          |t)          |dt+                                                     n # t          $ r d t                    d<   Y nw xY w	 ddlm}m}	  || fd            |	             n# t          $ r Y nw xY w	  fd|_        n# t          $ r Y nw xY wt5                      t          5   t          v r)t7           t                              t                    d<   d d d            n# 1 swxY w Y   t9          d|           t;          d t=          |t                               i                                d S )Nr  r   r  r  r:  r   inflight_turnrH  rG  r   Fr  r  r   r  r  r  r  r  )r  r|  r!  z%failed to persist resumed session cwdTr   r   r  c                 &    t          d|           S r  r  r  s    r@   rx   z_init_session.<locals>.<lambda>  s    %8JCQU2V2V rw   c                 B    t          d|dt          |           i          S )Nzreview.summaryr   )r  r2   )r  _sids     r@   rx   z_init_session.<locals>.<lambda>  s$    UdVS\\$:F
 F
 rw   r  r  r  )r/   r  r   r   r  r  r  r   r  rM   r  r  r   r&  r1   r   r   r  r  r   r   r  r  r  r  background_review_callbackr  r  r   r  r  )
r  r  r  r  r  rD  r  rt  r  r  s
   `         r@   _init_sessionr  n  s   
)++C	 
 

U
3
 w
 IN,,	

 q
 T
 #
 3
 u
 r
 Q
 ?$$
 D
 D
 244
  !":"<"<!
" b#
$  " # +,,@0@3
 
 
	#
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8 
B	~nnS!! 	U3775>> 	U 7 7)##,/JIcN5)7 7 7 7 7 7 7 7 7 7 7 7 7 7 7U%%c9S>%+@AAAA U U UDtTTTTTU)C.))).cNgeWn6F6FGGHH	
 	
 	
 	

  . . .)-	#~&&&.TTTTTTTT%V%V%V%VWWW  """"   @C ,
 ,
 ,
((     	 C	 \ \),FsIVYN,[,[IcN=)\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ /555	.#}UIMM#r4J4JKKLLLLLs   BB44B8;B8 D..D25D2;'E# #&FF*AG0 0HH!H3 3
I ?I 
I 
II53J44J8;J8c                      t          j                                        d           dt          j                    j        d d          S )N%Y%m%d_%H%M%SrH     )r   rD  r0   rM  rN  rO  rv   rw   r@   _new_session_keyr    s<    lnn%%o66OO9I"1"9MOOOrw   c                 J     || d         j         t          |                     S )Nr  )_checkpoint_mgrr  )r   r  s     r@   _with_checkpointsr    s$    2gg.W0E0EFFFrw   refc                 *   	 |                      |          }t          |          dz
  }n# t          $ r |cY S w xY wd|cxk    rt          |          k     rn n||                             d|          S t          dt          |           d          )Nr   r   hashz!Invalid checkpoint number. Use 1-rq  )list_checkpointsr  r%  r  r   )mgrr   r   checkpointsr  s        r@   _resolve_checkpoint_hashr    s    **3//#hhl   


C""""#k"""""""3##FC000
L[9I9ILLL
M
MMs   '* 99	user_textimage_pathsc           
      H   ddl }ddl}ddlm} d}g }|D ]}t	          |          }|                                s&d| d}		 |                    |                     |t          |          |                              }
|
	                    d          r|
	                    d	d
          nd}|
                    |rd| d|	 nd|	            # t          $ r |
                    d|	            Y w xY w| pd
}d                    |          }|r|r| d| n|S |pdS )zMPre-analyze attached images via vision and prepend descriptions to user text.r   N)vision_analyze_toolzDescribe everything visible in this image in thorough detail. Include any text, code, data, objects, people, layout, colors, and any other notable visual information.z9[You can examine it with vision_analyze using image_url: r  )	image_urluser_promptr+  analysisr   z[The user attached an image:
z]
z2[The user attached an image but analysis failed.]
r  zWhat do you see in this image?)asyncior   tools.vision_toolsr
  r   rl  r   r   r2   r   r  r1   r&   )r  r  r  _jsonr
  ri  rn  r*   r|  hintrdescr   prefixs                 r@   _enrich_with_attached_imagesr    s   !!!!!!!!666666	4  E W WJJxxzz 	O1OOO	W//#a&&fUUUVV A -.EE),<,<F155R((($DLLR@@@$@@@Q4QQ   
  	W 	W 	WLLUtUUVVVVV	W ?D[[F 9(,8&$$d$$$&8333s   BC"C76C7r  c                    | dS t          | t                    r| S t          | t          t          f          rt          |           S t          | t                    rTg }| D ]:}t          |                                          }|r|                    |           ;d                    |          S t          | t                    r| 
                    d          }|dv r9t          | 
                    d          p| 
                    d          pd          S |dv rdS |d	v rd
S |rd| dS d| v r$t          | 
                    d          pd          S dS t          |           S Nr   r   r  >   r   
input_textoutput_textr   r  >   imager  input_image[image]>   audioinput_audio[audio][r  [structured content]r   r2   r  rK  r	  _content_display_textr3   r  r&   r   r   r  rn  r  r   r  s        r@   r#  r#       r'3 'C<(( 7||'4     	# 	#D(..4466D #T"""yy'4   &{{6""888w{{6**Jgkk).D.DJKKK8889+++9 	t;;;Ww{{6**0b111%%w<<rw   c                    | dS t          | t                    r| S t          | t          t          f          rt          |           S t          | t                    rg }| D ]}t          |t                    r|                    |           .t          |t                    sD|                    d          }t          |t                    r|                    |           |                    d          }|dv rQ|                    d          p|                    d          pd}|r"|                    t          |                     |dv r|                    d          }d}t          |t                    r-|                    d	          }t          |t                    r|}nt          |t                    r|}|r|                    d
|            n|                    d           |dv r|                    d           |r|                    d| d           d                    |          S t          | t                    r|                     d          }|dv r9t          |                     d          p|                     d          pd          S |dv rt|                     d          }d}t          |t                    r-|                    d	          }t          |t                    r|}nt          |t                    r|}|pdS |dv rdS |rd| dS d| v r$t          |                     d          pd          S dS t          |           S )u  Render ``message['content']`` as a plain string for transport.

    Provider-side, ``content`` may be a string (most common), a list of
    multimodal parts (e.g. ``[{"type": "text", "text": "..."},
    {"type": "image_url", "image_url": {...}}]``), or a single structured
    dict. Calling ``.strip()`` on a list raises ``'list' object has no
    attribute 'strip'`` and breaks session resume entirely.

    Image parts (``image_url``) are preserved by appending the underlying
    URL (data: or http:) into the text. The desktop renderer pulls these
    back out via ``extractEmbeddedImages`` so the user sees the image
    instead of the URL — and it stops the resume payload from disagreeing
    with the cached message (which would otherwise cause the inline image
    to flash, then disappear when the resume payload overwrites the cache).

    Other structured dict shapes (audio, unknown types) fall back to a
    bracketed placeholder so resume doesn't drop the message entirely.
    Nr   r   r  >   r   r  r  r  >   r  r  r  r  urlr   z
[image]>   r  r  z
[audio]z
[r  r  r  r   r!  )	r   r2   r  rK  r	  r  r   r   r&   )	r  chunksr  r   r  r  r  r'  r  s	            r@   _coerce_message_textr)    s   & r'3 'C<(( 7||'4   % "	- "	-D$$$ d###dD)) 88F##D$$$ d###88F##D<<<HHV$$A(;(;Ar *MM#a&&)))<<< HH[11	i.. $ )e 4 4I!)S11 ('	3// $#C /MM*s**----MM+...///k*** -mDmmm,,,wwv'4   &{{6""888w{{6**Jgkk).D.DJKKK888K00IC)T**  %MM%00	i-- $#CIs++  #)#+++9 	t;;;Ww{{6**0b111%%w<<rw   c           	      ^   g }i }| D ]$}t          |t                    s|                    d          }|dvr3t          |                    d                    }|dk    r|                    d          r|d         D ]}|                    di           }|                    dd          }|rj|                    d	          rU	 t	          j        |                    d
d                    }	n# t          j        t          f$ r i }	Y nw xY w|d	         |	f||<   |                                s)|dk    r|                    dd          }|r|                    |          nd }
|
r|
d         nd p|                    d          pd}|
r|
d         nd pi }	|	                    d|t          ||	          d           |                                s||d}|dk    r6dD ]3}||v r-|                    |          |                    |          ||<   4|	                    |           &|S )Nr  >   r  r  r  r  r  r  
tool_callsr  r   r   rE   	argumentsz{}r  r  r   r-  r   )r  rE   r  )r  r   )rh  reasoning_contentreasoning_detailscodex_reasoning_items)r   r   r   r)  r   r   r   r1  r3   r  r  )r  messagestool_call_argsrg  r  content_texttcr  r8  rF   tc_inforE   r   r  s                 r@   _history_to_messagesr5  k  s   HN ( (!T"" 	uuV}}>>>+AEE),<,<==;155#6#6o ? ?VVJ++tR(( ?RVVF^^ ?"#z"&&d*C*CDD 0)< " " "!"-/Z,>N5)%%'' 6>>EE."--E38Bn((///dG")3GAJJtTk8J8JTfD")3GAJJt:DOO)D$:O:OPP   !!## 	\22; * * !88c

 6 uuSzzCHOs   (C..D	D	c                 ~   t          | t                    sg S g }| D ]}t          |t                    s|                    d          }|dvr2|                    d          }||                    d          }t          |t                    r|                                s|                    ||d           |S )Nr  )r  r  r  r  r   r  )r   r	  r   r   r2   r3   r  )r  r  r  r  r  s        r@   _coerce_seed_historyr7    s    eT"" 	G ; ;$%% 	xx666((9%%?hhv&&G'3'' 	w}} 	99::::Nrw   c                    | dS t          | t                    r| S t          | t          t          f          rt          |           S t          | t                    rTg }| D ]:}t          |                                          }|r|                    |           ;d                    |          S t          | t                    r| 
                    d          }|dv r9t          | 
                    d          p| 
                    d          pd          S |dv rdS |d	v rd
S |rd| dS d| v r$t          | 
                    d          pd          S dS t          |           S r  r"  r$  s        r@   r#  r#    r%  rw   c                 D    t          |                                           S r   )r#  r3   r}  s    r@   _inflight_textr:    s     ''--///rw   c                 \    t          j                     }d|d|t          |          d| d<   d S )Nr   T)r  r  	streaming
updated_atr  r  )r/   r:  )r   r   rD  s      r@   _start_inflight_turnr>    s;    
)++Ct$$   GOrw   deltac                    |dnt          |          }|sd S |                     d          }t          |t                    sdddd}|                    d          pd | |d<   d|d<   t	          j                    |d<   || d<   d S )Nr   r  Tr  r<  r  r  r<  r=  )r2   r   r   r   r/   )r   r?  r   turns       r@   _append_inflight_deltarC    s    22CJJD ;;''DdD!! @dB??88K006B>>>DDD#GOrw   c                     d | d<   d S )Nr  rv   r#  s    r@   _clear_inflight_turnrE    s    #GOrw   c                 n   |                      d          }t          |t                    sd S t          |                     d          pd                                          }t          |                     d          pd          }t          |                     d                    }|s|s|sd S |||dS )Nr  r  r   r  r<  rA  )r   r   r   r2   r3   r   )r   rB  r  r  r<  s        r@   _inflight_snapshotrG    s    ;;''DdD!! ttxx%2&&,,..DDHH[))/R00ITXXk**++I 	 ) t  rw   zsession.createc                 \   t          j                    j        d d         t                      }t	          |                    dd                    }t          |                    d                    }t          |                    d          pd                                          }t          |                    d          pd                                          }	 t          |          oXt          j                            t          j                            t          j                            |                              }n# t          $ r d}Y nw xY wt!          |          }t#                       |                    d	          pd                                pd }	t%          |	          }
t'          j                    }t+          j                    }t-          |
          \  }}|t/          | d|          S t0          5  i dd dd d|dg dt3          |                    dd                    d|d|d|di d|d|dt'          j                    ddddd|dd d||pd |
t          |
          nd d|t7                      d t9                      i t;                      pt<          d	t>          <   tA          t>                              d d d            n# 1 swxY w Y   d#fd}t'          j!        d|          }d |_"        |#                                 tI          | |tK          |          tM          |          tO                      i i t>                   d         tQ          t>                   d                   d tR          tU                      d!d"          S )$NrK  r  r  r0  titler   r   Frd  r     r  r  rF  r  r7  r   rH  r  r  r  r  r:  r   r  r  rG  )	rR  rr  r   r   r  r  r  r  r!  r|   c                  d    t                                         } | t          |            d S d S r   )rM   r   r  )r   r  s    r@   _deferred_buildz_.<locals>._deferred_buildN  s8    --$$sG,,,,, rw   g?T)r   r\   r  r   r	  lazyr  r  )r   stored_session_idmessage_countr0  r  r   )+rM  rN  rO  r  r  r   r7  r2   r3   r   r(   r*   r{  ry  rz  r1   r  rH  ro  r   rP  r/   r   ra  r  r   r   r  r  r   r  rM   r  r,  r   r   r  r  r5  r  r  r  r  )r   r  r  r  r  rI  raw_cwdr  resolved_cwdrd  rr  rM  rD  r   limit_messagerM  build_timerr  s                    @r@   rH  rH    s6   
*,,
2A2
C


Cvzz&"%%&&D"6::j#9#9::G

7##)r**0022E
 &**U##)r**0022GG}}drwrwGYGYZaGbGb7c7c)d)d   "6**L zz)$$*1133;tG ))LOE
)++C5c3OOOE= C}---	 . .
T
4
 5
 r	

 "?6::>SUZ3[3[#\#\
 #E
 D
 #
 b
 L
 w
 IN,,
 q
 Q
 <
  T!
" 3#
$ #]d1=1IC---t244 ":"<"<!*,,@0@5
 
 
	#8 	in---;. . . . . . . . . . . . . . .R- - - - - -
 /$88KK!$ \\,W55')) ~e,-inU.CDD$< 5 7 7	 		
 	
  s&   "A(E EECK((K,/K,zsession.listc                    t                      }|t          | d          S 	 t          dh          t          |                    dd          pd          }t          |dz  d          }fd|                    d |          D             d |         }t          | d	d
 |D             i          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Ni  r_  r  limit   rk   c                     g | ]A}|                     d           pd                                                                v?|BS )r  r   )r   r3   r   )r4  r5  denys     r@   r6  z_.<locals>.<listcomp>  sU     
 
 
h%2,,..4466dBB BBBrw   r  rW  sessionsc           
          g | ]z}|d          |                     d          pd|                     d          pd|                     d          pd|                     d          pd|                     d          pdd{S )	r   rI  r   r  r  r   rP  r  )r   rI  r  r  rP  r  r3  r4  r5  s     r@   r6  z_.<locals>.<listcomp>  s     
 
 
   g!"w!52#$55#3#3#9r&'eeL&9&9&>Q)*)?)?)D1"#%%//"7R 
 
 
rw   )r  rc  	frozensetr  r   r  list_sessions_richr  r1   ra  r2   )r   r  r  rW  fetch_limitrowsr  rZ  s          @r@   rH  rH  l  s=   	B	z$St4444&' &""FJJw,,344 %!)S))
 
 
 
**$k*JJ
 
 
 5&	
  
 
 "
 
 

 
 	
   ' ' 'Cs1vv&&&&&&&&'s   BB3 3
C%=C C% C%zsession.most_recentc           
         t                      }|t          | ddi          S 	 t          dh          }|                    dd          }|D ]}|                    d          pd                                                                }||v rBt          | |                    d          |                    d	          pd|                    d
          pd|                    d          pdd          c S t          | ddi          S # t          $ r/ t          	                    d           t          | ddi          cY S w xY w)ae  Return the most recent human-facing session id, or ``None``.

    Mirrors ``session.list``'s deny-list behaviour (drops ``tool``
    sub-agent rows).  Used by TUI auto-resume when
    ``display.tui_auto_resume_recent`` is on; the field is also handy
    for any CLI tooling that wants "latest session" without paginating
    the full list.

    Contract: a ``{"session_id": null}`` result means "no eligible
    session found right now".  Errors are also folded into that
    null-result shape (and logged) so callers don't have to special-
    case JSON-RPC error envelopes for what is a normal "no answer".
    Nr   r  rX  r[  r  r   r   rI  r  r   )r   rI  r  r  zsession.most_recent failed)
r  r  r_  r`  r   r3   r   r1   r   	exception)r   r  r  rZ  rb  rt  srcs          r@   rH  rH    sr    
B	z3t,---.&""
 $$D$<< 	 	C778$$*113399;;Cd{{"%''$-- WWW--3"%'',"7"7"<1!ggh//52	      3t,--- . . .56663t,-----.s   CD
 8D
 
6EEri   c                 $   |                     dd          }|st          | dd          S 	 t          |                     dd                    }n# t          t          f$ r d}Y nw xY w|                     d          pd                                pd }t          |          }|dd	lm}  ||d
z            }nt                      }|t          | d          S |                    |          }|s1|                    |          }|r	|d         }nt          | dd          S t          5  t          |          }	|	M|	\  }
}t          |
||dt!                      pt"                    }||d<   t%          | |          cd d d            S 	 d d d            n# 1 swxY w Y   t'          j                    j        d d         }
t-          ||
          \  }}|t          | d|          S t/                       |t1          t3          |                    nd }	 |                    |           |                    |          }|                    |d          }|d t9          dt;          |          t;          |          z
                     }t=          |          }t?          |          }	 tA          |          }tC          |
|f||d|}tE          |           n# tE          |           w xY wnS# tF          $ rF}||$                                 t          | dd|           cY d }~|tK          |           S S d }~ww xY w	 |tK          |           n# |tK          |           w w xY wt          5  t          |          }	|		 tM          |d          r|'                                 n# tF          $ r Y nw xY w||$                                 |	\  }}t          |||dt!                      pt"                    }||d<   t%          | |          cd d d            S 	 tQ          |
||||           |
tR          v rj|                     d          |d         tR          |
         d<   |tR          |
         d<   |t3          |          tR          |
         d<   |tR          |
         d<   nM# tF          $ r@}||$                                 t          | dd|           cY d }~cd d d            S d }~ww xY wtR                               |
          pi }d d d            n# 1 swxY w Y   t%          | |
|t;          |          |tU          ||          d d |tW          |                     d!          ptY          j,                              d"d#
          S )$Nr   r     session_id requiredr  r  rd  r   r[  rg  r    rV  r     r  Tr  touchr!  resumedrK  rJ  rK  include_ancestors)r   r  zresume failed: r   r  r|  display_history_prefixrr  r   FrH  idle)
r   rm  rP  r0  r  inflightr   r   r  r  )-r   ra  r  r1  r%  r3   ro  r^  r\  r  rc  r  get_session_by_titler(  _find_live_session_by_key_live_session_payloadr   r  r  rM  rN  rO  r   rH  r   r2   reopen_sessionget_messages_as_conversationr  r  r5  r  r  r  r  r1   r   r   r
  r   r  rM   r  rK  r/   )r   r  r   r  rd  rr  r\  r  foundliver  r   r  r   rS  r  r  display_historyrq  r0  r  stored_runtime_overridesr  r  	other_sidother_sessions                             r@   rH  rH    sY   ZZb))F 6C45556::fb))**z"    zz)$$*1133;tG ))L ******Y|j8999YY	z$St4444NN6""E 8''// 	84[FFT#6777	 % %(00LC++--A1A  G "(GIsG$$% % % % % % % %% % % % % % % % % % % % % % %$ *,,
2A2
C5fcRRRE= C}---7C7O \!2!2333UY !3
&!!!11&9999d : 
 
 "19c!S))CLL8999"
 (88%f--	+ (I'O'O$ "	 
 + E #6****"6***** 6 6 6MMOOOC4445555555!&z2222 "6 + !&z222 !&z2222 " 
 &+ &+(005'** "KKMMM    '+$I}++--A1A  G "(GIsG$$'&+ &+ &+ &+ &+ &+ &+ &+(	:#vugDAAAAi+//0@AAM7O(8IcN#34 <R	#78  +585F5FIcN>29>	#56 	: 	: 	: T#8Q#8#89999999K&+ &+ &+ &+ &+ &+ &+ &+D	: --$$*M&+ &+ &+ &+ &+ &+ &+ &+ &+ &+ &+ &+ &+ &+ &+N  ]] !%11!L 9 9 HTY[[II	
 	
  s   #A A%$A%*AFFFBK1 , K K1 K--K1 0M 1
M;)L<$M%M <MM M+5T$N-,T-
N:7T9N::AT!BR)(T)
S33)S.S3T.S33TT"%T"zsession.cwd.setc                 |   t          ||           \  }}|r|S |                    d          rt          | dd          S t          |                    dd          pd                                          }|st          | dd          S 	 t          ||          }n5# t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w|                    d	          }|t          ||          n|t          |          d
d}t          d|                    dd          |           t          | |          S )Nr     session busyr   r     cwd required  r  T)r   r	  rN  r  r   )r  r   ra  r2   r3   r'  r%  r  r  r  r  )	r   r  r   r  r   r   r  r  r  s	            r@   rH  rH  _  s_   ,,LGS
 
{{9 /C~...
fjj##)r
*
*
0
0
2
2C /C~...'w,, ' ' 'Cs1vv&&&&&&&&'KK  E,1,==(((%c**D DD
 
.&**\266===sD>>s   	B 
C$CCCc                     t          t                                                    D ]R\  }\  }}|| k    rt                              |di f          \  }}t          |                              d          c S dS )Nzinput.requestz.requestr   )r	  rO   r8  rP   r   r2   removesuffix)r  r   rU  _evr  _payloads         r@   rI  rI  w  s~    !%hnn&6&6!7!7 3 3i266s_b<QRRx5zz&&z222222rw   c                     t          |           rdS |                    d          }||                                sdS |                    d          rdS dS )NwaitingrF  startingr   workingrr  )rI  r   rJ  )r  r   rM  s      r@   _session_live_statusr    s^    S!! yKK&&Ez{{9 y6rw   c           
      &   t          | pg           D ]~}t          |                    d|                    dd                                                              }|r1d                    |                                          d d         c S dS )Nr  r   r   r     )reversedr#  r   r3   r&   r  )r  r   r   s      r@   _message_previewr    s    2&& 0 0$SWWY8K8K%L%LMMSSUU 	088DJJLL))$3$////	02rw   c                 &   t          |                     d          pd                                          }t                      }|J	 t          |                    |          p|pd                                          }n# t
          $ r Y nw xY w|S )NrR  r   )r2   r   r3   r  get_session_titler1   )r   r  rI  r  s       r@   _session_live_titler    s    O,,23399;;E	B	~	,,S11@U@bAAGGIIEE 	 	 	D	Ls   8B 
BBcurrent_sidc                 p   t          |                    d          p|           }|                    d          }t          |                    d          pg           }t          | |          }t	          |          }t          |          }|rh|                    d          p|                    d          p|}d                    t          |                                                    d d         }t          j                    }	| |k    | t          |                    d          p|                    d	          p|	          t          |          t          t          |d
d          pt                                ||t          |                    d	          p|	          |t          ||          d
S )Nr   r  r  r  r  r  r  rG  rH  r   r   )
r  r   rG  rP  r   r  r   r  r  rI  )r2   r   r	  r  rG  r  r&   r  r/   rK  r  r   r  r  )
r  r   r  r  r  r  r  rs  r  rD  s
             r@   _session_live_itemr    s   
gkk-((/C
0
0CKK  E7;;y))/R00G!#w//F!'**Hw''G 7,,{++Nx||F/C/CNw((3w<<--//00#6
)++C+%W[[77[7;;|;T;T[X[\\WWUGR00DN4D4DEEGKK55<==$Wc22  rw   c                     t          t                                                    D ]I\  }}|                    d          rt	          |                    d          pd          | k    r||fc S Jd S )Nr   r   r   )r	  rM   r8  r   r2   )r   r  r   s      r@   ru  ru    s}    Y__..//    W;;|$$ 	w{{=))/R00K??< @4rw   c                     |                      d          }|t          |          S t          j        dt          j                              dt                      i i dS )Nr  r  T)r   rN  r   r  r\   )r   r  r(   getenvr   r  )r   r  s     r@   _fallback_session_infor    s]    KK  EU###y55!!  rw   rk  rl  c                   |d         5  |||d<   |||d<   |rt          j                     |d<   t          |                    d          pg           t          |                    d          pg           z   }t          |          }t	          |                    d                    }d d d            n# 1 swxY w Y   t          |          t          |          t          |          || |                    d          p| t          |                    d	          pt          j                               t          | |          d
}|r||d<   |S )Nr  r  r!  rG  rq  r  r   r   rH  )r  rP  r0  r   r   r   r  r  rs  )
r/   r	  r   rG  r   r  r  r5  rK  r  )	r  r   r  rl  r!  r  rs  r   r  s	            r@   rv  rv    s    
	  / /"GFO #,GK  	1%)Y[[GM"w{{#;<<BCCdKK	""(bG
 G
 
 &g..w{{9--../ / / / / / / / / / / / / / / 'w//W(11{{=118SGKK55DEE&sG44	 	G  '&
Ns   B!B66B:=B:zsession.active_listc                 p   t          |                    d          pd          	 t          5  t          t                                                    }ddd           n# 1 swxY w Y   n+# t          $ r}t          | dd|           cY d}~S d}~ww xY wfd|D             }t          | d|i          S )zReturn live TUI sessions in this gateway process.

    Unlike ``session.list`` this is not a historical DB browser: it reports only
    sessions with in-memory agents/workers that the current TUI can switch to
    without closing siblings.
    current_session_idr   N  %could not enumerate active sessions: c                 b    g | ]+\  }}|                     d           t          ||          ,S )r   )r   r  )r4  r  r   r  s      r@   r6  z_.<locals>.<listcomp>  sK       C{{<((311  rw   r\  )	r2   r   r  r	  rM   r8  r1   ra  r  )r   r  r
  r  rb  r  s        @r@   rH  rH    s)    &**1228b99GL 	/ 	/IOO--..H	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ L L LCJqJJKKKKKKKKL$   $  D
 sZ&'''s@   A- 'A!A- !A%%A- (A%)A- -
B7B
BBzsession.activatec           
          t          |                    d          pd          }t          d|i|           \  }}|r|S |J t          | t	          ||dt                      pt                              S )zAttach the frontend to an already-live TUI session.

    This intentionally does not close the previously focused session; it merely
    returns enough state for Ink to redraw around another live session id.
    r   r   NT)rl  r!  )r2   r   r  r  rv  r   r  )r   r  r  r   r  s        r@   rH  rH    s     fjj&&,"
-
-Cs 3S99LGS
 
'))=-=		
 	
 	
  rw   zsession.deletec                    |                     dd          }|st          | dd          S t                      }|t          | d          S 	 t          5  t          t                                                    }ddd           n# 1 swxY w Y   n+# t          $ r}t          | dd|           cY d}~S d}~ww xY wd	 |D             }||v rt          | d
d          S t                      dz  }	 |
                    ||          }n+# t          $ r}t          | dd|           cY d}~S d}~ww xY w|st          | dd          S t          | d|i          S )u  Delete a stored session and its on-disk transcript files.

    Used by the TUI resume picker (``d`` key) so users can prune old
    sessions without dropping to the CLI.  Refuses to delete a session
    that is currently active in this gateway process — those rows are
    still being written to and removing them out from under the live
    agent corrupts message ordering and trips FK constraints when the
    next message append flushes.
    r   r   rg  rh  Nr  rV  r  c                 b    h | ],}|                     d           |                     d           -S )r   r3  r^  s     r@   	<setcomp>z_.<locals>.<setcomp>K  s5    MMMqm8L8LMaeeM""MMMrw     zcannot delete an active sessionr\  )sessions_dirzdelete failed: rj  r  deleted)r   ra  r  rc  r  r	  rM   r;  r1   r	   delete_sessionr  )	r   r  r   r  r
  r  activer  r  s	            r@   rH  rH  .  s    ZZb))F 6C4555	B	z$St4444L 	0 	0I,,..//H	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 L L LCJqJJKKKKKKKKLMMHMMMFC@AAA"$$z1L6##F#FF 6 6 6C444555555556 4C2333sY'(((s`   B 'B:B B

B B
B 
B:B5/B:5B:0D 
D0D+%D0+D0zsession.titlec                    t          ||           \  }}|r|S t                      }|t          | d          S |d         }d|vr|                    d          pd}	 |                    |          pd}|rq|                    ||          rd |d<   |}nZ|                    |          }|pi                     d          pd                                }	|	|k    rd |d<   |}n|s|}n|rd |d<   n# t          $ r |}Y nw xY wt          | ||d          S |                    dd          pd                                }
|
st          | dd	          S 	 |                    ||
          rd |d<   t          | d
|
d          S |                    |          }|r-d |d<   t          | d
|                    d          p|
d          S |
|d<   t          | d|
d          S # t          $ r(}t          | dt          |                    cY d }~S d }~wt          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)N  rV  r   rI  rR  r   )rI  r   i  ztitle requiredF)pendingrI  Ti  )r  r  rc  r   r  set_session_titler  r3   r1   r  ra  r%  r2   )r   r  r   r  r  r  fallbackresolved_titleexisting_rowexisting_titlerI  r  s               r@   rH  rH  X  s   ,,LGS
 
	B	z$St4444
-
 Cf;;//52	&11#66<"N 0''X66 
2/3GO,%-NN#%>>##6#6L'3'9r&>&>w&G&G&M2%T%T%V%VN%11370)1+ 2)1 0+/( 	& 	& 	&%NNN	&'" 
 
 	
 ZZ$$*1133E 1C/000'U++ 	@'+GO$s>>??? ~~c** 	'+GO$$*..w77@5    $) 3D599::: ' ' 'Cs1vv&&&&&&&& ' ' 'Cs1vv&&&&&&&&'sP   BC/ /C>=C>-G  AG G 
H>&H	H>	H>H93H>9H>zhandoff.requestc           	      n   t          ||           \  }}|r|S |                    d          rt          | dd          S |                    dd          pd                                                                }|st          | dd          S 	 dd	lm}m} n+# t          $ r}t          | d
d|           cY d}~S d}~ww xY w	  ||          }n,# t          t          f$ r t          | dd| d          cY S w xY w	  |            }	n+# t          $ r}t          | d
d|           cY d}~S d}~ww xY w|	j                            |          }
|
r|
j        st          | dd| d          S |	                    |          }|r|j        st          | dd| d          S t          |           t!          |          5 }|t#          | d          cddd           S |d         }	 |                    |          s!|                    |d|dd                     |                    ||          }nA# t          $ r4}t          | dt+          |                    cY d}~cddd           S d}~ww xY w	 ddd           n# 1 swxY w Y   |st          | dd          S t-          | d|||j        d          S )a  Queue a handoff of this session to a messaging platform.

    Desktop parity with the CLI ``/handoff`` command: we only write
    ``handoff_state='pending'`` onto the persisted session row. The actual
    transfer is performed by the separate ``hermes gateway`` process, whose
    ``_handoff_watcher`` claims the row, re-binds the session to the platform's
    home channel, and forges a synthetic turn. The desktop then polls
    ``handoff.state`` for the terminal result.
    r   r  uL   session busy — wait for the current turn to finish, then retry the handoffr   r   r  zplatform requiredr   )Platformload_gateway_config  zcould not load gateway config: Ni  zunknown platform ''i  z
platform 'z*' is not configured/enabled in the gatewayi  zno home channel configured for u8    — set one with /sethome on the destination chat firstr  rV  r   zhandoff-rK  i  uN   session is already in flight for handoff — wait for it to settle, then retryT)queuedr   r   	home_name)r  r   ra  r3   r   gateway.configr  r  r1   r%  KeyError	platformsr  get_home_channelchat_idr  r!  rc  r  r  request_handoffr2   r  rE   )r   r  r   r  platform_namer  r  r  r   	gw_configpcfgrn  r  r  r   s                  r@   rH  rH    sF     ,,LGS
 
{{9 
Z
 
 	
 ZZ
B//52<<>>DDFFM 4C2333
F@@@@@@@@@ F F FCDDDEEEEEEEEFF8M**! F F FCDMDDDEEEEEFF''))		 F F FCDDDEEEEEEEEF""8,,D 
t| 
RRRR
 
 	

 %%h//D 
t| 
5m 5 5 5
 
 	
 7###	W		 	+:(4888	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ m$	+>>#&& @$$S*>S!W*>*>???##C77BB 	+ 	+ 	+T3q66*******	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+  
\
 
 	

 %		
 	
  s   B 
B?!B:4B?:B?C &C87C8<
D 
D/D*$D/*D/;I?I?$AH10I?1
I/;I*I/I?*I//I??JJzhandoff.statec                    t          ||           \  }}|r|S t          |          5 }|t          | d          cddd           S |                    |d                   }ddd           n# 1 swxY w Y   |pi }t	          | |                    d          pd|                    d          pd|                    d          pdd	          S )
zPoll the handoff state for a session.

    Returns ``{state, platform, error}`` where ``state`` is one of
    ``pending|running|completed|failed`` (or empty when no handoff record
    exists). Desktop polls this after ``handoff.request``.
    Nr  rV  r   stater   r   r   )r  r   r   )r  r!  rc  get_handoff_stater  r   )r   r  r   r  r  records         r@   rH  rH    sA     ,,LGS
 
	W		 >:(4888> > > > > > > > %%gm&<==> > > > > > > > > > > > > > >
 \rFZZ((.B

:..4"ZZ((.B	
 	
  s   A.A..A25A2zhandoff.failc                 >   t          ||           \  }}|r|S t          |                    d          pd                                          dd         }t	          |          5 }|t          | d          cddd           S |d         }|                    |          pi }|                    d          pd	}|d
v r5|                    ||           t          | ddd          cddd           S 	 ddd           n# 1 swxY w Y   t          | d|d          S )zMark an in-flight handoff as failed so the user can retry.

    Desktop calls this when its bounded poll times out. Only pending/running
    rows are changed so a late success from the gateway watcher is not clobbered.
    r   zhandoff failedN  r  rV  r   r  r   >   r  r   Tfailed)r  r  F)	r  r2   r   r3   r!  rc  r  fail_handoffr  )	r   r  r   r  reasonr  r  r  r  s	            r@   rH  rH  
  s     ,,LGS
 
G$$8(899??AA$3$GF	W		 A:(4888A A A A A A A A m$%%c**0b

7##)r***OOC(((sth??@@A A A A A A A A +A A A A A A A A A A A A A A A suu55666s   %DA"DDDzsession.usagec                     t          ||           \  }}|r|S |                    d          }|t          |          nddddd}	 ddlm}  |            }|r||d<   n# t
          $ r Y nw xY wt          | |          S )Nr  r   )rl  re  r   rk  )nous_credits_linescredits_lines)r  r   rB  agent.account_usager  r1   r  )r   r  r   r  r  rD  r  creditss           r@   rH  rH  "  s    ,,LGS
 
KK  E  	51A>> 
::::::$$&& 	-%,E/"   sE??s   A 
A+*A+zsession.statusc                    t          ||           \  }}|r|S ddlm} |                    d          p|                    d          pd}|                    d          }i }t	                      }|r-|r+	 |                    |          pi }n# t          $ r i }Y nw xY wd$dt          d z  dt          fd	}	 |	|                    d
                    }
|
}dD ]8}|                    |          r! |	|                    |          |
          } n9|t          |          ni }t          |dd           pd}t          |dd           pd}ddd| d |             g}|                    d          pd
                                }|r|                    d|            |                    d| d| dd|
                    d           d|                    d           dt          |                    d          pd          dd|                    d          rd nd! g           t          | d"d#                    |          i          S )%Nr   display_hermes_homer   r   r   r  r  r|   c                     | r2	 t          j        t          |                     S # t          $ r Y nw xY w|pt          j                    S r   )r   fromtimestamprK  r1   rD  )r  r  s     r@   _dtz_.<locals>._dtN  sW     	-eEll;;;   )8<>>)s    % 
22r  )r=  last_updated_atlast_activity_atrk  r  r   	(unknown)zHermes TUI StatuszSession ID: zPath: rI  zTitle: zModel:  ()z	Created: z%Y-%m-%d %H:%MzLast Activity: zTokens: rk  r  zAgent Running: r   YesNor   r   r   )r  r  r  r   r  r  r1   r   rB  r   r3   r  r  r0   r  r  r&   )r   r  r   r  r  r  r  r  r  r  createdupdatedfieldrD  rk  r   linesrI  s                     r@   rH  rH  <  s   ,,LGS
 
444444
++m
$
$
F

<(@(@
FBCKK  ED	B	 c 	>>#&&,"DD 	 	 	DDD	* *X_ * * * * * c$((<(())GGF  88E?? 	c$((5//733GE	 "'!2JuEuj$//<9HE7D))8[E
s($$&&((	E XXg$"++--E (&u&&'''	LL*e**x***<(()9::<<Bg../?@@BB7s599W--233777Iw{{9'='=Gee4II	
   sXtyy//0111s   4B BBzsession.historyc                 x   t          ||           \  }}|r|S t          |                    dg                     }t                      }|D|                    d          r/	 |                    |d         d          }n# t
          $ r Y nw xY wt          | t          |          t          |          d          S )Nr  r   Trn  )r  r0  )	r  r	  r   r  rx  r1   r  r  r5  )r   r  r   r  r  r  s         r@   rH  rH  u  s    ,,LGS
 
7;;y"--..G	B	~'++m44~	55&$ 6  GG  	 	 	D	\\,W55	
 	
  s   !A? ?
BBzsession.undoc                    t          ||           \  }}|r|S |                    d          rt          | dd          S d}|d         5  |                    dg           }|rU|d                             d          d	v r8|                                 |d
z  }|r|d                             d          d	v 8|r8|d                             d          dk    r|                                 |d
z  }|r)t	          |                    dd                    d
z   |d<   d d d            n# 1 swxY w Y   t          | d|i          S )Nr   r  9   session busy — /interrupt the current turn before /undor   r  r  r  r  >   r  r  r   r  r:  removed)r  r   ra  r   r  r  )r   r  r   r  r  r  s         r@   rH  rH    s   %%LGS
 
 {{9 
R
 
 	
 G		  	T 	T++i,, 	'"+//&115JJJKKMMMqLG  	'"+//&115JJJ  	wr{v..&88KKMMMqLG 	T),W[[9JA-N-N)O)ORS)SG%&	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T sY()))s   CD''D+.D+rj   c                    t          ||           \  }}|r|S |                    d          rt          | dd          S |                    dd          }t          |                    dd          pd                                          }	 ddlm} dd	lm} |d
         5  t          |                    dg                     }t          |                    dd                    }	d d d            n# 1 swxY w Y   t          |          }
|d         }t          |dd          pd}t          |dd           pd }|
r ||||          nd}|
dk    r&|rd| dnd}t          |dd|
 d|dd| d           	 t          |||||	          \  }}|d
         5  t          |                    dg                     }d d d            n# 1 swxY w Y   t          |          }t          |dd          p|}t          |dd           p|}|r ||||          nd}|d         }t          ||            |||||          }t!          ||          }t#          d||           t%          | d||
|||||||d
          t          |d           S # t          |d           w xY w# t&          $ r(}t          | dt          |                    cY d }~S d }~ww xY w) Nr   r  u=   session busy — /interrupt the current turn before /compressr   r   r7  r   )summarize_manual_compressionr<  r  r  r:  r  r>  r\   r?  rn   z
, focus: ""compressingu   ⠋ compressing z messages (~r  z tok)   …)r8  r9  r:  r  rG  )
r  r  r9  after_messagesbefore_tokensafter_tokensr  rD  r  r0  rM  i  )r  r   ra  r2   r3   !agent.manual_compression_feedbackr  rA  r=  r	  r  r  r   r  rI  rV  r  r  r  r1   )r   r  r   r  r  r7  r  r=  r9  r:  before_count_agentrE  rF  r  focus_suffixr  rD  r0  after_count_sys_prompt_after_tools_afterr  r  r  r  r  s                              r@   rH  rH    ss   %%LGS
 
{{9 
V
 
 	
 **\2
&
&Cfjj339r::@@BBKR'RRRRRRFFFFFF^$ 	E 	E"7;;y"#=#=>>O!'++.?"C"CDDO	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E ?++!f&=rBBHb$//74
 )){&     	 1:EM666662L=< = ="<= =+7= = =  4	)6+ / /  NGU ( < <Ir : :;;< < < < < < < < < < < < < < <h--K  7<<K  #67D99CVL --"3&      G$E,S':::22=, G !00D.#t,,,*&'3&1%2$0&"  (  & 3((((N3(((( ' ' 'Cs1vv&&&&&&&&'s   J"  AC3'J" 3C77J" :C7;A>J" :J $G	=J 	GJ GB+J <J" JJ" "
K,K	KKzsession.savec                    t          ||           \  }}|r|S |d         }t                      dz  dz  }	 |                    dd           n.# t          $ r!}t	          | dd| d|           cY d }~S d }~ww xY wt          j                                        d	          }|d
| dz  }|d         5  t          |	                    dg                     }	d d d            n# 1 swxY w Y   t          |dd           p|	                    d          pd}
t          |dd           }t          |t
                    r|                                }nY|	                    d          }t          |t          t          f          r&t          j        |                                          nd}	 t!          |dd          5 }t#          j        t          |dd          |
|t          |dd          pd|	d|dd           d d d            n# 1 swxY w Y   t'          | dt)          |          i          S # t          $ r(}t	          | dt)          |                    cY d }~S d }~ww xY w)Nr  r\  savedTparentsr   i  z failed to create save directory r!   r  hermes_conversation_.jsonr  r  r   r   r   session_startrH  r7  r   r   r   r>  )r   r   r  r@  r0  rk   F)r  r  r#   )r  r	   mkdirr1   ra  r   rD  r0   r	  r   r   r   	isoformatr  rK  r  r-   r   dumpr  r2   )r   r  r   r  r  	saved_dirr  	timestampr*   r0  r   agent_startr  rH  r>   s                  r@   rH  rH    s=   %%LGS
 
GE  !!J.8ITt4444 T T TCR)RRqRRSSSSSSSST ''88I>i>>>>D		  4 4Ir22334 4 4 4 4 4 4 4 4 4 4 4 4 4 4 d33Ww{{=7Q7QWUWJ %$77K+x(( 
#--//[[..
 *sEl33H":..88::: 	'$g... 	!I$UGR88",%2%,U4KR%P%P%VTV (  "   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 3T+,,, ' ' 'Cs1vv&&&&&&&&'sq   A 
A8A3-A83A82$C""C&)C&*H1 <?H;H1 HH1 H!H1 1
I#;II#I#zsession.closec           	          |                     dd          }t          5  t          | dt          |d          i          cd d d            S # 1 swxY w Y   d S )Nr   r   closedr   r  )r   r(  r  r  )r   r  r  s      r@   rH  rH  ?  s    
**\2
&
&C 
 W W3#7#T#T#TUVVW W W W W W W W W W W W W W W W W Ws   !AAArh   c           
         t          ||           \  }}|r|S t                      }|t          | d          S |d         }|d         5  d |                    dg           D             }d d d            n# 1 swxY w Y   |st	          | dd          S t                      }t          j                    j        d d	         }t          ||
          \  }	}
|
t	          | d|
          S |                    dd          }	 |r|}nA|
                    |          pd}t          |d          r|                    |          n| d}|                    |dt                      d|i|t          |                     |D ]A}|                    ||                    dd          |                    d                     B|                    ||           nA# t$          $ r4}|	|	                                 t	          | dd|           cY d }~S d }~ww xY w	 t)          |          }	 t+          |||          }t-          |           n# t-          |           w xY wt/          |||t1          |          |                    dd                     |t2          v r|	t2          |         d<   nA# t$          $ r4}|	|	                                 t	          | dd|           cY d }~S d }~ww xY wt5          | |||d           S )!N  rV  r   r  c                 ,    g | ]}t          |          S rv   )r   )r4  r   s     r@   r6  z_.<locals>.<listcomp>U  s    CCC499CCCrw   r  i  u*   nothing to branch — send a message firstrK  rJ  rK  rE   r   r	  get_next_title_in_lineagez	 (branch)r   _branched_from)r  r   rv  parent_session_idr   r  r  r  )r   r  r  zbranch failed: )r   r  r  rp  r   ri  zagent init failed on branch: )r   rI  r  )r  r  rc  r   ra  r  rM  rN  rO  r   r  r
  r  r  r  r  append_messager  r1   r   r  r  r  r  r	  rM   r  )r   r  r   r  r  rT  r  new_keynew_sidr   rS  branch_namerI  r  r   r  r  r  s                     r@   rH  rH  K  s   %%LGS
 
	B	z$St4444m$G		  D DCCIr(B(BCCCD D D D D D D D D D D D D D D MCKLLL  Gjllrr"G5gwWWWE= C}---**VR((K!6 	EE**733?xG 2:;;+,,W555*** 
 	 "" +G4%W%% 	 	
 	
 	
  	 	C"WWVV,,	**     
 	We,,,, 6 6 6MMOOOC444555555556D%g..	+WEEEE"6****"6****WeT']]VR9P9P	
 	
 	
 	
 i9>Ig56 D D DMMOOOCBqBBCCCCCCCCD s7UgNNOOOsh   	!A66A:=A: CG 
H!)H
HHJ. )I ;J. IAJ. .
K,8)K'!K,'K,zsession.interruptc                 R   t          ||           \  }}|r|S t          |d         d          r|d                                          t          |                    dd                     	 ddlm}  ||d         dd	
           n# t          $ r Y nw xY wt          | ddi          S )Nr  r   r   r   r   resolve_gateway_approvalr   rZ  Tresolve_allr  interrupted)	r  r
  r   rV  r   r  r  r1   r  )r   r  r   r  r  s        r@   rH  rH    s    %%LGS
 
ww-- %""$$$
 6::lB//000;;;;;;  !7TRRRRR   sX}-...s   ,B 
BBzdelegation.statusc                     ddl m}m}m}m} t          |  |             |             |             |            d          S )Nr   )is_spawn_pausedlist_active_subagents_get_max_concurrent_children_get_max_spawn_depth)r  pausedmax_spawn_depthmax_concurrent_children)tools.delegate_toolr  r  r  r  r  )r   r  r  r  r  r  s         r@   rH  rH    s                ++--%o''3355'C'C'E'E		
 	
  rw   zdelegation.pausec                     ddl m} t          |                    dd                    }t	          | d ||          i          S )Nr   )set_spawn_pausedr  T)r  r  r   r   r  )r   r  r  r  s       r@   rH  rH    sP    444444&**Xt,,--FsX//778999rw   zsubagent.interruptc                     ddl m} t          |                    d          pd                                          }|st          | dd          S  ||          }t          | ||d          S )Nr   )interrupt_subagentr  r     zsubagent_id required)ry  r  )r  r   r2   r   r3   ra  r  )r   r  r   r  r   s        r@   rH  rH    s    666666fjj//5266<<>>K 7C5666		K	(	(Bsb==>>>rw   c                  Z    ddl m}   |             dz  }|                    dd           |S )Nr   )r	   zspawn-treesTr  )r  r	   r  )r	   roots     r@   _spawn_trees_rootr$    sA    000000?},DJJtdJ+++Krw   c                     d                     d | D                       pd}t                      |z  }|                    dd           |S )Nr   c              3   N   K   | ] }|                                 s|d v r|ndV  !dS )z-_rH  N)isalnumr4  rJ  s     r@   r  z*_spawn_tree_session_dir.<locals>.<genexpr>  s;      KK1QYY[[6AII3KKKKKKrw   r  Tr  )r&   r$  r  )r   safeds      r@   _spawn_tree_session_dirr+    sW    
KK
KKKKKXy 	 	d"AGGD4G(((Hrw   z_index.jsonlentryc                 6   	 | t           z                      dd          5 }|                    t          j        |d          dz              d d d            d S # 1 swxY w Y   d S # t
          $ r&}t                              d|           Y d }~d S d }~ww xY w)Nr   r   r   Fr  r   z"spawn_tree index append failed: %s)_SPAWN_TREE_INDEXr-   r.   r   r   OSErrorr   r   )session_dirr,  r>   r   s       r@   _append_spawn_tree_indexr2    s   @--33C'3JJ 	BaGGDJu5999D@AAA	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B @ @ @ 	93?????????@s:   A( -AA( AA( "A#A( (
B2BBc                    | t           z  }|                                sg S g }	 |                    dd          5 }|D ]V}|                                }|s	 |                    t          j        |                     B# t
          j        $ r Y Sw xY w	 d d d            n# 1 swxY w Y   n# t          $ r g cY S w xY w|S )Nr  r   r   )	r/  rl  r-   r3   r  r   r   r   r0  )r1  
index_pathoutr>   r   s        r@   _read_spawn_tree_indexr6    s7   00J 	C__S7_33 	q  zz|| JJtz$//0000+   H	 	 	 	 	 	 	 	 	 	 	 	 	 	 	    			JsX   B. B"'B ?B" BB"BB"B. "B&&B. )B&*B. .B=<B=zspawn_tree.savec                    t          |                    d          pd                                          }|                    d          pg }t          |t                    r|st          | dd          S ddlm} |                    d          }|                    d	          pt          j                    }t          |                    d
          pd          } |j        t          |                    
                    d          }| d}	t          |pd          }
|
|	z  }	 ||rt          |          nd t          |          ||d}|                    t          j        |d          d           n+# t          $ r}t          | dd|           cY d }~S d }~ww xY wt!          |
t          |          ||d         |d	         |t#          |          d           t%          | t          |          |d          S )Nr   r   r]   r!  zsubagents list requiredr   r   r  finished_atr  z%Y%m%dT%H%M%Sr  rf  )r   r  r8  r  r]   Fr.  r   r   ri  zspawn_tree.save failed: )r*   r   r  r8  r  r  )r*   r   )r2   r   r3   r   r	  ra  r   r/   utcfromtimestamprK  r0   r+  
write_textr   r   r0  r2  r  r  )r   r  r   r]   r   r  r8  r  tsfnamer*  r*   r  r   s                 r@   rH  rH    s4   VZZ--344::<<J

;''-2Ii&& :i :C8999!!!!!!L))J**]++:ty{{K

7##)r**E	"	"5#5#5	6	6	?	?	P	PBLLLE
 7i88Au9D
A$/9C%
+++t --"
 
 	
7???'RRRR A A AC?#??@@@@@@@@A 	II$!,/"=1^^	
 	

 
 
 sSYYjAABBBs   )AE; ;
F#FF#F#zspawn_tree.listc                    t          |                    d          pd                                          }t          |                    d          pd          }t	          |                    d                    }|r-t                      }d |                                D             }nt          |pd          g}g }|D ]}t          |          }	|	r"|	                    fd|	D                        6|
                    d	          D ]6j        t          k    r	                                 }
	 t          j                            d
                    }n# t"          $ r i }Y nw xY w|                    d          pg }|                    t                    |                    d          p|j        |                    d          p|
j        |                    d          |                    d          pdt)          |t*                    rt-          |          ndd           '# t.          $ r Y 4w xY w|                    d d           t3          | d|d |         i          S )Nr   r   rW  2   cross_sessionc                 :    g | ]}|                                 |S rv   )is_dirr)  s     r@   r6  z_.<locals>.<listcomp>E  s%    999qahhjj9999rw   rf  c              3      K   | ]>}|                     d           xt                                                    :|V  ?dS )r*   N)r   r   rl  )r4  r  r|  s     r@   r  z_.<locals>.<genexpr>N  sc        AEE&MM'9q?CAww~~?O?O     rw   z*.jsonr   r   r]   r8  r  r  r   )r*   r   r8  r  r  r  c                 0    |                      d          pdS )Nr8  r   r3  )r  s    r@   rx   z_.<locals>.<lambda>l  s    quu]338q rw   T)r  reverseentries)r2   r   r3   r  r   r$  iterdirr+  r6  r  globrE   r/  r.  r   r   	read_textr1   r  r/  r   r	  r  r0  sortr  )r   r  r   rW  r?  r#  rootsrE  r*  indexedr.  r   r]   r|  s                @r@   rH  rH  =  s   VZZ--344::<<J

7##)r**EO4455M C ""99DLLNN999()@yAABG    (++ 	NN    "       !! 	 	Av***vvxx*Q[['[%B%BCCCC    CCCGGK006B	 #A&)ggl&;&;&Eqv'*ww}'='='N&)ggl&;&;!$!1!1!7R3=i3N3N!UYTU 	 	 	 	    )	. LL88$LGGGsY0111s7   #H58(E! H5!E0-H5/E00CH55
IIzspawn_tree.loadc                    ddl m} t          |                    d          pd                                          }|st          | dd          S t                                                      }	  ||                                          }|                    |           n2# t          t          f$ r}t          | dd|           cY d }~S d }~ww xY w	 t          j        |                    d	
                    }n7# t          t          j        f$ r}t          | dd|           cY d }~S d }~ww xY wt          | |          S )Nr   r   r*   r   r!  path requiredi  zpath outside spawn-trees root: r   r   ri  zspawn_tree.load failed: )pathlibr   r2   r   r3   ra  r$  rj  relative_tor%  r0  r   r   rH  r   r  )r   r  r   raw_pathr#  r~  r   r  s           r@   rH  rH  p  s   6::f%%+,,2244H 0C/// &&((DH4>>))++T""""  H H HCFFFGGGGGGGGHA*X///AABBT)* A A AC?#??@@@@@@@@A sGs<   12B$ $C5CCC(D   D4D/)D4/D4zsession.steerc                    |                     d          pd                                }|st          | dd          S t          ||           \  }}|r|S |                     d          }|t	          |d          st          | dd	          S 	 |                    |          }n+# t          $ r}t          | d
d|           cY d}~S d}~ww xY wt          | |rdnd|d          S )uG  Inject a user message into the next tool result without interrupting.

    Mirrors AIAgent.steer(). Safe to call while a turn is running — the text
    lands on the last tool result of the next tool batch and the model sees
    it on its next iteration. No interrupt, no new user turn, no role
    alternation violation.
    r   r     ztext is requiredr  Nr   i  zagent does not support steerri  zsteer failed: r  rejected)r  r   )r   r3   ra  r  r
  r   r1   r  )r   r  r   r   r  r  acceptedr   s           r@   rH  rH    s    JJv$"++--D 3C1222,,LGS
 
KK  E}GE733}C=>>>7;;t$$ 7 7 7C555666666667s8CxxTRRSSSs   B# #
C-C CCzterminal.resizec                     t          ||           \  }}|r|S t          |                    dd                    |d<   t          | d|d         i          S )Nr  r  )r  r  r   r  )r   r  r   r  s       r@   rH  rH    sZ    ,,LGS
 
&**VR0011GFOsVWV_-...rw   zprompt.submitc                 4    |                     dd          |                     dd          c|                     d          }t          |           \  }|r|S t                      x}|d<   d         5                       d          rt           dd	          cd d d            S |E	 t	          |          }n4# t
          t          f$ r  t           d
d          cY cd d d            S w xY w                     dg           }d t          |          D             }|t          |          k    rt           dd          cd d d            S |d ||                  }|d<   t	                               dd                    dz   d<   t                      x}	S	 |	
                    d         |           n5# t          $ r(}
t          d|
 t          j                   Y d }
~
nd }
~
ww xY wdd<   t          j                    d<   t!                     d d d            n# 1 swxY w Y   t#                     t%                     d fd}t'          j        |d                                           t-           ddi          S )Nr   r   r   truncate_before_user_ordinalr!  r  r   r  r    z/truncate_before_user_ordinal must be an integerr  c                 J    g | ] \  }}|                     d           dk    |!S )r  r  r3  )r4  irg  s      r@   r6  z_.<locals>.<listcomp>  s1    XXX$!QfQW@W@WA@W@W@Wrw     z3target user message is no longer in session historyr:  r   r   r   z6[tui_gateway] prompt.submit: replace_messages failed: r#   TrG  r|   c            	      2   t                    } | rqt          dd|                     di                               dd          i           d         5  dd<   t                     d d d            n# 1 swxY w Y   d S t	                     d S )Nr   r  agent initialization failedr  Fr   )r  r  r   rE  _run_prompt_submit)r  r   r   r  r   s    r@   run_after_agent_readyz _.<locals>.run_after_agent_ready  s    '3'' 	swww3377!#@      ( . .%*	"$W---. . . . . . . . . . . . . . . F3Wd33333s   A88A<?A<r   r  r<  r   )r   r  r   ra  r  r1  r%  	enumerater  r  replace_messagesr1   r6   r7   r8   r/   r>  r  r  r   r   r   r  )r   r  truncate_user_ordinalr  r  ordinalr  user_indices	truncatedr  r   r`  r   r  r   s   `           @@@r@   rH  rH    s   

<,,fjj.D.DIC"JJ'EFF,,LGS
 
    - 		  , ,;;y!! 	3T>22, , , , , , , , !,Z344z* Z Z ZC'XYYYY, , , , , , , ,Zkk)R00GXX)G*<*<XXXL#l++++C'\]], , , , , , , ,   7,w"7 78I!*GI),W[[9JA-N-N)O)ORS)SG%&ii,k''(>	JJJJ  k k kXSVXX_b_ijjjjjjjjjk!	!%Wd+++-, , , , , , , , , , , , , , ,2 7###sG$$$4 4 4 4 4 4 4 4 4$ 1$???EEGGGsX{+,,,sn   ;&H-.H-2CH-"C3$H-2C33AH-AH-$G H-
G3G.)H-.G33.H--H14H1evtc                     t          |                    d          pd          sdS t                               d          pd          k    rdS 	 t          5  t          t                                                    }ddd           n# 1 swxY w Y   n# t          $ r Y dS w xY wt           fd|D                       S )uA  True if ``evt`` is owned by a *different* live session.

    Background-process events carry the ``session_key`` of the session that
    started the process. Since all desktop sessions share one process-wide
    completion queue, each poller must skip events it doesn't own so a
    background job's completion surfaces in the session that launched it — not
    whichever poller happened to dequeue first. Orphaned events (owner gone)
    and global/system events (empty ``session_key``) return False so the
    current poller still handles them rather than losing them.
    r   r   FNc              3   p   K   | ]0}|uo't          |                    d           pd          k    V  1dS )r   r   N)r2   r   )r4  r5  evt_keyr   s     r@   r  z8_notification_event_belongs_elsewhere.<locals>.<genexpr>  s_         	
GS}!5!5!;<<G     rw   )r2   r   r  r	  rM   r;  r1   r  )r   rg  r
  rj  s   `  @r@   %_notification_event_belongs_elsewhererk    s7    #''-((.B//G u#gkk-006B7777u 	0 	0I,,..//H	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0    uu
           s6   B 'BB BB BB 
B*)B*c           
         |                      dd          }|                      dd          }|dk    rm|||                      dd          |                      dd          |                      dd          |                      d	d
          |                      dd          fS |                    d          s|dk    rC|||                      dd          |                      dd          |                      d	d
          fS ||fS )a  Return the UI-emission identity for a process notification event.

    Completion events are terminal notifications for a background process, so
    they remain one-shot per process session. Watch-match events are not
    terminal: a single background process can legitimately match the same or
    different patterns many times, so include event-specific content to avoid
    suppressing later distinct matches from the same process.
    r  rj  r   r   watch_matchr   patternr   
suppressedr   
message_idwatch_overflow_watch_disabledr  )r   r0  )rg  evt_typeevt_sids      r@   _notification_event_dedup_keyru  	  s    wwv|,,HgglB''G=  GGIr""GGIr""GGHb!!GGL!$$GGL"%%
 	
 ,-- 
=M1M1MGGIr""GGIr""GGL!$$
 	
 Xrw   r  c                 	   ddl m}m} t                      }|                                 sV|                    d          s@	 |j                            d          }n# t          $ r Y Tw xY wt          ||          r/|j        	                    |           t          j        d           |                    dd          }|                    d	          d
k    r|                    |          r ||          }|st          |          }	|	|vr)t          d|d|d           |                    |	           |d         5  |                    d          r(|j        	                    |           	 ddd           ld|d<   ddd           n# 1 swxY w Y   dt!          t          j
                    dz             }
	 t          d|           t#          |
|||           no# t          $ rb}t%          dt'          |          j         d| t*          j                   |d         5  d|d<   ddd           n# 1 swxY w Y   Y d}~nd}~ww xY w|                                 s|                    d          @g }|j                                        s	 |j                                        }n# t          $ r Y nw xY wt          ||          r|                    |           l|                    dd          }|                    d	          d
k    r|                    |          r ||          }|st          |          }	|	|vr)t          d|d|d           |                    |	           |d         5  |                    d          r'|j        	                    |           	 ddd           nd|d<   ddd           n# 1 swxY w Y   dt!          t          j
                    dz             }
	 t          d|           t#          |
|||           no# t          $ rb}t%          dt'          |          j         d| t*          j                   |d         5  d|d<   ddd           n# 1 swxY w Y   Y d}~nd}~ww xY w|j                                        |D ]}|j        	                    |           dS )a  Poll completion_queue and dispatch notifications autonomously.

    Runs in a daemon thread started by _init_session(). Emits a
    status.update (kind=process) for user visibility, then chains an
    agent turn via _run_prompt_submit if the session is idle.

    NOTE: The completion_queue is global (one per process). If multiple
    TUI sessions coexist, whichever poller wakes first grabs the event,
    even if the process was started by a different session. This matches
    CLI/gateway behavior (single session per process).
    r   )process_registryformat_process_notificationr   r  r   g?r   r   r  rj  r  processr  r  r   NT	__notif__r  message.startz3[tui_gateway] notification poller dispatch failed: r!   r\  F)tools.process_registryrw  rx  r  rJ  r   completion_queuer1   rk  r   r/   rV  is_completion_consumedru  r  r  r  r_  r6   r  r5   r7   r8   empty
get_nowaitr  )r  r  r   rw  rx  _emittedrg  _evt_sidr   
_dedup_keyr   r   deferreds                r@   _notification_poller_loopr  )  s    UTTTTTTTuuH!! 2+'++l*C*C 2+	"3777DDCC 	 	 	H	 1#>> 	-11#666JsOOO77<,,776??l**/?/V/VW_/`/`***3// 	 3377
X%%/3D(I(IJJJLL$$$^$ 	& 	&{{9%%  155c:::	& 	& 	& 	& 	& 	& 	& "&GI		& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 4#dikkD01133
	+/3'''sC$7777 	+ 	+ 	+/99%/ /),/ /Z   
 ( + +%*	"+ + + + + + + + + + + + + + +	+W !! 2+'++l*C*C 2+n H/5577 %+	"3>>@@CC 	 	 	E	0#>> 	OOC   77<,,776??l**/?/V/VW_/`/`***3// 	2377
X%%/3D(I(IJJJLL$$$^$ 	& 	&{{9%%  155c:::	& 	& 	& 	& 	& 	& 	& "&GI		& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 4#dikkD01133
	+/3'''sC$7777 	+ 	+ 	+/99%/ /),/ /Z   
 ( + +%*	"+ + + + + + + + + + + + + + +	+= /5577 %+P  3 3)--c22223 3s   A 
A,+A,1FFFF"G) )
I3;I.I 4I I	II	IIJ9 9
KK1OOOO"P* *
R4;R/R5RR	RR		RRc                     t          j                    }t          j        t          || |fd          }|                                 |S )z;Start the background notification poller for a TUI session.Tr   rF   r   )r   rP  r   r  r   )r  r   stopr  s       r@   r  r    sJ    ?D(C!	 	 	A
 GGIIIKrw   c                     d         5  t          d                   t                              dd                    t                              dg                     g d<   t                              d          t                    st                     d d d            n# 1 swxY w Y   d         t          d            fd	}t          j        |d
          	                                 d S )Nr  r  r:  r   r  r  r  r{  c                    > d } g }d }d }	 ddl m}m}  |Dd                   } t          Dd                   }D                    d          }|rt          |          }t          E           t          D          }t          D           D                    dd          }t          |          >F}	t          |	t                    rud|	v rpddlm}
 dd	lm}  |t!          ?d
d          pt#                      t!          ?dd          pdt!          ?dd          pdt!          ?dd          pdt!          ?dd                     } |
|	|||          }|j        rt'          dEdd                    |j                  pdi           	 	 |  ||            n# t,          $ r Y nw xY w|t/          |           t1          |           Dd         5  dDd<   t3          j                    Dd<   t5          D           d d d            n# 1 swxY w Y   t'          dEt7          ?D                     d S |j        }	|	}BrS	 ddlm}m} ddl m!}m"} ddl#m$}  |            } | |             |            |          }t!          ?dd          dk    rd }n7# t,          $ r*}tK          d!| tL          j'        "           d }Y d }~nd }~ww xY w|d#k    r	  ||	B          \  }}|r,tK          d$tQ          |           d%tL          j'        "           tS          d& |D                       r|}ntU          |	B          }nU# t,          $ r8}tK          d'| tL          j'        "           tU          |	B          }Y d }~nd }~ww xY wtU          |	B          }DE>fd(}tW          @          |d)}	 d*tY          j-        ?j.                  j/        v rDd         |d*<   n# t`          tb          f$ r Y nw xY w ?j.        |fi |}d }d }t          |td                    rt          |                    d+          tV                    rDd         5  tg          D                    d,d                    }|Ak    r|d+         Dd-<   Ad.z   Dd,<   n$tK          d/A d0| d1tL          j'        "           d2}d d d            n# 1 swxY w Y   ti          EDdd34           |                    d5d          }|                    d6          rd6n|                    d          rdnd7} |sW|                    d          rB|                    d8          s|                    d9          rd:|                    d           }|                    d;          }!t          |!t                    r(|!5                                r|!5                                }nt          |          }d7} |tm          ?          | d<}"|r||"d=<   |r||"d><   to          ||          }#|#r|#|"d?<   Dd         5  t5          D           d d d            n# 1 swxY w Y   t'          d@E|"           | d7k    rt          |t                    rq|5                                r\	 ddAl8m9}$ D                    d          pd}%|%r	 tu                                          dB          pi }&tg          |&                    dCdD          pdD          }'n# t,          $ r dD}'Y nw xY w |$|%|'E          }(|(;                                rt|(<                    |d3F          })|)                    d          pd}*|*rt'          dGEdH|*dI           |)                    dJ          r|)                    dK          pd}+|+r|+}nJ# t,          $ r=},tK          dLt{          |,          j>         dM|, tL          j'        "           Y d },~,nd },~,ww xY wD                    dN          }-|-r| d7k    rt                      }.|.rwD                    d          pE}/	 |.@                    |/|-          rd DdN<   nC# tb          $ r+}0d DdN<   t          B                    dO|/|0           Y d }0~0nd }0~0wt,          $ r Y nw xY w| d7k    rt          |t                    r|5                                rt          Ft                    rpF5                                r\	 ddPlCmD}1  |1t                      D                    d          pEF|D                    d-g                      n# t,          $ r Y nw xY w| d7k    rt          |t                    r|5                                rt                      r	 ddQlFmG}2 |}3t          jI        |2|3fd3R          J                                 nW# t          $ r t          L                    dS           Y n1t,          $ r%}4t          L                    dT|4           Y d }4~4nd }4~4ww xY wn@# t,          $ r2}4dd lM}5|5N                                }6	 t          jP        t          jQ        R                    t                    d3U           t          t          dVdWX          5 }7|7U                    dYt3          jV        dZ           d[E d\           |7U                    |6           d d d            n# 1 swxY w Y   n# t,          $ r Y nw xY wtK          d]t{          |4          j>         dM|4 tL          j'        d3^           t'          dEdt          |4          i           Y d }4~4nd }4~4ww xY w	 |  ||            n# t,          $ r Y nw xY w|t/          |           t1          |           Dd         5  dDd<   t3          j                    Dd<   t5          D           d d d            n# 1 swxY w Y   t'          dEt7          ?D                     n# 	 |  ||            n# t,          $ r Y nw xY w|t/          |           t1          |           Dd         5  dDd<   t3          j                    Dd<   t5          D           d d d            n# 1 swxY w Y   t'          dEt7          ?D                     w xY w|rۉDd         5  D                    d          r	 d d d            d S d3Dd<   d d d            n# 1 swxY w Y   	 t'          d_E           t          CED|           no# t,          $ rb}8tK          d`t{          |8          j>         dM|8 tL          j'        "           Dd         5  dDd<   d d d            n# 1 swxY w Y   Y d }8~8nd }8~8ww xY w	 ddalXmY}9 |9Z                                D ]\  }:};Dd         5  D                    d          r)|9j[        \                    |:           	 d d d             d S d3Dd<   d d d            n# 1 swxY w Y   	 t'          d_E           t          CED|;           # t,          $ rb}<tK          dbt{          |<          j>         dM|< tL          j'        "           Dd         5  dDd<   d d d            n# 1 swxY w Y   Y d }<~<d }<~<ww xY wd S # t,          $ r>}=tK          dct{          |=          j>         dM|= tL          j'        "           Y d }=~=d S d }=~=ww xY w)dNr   )reset_current_session_keyset_current_session_keyr   rr  r  r  @)preprocess_context_references)get_model_context_lengthr   r   rx  r  rk  _config_context_length)rx  r  rk  config_context_length)r   allowed_rootro  r   r  r   zContext injection refused.r  Fr   rG  r  )decide_image_input_modebuild_native_content_parts)_read_main_model_read_main_providerr  ry  codex_app_serverr   zA[tui_gateway] image_routing decision failed, defaulting to text: r\  nativez.[tui_gateway] native image attachment skipped z unreadable path(s)c              3   H   K   | ]}|                     d           dk    V  dS )r  r  Nr3  r)  s     r@   r  z2_run_prompt_submit.<locals>.run.<locals>.<genexpr>  s1      LLquuV}};LLLLLLrw   z:[tui_gateway] native attach failed, falling back to text: c                     d         5  t          |            d d d            n# 1 swxY w Y   d| i}r                    |           x}||d<   t          d|           d S )Nr  r   r  zmessage.delta)rC  feedr  )r?  r  r  r   r  streamers      r@   _streamz0_run_prompt_submit.<locals>.run.<locals>._stream*  s    ^, ; ;*7E:::; ; ; ; ; ; ; ; ; ; ; ; ; ; ;!5/ ,hmmE&:&:!: G*+GJ'osG44444s   '++)conversation_historystream_callbackr  r0  r:  r  r   z@[tui_gateway] prompt.submit: history_version mismatch (expected=z	 current=u1   ) — agent output NOT written to session historyuh   History changed during this turn — the response above is visible but was not saved to session history.TrJ  final_responser  completer  partialzError: last_reasoning)r   rD  r  rh  r   r  zmessage.completeGoalManagergoalsr     r   default_max_turns)user_initiatedr  r  r  should_continuecontinuation_promptz-[tui_gateway] goal continuation hook failed: r!   rR  z)Dropping pending title for session %s: %s)maybe_auto_title
speak_textr  z/voice TTS skipped: hermes_cli.voice unavailablezvoice TTS dispatch failed: %sr   r   r   r   u"   
=== turn-dispatcher exception · r   u    · sid=r    z[gateway-turn] r"   r{  z1[tui_gateway] goal continuation dispatch failed: rw  z7[tui_gateway] completion notification dispatch failed: z-[tui_gateway] completion queue drain failed: )]r  r  r  r  r   r   r  r  r  rJ   r   r2   agent.context_referencesr  rA  r  r   r  blockedr  r&   r  r1   r   r  r/   rE  r  r  agent.image_routingr  r  agent.auxiliary_clientr  r  r  r  r6   r7   r8   r  r  r  r	  inspect	signaturerun_conversation
parametersr1  r%  r   r  rV  r3   rB  rL   hermes_cli.goalsr  r   	is_activeevaluate_after_turnr  r5   r  r  r   r  agent.title_generatorr  _voice_tts_enabledhermes_cli.voicer  r   r   r   ImportErrorr   r%   
format_excr(   r)   r*   r+   r,   r-   r.   r0   r_  r|  rw  drain_notificationsr}  r   )Gapproval_tokensession_tokensr  goal_followupr  r  _profile_home_strr   r  ri  r  r  ctx_lenr  run_messager  r  r  r  _tui_load_config_cfg_mode_img_exc_parts_skippedr  
run_kwargsr  r  status_notecurrent_versionr   r  lrr  r  r  sid_key	goals_cfggoal_max_turnsgoal_mgrdecisionverdict_msgcont_prompt	_goal_excrO   _pdb_session_keyr   r  r  spokenr  r%   r=   r>   	_cont_excrw  _evtsynth_n_exc
_drain_excr  r  r  r:  imagesr   r   r  r   sG                                                                 @r@   r   z_run_prompt_submit.<locals>.run  sH   
Z	F       
 54W]5KLLN1'-2HIIN 'N ; ;  I56GHH
 C   w''C!'***;;vr**D+D11HF&#&& %3&==RRRRRRIIIIII22E7B//C>3C3C$UJ;;Ar#E9b99?R$UJ;;Ar*17+ +   43!$#*	   ; 	%tyy'>'> (<;   t!---n===   %*:666">222( . .%*	")-&$W---. . . . . . . . . . . . . . . .#}UG'D'DEEEEEK	   &K 1O#               RQQQQQ++--D33++--((** E
 uj"559KKK &  # # #f\dff Z    #EEEEEE# H$$S+E+E"", ,( $ ! sQTU]Q^Q^ s s s%(Z    LLVLLLLL W*0KK*Fvv*V*VK$ S S ScYacc!$    'C66&R&RS #?vv"N"NK5 5 5 5 5 5 5 )-W#* J 1%2H I I TTT,3M,BJy)z*   +U+KFF:FFF!NK&$'' <$fjj44d;;  0  *-gkk:KQ.O.O*P*P*o==17
1CGI.9H19LG$566 "!O-<!O !OGV!O !O !O &)Z	   !H ()              > 1eRV    jj!1266 zz-00HMM$*JJw$7$7GZ   :G!4!4 :JJx((:,2JJy,A,A: :FJJw$7$799CZZ 011b#&& 0288:: 0%'XXZZN&kk#"Z->->&QQG 6'5$ 1%0	"%c400H /&.
#( . .$W---. . . . . . . . . . . . . . .$c7333 ##
3(<(<###<<<<<<%kk-88>BG @0(1(@(@(FBI-0{B1O1O1USU-V-VNN( 0 0 0-/NNN0#.;'..<$ $ $ $--// @'/'C'C #/3 (D ( (H +3,,y*A*A*GRK* " %$3$'-3[$I$I!" !" !"
  (||,=>> @.6ll;P.Q.Q.WUW#. !@4?M    C	??3C C7@C C Z         {{?33H Fj00yy #*;;}#=#=#DL11,II <7;GO4%    480G(#        %   
 *$$sC(( %IIKK % tS)) % JJLL	 %FFFFFF$$		M229cIr22    !   D *$$sC(( %IIKK % '(( %

G;;;;;; F$)	$  egggg" V V VNN#TUUUUU  G G GNN#BAFFFFFFFFG 	5 	5 	5((**E	BGOOJ77$GGGG*cG<<< #GGS=)<==S SGJS S S   GGENNN# # # # # # # # # # # # # # #    9$q''"299a99
RV    '3CFF 344444444#	5&!---n===   %*:666">222( . .%*	")-&$W---. . . . . . . . . . . . . . . .#}UG'D'DEEEE!---n===   %*:666">222( . .%*	")-&$W---. . . . . . . . . . . . . . . .#}UG'D'DEEEE  	/( * *;;y))  	* * * * * * * *
 &*	"* * * * * * * * * * * * * * *
/os+++"3WmDDDD / / /?I/? ?3<? ?   
 ^, / /).GI&/ / / / / / / / / / / / / / //	??????/CCEE 3 3e^, . .{{9-- (9==dCCC. . . . . . . . . *.GI&	. . . . . . . . . . . . . . .

3/3///&sC%@@@@  3 3 3=<<0= =4:= = Z   
 !0 3 3-2	*3 3 3 3 3 3 3 3 3 3 3 3 3 3 333 3"  	 	 	=
##,= =0:= =Z         	s  Fh F 
F*)F*+HHH8h AJ h 
K$ K	h 	K	h A)M h 
N.M?:h ?N,h 1+O h O1.h 0O11Ah A"R:.h :R>>h R>Eh X7+h 7X;;h >X;?Ah ^ &A[/ .^ /[>;^ =[>>B^ h 
_!3_h _Ah &a h 
b!a2-h 2b?h bAh A
d) (h )
d63h 5d66A h 72f* )h *$g>h 	g>g94h 9g>>h o, m l;'Ak6Ak:kk
	
kk
	kl;
kl;kAl;6o, ;m  o, m 
mm
+ooo,r.o<;r<
p	rp		+r4+q+r+q//r2q/3#r#ssss$"t 
u3;u.uu.u"	"u.%u"	&u..u37'z 1w.z w."z .w2	2z 5w2	6z :"xz 
z	';z"y4(z4y88z;y8<z?z z		z 
{3{{Tr   )
r	  r  r   r   r   r>  r  r   r   r   )	r   r  r   r   r   r  r  r:  r  s	   ```` @@@@r@   r_  r_    s|   		  0 0wy)**gkk*;Q??@@gkk"3R8899%'!"'++o66== 	0 $///0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 GE	/3V V V V V V V V V V V Vp C---3355555s   BB66B:=B:zclipboard.pastec           	         t          ||           \  }}|r|S 	 ddlm}m} n+# t          $ r}t          | dd|           cY d }~S d }~ww xY w|                    dd          dz   |d<   t          dz  }|                    dd	           |d
t          j
                                        d           d|d          dz  } ||          s=t          d|d         dz
            |d<    |            rdnd}	t          | d|	d          S |                    dg                               t!          |                     t          | dt!          |          t#          |d                   dt%          |                    S )Nr   )has_clipboard_imagesave_clipboard_image  zclipboard unavailable: r  r   r  Tr  clip_r  rH  .pngz)Clipboard has image but extraction failedzNo image found in clipboardF)attachedr  r  )r  r*   r  )r  hermes_cli.clipboardr  r  r1   ra  r   rk  r  r   rD  r0   r  r  r  r  r2   r  r  )
r   r  r   r  r  r  r  img_dirimg_pathr   s
             r@   rH  rH  P  s   %%LGS
 
>RRRRRRRRR > > >C<<<========>  '{{?A>>BGOX%GMM$M...
[(,..))/::
[
[W_=U
[
[
[	\   )) =#&q'/*BQ*F#G#G  #"$$/77. 	
 3Us;;<<<("--44S]]CCCMM!2344	
 	
 (##		
  s   " 
A
AA
A
zimage.attachc           
      V   t          ||           \  }}|r|S t          |                    dd          pd                                          }|st	          | dd          S 	 ddlm}m}m}m	}  ||          }	|	r|	d         }
|	d         }n/ ||          \  }} ||          }
|
t	          | dd	|           S |
j
                                        |vrt	          | dd
|
j                   S |                    dg                               t          |
                     t          | dt          |
          t!          |d                   ||p
d|
j         ddt#          |
                    S # t$          $ r(}t	          | dt          |                    cY d }~S d }~ww xY w)Nr*   r     rM  r   )_IMAGE_EXTENSIONS_detect_file_drop_resolve_attachment_path_split_path_input	remainderr  zimage not found: zunsupported image: r  T[User attached image: r  )r  r*   r  r  r   r  )r  r2   r   r3   ra  r  r  r  r  r  r  r   rE   r  r  r  r  r  r1   )r   r  r   r  r   r  r  r  r  dropped
image_pathr  
path_tokenr  s                 r@   rH  rH  x  s1   %%LGS
 

fjj$$*
+
+
1
1
3
3C 0C/// '	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 $#C(( 	I J,II$5$5c$:$:!J	11*==J!C'G:'G'GHHH""$$,===T#J#J#JKKK,b1188ZIII JW%6788&!P%Pjo%P%P%P  j))

 

 
	
  ' ' 'Cs1vv&&&&&&&&'s,   #AE6 <3E6 0BE6 6
F( F#F(#F(i  i   r  ))s   PNG

r  )s   .jpg)s   GIF87a.gif)s   GIF89ar  )s   BM.bmp_IMAGE_MAGICr   mime_prefixc                N   ddl }ddl}|                                 }|                    d|                    |           d||j                  }|r|                    d          }|                    dd|          }	 |                    |d	          S # t          $ r Y dS w xY w)
zDecode a base64 (optionally data-URL-wrapped) payload.

    Accepts ``data:<mime_prefix>...;base64,<b64>`` plus embedded whitespace.
    Returns the decoded bytes, or ``None`` when the input isn't valid base64.
    r   Nz^data:z[a-zA-Z0-9.+-]*;base64,(.*)$r   \s+r   Tvalidate)
base64rer3   matchescapeDOTALLgroupsub	b64decoder1   )r   r  _base64_recleanedrg  s         r@   _decode_attach_base64r    s     iikkG		G#**[))GGG
	 	A
 	 ''!**ggfb'**G  4 888   tts   ?B 
B$#B$	img_bytesfilenamec                    |r*t          |          j                                        }|r|S | dd         }|                    d          r|dd         dk    rdS t          D ]\  }}|                    |          r|c S dS )	zResolve an image extension from a filename hint, else magic bytes.

    Falls back to ``.png``. WebP needs the RIFF/WEBP container check, handled
    before the generic table.
    Nr  s   RIFFrK     s   WEBP.webpr  )r   r  r   r0  r  )r  r  r  r  sigexts         r@   _sniff_image_extr    s      h&,,.. 	MSbS>Dw D2J'$9$9w   S??3 	JJJ	6rw   c                  p    	 ddl m}  t          |           S # t          $ r t          h d          cY S w xY w)Nr   r  >   .jpegr  r  r  r  r  )r  r  r_  r1   r  s    r@   _allowed_image_extensionsr    sc    M))))))*+++ M M MKKKLLLLLMs    55r  r  c                   |                      dd          dz   | d<   t          dz  }|                    dd           t          j                                        d          }|| d| d| d          | z  }	 |                    |           n+# t          $ r t          d| d         dz
            | d<    w xY w| 	                    d	g           
                    t          |                     |S )
a#  Write image bytes into the gateway's images dir and queue them.

    Mirrors what ``image.attach`` does for a local path: appends to
    ``session["attached_images"]`` so the next ``prompt.submit`` picks it up via
    the existing native-image-attach pipeline. Returns the written path.
    r  r   r   r  Tr  r  rH  r  )r   rk  r  r   rD  r0   write_bytesr1   r  r  r  r2   )r   r  r  r  r  r;  r  s          r@   _queue_attached_imager    s     '{{?A>>BGOX%GMM$M...		 	 	1	1BFIIRII'/*BICIIIHY''''   #&q'/*BQ*F#G#G  ("--44S]]CCCOs   :B (B8zimage.attach_bytesc                    t          ||           \  }}|r|S t          |                    d          p|                    d          pd                                          }|st	          | dd          S t          |d          }|t	          | d	d
          S |st	          | d	d          S t          |          t          k    r/t          dz  }t	          | ddt          |           d| d          S t          |                    dd          pd          }t          |                    dd          pd                                                                          }|r|	                    d          sd|z   }t          ||p|rd| nd          }	|	t                      vrt	          | dd|	           S 	 t          |||	d          }
n+# t          $ r}t	          | dd|           cY d}~S d}~ww xY wt          | dt          |
          t          |d                   dd|
j         dt          |          dt!          |
                    S ) u  Attach an image to the session from base64 bytes (remote-client path).

    A desktop app or web dashboard running on a DIFFERENT machine than the
    gateway can't hand us a local path — that file only exists on the client's
    disk. So it uploads the raw image bytes (base64) and we write them into the
    gateway's own images dir. The response shape mirrors ``image.attach`` so the
    client treats both identically.

    Params:
      content_base64 / data (str, required): base64 image bytes. Accepts a
        ``data:image/...;base64,`` prefix and embedded whitespace. ``data`` is
        an accepted alias for older desktop builds.
      filename / ext (str, optional): extension hint. Without it, magic bytes
        identify PNG/JPEG/GIF/WebP/BMP, falling back to ``.png``.
    content_base64r}  r   r  zcontent_base64 requiredzimage/r  Nr  data is not valid base64zimage is empty   r[  zimage too large ( bytes; cap is  MB)r  r  rq  xr  zunsupported image extension: uploadr  r  zwrite failed: Tr  r  r  )r  r*   r  r  r   bytes)r  r2   r   r3   ra  r  r  _ATTACH_BYTES_MAX_BYTESr   r0  r  r  r  r1   r  rE   r  )r   r  r   r  raw_b64r  mbr  ext_hintr  r  r  s               r@   rH  rH    s   " %%LGS
 
&**-..J&**V2D2DJKKQQSSG :C8999%g8DDDIC9::: 1C/000
9~~///$5CZ3y>>ZZRTZZZ[[[6::j"--344H6::eR((.B//5577==??H "++C00 ">
9h&VX3U>x>>>SU
W
WC
+----CDsDDEEE5()SRRR 5 5 5C333444444445 MM!2344=X]===^^	
 	
 (##	
  s   <G 
G8G3-G83G8z
pdf.attachc                 |   ddl }ddl}ddl}t          ||           \  }}|r|S |                    d          t          | dd          S t          |                    dd          pd                                          }t          |                    d          p|                    d	          pd                                          }|s|st          | d
d          S |	                    d          5 }	t          |	          }
|rt          |d          }|t          | dd          cddd           S |st          | dd          cddd           S t          |          t          k    r;t          dz  }t          | ddt          |           d| d          cddd           S |dd         dk    rt          | dd          cddd           S |
dz  }|                    |           t          |                    dd          pd          }n4	 ddlm}  ||          }n# t"          $ r d}Y nw xY w|!t          |                                          s t          | dd |           cddd           S t          |          j                                        d!k    r2t          | dd"t          |          j                   cddd           S t          |                                          j        t          k    r+t          dz  }t          | dd#| d$          cddd           S t          |          }|j        }	 t1          |                    d%          pd&          }|                    d'          }|t1          |          nd}n4# t2          t4          f$ r  t          | d
d(          cY cddd           S w xY w|d&k     rt          | d
d)          cddd           S ||t6          z   d&z
  }||k     rt          | d
d*          cddd           S ||z
  d&z   t6          k    r&t          | d+d,t6           d-          cddd           S |
d.z  }dd/d0d1d2t          |          d3t          |          t          |          t          |          g
}	  |j        |d4d4d5|j        6          }n-# |j        $ r  t          | dd7          cY cddd           S w xY w|j        dk    ro|j         p|j!        pd                                "                                d8d         }t          | dd9d:#                    |          z             cddd           S tI          |
%                    d;                    }|st          | dd<          cddd           S g }|D ]}|j&        '                    d=d&          d>         }	 t1          |          }n"# t4          $ r |t          |          z   }Y nw xY wtQ          ||)                                d?d@|           }|*                    t          |          |dAtW          |                     tY          | d4|t          |          |t          |dB                   dC| dDt          |           dEdF          cddd           S # 1 swxY w Y   dS )Ga  Attach a PDF by rendering each page to PNG and queuing the pages.

    Anthropic's vision pipeline accepts images, not PDFs, so this runs
    ``pdftoppm`` (poppler-utils) at 150 DPI per page and queues each rendered
    page as an attached image. Accepts either a host ``path`` (local mode) or
    base64 ``content_base64`` (remote upload). Caps at 50 MB / 25 pages per call.

    Requires ``pdftoppm`` on $PATH (``apt install poppler-utils``); returns 5028
    if missing.
    r   Npdftoppm  z7pdftoppm not installed (poppler-utils package required)r*   r   r  r}  r  zpath or content_base64 requiredpdf_attach_r%  zapplication/pdfr  r  r  zdecoded PDF is emptyr   r[  zPDF too large (r!  r"     s   %PDF-z0payload is not a PDF (missing %PDF- magic bytes)z	input.pdfr  zuploaded.pdf)r  r  zPDF not found: z.pdfznot a PDF: zPDF too large; cap is z MB
first_pager   	last_pagez%first_page/last_page must be integerszfirst_page must be >= 1zlast_page must be >= first_page  zpage range exceeds cap of z pages per attach callr  z-pngz-r150z-fz-lTr`  )r
  r   r   r   zpdftoppm timed out (>120s)zpdftoppm failed: z | z
page-*.pngz)pdftoppm produced no pages (corrupt PDF?)-r  r  pdf_p)r*   r  r  z[User attached PDF: r  z
 page(s))])r  r  pages_attachedr  r  r   )-shutilr   tempfiler  whichra  r2   r   r3   TemporaryDirectoryr   r  r  _PDF_ATTACH_MAX_BYTESr  r  r  r1   is_filer  r   rE   r.  st_sizer  r1  r%  _PDF_ATTACH_MAX_PAGESr   r  TimeoutExpiredr  r8   r   r4   r&   r  rG  stemr  r  
read_bytesr  r  r  )r   r  r8  r   r9  r   r  rP  r(  tdtd_path	pdf_bytesr)  pdf_pathdisplay_namer  r~  r0  last_page_paramr1  
out_prefixr   resr  r  attached_pagesre  page_numpage_intdsts                                 r@   rH  rH  9  s	    MMMOOO%%LGS
 
||J'CXYYY6::fb))/R006688H&**-..J&**V2D2DJKKQQSSG BG BC@AAA		$	$M	$	:	: W
br(( 	)-gCTUUUI C'ABBW
 W
 W
 W
 W
 W
 W
 W
  ?C'=>>W
 W
 W
 W
 W
 W
 W
 W
 9~~ 555*{;C'`Y'`'`XZ'`'`'`aaW
 W
 W
 W
 W
 W
 W
 W
 !}((C'YZZW
 W
 W
 W
 W
 W
 W
 W
 ,H  +++vzz*b99K^LLLL 88888833H==       tH~~'='='?'?C'C'C'CDD1W
 W
 W
 W
 W
 W
 W
 W
2 H~~$**,,66C'JT(^^5H'J'JKK5W
 W
 W
 W
 W
 W
 W
 W
6 H~~""$$,/DDD*{;C'G'G'G'GHH;W
 W
 W
 W
 W
 W
 W
 W
< H~~H#=L	LVZZ55:;;J$jj55O0?0KO,,,QUII:& 	L 	L 	LT#JKKKKMW
 W
 W
 W
 W
 W
 W
 W
J	L >>T#<==SW
 W
 W
 W
 W
 W
 W
 W
T "%::Q>Iz!!T#DEE[W
 W
 W
 W
 W
 W
 W
 W
\ z!A%(===T#m@U#m#m#mnn_W
 W
 W
 W
 W
 W
 W
 W
b v%
e#j//4YMM3z??

	A *.dsZdZlmmmCC( 	A 	A 	AT#?@@@@uW
 W
 W
 W
 W
 W
 W
 W
r	A>QJ2#*299;;FFHHMDT#6D9I9I#IJJ{W
 W
 W
 W
 W
 W
 W
 W
~ ',,|4455 	PT#NOOCW
 W
 W
 W
 W
 W
 W
 W
F  	\ 	\Cx~~c1--b1H<x== < < <%N(;(;;<'1A1A6RdZbRdRdeeeC!!3s88X"Z"ZUXIYIY"Z[[[[ ("%n"5"5'W%6788^|^^s>?R?R^^^ 

 

[W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
 W
s   76Z1:Z1AZ1,Z1AZ1H+*Z1+H:7Z19H::9Z1 AZ1AZ16Z1ANZ1"O<Z1
OZ11%Z1#*Z1AZ1 R;:Z1;S%Z1$S%%A0Z1"4Z1#'Z1WZ1W:7Z19W::B*Z11Z58Z5c                     ddl }t          |                    d          a| rt                              |           s| S d| vrd|  dS d| vrd|  dS d| vrd|  dS | S )zQuote a context-ref value when it contains whitespace or bracket chars.

    Mirrors the desktop ``formatRefValue`` so the staged ``@file:`` ref round-trips
    through ``agent.context_references`` cleanly.
    r   Nz[\s()\[\]{}<>"'`]r  r  r  )r   _ATTACHMENT_REF_NEEDS_QUOTING_REcompiler  )r  r
  s     r@   _format_ref_valuerR    s      (/+.;;7O+P+P( 8??FF 
%5|||
%5|||
%5|||Lrw   r   c                 j   t          t          |                                                     }	 |                                                    |          }t	          |                              t          j        d          S # t          $ r$ t	          |                                          cY S w xY w)zKWorkspace-relative path for an attachment, or the absolute path if outside.r  )	r   r  rj  rO  r2   r  r(   sepr%  )r   r   	workspacerels       r@   _attachment_ref_pathrW    s    \'**++3355I%nn**9553xx,,, % % %6>>##$$$$$%s   AB +B21B2c                     t          t          |                                                     dz  dz  }|                    dd           |S )Nz.hermeszdesktop-attachmentsTr  )r   r  rj  r  )r   r#  s     r@   _desktop_attachment_dirrY    sI    W%%&&..009<?TTDJJtdJ+++Krw   c                     dd l }t          t          | pd                                                    j        }|                    dd|          }|                                                    d          }|pdS )Nr   r   z[\x00-\x1f]+rH  rq  
attachment)r  r   r2   r3   rE   r  )rE   r
  r  s      r@   _sanitize_attachment_namer\    sq    S__**,,--2Ii88I!!'',,I$$rw   r#  c                     | |z  }|                                 s|S t          |          j        pd}t          |          j        }d}	 | | d| | z  }|                                 s|S |dz  }()Nr[  rk   Tr5  r   )rl  r   rA  r  )r#  r  r  rA  r  counternext_candidates          r@   _unique_attachment_pathr`    s    xI >>.,D(^^"FG4 ; ;' ;6 ; ;;$$&& 	"!!1	rw   c                 (   | sdS 	 ddl m}m}m} n# t          $ r Y dS w xY w ||           }|r't          |d                                                   S  ||           \  }} ||          }|!t          |                                          ndS )z<Resolve a raw path token to a gateway-visible file, or None.Nr   )r  r  r  r*   )r  r  r  r  r1   r   rj  )r   r  r  r  r  r  
_remainderr~  s           r@    _resolve_gateway_attachment_pathrc    s     tVVVVVVVVVVV   tt  $$G /GFO$$,,.....s33J
''
33H'/';4>>!!###Es   
 
data_urlc                 l   ddl }ddl}ddl}| pd                                }|                    d||j        |j        z            }|r|                    d          }|                    dd|          }	 |	                    |d          S # t          |j        f$ r}t          d	          |d}~ww xY w)
u,  Decode a ``data:<any-mime>;base64,<b64>`` payload to bytes.

    Unlike ``_decode_attach_base64`` (image-mime-specific), this accepts any
    media type — text/csv, application/pdf, etc. — so non-image file uploads
    round-trip. Also tolerates a bare base64 string with no data-URL prefix.
    r   Nr   z-^data:[^;,]*(?:;[^;,=]+=[^;,]+)*;base64,(.*)$r   r  Tr  zinvalid data_url payload)r  binasciir  r3   r  r  Ir  r  r  r%  Error)rd  r	  	_binasciir
  r  rg  r   s          r@   _decode_attachment_data_urlrj     s         ~2$$&&G		BGSZZ]Z_M_``A ''!**ggfb'**G>  4 888	( > > >344#=>s   6B B3B..B3rP  c                \   t          t          |                                                     }t          |          }|E	 |                    |           |dfS # t
          $ r |                                }|j        }Y nVw xY w|st          d          t          |          }t          |p"t          t          |pd                    j                  }t          |           }t          |t          |                    }	|	                    |           |	                                dfS )u  Make a desktop file attachment available to the remote gateway agent.

    Three cases:
      1. The path resolves to a file already INSIDE the session workspace — use
         it as-is (no copy, ``uploaded=False``).
      2. The path resolves to a gateway-visible file OUTSIDE the workspace — copy
         it into ``.hermes/desktop-attachments/`` so the ``@file:`` ref resolves.
      3. The path doesn't exist on the gateway (the common remote case: it's a
         path on the CLIENT's disk) — decode the uploaded ``data_url`` bytes and
         write them into ``.hermes/desktop-attachments/``.

    Returns ``(stored_path, uploaded)``.
    NFz2file not found on gateway and no data_url providedr   T)r   r  rj  rc  rO  r%  rB  rE   rj  r\  r2   rY  r`  r  )
r   rP  rd  rE   rU  r~  r  r  
upload_dirr   s
             r@   _stage_session_file_attachmentrm    s0   ( \'**++3355I/99H	%  +++U?" 	% 	% 	%))++G}HHH	%  	SQRRR-h77,T-ST#hn":M:M5N5N5STT(11J$Z1J81T1TUUF
w>>T!!s   A %BBzfile.attachc                    t          ||           \  }}|r|S t          |                    dd          pd                                          }t          |                    dd          pd                                          }t          |                    dd          pd                                          }|s|st	          | dd          S 	 t          ||||          \  }}t          ||          }	t          | d|j        t          |          |	d	t          |	           |d
          S # t          $ r(}
t	          | dt          |
                    cY d}
~
S d}
~
ww xY w)aB  Stage a non-image file attachment into the session workspace.

    The image/PDF path renders to vision tiles; this one keeps the file as a
    readable artifact and returns a workspace-relative ``@file:`` ref so the
    agent's file tools (and ``agent.context_references``) can read it. Solves the
    remote-gateway case where the desktop passes a path that only exists on the
    CLIENT's disk: the client uploads ``data_url`` bytes and we materialize the
    file on the gateway.

    Params:
      session_id (str, required)
      path (str): client/host path of the file (used for naming + local-mode
        gateway-visible resolution).
      data_url (str): ``data:<mime>;base64,<b64>`` upload of the file bytes,
        required when the path isn't visible to the gateway.
      name (str, optional): preferred filename.
    r*   r   rd  rE   r  zpath or data_url required)rP  rd  rE   T@file:)r  rE   r*   ref_pathref_textuploadedr-  N)r  r2   r   r3   ra  rm  rW  r  rE   rR  r1   )r   r  r   r  r   rd  rE   stored_pathrr  rp  r  s              r@   rH  rH  ?  s   & %%LGS
 

fjj$$*
+
+
1
1
3
3C6::j"--344::<<Hvzz&"%%+,,2244D <x <C:;;;' >cH4!
 !
 !
X (== #(K(($B%6x%@%@BB$ 

 

 
	
  ' ' 'Cs1vv&&&&&&&&'s   AD2 2
E$<EE$E$zimage.detachc                    t          ||           \  }}|r|S t          |                    dd          pd                                          st	          | dd          S |                    dg           }t          |          }fd|D             |d<   t          | t          |d                   |k    t          |d                   d          S )Nr*   r   r  rM  r  c                      g | ]
}|k    |S rv   rv   )r4  r*   r   s     r@   r6  z_.<locals>.<listcomp>x  s    !I!I!I4TS[[$[[[rw   )r;  r  )r  r2   r   r3   ra  r  r  r  )r   r  r   r  r  beforer   s         @r@   rH  rH  n  s    %%LGS
 

fjj$$*
+
+
1
1
3
3C 0C/// 1266F[[F!I!I!I!I6!I!I!IGG$56776A!2344	
 	
  rw   zinput.detect_dropc           
         t          ||           \  }}|r|S 	 ddlm} t          |                    dd          pd          } ||          }|st          | ddi          S |d         }|d         }|d	         r|                    d
g                               t          |                     |p
d|j         d}	t          | ddt          |          t          |d
                   |	dt          |                    S d| d|rd| ndz   }	t          | ddt          |          |j        |	d          S # t          $ r(}
t          | dt          |
                    cY d }
~
S d }
~
ww xY w)Nr   )r  r   r   matchedFr*   r  is_imager  r  r  T)rx  ry  r*   r  r   z[User attached file: r   )rx  ry  r*   rE   r   r  )r  r  r  r2   r   r  r  r  rE   r  r  r1   ra  )r   r  r   r  r  r   r  	drop_pathr  r   r  s              r@   rH  rH    s   ,,LGS
 
''))))))&**VR((.B//##C(( 	0sY.///FO	K(	: 	0"55<<S^^LLLJ J J J JD# $	NN ):!;<<   "),,
 
 
 4y333 )1r
 !I! 	
 	
 		
  ' ' 'Cs1vv&&&&&&&&'s+   A	D; #BD; 7D; ;
E-E("E-(E-zprompt.backgroundc                    t          ||           \  }|r|S |                    dd          |                    dd          cst          | dd          S dt          j                    j        d d          fd}t          j        |d	
                                           t          | di          S )Nr   r   r     text requiredbg_r  c                  
   t          t                              } 	 ddlm}  |d
i t	          d                                                 }t          dt          |t                    r#|	                    dt          |                    nt          |          d           n.# t          $ r!}t          dd	| d           Y d }~nd }~ww xY wt          |            d S # t          |            w xY w)Nr   r   r  r  )user_messager  zbackground.completer  r  r   error: rv   )r  r  r  r  r  r  r  r   r   r   r2   r1   r  )r  r  r  r  r  r   r  r   s       r@   r   z_.<locals>.run  sp   -g<;P;PQQQ	3))))))W  *77+;WEE !     %& &fd33)

#3S[[AAA [[      	 	 	%#]q]];;       	 #>22222">2222s0   BB2 1C1 2
C<CC1 CC1 1DTr   r  )
r  r   ra  rM  rN  rO  r   r   r   r  )r   r  r  r   r  r   r  r   s       @@@@r@   rH  rH    s    %%LGS
 
::fb))6::lB+G+GLD& 0C///*DJLL$RaR(**G3 3 3 3 3 3 3 3@ C---33555sY()))rw   zpreview.restartc                 b  	
 t          ||           \  }|r|S t          |                    d          pd                                          }t          |                    d          pd                                          }t          |                    d          pd                                          }|st	          | dd          S dt          j                    j        d d          |                    d	d          t                    	t          	          }d

                    d ddd| d|pd d|rd| nd|rdnd|rdnd ddddddddddddddfD                       	 |r<t          j                            t          j                            |                    nd

r!t          j                            
          sd
n# t           $ r d
Y nw xY w	
fd }t#          j        |d!"                                           t)          | d#i          S )$Nr'  r   r   r  r|  zurl requiredpreview_r  r   r   c              3      K   | ]}||V  	d S r   rv   )r4  r   s     r@   r  z_.<locals>.<genexpr>  s>        8 =     rw   z8The desktop preview pane cannot load a local server URL.zPreview URL: zCurrent working directory: r  zPreview console:
uC  The conversation history above is from the user's main session — including the commands you (the assistant) previously ran to start servers, edit files, or check ports. Use it to figure out exactly which server should be running at this Preview URL. The user did not start a brand new task; recover what they had working.zPRestart exactly the app intended for the Preview URL, not Hermes Desktop itself.zcThe Preview URL and port are the target. Preserve that target unless you conclude it is impossible.zIf the prior conversation shows a specific command that bound this URL/port, prefer re-running THAT exact command (in the same cwd) over guessing a new one.zFirst inspect what process, if any, owns the Preview URL port. If a stale server exists, inspect its cwd and prefer that cwd over the Hermes/Desktop process cwd.zThe Current working directory is only a hint. Do not assume it is the preview app root when the port owner or files indicate another root.zIf the console shows a module-script MIME error for src/main.tsx or similar, a static server is serving source files. Do not restart python -m http.server or any dumb static server for that app.zFor module-script MIME failures, inspect package.json/vite config in the candidate app root and start the real dev server/bundler (for example npm/pnpm/yarn dev) so module transforms happen.zBefore declaring success, verify the Preview URL responds with the intended app, not Hermes Desktop. If it serves Hermes/Desktop UI or another unrelated app, stop that process and report failure.z8Do not modify files. Do not ask the user unless blocked.z@Prefer existing project scripts or commands when they are clear.z:If a stale process owns the needed port, handle it safely.zOStart long-running servers detached/in the background, then return immediately.zLDo not run a foreground dev server command that blocks this background task.zaKeep the final response short: what command/server was started, or why it could not be restarted.c                  L   t          
pt                              } 	 ddlm} ddlm} 
r |d
i           	rdt          	           dnd}t          d	d
| d            |di t          d                   t                    
                    	pd           }t          |t                    r#|                    dt          |                    nt          |          }t          d|d           n.# t          $ r!}t          dd| d           Y d }~nd }~ww xY w	 ddlm}  |           n# t          $ r Y nw xY wt#          |            d S # 	 ddlm}  |           n# t          $ r Y nw xY wt#          |            w xY w)Nr  r   r  r  r   z (with z$ parent-session messages of context)r   r  zStarting hidden restart agentr  r  )r  r  r  r  zpreview.restart.completer  )clear_task_env_overridesrv   )r  r  r  r  r  r  r  r  r  r  r  r   r   r   r2   r1   r  r  )r  r  r  history_noter  r   r  r  r  parent_historypreview_cwdri  r   r  s           r@   r   z_.<locals>.run  s    .gK<`<X_K`K`bbb,	3))))))GGGGGG K++Ge[5IJJJ "S#n--SSSS 
 *#-[\-[-[\\  
 W  1''2BGLL,VW==  #%3%;t     fd++!

+S[[999[[ 
 ,f'SW6X6XYYYY 	 	 	*#]q]];;       	HHHHHH((1111   ">22222HHHHHH((1111   ">2222sf   C)D E/ 
D8D3.E/ 3D88E/ <E 
EE/F#1FF#
FF#FF#Tr   r  )r  r2   r   r3   ra  rM  rN  rO  r  r   r&   r(   r*   ry  rz  r{  r1   r   r   r   r  )r   r  r  r'  r   r  has_historyr   r  r  r  ri  r   r  s           @@@@@@r@   rH  rH    s   %%LGS
 

fjj%2
&
&
,
,
.
.C
fjj%2
&
&
,
,
.
.C&**Y''-2..4466G /C~.../)"1"-//GZZb))F-g66N~&&KYY   G!C!!>#*<>>.5=****2!BBr   V  V^q k p Y Q M RFNH]Zo5
    FFBEMbgoobg&8&8&=&=>>>2 	rw}}[99 	K   03 03 03 03 03 03 03 03 03 03d C---33555sY()))s   7A#G G*)G*c                 x   |                     dd          }t          5  t                               |          }|s!t          | dd| d          cd d d            S |\  }}|                     |d          t          |<   |                                 d d d            n# 1 swxY w Y   t          | ddi          S )NrL  r   r  zno pending z requestr  r   )r   rQ  rO   ra  rQ   r  r  )r   r  r  r  r,  rH  rR  s          r@   _respondr  S  s   

<$$A	  Q 	@T#>#>#>#>??        2jjb))
               sXt$%%%s   1B7BB#&B#zclarify.respondc                 $    t          | |d          S )Nanswerr  r   r  s     r@   rH  rH  _  s    C***rw   zterminal.read.respondc                 $    t          | |d          S )Nr   r  r  s     r@   rH  rH  d  s     C(((rw   zsudo.respondc                 $    t          | |d          S )Npasswordr  r  s     r@   rH  rH  j  s    C,,,rw   zsecret.respondc                 $    t          | |d          S )Nr  r  r  s     r@   rH  rH  o  s    C)))rw   zapproval.respondc                 @   t          ||           \  }}|r|S 	 ddlm} t          | d ||d         |                    dd          |                    dd          	          i          S # t
          $ r(}t          | d
t          |                    cY d }~S d }~ww xY w)Nr   r  r~  r   choicerZ  r  Fr  i  )r  r  r  r  r   r1   ra  r2   )r   r  r   r  r  r  s         r@   rH  rH  t  s    %%LGS
 
';;;;;;44M*JJx00 &

5% 8 8  	
 	
 		
  ' ' 'Cs1vv&&&&&&&&'s   AA+ +
B5BBBz
config.setc                 )  2 |                     dd          |                     dd          }}t                               |                     dd                    }|dk    r	 |st          | dd          S |r|                     d          rt          | d	d
          S |                     d          `|                     dd          }t          ||           t	          ||           }|r|S |                     d          t          | dd          S t          |                     dd          ||t          |                     dd                              }n6t          ddd i|t          |                     dd                              }t          | ||d         |d         |                     dd          |                     dd          d          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w|dk    rt          |pd          
                                                                2|r|                     d          nd }	|	t          |	dd           dk    }
nt                      dk    }
2dv rt          | ||
rdndd          S 2dv r|
rdnd}n"2dv rd}n2dv rd}nt          | dd|           S d }|dk    rXd d!lm} |	t          |	dd           nt!                      }|st          | dd"          S  ||          }|t          | dd#          S t#          d$|           |	|dk    rdnd |	_        t'          t          |	d%i           pi           }|                    dd            |                    d&d            |dk    r|                    |           ||	_        t/          |           t1          d'|                     dd          t3          |	|                     t          | ||d          S |d(k    rt          |pd          
                                                                22d)v rt          | |t5                      d          S 2d*vrt          | dd+|           S t#          d,2           t          | |2d          S |d-k    rg d.}|r"|                     d/t7                                nt7                      }|rR|d0k    rLt          |          
                                                                }||vrt          | dd1|           S nD	 |                    |          }n# t:          $ r d2}Y nw xY w||d3z   t=          |          z           }t#          d4|           |r'||d/<   |                     d          }	|	|d-k    |	_        t          | ||d          S |d5k    r t          |                     d6          pd7          
                                                                }	 d d8l m!}m"}m#} t          |pd          
                                                                2d9t          d:t          f2fd;}|d<k    rd d=l m$} tK                      }tM          |t&                    r|                     d>          nd }tM          |t&                    si } ||                     d?d@                    dAk    } ||          }t#          dB|rdAnd@           |rdCndD}tO          t          (                                          D ];\  }}|                     d          }	|	t1          d'|t3          |	|                     <t          | ||d<dE          S |r ||dF                   } ||          }|r ||dF                    dC}n ||dF                    dD}|                     d          }	|	3t1          d'|                     dd          t3          |	|                     nmtS          tT          j+                             dG                    } ||          }|rdCtT          j+        dG<   dC}n"tT          j+                            dGd            dD}t          | ||d7dE          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w|dHk    r	 d dIl,m-} t          |pd          
                                                                } | dJv rtK                      }tM          |                     dK          t&                    r|                     dK          ni }!tM          |!                     dL          t&                    r|!                     dL          ni }"dM|!dN<   dO|"dP<   |"|!dL<   |!|dK<   t]          |           |rdM|dN<   t          | |dQd          S | dRv rtK                      }tM          |                     dK          t&                    r|                     dK          ni }!tM          |!                     dL          t&                    r|!                     dL          ni }"d|!dN<   dS|"dP<   |"|!dL<   |!|dK<   t]          |           |rd|dN<   t          | |dTd          S  ||           }#|#t          | ddU|           S t#          dV|            |rj|                     d          U|#|d         _/        t/          |           t1          d'|                     dd          t3          |d         |                     t          | || d          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w|dWk    rt          |pd          
                                                                }|t`          vrt          | ddX|           S tK                      }tM          |                     dK          t&                    r|                     dK          ni }!tM          |!                     dL          t&                    r|!                     dL          ni }"||!dW<   tb          D ]}$||"|$<   |"|!dL<   |!|dK<   t]          |           t          | ||d          S |2                    dY          r|3                    dZd3          d3         }$|$tb          vrt          | dd[|$           S tK                      }tM          |                     dK          t&                    r|                     dK          ni }!tM          |!                     dL          t&                    r|!                     dL          ni }%t          |pd          
                                                                }|sB|%                    |$d            |%|!dL<   |!|dK<   t]          |           t          | |dd          S |t`          vrt          | ddX|           S ||%|$<   |%|!dL<   |!|dK<   t]          |           t          | ||d          S |d\k    rt          |pd          
                                                                }ti          h d]          }&||&vrt          | dd^|           S t#          d_|           t#          d`|dak    rdOndb           t          | ||d          S |dck    rt          |pd          
                                                                2tK                      }'tM          |'                     dK          t&                    r|'                     dK          ni }(t          |(                     ddd                    })2dv r|) }*n&2dek    rdM}*n2dAk    rd}*nt          | ddf|           S t#          dg|*           t          | ||*rdendAd          S |dhk    rt          |pd          
                                                                2tK                                           dK          }!tM          |!t&                    r|!ni }(tk          |(                     didj                    }2dv r|dAk    rdjndA}n)2dek    rdj}n 2tl          v r2}nt          | ddk|           S t#          dl|           t          | ||d          S |dmk    r|dnt          |          
                                                                2tK                      }tM          |                     dK          t&                    r|                     dK          ni }!to          |!          }2dv r|dAk    rdnndA}n+2tp          v rtp          2         }nt          | ddo|           S t#          dp|           t          | ||d          S |dqk    r|dnt          |          
                                                                22tr          vr/t          | ddr2dsdt:                    tr                               S t#          du2           t          | |2d          S |dvv rt          |pd          
                                22st          | ddw          S tT          j;        <                    tT          j;        =                    2                    }+tT          j;        >                    |+          st          | ddx2           S t#          dy|+           |+tT          j+        dz<   t          | dy|+|+t          |+          d{          S |d|v rd	 tK                      }|d}k    r6|d~k    r|                    dd            d}n||d<   |}t]          |           n|dk    r|                     dd          },t          t          |pd          |          \  }-}.t#          d|-           t#          d|.           t          |pd          }t          |,||.|-          \  }/}0n8t#          d| |           |}|dk    rt1          ddt                                 ||d}1|dk    r|/|1d<   |0|0|1d<   t          | |1          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY wt          | dd|           S )Nr  r   r  r   r   rR  r  r   r  uD   session busy — /interrupt the current turn before switching modelsr  r  r^  r  Fr  r   r%  r&  )r  r  r   r%  r&    r  r{  r  >   r  r  )r  r  >   r   toggle>   r  r  >   r  r  zunknown fast mode: r   )resolve_fast_mode_overridesz3fast mode is not available without a selected modelz)fast mode is not available for this modelzagent.service_tierr  speedr  busy>   r   r  >   r   r   r   zunknown busy mode: zdisplay.busy_input_moder  )r  r  r  r  r  cyclezunknown verbose mode: rk   r   zdisplay.tool_progressr  scoper   )rN  rO  rP  r  r|   c                 "    dv rdS dv rdS |  S )N>   rD  r  r  r  T>   r  r  r  r  Frv   )r  r   s    r@   _resolve_togglez_.<locals>._resolve_toggle=  s-    4444555 5"{"rw   global)_normalize_approval_mode	approvalsr  manualr  zapprovals.moderD  r  )r  r  r  r   HERMES_YOLO_MODErh  r  >   r  showr   sectionsTr  r`   r[   r  >   r  hider_   r  zunknown reasoning value: zagent.reasoning_effortdetails_modezunknown details_mode: zdetails_mode.rq  zunknown section: thinking_mode>   r  ra   rf  zunknown thinking_mode: zdisplay.thinking_modezdisplay.details_moder  ra   compacttui_compactr  zunknown compact value: zdisplay.tui_compact	statusbartui_statusbarr  zunknown statusbar value: zdisplay.tui_statusbarmouser  zunknown mouse value: zdisplay.mouse_tracking	indicatorzunknown indicator: z; pick one of |zdisplay.tui_status_indicator>   r   workdirterminal.cwdr  r#  r  r  )r  r  r   r	  >   ra  ri  r  ri  clearcustom_promptr  zdisplay.personalityzagent.system_promptr  zdisplay.ra  zskin.changedhistory_resetr  unknown config key: )Cr   rM   ra  r  r  r6  r   r  r1   r2   r3   r   r   r  rm  r  r  r  r{  r   r   r  r  r  r  r  r   r  indexr%  r  r  r  rN  rO  rP  r  r   r   r	  r8  r   r(   r   r  r  r9  rz  _DETAIL_MODES_DETAIL_SECTION_NAMESr0  r  r_  r  r  r  r  r,  r&   r*   ry  rz  r{  r  ry  r  rb  )3r   r  r  r  r   r   init_errr  r  r  current_fastnvr  r  r  current_overridesr  r  r  r  rN  rO  rP  r  r  r5  apprr  enabler  r<  r  argr   r  r  sectionsections_cfg
allowed_tmcfg0d0cur_bnv_br   r  pnamer  r  r  r  r   s3                                                     @r@   rH  rH    s   E2&&

7B(?(?CmmFJJ|R8899G
g~~6	+ ?C'=>>> ' ;;y)) ^  
 ;;w''/!'L"!=!=J&z7;;;*7C88H ('{{7++3#C/LMMM,JJ|R00,0

#<eDD- -	   -dO,0

#<eDD- -	   #G_%i0(.

3Eu(M(M'-zz2CR'H'H 	 	 	  	+ 	+ 	+T3q66********	+ f}}%+2$$&&,,..(/9G$$$T"5.$??:MLL-//:=L*&Jff(KK  
 .  )5vBBN""BB%%%BBT#@#@#@AAA	<<EEEEEE 271Bw---HXHX    I  
 43LAAI ?   	.333/1V||E $WU4G%L%L%RPR S S!!.$777!!'4000V||!((333&7E#)'222

<,,eW--  
 3b11222
f}}%+2$$&&,,...  sC2G2I2IJJKKK555T#@#@#@AAA3S9993c22333
i000 ,GKK,.F.H.HIII)++ 	
  		/Ug%%U!!##))++BC'G'G'GHHH kk#&&   a3u::-.B12666 	8,.G()KK((E (*i%3b11222
f}} FJJw''4955;;==CCEEA	+          ekr""((**0022C# #$ # # # # # #   CCCCCCkk/9#t/D/DNsww{+++$!$-- D22488FH3M3MNNRWW(11
 ""2V4QEERRR"+SS!%ioo&7&7!8!8 O OIC HHW--E(nc=3M3MNNN3b8 L LMMM 11'-2HII(11 ''(>???BB(()?@@@BG,,$&

<44%eW55   *"*..9K*L*LMM(11 58BJ12BBJNN#5t<<<BsC"yIIJJJ 	+ 	+ 	+T3q66********	+ k7	+??????ekr""((**0022Cn$$kk*4SWWY5G5G*N*NVCGGI&&&TV 
 "'++j"9"94@@GKK
+++ 
 -1()'1$&.
#!(I# 504G,-3f = =>>>o%%kk*4SWWY5G5G*N*NVCGGI&&&TV 
 "'++j"9"94@@GKK
+++ 
 -2()'/$&.
#!(I# 605G,-3f = =>>>++C00F~C'J5'J'JKKK6<<< 7;;w//;4: 1-g666"JJ|R00!''"2G<<  
 sC#66777 	+ 	+ 	+T3q66********	+ n"##%%++--]""T#CE#C#CDDDkk(237793E3Et(L(LT#'')$$$RT'1'++j2I2I4'P'PXGKK
###VX 	 #%, 	# 	#G "HW&
 I#3b11222
~~o&& 3
 ))C##A&///T#@w#@#@AAAkk(237793E3Et(L(LT#'')$$$RT'1'++j2I2I4'P'PXGKK
###VX 	 "##%%++-- 	7Wd+++".GJ$C	NcNNNsC"55666]""T#CE#C#CDDD "W*
 I#3b11222
o"##%%++--AAABB
ZT#DU#D#DEEE12666"",,JJK	
 	
 	
 3b11222
i%+2$$&&,,..{{$.txx	/B/BD$I$IQTXXi   rRVVM51122.  9DDD[[DDE\\DDT#DU#D#DEEE/6663d.EddFFGGG
k%+2$$&&,,..++//),,"7D119WWr#BFF?E$B$BCC.  !U**BBD[[BB$$$BBT#Fu#F#FGGG126663b11222
g~~ ]rrE

99;;AACCkk(237793E3Et(L(LT#'')$$$RT)'22.  !U**BB+++(-BBT#B5#B#BCCC2B7773b11222
k ]rrE

99;;AACC'''XcXX388DU;V;VXX  
 	8#>>>3c22333
000%+2$$&& 	3T>222goobg005566w}}S!! 	OT#M#M#MNNN.#...%(
>""SH[\_H`H`aa
 
 	

 ///	+++ChG##GGOT222BB+0C(B#%% **\266$9#ekr:J:JC$P$P!z!"7???!"7DDD&))&CWj%' '#tt ""2S"2"2E:::&==."lnn===,,Dm##(5_%##'DLsD>>! 	+ 	+ 	+T3q66********	+ T7#77888s   $G 7'G AG .%G CG 
H'H
H
HU U-,U-'E.b) Db) )
c3ccc&Dm+ .Cm+ ; m+ Bm+ +
n5nnnM7D-AR% R%
ASR/ASSASSASz
config.getc           
      b   |                     dd          }|dk    r	 ddlm}m} t	                      }|                    dd          }t          | |t          |          dk    r ||d                   nd |            d	          S # t          $ r(}t          | d
t          |                    cY d }~S d }~ww xY w|dk    r3ddlm} t          | t          t                     |            d          S |dk    rt                                           d          pi }	t          |                     dd          p|	                     dd          pd                                          }
t!          |
rd|
ini           }t          | |t#          |          d          S |dk    rt          | dt                      i          S |dk    r2t          | dt                                           dd          i          S |dk    rGt          | dt                                           d          pi                      dd          i          S |dk    rt                                           d          pi                      dd          }
t          |
                                                                          }t          | d|t&          v r|nt(          i          S |dk    rHt          | dt                                           d          pi                      d          pdi          S |dk    rt                      }t          |                     d          pi                      d d!          pd!          }t+          |                     d          pi                      d"d#                    rd$nd%}t          | ||d&          S |d'k    rt          | dt,                               |                     d(d                    x}r*t/          |                     d          d)d           d*k    rd'nt1                      d*k    rd'nd+i          S |d,k    rt          | dt3                      i          S |d-k    rt5          h d.          }t          t                                           d          pi                      d-d/          pd/                                                                          }
|
|v r|
nd/}t          | d|i          S |d0k    rt5          h d1          }t                      }t          |                     d          pi                      d0d          pd                                                                          }
|
|v r|
}nht          |                     d          pi                      d-d/          pd/                                                                          }|d2k    rdnd/}t          | d|i          S |d3k    rZt+          t                                           d          pi                      d4d#                    }t          | d|rd5nd6i          S |d7k    rmt                                           d          }t7          |t8                    r|                     d8d9          nd9}
t          | dt;          |
          i          S |d:k    r@t                                           d          }t          | dt=          |          i          S |d;k    rlt          d<z  }	 t          | d;|                                r|                                 j!        ndi          S # t          $ r t          | d;di          cY S w xY wt          | d=d>|           S )?Nr  r   rk  r   )list_available_providersnormalize_providerr  r   r  )r   rk  r  i  rd  r  )rn  r   projectru  r   )r   r	  r  r   ri  r  ra  r  r   rf  r  tui_status_indicatorr  r  rh  r  r  mediumr  Fr  r  )r  r   r  r   r{  r  r  r  r  >   r_   r`   ra   ra   r  >   r  ra   rf  r`   r  r  r  r  r  r  r  r  r4  rt  rR  r  )"r   rm  r  r  r  r  r  r  r1   ra  r2   r  r  rk  r   r3   r  r  r   r,  _INDICATOR_DEFAULTr   rM   r   r  r   r_  r   r   r  r  rl  r.  r/  )r   r  r  r  r  r   rn  r  r  cfg_terminalr   r   normr5  r  r   r   
allowed_dmr  r  dmr  cfg_paths                          r@   rH  rH  f  s   
**UB

C
j	+VVVVVVVV"$$EKKQ''E"8;E

Q**58444I!9!9!;!; 	 	 	  	+ 	+ 	+T3q66********	+
i8888883\!2!2?R?R?T?TUUVVV
i {{z228b&**UB''L<+;+;E2+F+FL"MMSSUUc9ucllr::3/B3/G/GHHIII
f}}39;;/000
h39;;???B#G#GHIII
f}}'IKKOOI66<"AA&)TTU
 
 	
 k {{y))/R445KRPP3xx~~%%''d&777dd=OP
 
 	
 my{{y117R<<]KKUvV
 
 	
 kkkWWW#(();XFFR(
 

 SWWY''-2223CUKKLLFF 	
 3&W==>>>
f}}#,==L"1M1M#N#NNVG 4 4ndKK!" " F %7$8$8J$F$F&&H
 
 	
 f}}3"7"9"9:;;;
nBBBCC
++1r66~{SS   UWWUWW 	 :%%SS;3"&&&
oAAABB
kk##)r..CCIrJJUWWUWW 	
 *BB WWY''-222>;OO #"    ++B3"&&&
i9;;??9--388NNOO3""7$$%8999
k++//),,3=gt3L3LWGKK///RW 	 3"3C"8"89:::
g~~++//),,3"9'"B"BCDDD
g~~-/	*g8??;L;LSx}}77RST    	* 	* 	*sWaL)))))	*T7#77888s0   A+B
 

B<B71B<7B<<>]; ;^^zsetup.statusc                     	 ddl m} t          | dt           |                      i          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   _has_any_provider_configuredprovider_configured  )hermes_cli.mainr  r  r   r1   ra  r2   )r   r  r  r  s       r@   rH  rH    s    '@@@@@@3.5Q5Q5S5S0T0TUVVV ' ' 'Cs1vv&&&&&&&&'s   ,/ 
A!AA!A!zsetup.runtime_checkc           
         	 ddl m} ddlm} ddlm}  |d          }t           |                      }|                    d          pd}t          |                    d          pd	          }|s3|d
k    r-|dv r)t          | d||                    d          |dd          S |                    d          }	t          |	          rd	n"t          |	pd	                                          }
t          |	          p0|
dv p, ||
          p!t          |                    d                    }|s@t          | d||                    d          |                    d          d| dd          S t          | d|                    d          |                    d          |                    d          d          S # t          $ r*}t          | dt          |          d          cY d}~S d}~ww xY w)a  Strict provider check: does the configured/default model actually resolve to a usable runtime?

    Unlike setup.status (which returns True if ANY provider auth state is
    discoverable, including indirect fallbacks like ``gh auth token`` for
    Copilot), this runs the same resolve_runtime_provider() call the agent
    uses on session creation. It returns ok=False with the auth error message
    when the user's configured model cannot actually be served, so UIs can
    surface onboarding before the user submits a doomed prompt.
    r   r  )has_usable_secretr  Nr  rk  r  r   bedrock>   iam-roleaws-sdk-default-chainFr   z!No Hermes provider is configured.)r   rk  r   r  r   r  >   aws-sdkr  r   z No usable credentials found for rq  T)r   rk  r   r  )r   r   )r)  r  hermes_cli.authr  r  r  r   r   r2   r  r*  r3   r1   )r   r  r  r  r  r2  r  rk  r  r  api_key_textcredential_okr  s                r@   rH  rH    s   78HHHHHH555555@@@@@@**T:::"#?#?#A#ABB;;z**8jW[[**0b11" 	x9'<'< L
 B
 B
  ($[[11$@ 	 	 	 ++i((%g..NrrC24F4F4L4L4N4NW ,==,  .., GKK	**++	 	  
	 ($[[11%kk(33KKKK 	 	 	 #KK
33 W--!++h//	 
 
 	
  8 8 83us1vv66777777778s,   B$G  'C
G  2AG   
G4
G/)G4/G4zprocess.stopc                     	 ddl m} t          | d|                                i          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   r  killedi  )r|  rw  r  kill_allr1   ra  r2   )r   r  rw  r  s       r@   rH  rH  A  s    ';;;;;;3#3#<#<#>#>?@@@ ' ' 'Cs1vv&&&&&&&&'s   ), 
AAAAz
reload.mcpc                    t                               |                    dd                    }	 t          |                    dd                    }|s	 ddlm}  |            }t          |t                    r|                    d          nd }d}t          |t                    r#t          |                    d	d                    }n# t          $ r d}Y nw xY w|rt          | d
dd          S ddl	m
}m}	  |              |	             |r|d         }
	 ddlm}  |t                      d          }||
_        |rd |D             nt!                      |
_        n2# t          $ r%}t$                              d|           Y d }~nd }~ww xY wt)          d|                    dd          t+          |
|                     t          |                    dd                    rF	 ddlm}  |dd           n2# t          $ r%}t$                              d|           Y d }~nd }~ww xY wt          | ddi          S # t          $ r(}t1          | dt3          |                    cY d }~S d }~ww xY w)Nr   r   confirmFr   r  r  Tmcp_reload_confirmr%  u   ⚠️  /reload-mcp invalidates the prompt cache (next message re-sends full input tokens). Reply `/reload-mcp now` to proceed, or `/reload-mcp always` to proceed and silence this prompt permanently.)r  r  )shutdown_mcp_serversdiscover_mcp_toolsr  )get_tool_definitionsr  r  c                 *    h | ]}|d          d         S )r  rE   rv   r$  s     r@   r  z_.<locals>.<setcomp>  s!    ===qQz]6*===rw   z:Failed to refresh cached agent tools after /reload-mcp: %sr  always)save_config_valuezapprovals.mcp_reload_confirmz.Failed to persist mcp_reload_confirm=false: %sr  reloaded  )rM   r   r   r  r  r   r   r1   r  r  r  r  r  r  r  r\   r  valid_tool_namesr   r   r  r  r  r  ra  r2   )r   r  r   user_confirm_load_configr  
_approvals_confirm_requiredr  r  r  r  new_defs_excr9  r  s                   r@   rH  rH  K  s\   mmFJJ|R8899GT' FJJy%8899 		)IIIIII#|~~6@t6L6LVTXXk222RV
$(!j$// Y(,Z^^<PRV-W-W(X(X% ) ) )$(!!!)   "4?    	LKKKKKKK 	G$E<<<<<<//%;%=%=#   'AIT==H====suu &&    P       
 

<,,eW--   

8U++,, 	WW>>>>>>	8%@@@@ W W WOQUVVVVVVVVW 3:./// ' ' 'Cs1vv&&&&&&&&'s   %I A6C I CI CI 4&I AE# "I #
F-FI FAI ,G? >I ?
H.	H)$I )H..I 
I5I0*I50I5z
reload.envc                     	 ddl m}  |            }t          | dt          |          i          S # t          $ r(}t          | dt          |                    cY d}~S d}~ww xY w)u  Re-read ``~/.hermes/.env`` into the gateway process via
    ``hermes_cli.config.reload_env``, matching classic CLI's ``/reload``
    handler.  Newly added API keys take effect on the next agent call
    without restarting the TUI.

    The credential pool / provider routing for any *already-constructed*
    agent does not auto-rebuild — that's the same behaviour as classic
    CLI's ``/reload``.  Users who want a brand-new credential resolution
    should follow with ``/new``.
    r   )
reload_envr  r  N)r  r  r  r  r1   ra  r2   )r   r  r  r  r  s        r@   rH  rH    s    '000000
3CJJ/000 ' ' 'Cs1vv&&&&&&&&'s   .1 
A#AA#A#>   set-homerZ  approvesethomecommands_TUI_HIDDEN))/compactToggle compact display modeTUI)/logsShow recent gateway log linesr  )/mouse;Set mouse tracking preset [on|off|toggle|wheel|buttons|all]r  )z	/sessionsz Switch between live TUI sessionsr  
_TUI_EXTRA>   rI  r  planundor   retryr   _PENDING_INPUT_COMMANDSr
  snap_WORKER_BLOCKED_COMMANDSzcommands.catalogc           
      R   	 ddl m}m}m} g }i }g }i }g }	|D ]}
|
j        t
          v s|
j        rd|
j         }|||                                <   |
j        D ]}||d|                                 <    ||
          }|	                    ||g           |
j
        }||vrg ||<   |		                    |           ||         	                    ||g           t          D ]X\  }}}|	                    ||g           ||vrg ||<   |		                    |           ||         	                    ||g           Yd}	 t                                          di           pi }t          |t                    rR|rOd}||vrg ||<   |		                    |           t!          |                                          D ]\  }}t          |t                    sd| }|||                                <   |                    dd          }|dk    rd	|                    d
d           }n$|dk    rd|                    dd           }n|pd}t%          |                    d          p|          }|dd         t'          |          dk    rdndz   }|	                    ||g           ||         	                    ||g           n# t(          $ r}|sd| }Y d}~nd}~ww xY wd}	 ddlm} t!           |                                                      D ]d\  }}t%          |                    dd                    }|	                    ||dd         t'          |          dk    rdndz   g           |dz  }en# t(          $ r}d| }Y d}~nd}~ww xY w|	D ] }|	                    |||         d           !d |                                D             }t/          | ||||||d          S # t(          $ r(}t1          | dt%          |                    cY d}~S d}~ww xY w)uG   Registry-backed slash metadata for the TUI — categorized, no aliases.r   )COMMAND_REGISTRYSUBCOMMANDS_build_descriptionr  r   quick_commandszUser commandsr  execzexec: r   aliasu
   alias → r   zquick commanddescriptionNr`  r  z&quick_commands discovery unavailable: )scan_skill_commandsSkillr   zskill discovery unavailable: )rE   pairsc                 *    i | ]\  }}||d d          S r   rv   r  s      r@   rM  z_.<locals>.<dictcomp>4  s&    77741aq!AAA$777rw   )r  r  canon
categoriesskill_countr     )hermes_cli.commandsr  r  r  rE   r  gateway_onlyr   aliasesr  categoryr  r   r   r   r   r  r8  r2   r  r1   r  r  r  ra  ) r   r  r  r  r  	all_pairsr  r  cat_map	cat_ordercmdrJ  r   r  catrE   r   qcmdsbucketqnameqcr  qtypedefault_descqdescr  r   r  rZ  r  r*  r  s                                    r@   rH  rH    sR   ]'	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 &(	 "!#
.0!	# 	+ 	+Cx;&&#*:&CHA E!''))[ + +)*g!ggmmoo&&%%c**DaY''',C'!!!  %%%CLD	****) 	. 	.OD$dD\***'!!!  %%%CLt----	GKKOO$4b99?RE%&& 95 9(((&(GFO$$V,,,!'!6!6 9 9IE2%b$// ! %e++C),E#))++&FF62..E'Gy"0E0E'G'G'))'JBFF8R4H4H'J'J','?} 5 5 EFFE!$3$KCJJ4D4D55"ME$$c5\222FO**C<8888 	G 	G 	G GF1FF	G 	:@@@@@@!"5"5"7"7"="="?"?@@ ! !48899  !QttWQ#2%N!OPPPq !  	: 	: 	:9a99GGGGGG	:  	D 	DCsWS\BBCCCC77;#4#4#6#6777"(*" 

 

 
	
  ' ' 'Cs1vv&&&&&&&&'su   D:O4 =FK
 	O4 

K%K O4  K%%O4 +BN  ?O4  
N
NO4 NAO4 4
P&>P!P&!P&r   c                 F   | sdS | d                                          }|dk    rdS |dk    rdS |dk    r3t          |           dk    r | d                                          d	k    rd
S |dk    r3t          |           dk    r | d                                          dk    rdS dS )zKReturn user hint if this argv must not run headless in the gateway process.u^   bare `hermes` is interactive — use `/hermes chat -q …` or run `hermes` in another terminalr   setupu?   `hermes setup` needs a full terminal — run it outside the TUIgatewayu?   `hermes gateway` is long-running — run it in another terminalr\  r   browseu_   `hermes sessions browse` is interactive — use /resume here, or run browse in another terminalr   editz5`hermes config edit` needs $EDITOR in a real terminalN)r   r  )r   a0s     r@   _cli_exec_blockedr8  D  s     poo	aB	W}}PP	YPP	ZCIIMMd1gmmoo.I.Ipp	X~~#d))a--DGMMOOv,E,EFF4rw   rb   c                    |                     dg           }t          |t                    rt          d |D                       st	          | dd          S t          |          }|rt          | d|ddd          S 	 t          j        t          j
        d	d
g|ddt          t          |                     dd                    d          t          j                    t          j                                        t          j                  }|j        pd|j        pdg}d                    d |D                                                       pd}t          | d|j        |dd         d          S # t          j        $ r t	          | dd          cY S t0          $ r(}t	          | dt3          |                    cY d}~S d}~ww xY w)zXRun `python -m hermes_cli.main` with argv; capture stdout/stderr (non-interactive only).r   c              3   @   K   | ]}t          |t                    V  d S r   )r   r2   )r4  r#  s     r@   r  z_.<locals>.<genexpr>X  s,      ,N,NAZ3-?-?,N,N,N,N,N,Nrw     zargv must be list[str]Tr  r   )r  r  r_  r   r   zhermes_cli.mainr      iX  )r
  r   r   r   r   r   r   c              3      K   | ]}||V  	d S r   rv   r)  s     r@   r  z_.<locals>.<genexpr>h  s'      ..aA.......rw   (no output)FNi  )r  r_  r   r  zcli.exec: timeout  )r   r   r	  r  ra  r8  r  r   r   r7   r   r  r  r(   r   r   r   r  r   r8   r&   r3   r  r@  r1   r2   )r   r  r   r  r  rn  r5  r  s           r@   rH  rH  T  s    ::fb!!DdD!! 9,N,N,N,N,N)N)N 9C7888T""D S3D$bQQRRR'N^T#4<t<FJJy#6677==	
!!$
 
 
 RR0ii..5.....4466G-UALCLQQ
 
 	
 $ 4 4 4C233333 ' ' 'Cs1vv&&&&&&&&'s%   =C5E3 3 G	GG;GGzcommand.resolvec                 P   	 ddl m}  ||                    dd                    }|r#t          | |j        |j        |j        d          S t          | dd|                    d                     S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)	Nr   resolve_commandrE   r   )	canonicalr  r%  i  zunknown command: i  )
r"  rB  r   r  rE   r  r%  ra  r1   r2   )r   r  rB  r  r  s        r@   rH  rH  r  s    '777777OFJJvr2233 	!"#$= !
    CG6::f3E3EGGHHH ' ' 'Cs1vv&&&&&&&&'s$   A	A3 &A3 3
B%=B B% B%c                 `    	 ddl m}  ||           }|r|j        n| S # t          $ r | cY S w xY w)Nr   rA  )r"  rB  rE   r1   )rE   rB  r  s      r@   _resolve_namerE    s]    777777OD!!$qvv$   s    --zcommand.dispatchc           	         |                     dd                              d          |                     dd          }}t          |          }||k    r|}t                               |                     dd                    }t	                                           di           }||v r||         }|                     d          dk    rt          j        |                     d	d          d
d
d
dt
          j                  }|j        pd|j        r	|j	        rdndz   |j	        pdz   
                                d d         }	|j        dk    rt          | d|	p	d|j                   S t          | d|	d          S |                     d          dk    r't          | d|                     dd          d          S 	 ddlm}
m}  |
|          }|r6 | ||                    }t          | dt#          |pd          d          S n# t$          $ r Y nw xY w	 ddlm}m}  |            }d| }||v rV ||||r|                     dd          nd          }|r.t          | d|||                              d|          d          S n# t$          $ r Y nw xY w|dv r&|st          | dd          S t          | d |d!          S |d"k    r|st          | d#d$          S |                     d%          rt          | d&d'          S |                     d(g           }|st          | dd)          S d }t-          t/          |          d*z
  d+d+          D ]%}||                              d,          d-k    r|} n&|t          | dd)          S ||                              d.d          }t1          |t2                    rd/                    d0 |D                       }|st          | dd1          S |d2         5  |d |         |d(<   t7          |                     d3d                    d*z   |d3<   d d d            n# 1 swxY w Y   t          | d |d!          S |d4k    r|st          | dd5          S |r|                     d6          nd }|rnt9          |d4          r^	 |                    |          }|r5t          | dd7|d d8          t/          |          d8k    rd9nd d          S n# t$          $ r Y nw xY wt          | d |d!          S |d:k    rw|st          | d#d;          S 	 dd<lm} n+# t$          $ r}t          | d=d>|           cY d }~S d }~ww xY w|                     d          pd}|st          | d#d?          S 	 t	                                           d@          pi }t7          |                     dAdB          pdB          }n# t$          $ r dB}Y nw xY w |||C          }|
                                                                 }|
                                r|dDk    r%t          | d|!                                d          S |dEk    r7|"                    dFG          } | dHn	dI| j#         }!t          | d|!d          S |dJk    rE|$                                } | t          | ddKd          S t          | ddL| j#         dMd          S |dNv r?|%                                }"|&                                 t          | d|"rdOndPd          S 	 |'                    |          } n+# tP          $ r}t          | ddQ|           cY d }~S d }~ww xY wdR| j)         dS| j#         dT}#t          | d |#| j#        dU          S |dVk    r|st          | d#dW          S |                     d%          rt          | d&dX          S tU                      }$|$tW          | dYZ          S |                     dd          }%|%st          | d#d[          S d*}&|pd
                                }'|'rU	 t7          |',                                d                   }&n,# tP          tZ          f$ r t          | dd\|'d]          cY S w xY w|&d*k     rd*}&	 |$.                    |%t_          |&d^          _          }(n+# t$          $ r})t          | dYd`|)           cY d })~)S d })~)ww xY w|(st          | dda          S ta          |&d*z
  t/          |(          d*z
            }*|(|*         db         }+	 |$1                    |%|+          }nQ# tP          $ r})t          | ddc|)           cY d })~)S d })~)wt$          $ r})t          | dYdc|)           cY d })~)S d })~)ww xY w	 |$2                    |%          },n# t$          $ r g },Y nw xY w|d2         5  t3          |,          |d(<   t7          |                     d3d                    d*z   |d3<   d d d            n# 1 swxY w Y   |                     d6          }|tg          |ddd           }-|-+	 |-4                    |%dded
f           n# t$          $ r Y nw xY wt9          |dg          r&	 |5                                 n# t$          $ r Y nw xY wt9          |dh          r&	 t/          |,          |_6        n# t$          $ r Y nw xY w|                     di          pi }.|.                     d.          pd}/t1          |/t2                    r+dj |/D             }0d                    dk |0D                       }/t1          |/t"                    sd}/|                     dld          }1|*d*z   }2|2d*k    rdmndn}3do|2 d/|3 dp|1 dq}#t          | dr|/|#ds          S |dtv rI|r.|,                    d*u          d                                          nd}4|4dvv rt          | ddwd          S t          | ddx|           S )yNrE   r   r  r  r   r  r  r  r   TrN  )shellr
  r   r   r   r   r!  r   r[  z$quick command failed with exit code )r  r   r  r   )r  r   get_plugin_command_handlerresolve_plugin_command_resultplugin)r  build_skill_invocation_messager   r  skill)r  r  rE   >   rI  r   rX  zusage: /queue <prompt>send)r  r  r  r  zno active session to retryr   r  u:   session busy — /interrupt the current turn before /retryr  z!no previous user message to retryr   r  r  r  r  r  c              3      K   | ]H}t          |t                    r1|                    d           dk    0|                    dd          V  IdS )r  r   r   Nr   r   r   r)  s     r@   r  z_.<locals>.<genexpr>  se        a&& ,-55==F+B+B fb!!+B+B+B+B rw   zlast user message is emptyr  r:  r   zusage: /steer <prompt>r  u7   ⏩ Steer queued — arrives after the next tool call: r  z...r  zno active sessionr    zgoals unavailable: zno session keyr  r  r  r  r  pausezuser-paused)r  zNo goal set.u   ⏸ Goal paused: resumezNo goal to resume.u   ▶ Goal resumed: uT   
Send any message to continue, or wait — I'll take the next step on the next turn.>   doner  r  u   ✓ Goal cleared.zNo active goal.zinvalid goal: u   ⊙ Goal set (z-turn budget): u   
I'll keep working until the goal is done, you pause/clear it, or the budget is exhausted.
Controls: /goal status · /goal pause · /goal resume · /goal clear)r  noticer  r  zno active session to undor  r  rV  zno session key for undozundo: invalid count u    — use /undo or /undo Nr   rW  zundo: failed to load history: zno user messages to undor   zundo: _memory_managerF)r	  resetrewound_invalidate_system_prompt_last_flushed_db_idxtarget_messagec                     g | ]F}t          |t                    r/|                    d           dk    0|                    dd          GS )r  r   r   rP  r)  s     r@   r6  z_.<locals>.<listcomp>  sW       &'a&&+,55==F+B+B fb!!+B+B+Brw   c              3      K   | ]}||V  	d S r   rv   r$  s     r@   r  z_.<locals>.<genexpr>  s'      #:#:!#:A#:#:#:#:#:#:rw   rewound_countrB  turnsu
   ↶ Undid r  z7 message(s)). Edit and resubmit, or send a new message.prefill)r  r  rU  >   r  r
  maxsplit>   rewindrestorez/snapshot restore is blocked in the TUI because it changes config/state on disk while the live agent has cached settings. Run it in the classic CLI, then restart the TUI.z"not a quick/plugin/skill command: )7r   r  rE  rM   r   r   r   r  r   r8   r3   r  ra  r  r   rI  rJ  r2   r1   r  r  rL  r  r  r   r	  r&   r  r
  r   r  r  r   status_linerR  r  rS  has_goalr  r  r%  r  r  rc  r  
IndexErrorlist_recent_user_messagesr  r  rewind_to_messagerx  r   on_session_switchrZ  r[  )5r   r  rE   r  r~  r   r+  r.  r  r   rI  rJ  handlerr  r  rL  cmdsr  r   r  r  rZ  r  r  rT  r  r   r  r  r  r  r   r  r5  hadrU  r  r   r   arg_strrecentsr  
target_idx	target_idr  mm
target_msgtarget_textrn  r_  turns_undone	turn_word
subcommands5                                                        r@   rH  rH    s   

62&&--c22FJJub4I4I#DT""H4mmFJJ|R8899GKKOO,b11Eu}}4[66&>>V##y"%%# (  A R88844b:8>r# eggete	F
 |q  SSQ\SS  
 sVv>>???66&>>W$$sWx8L8LMMNNN	
 	
 	
 	
 	
 	
 	
 	

 -,T22 	M22773<<@@FsXV\r9J9JKKLLL	M    	
 	
 	
 	
 	
 	
 	
 	

 #"$$$jj$;;00SG"S'++mR"@"@"@QS  C   '#& $S	fd ; ;        ~ 	=T#;<<<3C88999w 	AT#?@@@;;y!! 	TW   ++i,, 	HT#FGGGs7||a'R00 	 	Aqz~~f%%// ! 0  T#FGGG-(,,Y;;gt$$ 	hh       G
  	AT#?@@@ ^$ 	T 	T!(-!8GI),W[[9JA-N-N)O)ORS)SG%&	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 3G<<===w 	=T#;<<<(/9G$$$T 	WUG,, 	 ;;s++ $* 'K`cdgegdg`h  'Ksvwzs{s{  A  tA  tAjojo  GI  'K  'K        3C88999v~~ 	8T#6777	@4444444 	@ 	@ 	@T#>#>#>????????	@ ++m,,2 	5T#3444	!006BIIMM+r::@bAAII 	 	 	III	kW	JJJ		!!##yy{{ 	Kex//sVs7H7HIIJJJGII]I33E$)M..7W5:7W7WCsVs;;<<<HJJLLE}3;O P PQQQ"nUZ n n n 	 	 	 ---,,..CIIKKK"58O11>O   	;GGCLLEE 	; 	; 	;T#9C#9#9::::::::	;SU_ S SUZ S S S 	 v%*EE
 
 	

 v~~  	@T#>???;;y!! 	TV   YY:(48888kk-44 	>T#<===9"##%% 	dd*++
+ d d dC'bg'b'b'bcccccdq55A	I22;c!Rjj2QQGG 	I 	I 	IT#GA#G#GHHHHHHHH	I 	?T#=>>> QGq 011
J'-		1))+yAAFF 	1 	1 	1T<A<<00000000 	1 	1 	1T<A<<00000000	1	44[AAFF 	 	 	FFF	^$ 	T 	T!%fGI),W[[9JA-N-N)O)ORS)SG%&	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T G$$ 1488B~((#*,# $	 )     !   Du9:: 335555    Du455 14VE..    DZZ 0117R
 nnY//52k4(( 	; +6  E ))#:#:u#:#:#:::K+s++ 	K

?A66!A~*a//FFW	8 8 8	 8 8] 8 8 8 	 ;&II
 
 	

 ###9<DSYYY**1-33555"
..."K 
 
 
 TFFFGGGsT  ?A
H 
HHA0J 
JJ87P;;P?P?AS+ +
S87S8)T0 0
U:UUUAW WW\5 5
]?]]]1'a &bb%b4 4
c>ccc$d; ;
f	ef	f	+f>f	f	f# #f21f2=<hh	h	;i 
i"!i"6j 
jj,k 
kkzpaste.collapsec                    |                     dd          }|st          | dd          S t          dz  a|                    d          dz   }t          dz  }|                    dd	           d
dlm} |dt           d |j                                        d           dz  }|	                    |d           dt           d| d| d}t          | |t          |          |d          S )Nr   r   rX  zempty paster   r   pastesTr  r   r   paste_rH  z%H%M%Sz.txtr   r   z[Pasted text #r!   u    lines → r  )placeholderr*   r  )r   ra  _paste_counterr  rk  r  r   rD  r0   r:  r  r2   )r   r  r   
line_count	paste_dirr   
paste_filer|  s           r@   rH  rH    s&    ::fb!!D .C}---aND!!A%Jx'IOOD4O000!!!!!! 	U^UUlhlnn.E.Eh.O.OUUUU  $111 	SRR:RRZRRR  [#j//JWW  rw   i N  >   .hg.git.svn.next.venv.cache.mypy_cache.ruff_cache.pytest_cachedistvenvbuildr   __pycache__node_modules_fuzzy_cachec           
         t          j                    }t          5  t                              |           }|r(||d         z
  t
          k     r|d         cddd           S ddd           n# 1 swxY w Y   g }	 t          j        dd| ddgdd	d
t          j                  }|j	        dk    r8|j
                            dd                                          }t          j        dd|dddddgdd	d
t          j                  }|j	        dk    r|j
                            dd                              d          D ]}|st          j                            t          j                            ||          |                               t          j        d          }|                    d          rw|                    |           t-          |          t.          k    r nn# t0          t          j        f$ r Y nw xY w|s	 t          j        | d
          D ]\  }	}
}d |
D             |
dd<   t          j                            |	|           }|D ]^}|dk    r|n| d| }|                    |                    t          j        d                     t-          |          t.          k    r n_t-          |          t.          k    r nn# t0          $ r Y nw xY wt          5  ||ft          | <   ddd           n# 1 swxY w Y   |S )an  Return file paths relative to ``root``.

    Uses ``git ls-files`` from the repo top (resolved via
    ``rev-parse --show-toplevel``) so the listing covers tracked + untracked
    files anywhere in the repo, then converts each path back to be relative
    to ``root``. Files outside ``root`` (parent directories of cwd, sibling
    subtrees) are excluded so the picker stays scoped to what's reachable
    from the gateway's cwd. Falls back to a bounded ``os.walk(root)`` when
    ``root`` isn't inside a git repo. Result cached per-root for
    ``_FUZZY_CACHE_TTL_S`` so rapid keystrokes don't respawn git processes.
    r   r   Nr  r  r  z--show-toplevelT       @F)r
  r   r  r   r   r  zls-filesz-zz--cachedz--othersz--exclude-standard r  z../)followlinksc                 N    g | ]"}|t           v|                    d            |#S )rq  )_FUZZY_FALLBACK_EXCLUDESr0  )r4  r*  s     r@   r6  z$_list_repo_files.<locals>.<listcomp>T  s?        888cARAR8 888rw   rq  )r/   	monotonic_fuzzy_cache_lockr  r   _FUZZY_CACHE_TTL_Sr   r   r  r  r   decoder3   r  r(   r*   relpathr&   r  rT  r0  r  r  _FUZZY_CACHE_MAX_FILESr0  r@  walk)r#  rD  cachedfiles
top_resultr  list_resultr|  rV  dirpathdirnames	filenamesrel_dirr>   s                 r@   _list_repo_filesr    s    .

C	  !!$'' 	cF1Io(:::!9                      
 E)^D$->?$
 
 

  A%%#**7I>>DDFFC$.(	  $ (  K  %**$+227IFFLLTRR  A ! '//"',,sA*>*>EEMM C
 ~~e,, ! LL%%%5zz%;;; <Z./     	02%0P0P0P  ,9 %  
 '//'488"  A&#~~!!g3C3C3C3CCLLRVS!9!9:::5zz%;;; <u::!777E 8 	 	 	D	 
 * *!5\T* * * * * * * * * * * * * * * LsI   8A,,A03A0:E,G' 'H ?H C	K 
KK'L  LLqueryc                    |sdt          |           fS |                                 }|                                }||k    rdt          |           fS |                    |          rdt          |           fS g }d}| D ][}|dv s0|                                r<|r:|d                                         s |r|                    |           |dvr|nd}V||z  }\|r|                    |           |D ]<}|                                                    |          rdt          |           fc S =||v rdt          |           fS d}|D ]9}|||         k    r+|dz  }|t          |          k    rdt          |           fc S :d	S )
u  Rank ``name`` against ``query``; lower is better. Returns None to reject.

    Tiers (kind):
      0 — exact basename
      1 — basename prefix (e.g. `app` → `appChrome.tsx`)
      2 — word-boundary / camelCase hit (e.g. `chrome` → `appChrome.tsx`)
      3 — substring anywhere in basename
      4 — subsequence match (every query char appears in order)

    Secondary key is `len(name)` so shorter names win ties.
    r  r   r   r   z-_.r  rk   rn   N)r  r   r0  isupperr  )	rE   r  nlqlrn  bufchr|  rZ  s	            r@   _fuzzy_basename_rankr  j  s     3t99~	B	B	Rxx3t99~	}}R 3t99~
 E
C  ;;2::<<;C;B8I8I; "S!!!%""RCC2ICC
 S " "7799## 	"s4yy>!!!	" 
Rxx3t99~	A & &A;;FACGG||3t99~%%%4rw   zcomplete.pathc           	      v
   |                     dd          }|st          | dg i          S g }	 t          |          }|                    d          }|r
|dd          n|}|r4|s2ddddd	d	d
dddddddddddddddddg}t          | d|i          S |r	|dv r|d}}n;|r1|                    d          r|                    d          \  }}	}
|
}nd}|r|n|}|r8|r5t          |                                          dk    rd|vr
|dk    rg }t          |          D ]w}t          j	        
                    |          }|                    d          r|                    d          sLt          ||          }|_|                    |||f           x|                    d            |pd}|d d         D ]B\  }	}}|                    d| d| |t          j	                            |          d           Ct          | d|i          S |rt          |          nd}|dk    s|sd\  }}nZ|                    d          r|d}}n@t          j	                            |          pd}t          j	        
                    |          }t          j	                            |          r|nt          j	                            ||          }t          j	                            |          st          | dg i          S |dk    }|                                }t+          t          j        |                    D ]}|r(|                                                    |          s-|r
|t.          v r9|r|s|                    d          rSt          j	                            ||          }t          j	                            |          }|r||k    rt          j	                            ||                              t          j        d          }|rdnd}|r|rd| d| | }n|r|rdnd}d| d| | }n||                    d          rDd t          j	                            |t          j	                            d                    z   |z   }n#|                    d!          r	d!|z   |z   }n||z   }|                    |||z   |rd"ndd           t          |          dk    r nn5# t8          $ r(}t;          | d#t=          |                    cY d }~S d }~ww xY wt          | d|i          S )$Nwordr   r8  r  r   z@diffzgit diffr   r   r  z@stagedzstaged diffro  zattach filez@folder:zattach folderz@url:z	fetch urlz@git:zgit log>   r#   folder)zfile:zfolder:r  rk   r  r  rq  c                 J    | d         t          | d                   | d         fS )Nr   r   )r  )r  s    r@   rx   z_.<locals>.<lambda>  s    qtS1YY!&= rw   r  r#   rN  )rq  r   ~z~/z./dirr  )r   r  r  r0  	partitionr  r3   r  r(   r*   basenamer  r  rI  r+   r  endswithisabsr&   r{  r   r  listdirr  r  r  rT  rz  r1   ra  r2   )r   r  r  r8  r#  
is_contextr  
prefix_tagr  rH  r  rankedrV  r  ranktagr`   
search_dirr  want_dirmatch_lowerr,  r  rA  r  r   r  r  s                               r@   rH  rH    s@   ::fb!!D '3"&&&Ex'v&&__S))
&0QRRD 		.e 		. WjII"y-PP!hNN#
OTT WkJJ WiHHE sWe,---
  	7%#555$)2	JJ 	7E,,-ABB 	7"'//#"6"6J4IIJ!+6I 	.	. IOO%%&&!++9$$h&&=?F'-- 5 57++C00&&s++ I4H4H4M4M +Hi@@<tS(34444KK==K>>>&C$*3B3K   3 /C##+ " 4 4     sWe,---<EN-i8883s??(? 'Js## 	/ ("JJ229cJG$$X..E '--
33WJJdJ9W9W 	 w}}Z(( 	+sWbM***)kkmmBJz2233 %	 %	E U[[]]55kBB  e'??? * 1A1A#1F1F 7<<
E22DW]]4((F  h&00'//$--55bfcBBC"*SSF 
$j 
$5:555V55 $#)5xxv/4//#/v//%% $bgoodBG4F4Fs4K4KLLLvU&& $czF*V|LL $v~%+3EE    5zzR   ' ' 'Cs1vv&&&&&&&&' sWe$%%%s3   A'S4 F S4 C,S4 G/S4 4
T&>T!T&!T&r  c                     | | |dS )Nr  rv   )r  r  s     r@   _details_completion_itemr  %   s    eT:::rw   needs_leading_spacec                 0    t          |rd|  n| |          S )Nr  )r  )r  r  r  s      r@   _details_root_completion_itemr  )   s+     $*5E  rw   c                    |                                                      d          sd S |                                 }|rAd                    |                                                                 d                   sd S | t	          d          d          }|                    d          r
|dd          }|                                |                     d          dd}|rt	                    dk    r2r0g fd|D             t          dd	           fd
D             S t	                    dk    r3s1d                                          g |d}fd|D             S t	                    dk    rZrXd                                          v r<g fd|D             t          ddd                                           d          S t	                    dk    rLsJd                                          v r.d                                          fdg |dR D             S g S )N/detailsr   r  r   rZ   )r_   ra   r`   c                 4    g | ]}t          |d            S )global moder  )r4  r  has_trailing_spaces     r@   r6  z(_details_completions.<locals>.<listcomp>D   s@         .--?)?   rw   r  cycle global modec                 4    g | ]}t          |d            S )section overrider  )r4  r  r  s     r@   r6  z(_details_completions.<locals>.<listcomp>M   sA         ./5G1G   rw   c                     g | ];}|                               r$|k    t          ||v rd n	|dk    rdnd          <S )r  r  r  r  )r0  r  )r4  r  r  r  s     r@   r6  z(_details_completions.<locals>.<listcomp>X   s     
 
 
 ##F++
 1:V0C0C % !H,, '&09W0D0D,,-  1D0C0Crw   c                 f    g | ]-}t          |d d                                                    .S )set r   )r  r   )r4  r  rn  s     r@   r6  z(_details_completions.<locals>.<listcomp>g   sJ        )/HeAhnn6F6F/H/HII  rw   rX  clear 	 overriderk   c                     g | ]l}|                               rU|k    t          ||d k    rdd                                          dndd                                                    mS )rX  r  r   r  r  )r0  r  r   )r4  r  rn  r  s     r@   r6  z(_details_completions.<locals>.<listcomp>p   s     
 
 
 ##F++
 1:V0C0C % !G++ 9U1X^^--88882a 0 022  1D0C0Crw   )r   r0  r3   r  r  r  r  r  )	r   strippedr  modes
candidatesr  rn  r  r  s	        @@@@r@   _details_completionsr  2   s   ::<<"":.. tzz||H 
--hnn.>.>.D.D.F.Fq.IJJ tJ!!"Ds ABBxJJLLEs++=H/E 
CJJ!OO(:O
    "	  
 *,2D.D 
     (	  
 	
$ 5zzQ1q!!1u1g11

 
 
 
 
 (
 
 
 	
 5zzQ-%(..2B2Bh2N2N
   !  

 %W.RuQx~~7G7G.R.R.RSS
 	
 5zzQ1eAhnn6F6F(6R6Rq!!
 
 
 
 
 /u.g..
 
 
 	
 Irw   zcomplete.slashc                    |                     dd          }|                    d          st          | dg i          S 	 ddlm} ddlm} ddlm dd	l	m
 dd
lm  |fdfd          } ||t          |                    }fd|                    |d           D             d d         }|                                }ddddddddddddddddg}	|	D ]Md                             |          r0t!          fd|D                       s|                               Nt%          |          }
|
<t          | |
d|v r|                    d          dz   nt          |          d          S t          | |d|v r|                    d          dz   ndd          S # t(          $ r(}t+          | dt-          |                    cY d }~S d }~ww xY w)Nr   r   r  r8  r   )SlashCommandCompleter)Document)to_plain_textget_skill_commandsget_skill_bundlesc                                    S r   rv   r  s   r@   rx   z_.<locals>.<lambda>   s    ,>,>,@,@ rw   c                                    S r   rv   r  s   r@   rx   z_.<locals>.<lambda>   s    +<+<+>+> rw   )skill_commands_providerskill_bundles_providerc                     g | ]@}|j         |j        r |j                  n|j         |j        r |j                  nd dAS )r   r  )r   r   display_meta)r4  rJ  r  s     r@   r6  z_.<locals>.<listcomp>   sq     
 
 
   89yL==333af9:Oan555R	 	
 
 
rw   rN  r  r  r  r  zControl agent detail visibilityr  r  r	  r
  c              3   <   K   | ]}|d          d          k    V  dS )r   Nrv   )r4  r  extras     r@   r  z_.<locals>.<genexpr>   sI       @ @26Vf-@ @ @ @ @ @rw   r  r   )r8  replace_fromr!  )r   r0  r  r"  r  prompt_toolkit.documentr  prompt_toolkit.formatted_textr  r  r  agent.skill_bundlesr  r  get_completionsr   r  r  r  r  r1   ra  r2   )r   r  r   r  r  	completerdocr8  
text_lowerextrasdetails_itemsr  r  r  r  r  s               @@@@r@   rH  rH     s   ::fb!!D??3 '3"&&&F'======444444??????;;;;;;999999))$@$@$@$@#>#>#>#>
 
 
	 htSYY''
 
 
 
 ..sD99
 
 
 2# ZZ\\
 #%5  #%9   "7  !#U !
,  	$ 	$EV}''
33 $C @ @ @ @:?@ @ @ = = $ U###,T22$*;>$;;DJJsOOa$7$7CPTII    C4KKTZZ__q-@-@UVWW
 
 	
  ' ' 'Cs1vv&&&&&&&&'s%   D:F- >.F- -
G7GGGzmodel.optionsc           	         	 ddl m}m} t                              |                    dd                    }|r|                    d          nd } |                                |rt          |dd          nd|rt          |dd          ndpt                      |rt          |dd          nd	          } ||d
d
d
d
d
d          }t          | |          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   build_models_payloadload_picker_contextr   r   r  rk  r   rx  rp  r  r  Tr>  )include_unconfiguredpicker_hintscanonical_orderpricingcapabilities
max_models  )hermes_cli.inventoryr  r  rM   r   with_overridesr   r  r  r1   ra  r2   )	r   r  r  r  r   r  r  r  r  s	            r@   rH  rH     sZ   #'RRRRRRRR--

< < <==(/9G$$$T
 "!##22?DLWUJ;;;"05=,,,2R.BRBR?DLWUJ;;;" 3 
 
 '&!% 
 
 
 3    ' ' 'Cs1vv&&&&&&&&'s   CC 
D$DDDzmodel.save_keyc           	         	 ddl m} ddlm}m} ddlm}m} |                    d          pd	                                |                    d          pd	                                }r|st          | dd	          S  |            rt          | d
d          S |                              }|st          | dd           S |j        dk    r!t          | d|j         d|j         d          S |j        st          | dd|j                   S |j        d         }	 ||	|           ddl}
||
j        |	<   t                               |                    dd                    }|r|                    d          nd} |                                |rt%          |dd          nd|rt%          |dd          ndpt'                      |rt%          |dd          nd          } ||dd          }t)          fd|d         D             d          }||j        dg ddd }d|d!<   t+          | d|i          S # t,          $ r(}t          | d"t/          |                    cY d}~S d}~ww xY w)#a  Save an API key for a provider, then return its refreshed model list.

    Params:
        slug: provider slug (e.g. "deepseek", "xai")
        api_key: the key value to save

    Returns the provider dict with models populated (same shape as
    model.options entries) on success.
    r   )PROVIDER_REGISTRY)
is_managedsave_env_valuer  slugr   r  r  zslug and api_key are requiredrg  u-   managed install — credentials are read-onlyrR  zunknown provider: r;  z uses u)    auth — run `hermes model` to configurerX  zno env var defined for Nr   r  rk  r   rx  r  Tr>  )r  r  c              3   4   K   | ]}|d          k    |V  dS )r	  Nrv   )r4  r|  r	  s     r@   r  z_.<locals>.<genexpr>5!  s1      BB1&	T0A0AQ0A0A0A0ABBrw   r  F)r	  rE   
is_currentmodelstotal_modelsauthenticatedr	    )r  r	  r  r	  r	  r	  r  r  r   r3   ra  	auth_typerE   api_key_env_varsr(   r   rM   r	  r   r  nextr  r1   r2   )r   r  r	  r	  r	  r  r  r  pconfigrb  r(   r   r  r  r  provider_datar  r	  s                    @r@   rH  rH     sK   D'555555@@@@@@@@RRRRRRRR

6""(b//11::i((.B5577 	D7 	DT#BCCC:<< 	TT#RSSS#''-- 	@T#>#>#>???	))< 3 3w'8 3 3 3   ' 	MT#KW\#K#KLLL *1-w(((			%
7 --

< < <==(/9G$$$T!!##22?DLWUJ;;;"05=,,,2R.BRBR?DLWUJ;;;" 3 
 
 '&dr
 
 
 BBBB,BBBD
 
   # !!% M *.o&3]3444 ' ' 'Cs1vv&&&&&&&&'s=   A<H>  H> *H> +H> 2H> D+H> >
I0I+%I0+I0zmodel.disconnectc                    	 ddl m}m} ddlm} |                    d          pd                                }|st          | dd          S |                    |          }d}d}|r|j        r|j        D ]}	 ||	          rd	} ||          }|s|st          | d
d|           S |r|j	        n|}
t          | ||
d	d          S # t          $ r(}t          | dt          |                    cY d}~S d}~ww xY w)zRemove credentials for a provider.

    Params:
        slug: provider slug (e.g. "deepseek", "xai")

    Returns success status and the provider's slug.
    r   )r	  clear_provider_auth)remove_env_valuer	  r   r  zslug is requiredFT  zno credentials found for )r	  rE   disconnected  N)r  r	  r	  r  r	  r   r3   ra  r	  rE   r  r1   r2   )r   r  r	  r	  r	  r	  r	  cleared_envcleared_authrR  provider_namer  s               r@   rH  rH  I!  s   "'JJJJJJJJ666666

6""(b//11 	7T#5666#''--  	'w/ 	'. ' '##B'' '"&K +*400 	G< 	GT#Et#E#EFFF(/9T% $ 
 
 	
  ' ' 'Cs1vv&&&&&&&&'s+   A	C AC (C 
C9C4.C94C9r   c                    |                     d                              dd          }|sdS |d         t          |          dk    r|d                                         nd|                    d          }}}h d}||v r|                    d          rd	| S 	 |d
k    r+|r)|r't          | ||          }|                    dd          S |dk    r7|r5|r3t          |t                                \  }	}
t          | ||
|	           nG|dk    rY|rWt                      }t          |                    d          pi                     dd                    }
|
pd|_
        d|_        n|dk    rB|r@t          ||           t          | |           t          d| t          ||                     n|dk    rM|rK|                                }|dv rd|_        n|dv rd|_        t          d| t          ||                     nM|dk    r'|r%t%          |d          r|                                 n |dk    rddlm} |                                 n# t.          $ r}d| cY d}~S d}~ww xY wdS )z?Apply side effects that must also hit the gateway's live agent.r  Nr   r   r   r  >   r   ri  compressr  r   u=   session busy — /interrupt the current turn before running /r   r   r  ri  r@  r	  r  r  >   r  r  r  >   r  r  z
reload-mcpreload_mcp_toolsr  r  zlive session sync failed: )r  r  r  r3   r   r6  ry  r   r  r~  r  r>  rI  rV  r  r  r   r{  r
  r	  r|  rw  r  r1   )r  r   r   rn  rE   r  r  _MUTATES_WHILE_RUNNINGr  r  r  r5  r  rw  r  s                  r@   _mirror_slash_side_effectsr 	  z!  s   NN3%%dA..E ra ZZ!^^q			G #D LKK%%%'++i*@*@%UtUUU07??s?u?(gs;;F::i,,,]""s"u" 5c9;; G GE:)#w
EJJJJX%++C%swww'7'7'=2&B&B?TV&W&WXXJ,6,>$E)*.E''ZE%gs333,S':::.#}UG'D'DEEEEV^^^99;;D~%%%/""***%)".#}UG'D'DEEEE\!!e!?Q0R0R!""$$$$V^^??????%%''' 0 0 0/A////////02s%   0I FI 
I,I'!I,'I,rd   c           	         t          ||           \  }}|r|S |                    dd                                          }|st          | dd          S |                    d          r|                    d          n|}|                    d          }|r|d         nd                                }t          |          dk    r|d         nd}|t          v rt          | d	d
|           S |t          v rG|r.|                    d          d                                         nd}	|	dv rt          | d	d          S 	 ddlm}
 d| }| |
            v rt          | d	d|           S n# t          $ r Y nw xY wd }d }|r)	 ddlm}m}  ||          }n# t          $ r d }d }Y nw xY w|rd|rb	  | ||                    }t#          | dt%          |pd          i          S # t          $ r}t#          | dd| i          cY d }~S d }~ww xY w|                    d          }|s	 t'          |d         t)          |                    d          dt+                                          }t-          |                    dd          ||           n+# t          $ r}t          | dd|           cY d }~S d }~ww xY w	 |                    |          }t1          |                    dd          ||          }d|pdi}|r||d<   t#          | |          S # t          $ rS}	 |                                 n# t          $ r Y nw xY wd |d<   t          | dt%          |                    cY d }~S d }~ww xY w)Nr   r   rX  empty commandr  r   rb  r   r[  z1pending-input command: use command.dispatch for />   rd  re  zVsnapshot restore mutates live config/state; use command.dispatch for /snapshot restorer  z(skill command: use command.dispatch for rH  r   r>  zPlugin command error: r  r   r  r   r   rQ  zslash worker start failed: r   )r  r   r3   ra  r0  r  r  r   r  r  r  r  r  r1   r   rI  rJ  r  r2   r   r   r  r  r   r 	  r   )r   r  r   r  r)  	_cmd_text
_cmd_parts	_cmd_base_cmd_argrx  r  _cmd_keyplugin_handlerrJ  rI  r  r  r  r   r   r  s                        r@   rH  rH  !  s   %%LGS
 

**Y
#
#
)
)
+
+C 0C/// $'>>##6#6?

3CI!,,J",4A";;==I #J! 3 3z!}}H+++V9VV
 
 	
 ,,,>FNX^^Q^//288:::B
...h  	;;;;;;"y??))++++TPhPP   ,     N$(! 
1		1       
 87	BBNN 	1 	1 	1!N,0)))	1  F7 F	F22>>(3K3KLLFsXs6+B]'C'CDEEE 	F 	F 	FsX'C'C'CDEEEEEEEE	F [[((F F	F!&G,,g~7G7GHH F 6::lB77&IIII 	F 	F 	FT#D#D#DEEEEEEEE	F'C,VZZb-I-I7TWXXV4}5 	)!(GI3    ' ' '	LLNNNN 	 	 	D	"&Cs1vv&&&&&&&&'s   >*E* *
E76E7F F&%F&.4G# #
H-HHH'A)J 
J9J4.J94J9=AL 
M1L43M,4
M>M, M%M,&M1,M1_voice_event_sidc                 t    t           5  t          }ddd           n# 1 swxY w Y   t          | ||           dS )a4  Emit a voice event toward the session that most recently turned the
    mode on. Voice is process-global (one microphone), so there's only ever
    one sid to target; the TUI handler treats an empty sid as "active
    session". Kept separate from _emit to make the lack of per-call sid
    argument explicit.N)_voice_sid_lockr)	  r  )r  r  r  s      r@   _voice_emitr,	  "  s|     
                	%gs     c                  n    t           j                            dd                                          dk    S )a  Current voice-mode flag (runtime-only, CLI parity).

    cli.py initialises ``_voice_mode = False`` at startup and only flips
    it via ``/voice on``; it never reads a persisted enable bit from
    config.yaml.  We match that: no config lookup, env var only.  This
    avoids the TUI auto-starting in REC the next time the user opens it
    just because they happened to enable voice in a prior session.
    HERMES_VOICEr   rD  r(   r   r   r3   rv   rw   r@   _voice_mode_enabledr0	  "  s+     :>>."--3355<<rw   c                  n    t           j                            dd                                          dk    S )zCWhether agent replies should be spoken back via TTS (runtime only).HERMES_VOICE_TTSr   rD  r/	  rv   rw   r@   r  r  *"  s*    :>>,b117799S@@rw   c                      t                      } t          | t                    r|                     d          nd}t          |t                    r|ni S )u*  Shape-safe accessor for the ``voice:`` block in config.yaml.

    ``_load_cfg()`` returns raw ``yaml.safe_load()`` output, so both the
    root AND ``voice`` may be any YAML scalar / list / None. A hand-edit
    like ``voice: true`` or a malformed top-level config that parses to
    a scalar would otherwise break ``.get("…")`` and take every
    ``voice.*`` branch down with it (Copilot round-3..7 review on
    #19835). Coerce through ``isinstance`` at every level so malformed
    config falls back to an empty dict instead of crashing /voice.
    voiceN)r   r   r   r   )r5  	voice_cfgs     r@   _voice_cfg_dictr6	  /"  sK     ++C$.sD$9$9C   tI"9d33;99;rw   c                      t                                          d          } t          | t                    r| rt          |           ndS )z@Current ``voice.record_key`` value, documented default on error.
record_keyzctrl+b)r6	  r   r   r2   )r8	  s    r@   _voice_record_keyr9	  @"  s?     ""&&|44J(S99VjV3z???hVrw   zvoice.togglec                    |                     dd          }|dk    rt                      t                      t                      d}	 ddlm}  |            }t          |                     d                    |d<   t          |                     d                    |d<   t          |                     d                    |d<   |                     d	          pd
|d	<   n2# t          $ r%}t          	                    d|           Y d}~nd}~ww xY wt          | |          S |dv r|dk    }|rdndt          j        d<   |s^	 ddlm}  |             n=# t          $ r Y n1t          $ r%}t          	                    d|           Y d}~nd}~ww xY wdt          j        d<   t          | |t                      t                      d          S |dk    rat                      st!          | dd          S t                       }	|	rdndt          j        d<   t          | dt                      |	d          S t!          | dd|           S )u3  CLI parity for the ``/voice`` slash command.

    Subcommands:

    * ``status`` — report mode + TTS flags (default when action is unknown).
    * ``on`` / ``off`` — flip voice *mode* (the umbrella bit). Turning it
      off also tears down any active continuous recording loop. Does NOT
      start recording on its own; recording is driven by ``voice.record``
      (Ctrl+B) after mode is on, matching cli.py's enable/Ctrl+B split.
    * ``tts`` — toggle speech-output of agent replies. Requires mode on
      (mirrors CLI's _toggle_voice_tts guard).
    actionr  )r  r8	  ttsr   )check_voice_requirementsrw  audio_availablestt_availabledetailsr   z2voice.toggle status: requirements probe failed: %sN>   r  r  r  rD  r  r.	  stop_continuousz3voice: stop_continuous failed during toggle off: %sr2	  r<	    z"enable voice mode first: /voice onTi  unknown voice action: )r   r0	  r9	  r  tools.voice_moder=	  r   r1   r   r   r  r(   r   r  rB	  r  ra  )
r   r  r;	  r  r=	  reqsr  r  rB	  	new_values
             r@   rH  rH  G"  s    ZZ(++F +,,+--%''
 

	TAAAAAA++--D#'(=(=#>#>GK )-dhh7H.I.I)J)JG%&'+DHH_,E,E'F'FGO$!%)!4!4!:GI 	T 	T 	T NNOQRSSSSSSSS	T
 3   D. -4%<SS
>" 	1Y<<<<<<!!!!    Y Y YTVWXXXXXXXXY .1BJ)*"/11)++ 
 
 	
 "$$ 	IT#GHHH*,,,	09)Bs
%&
 /11  
 
 	
 T<F<<===s7   	BC# #
D-DDE 
F"	F+FFzvoice.recordc                 J   |                     dd          }|dvrt          | dd|           S 	 |dk    r>t                      st          | dd          S t          5  |                     d          pt          ad	d	d	           n# 1 swxY w Y   d
dlm} t                      }|                     d          }|                     d          }t          |t          t          f          rt          |t                    s|nd}t          |t          t          f          rt          |t                    s|nd} |d d d ||d          }	|	du rt          | ddi          S t          | ddi          S t          5  |                     d          pt          ad	d	d	           n# 1 swxY w Y   d
dlm}
  |
d           t          | ddi          S # t          $ r t          | dd          cY S t          $ r(}t          | dt!          |                    cY d	}~S d	}~ww xY w)a  VAD-bounded push-to-talk capture, CLI-parity.

    ``start`` begins one VAD-bounded capture and emits ``voice.transcript``
    after silence stops the recorder. ``stop`` forces transcription of the
    active buffer, matching classic CLI push-to-talk. The voice wrapper retains
    no-speech counts across single-shot starts, so three consecutive silent
    captures emit ``voice.transcript`` with ``no_speech_limit=True``.
    r;	  r   >   r  r   r2  rD	  r  u+   voice mode is off — enable with /voice onr   Nr   )start_continuoussilence_thresholdsilence_durationrX  g      @c                 &    t          dd| i          S )Nvoice.transcriptr   r,	  r  s    r@   rx   z_.<locals>.<lambda>"  s    4FQR(T(T rw   c                 &    t          dd| i          S )Nzvoice.statusr  rN	  )r5  s    r@   rx   z_.<locals>.<lambda>"  s    K!$M$M rw   c                  &    t          dddi          S )NrM	  no_speech_limitTrN	  rv   rw   r@   rx   z_.<locals>.<lambda>"  s    &):D(A) ) rw   F)on_transcript	on_statuson_silent_limitrJ	  rK	  auto_restartr  r  	recordingrA	  T)force_transcribestopped  u9   voice module not available — install audio dependencies)r   ra  r0	  r+	  r)	  r  rI	  r6	  r   r  rK  r   r  rB	  r  r1   r2   )r   r  r;	  rI	  r5	  	thresholddurationsafe_thresholdsafe_durationstartedrB	  r  s               r@   rH  rH  "  sY    ZZ'**F&&&C@@@AAA;'W&(( VC'TUUU  P P#)::l#;#;#O?O P P P P P P P P P P P P P P P :99999 ())I!&9::I }}%788H i#u66"9d33		 	  he55>HSW>X>X 
 '&TTMM! ! #1!."	 	 	G %36 2333sX{3444  	L 	L%zz,77K;K	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	544444....39-... 
 
 
R
 
 	
 	
 	
  ' ' 'Cs1vv&&&&&&&&'s~   %G G B:G B

G B
CG #G 5G <F%G %F))G ,F)-&G H"1	H":HH"H"z	voice.ttsc                 |   |                     dd          }|st          | dd          S 	 ddlm} t	          j        ||fd                                           t          | d	d
i          S # t          $ r t          | dd          cY S t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   r   i  r}  r   r  Tr  r  speaking  zvoice module not available)r   ra  r  r  r   r   r   r  r  r1   r2   )r   r  r   r  r  s        r@   rH  rH  "  s    ::fb!!D 0C///'//////
$FFFLLNNN3:./// = = =C;<<<<< ' ' 'Cs1vv&&&&&&&&'s$   AA- -B;
	B;B60B;6B;zinsights.getc           	         |                     dd          }t                      }|t          | d          S 	 t          j                    |dz  z
  fd|                    d          D             }t          | |t          |          t          d	 |D                       d
          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)NdaysrN  r?  rV  iQ c                 J    g | ]}|                     d           pdk    | S )r  r   r3  )r4  r5  cutoffs     r@   r6  z_.<locals>.<listcomp>#  s?     
 
 
l##(qV33 333rw   r  rV  c              3   B   K   | ]}|                     d d          V  dS )rP  r   Nr3  r^  s     r@   r  z_.<locals>.<genexpr>#  s0      HHaoq 9 9HHHHHHrw   )rd	  r\  r0  )r   r  rc  r/   r`  r  r  sumr1   ra  r2   )r   r  rd	  r  rb  r  rf	  s         @r@   rH  rH  #  s   ::fb!!D	B	z$St4444'te|+
 
 
 
***55
 
 

 IIHH4HHHHH 
 
 	
  ' ' 'Cs1vv&&&&&&&&'s   A2B- -
C7CCCzrollback.listc                      t          |           \  }}|r|S 	  fd}t          ||          S # t          $ r(}t           dt	          |                    cY d }~S d }~ww xY w)Nc                     | j         st          dg d          S t          dd |                     |          D             d          S )NF)r  r  Tc                     g | ]D}|                     d d          |                     dd          |                     dd          dES )r  r   r   r  )r  r   r  r3  r(  s     r@   r6  z!_.<locals>.go.<locals>.<listcomp>2#  sd     $ $ $ 	 %&EE&"$5$5)*{B)?)?'(uuY';'; $ $ $rw   )r  r  r  )r  r   r   s     r@   goz_.<locals>.go+#  st    ; G3E" E EFFF#$ $ "%!5!5c!:!:$ $ $
 
  rw   r!  )r  r  r1   ra  r2   )r   r  r   r  rl	  r  s   `     r@   rH  rH  $#  s    %%LGS
 
'	 	 	 	 	$ !"--- ' ' 'Cs1vv&&&&&&&&'s   / 
A!AA!A!zrollback.restorec                    t          ||           \  }|r|S |                    dd          |                    dd          st          | dd          S s&                    d          rt          | dd          S 	 fd	}t          | t	          |                    S # t
          $ r(}t          | d
t          |                    cY d }~S d }~ww xY w)Nr  r   	file_pathrC	  hash requiredr   r  uI   session busy — /interrupt the current turn before full rollback.restorec                 ~   t          | |          }|                     ||pd           }|                    d          rsd}d         5                      dg           }|rU|d                             d          dv r8|                                 |d	z  }|r|d                             d          dv 8|r8|d                             d          d
k    r|                                 |d	z  }|r)t	                              dd                    d	z   d<   d d d            n# 1 swxY w Y   ||d<   |S )N)rn	  r+  r   r  r  r  r  >   r  r  r   r  r:  history_removed)r  re  r   r   r  )	r  r   r~  r  r  r  rn	  r   r   s	         r@   rl	  z_.<locals>.goX#  s   /S&AAH[[h):Kt[LLFzz)$$ 4Y 4^,  %kk)R88G! %gbkoof&=&=AV&V&V1 " %gbkoof&=&=AV&V&V  %72;??6#:#:f#D#D1 ,=q A ABBQF   12               -4()Ms   CD--D14D1r  )r  r   ra  r  r  r1   r2   )r   r  r  rl	  r  rn	  r   r   s        @@@r@   rH  rH  B#  s(   %%LGS
 
ZZ##F

;++I 0C///  
Y// 
W
 
 	

'	 	 	 	 	 	 	( 3)'266777 ' ' 'Cs1vv&&&&&&&&'s   $B( (
C2CCCzrollback.diffc                   	 t          ||           \  }}|r|S |                    dd          		st          | dd          S 	 t          |	fd          }|                    dd          d d         }|                    dd          |d	}t	          ||                    d
d                    }|r||d<   t          | |          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr  r   rC	  ro	  c                 N    |                      |t          | |                    S r   )diffr  )r  r   r   s     r@   rx   z_.<locals>.<lambda>|#  s"    SXXc+CCf+U+UVV rw   rt	  r!  r.  )r.  rt	  r  r  r  i  )r  r   ra  r  rK   r  r1   r2   )
r   r  r   r  r  r   r  r  r  r   s
            @r@   rH  rH  q#  s1   %%LGS
 
ZZ##F 0C///'VVVV
 
 eeFB&55,,c::sGKK$;$;<< 	+"*GJ3    ' ' 'Cs1vv&&&&&&&&'s   BC 
C:C5/C:5C:c                     t           j                            dd                                          } | r| S 	 ddlm}  |            }t          |t                    r|                    di           ni }t          |t                    r7t          |                    dd          pd                                          S n# t          $ r Y nw xY wdS )u6  Return the configured browser CDP override without network I/O.

    ``/browser status`` must be fast — calling
    ``tools.browser_tool._get_cdp_override`` would invoke
    ``_resolve_cdp_override``, which performs an HTTP probe to
    ``.../json/version`` for discovery-style URLs.  That probe has
    a multi-second timeout and would block the TUI on a slow or
    unreachable host even though status only needs to report whether
    an override is set.

    Mirrors the env/config precedence of ``_get_cdp_override`` (env
    var first, then ``browser.cdp_url`` from config.yaml) without the
    websocket-resolution step, so the answer reflects user intent
    even when the configured host is not currently reachable.  The
    actual WS normalization happens in ``browser_navigate`` on the
    next tool call.
    BROWSER_CDP_URLr   r   r  browsercdp_url)
r(   r   r   r3   r  r  r   r   r2   r1   )env_urlr  r5  browser_cfgs       r@   _resolve_browser_cdp_urlr{	  #  s    $ jnn.3399;;G 555555o0:30E0EMcggi,,,2k4(( 	E{y"55;<<BBDDD	E   2s   BC 
CCc                     	 | j         pd}n# t          $ r Y dS w xY w| j        dv }| j        dv o| j        dv o|dk    o|S )u  Match the discovery-style local default; never the concrete WS form.

    A user-supplied ``ws://127.0.0.1:9222/devtools/browser/<id>`` is a
    real, connectable endpoint — collapsing it to bare ``http://...:9222``
    would strip the path and break the connect.
    r  F>   r   r  /json/json/version>   wshttp>   	127.0.0.1	localhost$  )portr%  r*   schemehostname)r  r	  discovery_paths      r@   _is_default_local_cdpr	  #  s{    { b   uu [$GGN' 	O99	DL	 	s   	 
r'  c                     dd l }	 |j                            | |          5 }dt          |dd          cxk    odk     nc cd d d            S # 1 swxY w Y   d S # t          $ r Y dS w xY w)Nr   r   rX  r  rI  F)urllib.requestrequesturlopenr   r1   )r'  r   urllibr  s       r@   _http_okr	  #  s    ^##C#99 	=T'$#66<<<<<<<<	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	=   uus4   A AA AA AA 
A)(A)c                     ddd                     | j        | j                  }| d| j                             d          }| d| dgS )Nr	  https)r	  wss://r  r~	  r}	  )r   r	  netlocr   )r  r	  r#  s      r@   _probe_urlsr	  #  s`    7++//v}MMF((((//44D"""tNNN33rw   c                     | j                             d          r|                                 S |                     dddd                                          S )N/devtools/browser/r   )r*   r  r  fragment)r*   r0  geturl_replace)r  s    r@   _normalize_cdp_urlr	  #  sQ    
 {233 }}??2R"?EELLNNNrw   r	  r  c                 X    ddl m}  |||          }|rd|gndd| dg}d|  dg|d	S )
Nr   )manual_chrome_debug_commandzSStart a Chromium-family browser with remote debugging, then retry /browser connect:zNNo supported Chromium-family browser executable was found in this environment.zLInstall one or start a Chromium-family browser with --remote-debugging-port=z, then retry /browser connect.z Browser CDP is not reachable at rq  uj   Browser not connected — start a Chromium-family browser with remote debugging and retry /browser connect)hermes_cli.browser_connectr	  )r'  r	  r  r	  r   r  s         r@   _failure_messagesr	  #  s    FFFFFF))$77G 	
	^`ghh ][_
 	 	23111	 	u rw   rf   c                    |                     dd          }|dk    r.t                      }t          | t          |          |d          S |dk    rt	          |           S |dk    rt          | dd|           S t          | |          S )Nr;	  r  	connectedr'  
disconnectconnectr  zunknown action: )r   r{	  r  r   _browser_disconnectra  _browser_connect)r   r  r;	  r'  s       r@   rH  rH  #  s    ZZ(++F&((3d3ii<<==="3'''C:&::;;;C(((rw   c           	      F   dd l }ddlm} ddlm} ddlm} |                    d          }|;t          |t                    s&t          | ddt          |          j                   S |pd                                p|}|                    d	          pd|                                }g d
ddt          dt          dd ffd}	 |d|v r|nd|           }
|
j        dvrt          | dd|           S |
j        st          | dd|           S 	 |
j        p|
j        dv rdnd}n$# t$          $ r t          | dd|           cY S w xY wt'          |
          r|} ||          }
|
j        pd}	 |
j        dv r|
j                            d          rldd l}	 |                    |
j        |fd          5  	 d d d            n# 1 swxY w Y   nH# t0          $ r!}t          | dd| d |           cY d }~S d }~ww xY wt3          |
          }t5          d! |D                       }|st'          |
          rdd"lm}  |	d#            |||          rCt9          d$          D ]3}t;          j        d%           t5          d& |D                       rd'} n4|r |	d(|            npt?          |||          d)d          D ]} |	|d*           tA          | d+|d,          S |st          | dd|           S t'          |
          r |	d-|            tC          |
          } |             |tD          j#        d.<    |             n5# tH          $ r(}t          | dt          |                    cY d }~S d }~ww xY wd'|d/}r|d0<   tA          | |          S )1Nr   )DEFAULT_BROWSER_CDP_URLcleanup_all_browsers)urlparser'  r  z"browser url must be a string, got r   r   r  )rB  r  rB  r|   c                b                         |            rt          d| |d           d S d S )Nzbrowser.progress)r  rB  )r  r  )r  rB  r0  r  s     r@   announcez"_browser_connect.<locals>.announce$  sM         	Q$cw+O+OPPPPP	Q 	Qrw   r	  zhttp://>   r	  r	  r	  r	  zunsupported browser url: zmissing host in browser url: >   r	  r	  i  r  zinvalid port in browser url: r	  >   r	  r	  r	  r  r     zcould not reach browser CDP at r!   c              3   8   K   | ]}t          |d           V  dS )r  r   Nr	  r)  s     r@   r  z#_browser_connect.<locals>.<genexpr>:$  s/      >>!Xa--->>>>>>rw   )try_launch_chrome_debuguW   Chromium-family browser isn't running with remote debugging — attempting to launch...r  r  c              3   8   K   | ]}t          |d           V  dS )g      ?r   Nr	  r)  s     r@   r  z#_browser_connect.<locals>.<genexpr>F$  s/      HHAx3777HHHHHHrw   Tz7Chromium-family browser launched and listening on port r   r   F)r	  r'  r0  z5Chromium-family browser is already listening on port rv	  r	  r0  )%r   r	  r	  tools.browser_toolr	  urllib.parser	  r   r   r2   ra  r  r5   r3   r  r	  r	  r	  r%  r	  r*   r0  socketcreate_connectionr0  r	  r  r	  r  r/   rV  r	  r  r	  r(   r   r1   )r   r  r   r	  r	  r	  raw_urlr'  r  r	  r  r	  r	  r  probesr   r	  rH  r   r  r  r0  r  s                        @@r@   r	  r	  #  s   OOOBBBBBB777777%%%%%%jjG:gs#;#;TDMM<RTT
 
 	
 =b


!
!
<%<C
**\
"
"
(bC__FH/5 Q Q Q# Q Q$ Q Q Q Q Q Q Q XUc\\cc??F}:::C@3@@AAA? FCDsDDEEEF{Pfm7G&G&GssR F F FCDsDDEEEEEF
 V$$ #%#{"d7' =M))fk.D.D /
 /
) MMMU--v.Es-SS                 U U UC'S'S'SPQ'S'STTTTTTTTU !((F>>v>>>>>B Y/77 YNNNNNNm   +*488 ""2YY " "
3HHHHHHH "!%B!E"  H]W[]]^^^^ 1#tV D DQRR H 6 6 W555555(SS    YC'N'N'NOOO&v.. YWQUWWXXX'//
 	(2
$% ' ' 'Cs1vv&&&&&&&&' 04J!G!GG '&
sGs   D, ,EE6'M G <G
>G 
GG GG M 
H!G=7H8M =HC)M ,M AM 
NM?9N?Nc                     dd} |             t           j                            dd             |             t          | ddi          S )Nr|   c                  J    	 ddl m}   |              d S # t          $ r Y d S w xY w)Nr   r	  )r	  r	  r1   r	  s    r@   reapz!_browser_disconnect.<locals>.reapl$  sP    	??????  """"" 	 	 	DD	s    
""rv	  r	  Fr   )r(   r   r   r  )r   r	  s     r@   r	  r	  i$  sZ        	DFFFJNN$d+++DFFFs[%()))rw   zplugins.listc                     	 ddl m} t          | dd  |            j                                        D             i          S # t
          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   )get_plugin_managerpluginsc           	      \    g | ])\  }}|t          |d d          t          |dd          d*S )r  ?r  T)rE   r  r  rY  )r4  r   rZ  s      r@   r6  z_.<locals>.<listcomp>$  sV        1	 !"#*1i#=#=#*1i#>#>   rw   r  )r   r	  r  _pluginsr8  r1   ra  r2   )r   r  r	  r  s       r@   rH  rH  z$  s    '999999   !3 2 4 4 = C C E E  	
 
 	
  ' ' 'Cs1vv&&&&&&&&'s   A A 
A5A0*A50A5zconfig.showc                 L   	 t                      }t                      }t          j                            dd          p|                    dd          }t          |          dk    rd|dd           nd}t          j                            dd          p|                    d	d          }d
d
|gd|pdgd|ggdddt          t          |d                    gdd                    |                    dg                     pdgdt          |                    dd                    ggdddt          j	                    gdt          t          dz            ggdg}t          | d|i          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)NHERMES_API_KEYr   r  rn   z****z	(not set)HERMES_BASE_URLrx  ModelzBase URLz	(default)zAPI Key)rI  rb  Agentz	Max Turnsr  Toolsetsr  r  r  Verboser  FEnvironmentzWorking DirzConfig Filert  r  rQ  )r   r  r(   r   r   r  r2   r  r&   r   rk  r  r1   ra  )	r   r  r5  r   r  maskedrx  r  r  s	            r@   rH  rH  $  s   "'kk  *..!1266P#'')R:P:P*-g,,*:*:&&&&:>>"3R88SCGGJPR<S<S !e$!8[9'  ! #nS"&=&=">">?3773Er+J+J!K!K!TuUCGGIu$=$= > >?  '"BIKK0"C}(D$E$EF #
2 3X./// ' ' 'Cs1vv&&&&&&&&'s   E.E1 1
F#;FF#F#z
tools.listc           	      f   	 ddl m}m} t                              |                    dd                    }|r&t          t          |d         dg           pg           nt          t                      pg           }g }t           |            	                                          D ]C} ||          }|s|
                    ||d         |d         |r||v nd	|d
         d           Dt          | d|i          S # t          $ r(}	t          | dt          |	                    cY d }	~	S d }	~	ww xY w)Nr   get_all_toolsetsget_toolset_infor   r   r  r  r  r!  Tresolved_tools)rE   r  r!  r  r\   r  r	  r  r	  r	  rM   r   r  r   r  r  r  r  r  r1   ra  r2   
r   r  r	  r	  r   r  r8  rE   r  r  s
             r@   rH  rH  $  s   '????????--

< < <== 5C(*<bAAGRHHH+--344 	 ++--224455 	 	D##D))D LL #'#6"&|"429Ctwt!"23     3U+,,, ' ' 'Cs1vv&&&&&&&&'s   C;C> >
D0D+%D0+D0z
tools.showc                 \   	 ddl m}m} t                              |                    dd                    }|rt          |d         dd           nt                      } ||d          }i }t          |d	 
          D ]}|d         d         }	t          |d                             dd          pd          	                    d          d         }
d|
v r |
d |

                    d          dz            }
|                     ||	          pdg                               |	|
d           t          | d t          |                                          D             t          |          d          S # t           $ r(}t#          | dt          |                    cY d }~S d }~ww xY w)Nr   )r  r  r   r   r  r  Tr  c                     | d         d         S )Nr  rE   rv   rO	  s    r@   rx   z_.<locals>.<lambda>$  s    *f0E rw   r  r  rE   r  r   z. r   r  rE   r  c                     g | ]
\  }}||d S ))rE   r\   rv   )r4  rE   rb  s      r@   r6  z_.<locals>.<listcomp>$  s4       "d "D11  rw   )r  rk  r	  )r  r  r  rM   r   r   r  r  r2   r  r  r  r  r  r8  r  r1   ra  )r   r  r  r  r   r  r\   r  r  rE   r  r  s               r@   rH  rH  $  s   #'JJJJJJJJ--

< < <== *GGG$&8$???')) 	
 %$g$OOO5&E&EFFF 
	 
	D
#F+DtJ'++M2>>D"EEKKDQQRSTDt||2djj..223 4 4T : : GiLLSS #'      &,X^^-=-=&>&>   U 	
 	
 		
  ' ' 'Cs1vv&&&&&&&&'s   E6E9 9
F+F& F+&F+ztools.configurec           
      X   t          |                    dd          pd                                                                          }d |                    dg           pg D             }|dvrt	          | dd|           S |st	          | dd	          S 	 d
dlm}m} d
dlm	}m
}m}m}	m}
  |            }d |D              |
            z  d |D             }d |D             }fd|D             fd|D             }|r ||d||           |r ||||          nt                       ||           t                              |                    dd                    }|r$t!          |                    dd          |          nd }t#           |	 |            dd                    }fd|D             }t%          | |||t#                    t'          |          d          S # t(          $ r(}t	          | dt          |                    cY d }~S d }~ww xY w)Nr;	  r   c                     g | ]D}t          |                                          #t          |                                          ES rv   r|  r  s     r@   r6  z_.<locals>.<listcomp>%  sM       "s4yyGXGXD		  rw   rv  >   r  disabler  zunknown tools action: r[  znames requiredr   )r  r
  )CONFIGURABLE_TOOLSETS_apply_mcp_change_apply_toolset_changer  _get_plugin_toolset_keysc                     h | ]\  }}}|	S rv   rv   )r4  ts_keyrH  s      r@   r  z_.<locals>.<setcomp>%  s+     
 
 
#vq!F
 
 
rw   c                     g | ]}d |v|	S r  rv   r  s     r@   r6  z_.<locals>.<listcomp>%  s    GGGDs$4rw   c                     g | ]}d |v |	S r	  rv   r  s     r@   r6  z_.<locals>.<listcomp>%  s    ???3$;;t;;;rw   c                     g | ]}|v|	S rv   rv   r4  rE   valid_toolsetss     r@   r6  z_.<locals>.<listcomp>%  s#    RRRDt>7Q7Q47Q7Q7Qrw   c                     g | ]}|v |	S rv   rv   r	  s     r@   r6  z_.<locals>.<listcomp>%  s#    VVVDt~?U?U4?U?U?Urw   r  r   Fr  c                 `    g | ]*}|vr$d |vs|                     d d          d         v(|+S )r  r   r   )r  )r4  rE   missing_serversr  s     r@   r6  z_.<locals>.<listcomp>-%  sW     
 
 
7""DDJJsA$6$6q$9$P$P  %Q$P$Prw   )changedr  r  r	  rX  r  r	  )r2   r   r3   r   ra  r  r  r
  r  r	  r	  r	  r  r	  r  rM   r  r  r  r   r1   )r   r  r;	  targetsr  r
  r	  r	  r	  r  r	  r5  toolset_targetsmcp_targetsr   r  r  r	  r  r	  r  r	  s                      @@@r@   rH  rH  $  s9   Hb))/R006688>>@@F &,jj"&=&=&C  G ***C@@@AAA 1C/0007'>>>>>>>>	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 kmm
 
'<
 
 
$$&&' HGGGGG?????RRRRORRRVVVVOVVV 	G!!#uovFFF <GQc;777CEE 	 	C--

< < <==  L"!=!=wGGG 	
 uRWXXX
 

 
 
 
 

 
 
 "$+#)/#:#:g" 

 

 
	
  ' ' 'Cs1vv&&&&&&&&'s   EG7 7
H)H$H)$H)ztoolsets.listc                 X   	 ddl m}m} t                              |                    dd                    }|r&t          t          |d         dg           pg           nt          t                      pg           }g }t           |            	                                          D ]<} ||          }|s|
                    ||d         |d         |r||v nd	d
           =t          | d|i          S # t          $ r(}	t          | dt          |	                    cY d }	~	S d }	~	ww xY w)Nr   r	  r   r   r  r  r  r!  T)rE   r  r!  r  r  r  r	  r	  s
             r@   rH  rH  C%  s|   '????????--

< < <== 5C(*<bAAGRHHH+--344 	 ++--224455 	 	D##D))D LL #'#6"&|"429Ctwt	     3U+,,, ' ' 'Cs1vv&&&&&&&&'s   C4C7 7
D)D$D)$D)zagents.listc                     	 ddl m} |                                }t          | dd |D             i          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   r  	processesc                 \    g | ])}|d          |d         dd         |d         |d         d*S )r   r   Nr  r  uptime_seconds)r   r   r  uptimerv   r)  s     r@   r6  z_.<locals>.<listcomp>j%  sX         '(o#$Y<#4"#H+"#$4"5	   rw   r 	  )r|  rw  list_sessionsr  r1   ra  r2   )r   r  rw  procsr  s        r@   rH  rH  a%  s    ';;;;;; ..00   #  

 
 	
  ' ' 'Cs1vv&&&&&&&&'s   58 
A*A%A*%A*zcron.managec                 z   |                     dd          |                     dd          }}	 ddlm} |dk    r,t          | t	          j         |d                              S |dk    rWt          | t	          j         |d	||                     d
d          |                     dd                                        S |dv r-t          | t	          j         |||                              S t          | dd|           S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr;	  r	  rE   r   r   )cronjob)r;	  r  createscheduleri  )r;	  rE   r	  ri  >   rR  removerS  )r;	  job_idr  zunknown cron action: i  )	r   tools.cronjob_toolsr	  r  r   r   ra  r1   r2   )r   r  r;	  jidr	  r  s         r@   rH  rH  y%  sq   **Xv..

620F0FCF'//////VsDJwwf'='='=>>???U??
G' !'J!;!;%zz(B77	   
 
 
 222sDJwwfS'I'I'IJJKKKC?v??@@@ ' ' 'Cs1vv&&&&&&&&'s0   7D &AD 0D 4D 
D:D5/D:5D:re   c                    |                     dd          |                     dd          }}	 |dk    r ddlm} t          | d |            i          S |dk    rHdd	lm}m}m}  || | |                      d
d          pg }t          | dd |D             i          S |dk    r<ddlm	}	  G d d          }
 |	|d |
                       t          | d|d          S |dk    rddlm
} t          |                     dd          pd          p$|                                rt          |          nd}t          |  ||t          |                     dd                                        S |dk    r#ddlm} t          | d ||          pi i          S t          | dd |           S # t          $ r(}t          | d!t!          |                    cY d }~S d }~ww xY w)"Nr;	  r	  r  r   r   r  r  r  )
GitHubAuthcreate_source_routerunified_searchr  r  )source_filterrW  r  c                 ,    g | ]}|j         |j        d S )r	  r	  r4  r  s     r@   r6  z_.<locals>.<listcomp>%  s1          KLFF     rw   install)
do_installc                       e Zd Zd ZdS )_.<locals>._Qc                     d S r   rv   )r   r   rZ  s      r@   r6   z_.<locals>._Q.print%  s    Drw   N)r5   r   r   r6   rv   rw   r@   _Qr
  %  s#            rw   r
  T)skip_confirmconsole)	installedrE   r5  )browse_skillsr  r   	page_size)r  r
  r  )inspect_skillr  r  zunknown skills action: i  )r   r  r  r  tools.skills_hubr	  r	  r	  hermes_cli.skills_hubr
  r
  r  isdigitr
  ra  r1   r2   )r   r  r;	  r  r  r	  r	  r	  r   r
  r
  r
  pgr
  r  s                  r@   rH  rH  %  s   JJx00&**Wb2I2IEF5'V>>>>>>sX';';'='=>???X          ((66"'	          PS        Y888888        Ju4>>>>s$>>???X;;;;;;VZZ**/a00 #mmoo4E


1  ]]c&**[RT:U:U6V6VWWW   Y;;;;;;sV]]5%9%9%?R@AAACAAABBB ' ' 'Cs1vv&&&&&&&&'s>   %F3 AF3 "AF3 $BF3 6(F3 F3 3
G%=G G% G%zskills.reloadc                    	 ddl m}  |            }|                    d          pg }|                    d          pg }t          |                    d          pd          }dg}|s|s|                    d           |r4|                    d           |                    d	 |D                        |r4|                    d
           |                    d |D                        |                    | d           t          | d                    |          |d          S # t          $ r(}t          | dt          |                    cY d }~S d }~ww xY w)Nr   )reload_skillsaddedr  rk  zReloading skills...zNo new skills detected.zAdded skills:c              3   H   K   | ]}d |                     dd           V  dS z  - rE   r   Nr3  r  s     r@   r  z_.<locals>.<genexpr>%  s9      II46 4 466IIIIIIrw   zRemoved skills:c              3   H   K   | ]}d |                     dd           V  dS r
  r3  r  s     r@   r  z_.<locals>.<genexpr>%  s9      KK46 4 466KKKKKKrw   z skill(s) availabler   )r   r  rZ	  )r  r
  r   r  r  r  r  r&   r1   ra  r2   )	r   r  r
  r  r
  r  rk  r  r  s	            r@   rH  rH  %  s   '666666

7##)r**Y''-2FJJw'',1--&' 	4W 	4LL2333 	JLL)))LLII5IIIIII 	LLL*+++LLKK7KKKKKK2223333499U#3#3vFFGGG ' ' 'Cs1vv&&&&&&&&'s   D'D* *
E4EEErg   c           	         |                     dd          }	 ddlmmmm fd}|dk    rG |            }t          d |D                       }t          | ||t          |          |z
  d          S |dk    rdd	lm	} |                     d
          pd
                                st          | dd          S t          |                     d                    } ||          }|                     d          s&t          | d|                     d          pd          S t          fd |            D             d          }	t          | dt          |                     d                    |	d          S t          | dd|           S # t          $ r(}
t          | dt          |
                    cY d}
~
S d}
~
ww xY w)u=  List installed plugins with activation state, or toggle one on/off.

    Backs the TUI Plugins Hub. Uses the same disk-discovery + enable/disable
    primitives as ``hermes plugins`` / the dashboard, so the three surfaces
    agree on what's installed and what's enabled.

    Actions:
      - ``list``   → {"plugins": [{name, version, description, source,
                       status}], "user_count": N, "bundled_count": M}
      - ``toggle`` → flip ``name`` based on ``enable`` (bool). Returns the
                       refreshed row plus {"ok", "unchanged"}.
    r;	  r	  r   )_discover_all_plugins_get_disabled_set_get_enabled_set_plugin_statusc                                   }  
            }g }t           	                      D ]B\  }}}}}}|                    |t          |pd          |pd| || ||          d           C|S )Nr   r  )rE   r  r  r  r  )r  r  r2   )r  r  r5  rE   r  r  r  _dirr  r
  r
  r
  r
  s            r@   _rowsz_.<locals>._rows%  s    &&((G((**HC:@%%''; ;  6gtVT3 

 $#&w}"#5#5'+zr"("0.wc"R"R"R     Jrw   c              3   2   K   | ]}|d          dk    dV  dS )r  bundledr   Nrv   r
  s     r@   r  z_.<locals>.<genexpr>&  s0      II1(y0H0HQ0H0H0H0HIIrw   )r	  
user_countbundled_countr  )"dashboard_set_agent_plugin_enabledrE   r   r2  z plugins.toggle requires a 'name'r  )r  r   rb	  r   ztoggle failedc              3   4   K   | ]}|d          k    |V  dS )rE   Nrv   )r4  r  rE   s     r@   r  z_.<locals>.<genexpr>'&  s1      @@aai4.?.?.?.?.?.?@@rw   NT	unchanged)r   r'
  rE   rK  r  zunknown plugins action: )r   hermes_cli.plugins_cmdr
  r
  r
  r
  rh	  r  r  r%
  r3   ra  r   r	  r1   r2   )r   r  r;	  r 
  rb  r#
  r%
  r  r  rt  r  r
  r
  r
  r
  rE   s              @@@@@r@   rH  rH  %  s{    ZZ&))F='	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
	 	 	 	 	 	 	 	$ V577DIIIIIIIJ#",%(YY%;    XQQQQQQJJv&&,"3355D KC'IJJJ&**X..//F77fMMMF::d## OCvzz'':':'MoNNN@@@@5577@@@$GGC!%fjj&=&=!>!> !	    CB&BBCCC ' ' 'Cs1vv&&&&&&&&'s9   A F >AF A)F 1AF 
F 
G(GGGrc   c           	         |                     dd          }|st          | dd          S 	 ddlm}m}  ||          \  }}|rt          | dd| d	          S  ||          \  }}}	|rt          | dd
|	 d	          S n!# t
          $ r t          | dd          cY S w xY w	 t          j        |ddddt          j	                    t          j
                  }
t          | |
j        dd          |
j        dd          |
j        d          S # t          j        $ r t          | dd          cY S t           $ r(}t          | dt#          |                    cY d }~S d }~ww xY w)Nr   r   rX  r"	  r   )detect_dangerous_commanddetect_hardline_commandr	  zblocked (hardline): z'. Use the agent for dangerous commands.z	blocked: r  z=shell.exec unavailable: approval safety module not importableTrN  )rG  r
  r   r   r   r   i`i0)r   r8   r_  i  zcommand timed out (30s)i  )r   ra  r  r*
  r+
  r  r   r   r(   r   r  r  r   r8   r  r@  r1   r2   )r   r  r)  r*
  r+
  is_hardlinehardline_descis_dangerousrH  r  r  r  s               r@   rH  rH  7&  s    
**Y
#
#C 0C///`TTTTTTTT%<%<S%A%A"] 	Th-hhh   !9 8 = =a 	TTtTTT  	  ` ` `C^_____`'NtDtRRY[[$
 
 
 (566*(566* 
 
 	
 $ : : :C899999 ' ' 'Cs1vv&&&&&&&&'s<   ,A? %A? ?BB!A(D
 
 E,	E5EEE)r   r   r   )r  )rI  )NNNNrZ  )r   )r  r  )NNNNNN)r  (9  atexitconcurrent.futures
concurrentr  r  r   r  r   loggingr(   r   r   r7   r   r/   rM  r   rN  r   typingr   r   r  r	   r
   r   r   hermes_cli.env_loaderr   utilsr   tui_gateway.transportr   r   r   r   r   	getLoggerr5   r   rk  __file__r  r*   r&   r,   rA   
excepthookrH   r  rI   r1   tui_gateway.renderrJ   rK   rL   rM   r   r2   __annotations__rN   r*  rO   tuplerP  rP   rQ   r]  rR   r   _stdout_lockr0  RLockr  rQ  rS   rT   rK  r1  r(  r   r   _slash_timeoutr%  r1  r  r   _ws_orphan_reap_gracer+  r  r_  r  r  r  _rpc_pool_workersfuturesThreadPoolExecutorrt   registerr   r   r8   rz   r  r"  r   r   r   r   r   r  r  r  r   r  r$  r.  r<  r@  rL  rW  rC  rN  rS  rY  r  rc  ro  rx  r  r  r  r  r  r  r  ra  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  contextmanagerr!  r'  r,  r  r   r9  r=  r	  r  r  rH  rS  rV  rb  r  rs  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r6  rI  rV  rB  r  r  r  r  r  r  r  r  r  r  r  objectr  r  r  r  r  r  r5  r[  r  ro  rs  ry  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r)  r5  r7  r:  r>  rC  rE  rG  rH  rI  r  r  r  r  ru  r  rv  r$  r+  r/  r2  r6  rk  ru  r  r  r_  r'  r<  r?  r  r&  r  r  r  r  rP  rR  rW  rY  r\  r`  rc  rj  rm  r  r  r  r  r  r8  rE  r}  r  r  r  r  r  r  r  r  r  r  r 	  r+	  r)	  r,	  r0	  r  r6	  r9	  r{	  r	  r	  r	  r	  r	  r	  r	  rv   rw   r@   <module>rG
     s8                    				      



                                              5 4 4 4 4 4 ! ! ! ! ! !              
	8	$	$    $$x..*?*F*O    W\\,0GHH
4 4 44   : *	 	777777 	 	 	D	 Q P P P P P P P P P	4T	?    "$sH}
 " " "35$sE#y.//
0 5 5 58: $sE#t)$445 : : :$sCx.   
	3:   y~IN	 ""y~
D4K   
EDL   	%y~'' U2:>>*FGGO4PPNNI   NNN#c>22 !!E

:;;Ct  	I ! ! ! !#c#899 F 	===>> 
 
 
 	33rz~~;<<CDD  	I   --!  	. 	 	 GG H H H
 zZ
        ">"6"6EE 
 ()) d d d d d d d dNJs J J J J #*      	    	
 3d
?   (	M$+ 	M$ 	M 	M 	M 	M4 4td{ 4 4d 4 4 4 4n BM   td{ 3 QU    @ d t     9D   c #     >TD[ >T > > > ># $    > %4" " "!"
38_" " " "J= = = =%U2:>>*DEEQRRNN: % % %U8__NNN%S.))7T 7 7 7 7
Xs 
XT 
X 
X$ 
X 
X 
X 
X= = = =	8 	8 	8 	8 " # # #       $> > > > >K3: K$+ K K K K( )(( $+ #*    8@D @T @ @ @ @*H H H3 H H H H H  3 cDj    M# Ms Ms M M M Md t    ;T ;d ; ; ; ;RC Rc Rd R R R R    C E#sD.$9D$@    &	 	 	 	 	 	& &$ &8I#6 &$+ & & & &R1 1 1C 1% 14$; 1 1 1 1s9C s9$ s94 s9 s9 s9 s9lL L L
$ $ $# #     D4K 3    (!t ! ! ! ! !0S S    6$+ #    
4$; 
4 
 
 
 
2D 2T 2 2 2 2j     6d      < &N 5c? M M M 4    >4     c c      c d
 d    4 D    + + + +% %# %C %$ % %s % % % %$ d
 d    &d    &' ' ' ' ' %S4Z"8        F84$; 84 8 8 8 8v 4$; $    BN4$; N4 N N N NB	 	 	 	 	 955566 c     
5 
5	
 i y Y U E 	% 
5 	% g E W  
5! (T c    4*t * * * *
C$J 
 
 
 
Qd Q Q Q Q
G# 
G 
G 
G 
GLS	D 0 L L L L^QS QS Q Q Q Q9# 9$ 9 9 9 95 5 5 5 5 5-s -T - - - -,   . %*{ { {	{{ {
 "{ 
{ { { {@ # $#'"&21 2121t21 :21 D[	21
 4Z21 3921 21 21 21r !%!%I I I	II 	I
 I 
I I I IX3 3 3 3 3l	 	 	 	 	&d &s & & & &Bs      e e$+ e e e e ePC t       $   ! ! ! ! ! !H+3 +3 + + + +)$ )3 ) ) ) ))f ) ) ) ) )6 6 6 6 6 67V 7C 7C$J 7 7 7 7/ /S /edl /sTz / / / /8* *3 *c * * * * *6,-3 ,-c ,- ,-D ,-RU ,- ,- ,- ,-d N( N(	N(N( *N( 4Z	N(
 $;N( N( N( N(b3C 3D 3 3 3 3l+ + + + +<    K K$+ K K K K KA A A4$; A%S/ A A A A(3     BD+ +	++),+;>+
4+ + + +\N Ns Ns N N N N	tCy 	 	 	 	+ + +" " "#S #T # # # #L	C 	D 	 	 	 	8 8d 8# 8TW 8cghlcm 8 8 8 8v7s 7C 7C 7 7 7 7,s S T    Dc D T    F "(,$(-1(,v v	v	v d
v
 3J%v Tzv  $d{v :v v v vrMM MMs MM MMd MM# MM MM MM MM`P# P P P PG G GNs N N N N N N"4C "4d3i "4C "4 "4 "4 "4J3 3    <T# T# T T T Tn.$t* .d . . . .b T
    03 3    <0# 0# 0 0 0 0$ c d    
$D 
$ 
$ 
$ 
$ 
$ 
$$$ $4 $ $ $ $     & c4 cD c c c cL *'4 *'D *' *' *' *'Z (.4 (.D (. (. (. (.V U4 UD U U U Up 4 D    .s s    c D S    d s     C C     C $ S $    23 5d3Cd3J    
D 
T 
 
 
 
" "&     	   *	 
   4  
       F "(4 "(D "( "( "( "(J 4 D    . &)4 &)D &) &) &) &)R ;'4 ;'D ;' ;' ;' ;'| T4 TD T T T Tn 4 D    4 74 7D 7 7 7 7. 4 D    2 524 52D 52 52 52 52p 4 D    , *4 *D * * * *6 \'4 \'D \' \' \' \'~ 3'4 3'D 3' 3' 3' 3'l W4 WD W W W W CP4 CPD CP CP CP CPL /4 /D / / / /4 4 D    & :4 :D : : : : ?4 ?D ? ? ? ?&       # @ @$ @ @ @ @4:    ( 'C4 'CD 'C 'C 'C 'CT /24 /2D /2 /2 /2 /2d 4 D    . T4 TD T T T T0 /4 /D / / / / :-4 :-D :- :- :- :-z4 d t    <t     @r3r3&)r348r3	r3 r3 r3 r3j	C 	$ 	9? 	 	 	 	c6 c6t c63 c64 c6 c6 c6 c6L $4 $D $ $ $ $N ''4 ''D '' '' '' ''X + (  /eE%*%s*+   s C EDL    0   c    &M9S> M M M M4 E  PS X\    * 94 9D 9 9 9 9x r
4 r
D r
 r
 r
 r
j $(  S S    ,%$ % % % % % %T d    %C %C % % % %$ # $    F# F$+ F F F F"># >% > > > >,&"&" &" 	&"
 &" 4:&" &" &" &"R +'4 +'D +' +' +' +'\ 4 D    & +'4 +'D +' +' +' +'\ **4 **D ** ** ** **Z m*4 m*D m* m* m* m*f	& 	& 	& +4 +D + + + +   )4 )D ) ) ) ! )
 -4 -D - - - - *4 *D * * * * '4 'D ' ' ' '0 U94 U9D U9 U9 U9 U9p E94 E9D E9 E9 E9 E9P '4 'D ' ' ' ' A84 A8D A8 A8 A8 A8N '4 'D ' ' ' ' V'4 V'D V' V' V' V'r '4 'D ' ' ' '( (i   Ys^   	* 	* 	*
DsC}%& 	 	 	 +4)  
+ 
+ 3 
 
 
 ,59j&5I+J+J )C. J J J _'4 _'D _' _' _' _'DDI #*      
'4 'D ' ' ' ': '4 'D ' ' ' '&      AH4 AHD AH AH AH AHL
  4 D    8   $9    & #IN$$ 35d3eT#Y.//0 5 5 5W3 W49 W W W Wt4s 43 45c?T3I 4 4 4 4n @&4 @&D @& @& @& @&F; ;C ;s ;D ; ; ; ;04	   Ks KtDzD'8 K K K K\ K'4 K'D K' K' K' K'\ $'4 $'D $' $' $' $'N N'4 N'D N' N' N' N'b *'4 *'D *' *' *' *'`3C 3$ 3 3 3 3 3 3l X'4 X'D X' X' X' X'| !)."" #    s TD[ D    	=T 	= 	= 	= 	=AD A A A A
< < < < <"W3 W W W W ]>4 ]>D ]> ]> ]> ]>@ I'4 I'D I' I' I' I'X '4 'D ' ' ' '$ '4 'D ' ' ' '6 '4 'D ' ' ' ': +'4 +'D +' +' +' +'\ '4 'D ' ' ' '2#    BT    *#  $    449 4 4 4 4O# O O O O3 c 3 49    & )4 )D ) ) ) ) g$ g4 g g g gT* * * * *" '4 'D ' ' ' '* #'4 #'D #' #' #' #'L '4 'D ' ' ' '< $'4 $'D $' $' $' $'N A'4 A'D A' A' A' A'H '4 'D ' ' ' ': '4 'D ' ' ' '. '4 'D ' ' ' '4 7'4 7'D 7' 7' 7' 7't '4 'D ' ' ' '0 K'4 K'D K' K' K' K'\ #'4 #'D #' #' #' #' #' #'sZ   &C7 7C?>C?%H   	HH%I 	II:/J* *	J65J6%O* *O?>O?