
    i                     ^    d Z ddlZddlmZ d ZddeddfdZ	 	 	 ddeded	ed
ededdfdZdS )aJ  
Hermes Web UI -- Optional state.db sync bridge.

Mirrors WebUI session metadata (token usage, title, model) into the
hermes-agent state.db so that /insights, session lists, and cost
tracking include WebUI activity.

This is opt-in via the 'sync_to_insights' setting (default: off).
All operations are wrapped in try/except -- if state.db is unavailable,
locked, or the schema doesn't match, the WebUI continues normally.

The bridge uses absolute token counts (not deltas) because the WebUI
Session object already accumulates totals across turns. This avoids
any double-counting risk.
    N)Pathc            
         	 ddl m}  n# t          $ r Y dS w xY w	 ddlm} t           |                                                                                      }nS# t          $ rF t          t          j
        dt          t          j                    dz                                }Y nw xY w|dz  }|                                sdS 	  | |          S # t          $ r Y dS w xY w)zGet a SessionDB instance for the active profile's state.db.
    Returns None if hermes_state is not importable or DB is unavailable.
    Each caller is responsible for calling db.close() when done.
    r   )	SessionDBN)get_active_hermes_homeHERMES_HOMEz.hermeszstate.db)hermes_stater   ImportErrorapi.profilesr   r   
expanduserresolve	Exceptionosgetenvstrhomeexists)r   r   hermes_homedb_paths       +/home/ubuntu/hermes-webui/api/state_sync.py_get_state_dbr      s0   
*******   ttS777777113344??AAIIKK S S S29]C	i8O4P4PQQRRS J&G>> ty!!!   tts1   	 
AA AB-,B-
C 
C%$C%
session_idreturnc                    t                      }|sdS 	 |                    | d|           n# t          $ r Y nw xY w	 |                                 dS # t          $ r Y dS w xY w# 	 |                                 w # t          $ r Y w w xY wxY w)zjRegister a WebUI session in state.db (idempotent).
    Called when a session's first message is sent.
    Nwebuir   sourcemodel)r   ensure_sessionr   close)r   r   dbs      r   sync_session_startr!   .   s     
B 
! 	 	
 	
 	
 	

    	HHJJJJJ 	 	 	DD		HHJJJJ 	 	 	D	sV   - A% 
:A% :A% A 
A"!A"%B'A<;B<
B	BB		Binput_tokensoutput_tokenstitlemessage_countc                 
    t                      }|sdS 	 |                     d|           |                     ||||d           |r(	 |                     |           n# t          $ r Y nw xY w-	  fd}|                    |           n# t          $ r Y nw xY wn# t          $ r Y nw xY w	 |                                 dS # t          $ r Y dS w xY w# 	 |                                 w # t          $ r Y w w xY wxY w)zUpdate token usage and title for a WebUI session in state.db.
    Called after each turn completes. Uses absolute=True to set totals
    (the WebUI Session already accumulates across turns).
    Nr   r   T)r   r"   r#   estimated_cost_usdr   absolutec                 8    |                      df           d S )Nz2UPDATE sessions SET message_count = ? WHERE id = ?)execute)connr%   r   s    r   _set_msg_countz*sync_session_usage.<locals>._set_msg_countc   s.    LLL&
3        )r   r   update_token_countsset_session_titler   _execute_writer   )	r   r"   r#   estimated_costr   r$   r%   r    r,   s	   `     `  r   sync_session_usager2   D   s    
B #
ZuMMM
!%'- 	 	
 	
 	
  	$$Z7777    $     
 !!.1111      	HHJJJJJ 	 	 	DD		HHJJJJ 	 	 	D	s   5B# A# "B# #
A0-B# /A00B# 6B B# 
BB# BB# "C #
B0-C /B00C 4C
 

CCDC21D2
C?<D>C??D)N)r   r   NNNN)	__doc__r   pathlibr   r   r   r!   intr2    r-   r   <module>r7      s     
			        4 3 t    , QRCG*.- -3 -c -C -?B-&)-37- - - - - -r-   