
    iR                       U d Z ddlmZ ddlZddlZddlZddlmZmZ ddl	m
Z
 ddlmZ ddlmZmZ erddlmZ  ej        e          Z e
j                    d	z  d
z  ZdZd0dZd1dZddiZh dZd2dZd3dZddhZddddZd2dZ ddddddddddd Z!d4d%Z"e G d& d'                      Z#da$d(e%d)<   d5d6d-Z&d7d/Z'dS )8a  Honcho client initialization and configuration.

Resolution order for config file:
  1. $HERMES_HOME/honcho.json  (instance-local, enables isolated Hermes instances)
  2. ~/.honcho/config.json     (global, shared across all Honcho-enabled apps)
  3. Environment variables     (HONCHO_API_KEY, HONCHO_ENVIRONMENT)

Resolution order for host-specific settings:
  1. Explicit host block fields (always win)
  2. Flat/global fields from config root
  3. Defaults (host name as workspace/peer)
    )annotationsN)	dataclassfield)Path)get_hermes_home)AnyTYPE_CHECKINGHonchoz.honchozconfig.jsonhermesreturnstrc                     t           j                            dd                                          } | r| S 	 ddlm}  |            }|r|dvrt           d| S n# t          $ r Y nw xY wt          S )a	  Derive the Honcho host key from the active Hermes profile.

    Resolution order:
      1. HERMES_HONCHO_HOST env var (explicit override)
      2. Active profile name via profiles system -> ``hermes.<profile>``
      3. Fallback: ``"hermes"`` (default profile)
    HERMES_HONCHO_HOST r   )get_active_profile_name)defaultcustom.)osenvirongetstriphermes_cli.profilesr   HOST	Exception)explicitr   profiles      :/root/.hermes/hermes-agent/plugins/memory/honcho/client.pyresolve_active_hostr    "   s     z~~2B77==??H ??????))++ 	'w&;;;&&W&&&   Ks   !A 
A('A(r   c                     t                      dz  } |                                 r| S t          j                    dz  dz  }|| k    r|                                r|S t          S )uo  Return the active Honcho config path.

    Resolution order:
      1. $HERMES_HOME/honcho.json      (profile-local, if it exists)
      2. ~/.hermes/honcho.json          (default profile — shared host blocks live here)
      3. ~/.honcho/config.json          (global, cross-app interop)

    Returns the global path if none exist (for first-time setup writes).
    zhoncho.jsonz.hermes)r   existsr   homeGLOBAL_CONFIG_PATH)
local_pathdefault_paths     r   resolve_config_pathr'   8   sm     !""]2J  9;;*]:Lz!!l&9&9&;&;!    autohybrid>   toolsr*   contextvalc                R    t                               | |           } | t          v r| ndS )u?   Normalize legacy recall mode values (e.g. 'auto' → 'hybrid').r*   )_RECALL_MODE_ALIASESr   _VALID_RECALL_MODESr-   s    r   _normalize_recall_moder2   R   s,    

"
"3
,
,C,,,33(:r(   r   boolc               J    | t          |           S |t          |          S |S )z@Resolve a bool config field: host wins, then root, then default.)r3   )host_valroot_valr   s      r   _resolve_boolr7   X   s+    H~~H~~Nr(   unifieddirectional)sharedseparatecrossc                R    t                               | |           } | t          v r| ndS )z"Normalize observation mode values.r9   )_OBSERVATION_MODE_ALIASESr   _VALID_OBSERVATION_MODESr1   s    r   _normalize_observation_moder@   e   s,    
#
'
'S
1
1C11133}Dr(   Tuser_observe_meuser_observe_othersai_observe_meai_observe_othersF)r9   r8   modeobservation_objdict | Nonedictc                   t                               | t           d                   }|rt          |t                    st          |          S |                    d          pi }|                    d          pi }|                    d|d                   |                    d|d                   |                    d|d                   |                    d|d	                   d
S )aj  Resolve per-peer observation booleans.

    Config forms:
      String shorthand:  ``"observationMode": "directional"``
      Granular object:   ``"observation": {"user": {"observeMe": true, "observeOthers": true},
                                           "ai": {"observeMe": true, "observeOthers": false}}``

    Granular fields override preset defaults.
    r9   userai	observeMerB   observeOthersrC   rD   rE   rA   )_OBSERVATION_PRESETSr   
isinstancerI   )rF   rG   preset
user_blockai_blocks        r   _resolve_observationrT   y   s     "%%d,@,OPPF *_d"C"C F|| $$V,,2J""4((.BH &>>+v>O7PQQ)~~ovF[?\]]!k6/3JKK%\\/6BU;VWW	  r(   c                  (   e Zd ZU dZeZded<   dZded<   dZded<   d	Z	ded
<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   d Zded!<   d"Zded#<   dZded$<   d%Zded&<   dZded'<   dZded(<   dZded)<   dZded*<   d+Zded,<   dZded-<    ee .          Z!d/ed0<    ee .          Z"d1ed2<   dZ#ded3<   e$	 	 d>d?d5            Z%e$	 	 d@dAd8            Z&e'dBd:            Z(	 	 	 dCdDd=Z)dS )EHonchoClientConfigz>Configuration for Honcho client, resolved for a specific host.r   hostr   workspace_idN
str | Noneapi_key
productionenvironmentbase_url	peer_nameai_peerFr3   enabledTsave_messagesasyncz	str | intwrite_frequencyz
int | Nonecontext_tokenslowdialectic_reasoning_leveldialectic_dynamicX  intdialectic_max_charsa  message_max_chars'  dialectic_max_input_charsr*   recall_modeinit_on_session_startr9   observation_moderB   rC   rD   rE   per-directorysession_strategysession_peer_prefix)default_factoryzdict[str, str]sessionszdict[str, Any]rawexplicitly_configuredr   c                F   |pt                      }t          j                            d          }t          j                            dd                                          pd} | |||t          j                            dd          ||t          |p|                    S )z4Create config from environment variables (fallback).HONCHO_API_KEYHONCHO_BASE_URLr   NHONCHO_ENVIRONMENTr[   )rW   rX   rZ   r\   r]   r_   r`   )r    r   r   r   r   r3   )clsrX   rW   resolved_hostrZ   r]   s         r   from_envzHonchoClientConfig.from_env   s     5 3 5 5*..!122:>>"3R88>>@@HDs%
';\JJ!,H--
 
 
 	
r(   config_pathPath | Nonec                   |pt                      }|pt                      }|                                s1t                              d|           |                     |          S 	 t          j        |                    d                    }nU# t          j	        t          f$ r<}t                              d||           |                     |          cY d}~S d}~ww xY w|                    d          pi                     |i           }t          |          p|                    d          d	u }|                    d
          p|                    d
          p|}	|                    d          p|                    d          p|}
|                    d          p3|                    d          pt          j                            d          }|                    d          p|                    dd          }|                    d          pH|                    d          p3t          j                            dd                                          pd}|                    d          }|                    d          }||}n||}nt          |p|          }|                    d          p|                    d          pd}	 t#          |          }n&# t$          t&          f$ r t)          |          }Y nw xY w|                    d          }||n|                    dd	          }|                    d          p|                    dd          }|                    d          }||n|                    dd          } | d@i d|d|	d|d|d|d|                    d          p|                    d          d |
d|d!|d"|d#|                    d$          p|                    d$          d%|                    d&          p|                    d&          pd'd(t+          |                    d)          |                    d)          d	*          d+t#          |                    d,          p|                    d,          pd-          d.t#          |                    d/          p|                    d/          pd0          d1t#          |                    d2          p|                    d2          pd3          d4t-          |                    d5          p|                    d5          pd6          d7t+          |                    d8          |                    d8          d*          d9t/          |                    d:          p|                    d:          p|rd;nd<          t1          t/          |                    d:          p|                    d:          p|rd;nd<          |                    d=          p|                    d=                    |||                    d>i           ||d?S )AzCreate config from the resolved Honcho config path.

        Resolution: $HERMES_HOME/honcho.json -> ~/.honcho/config.json -> env vars.
        When host is None, derives it from the active Hermes profile.
        z2No global Honcho config at %s, falling back to env)rW   zutf-8)encodingz*Failed to read %s: %s, falling back to envNhostsr`   T	workspaceaiPeerapiKeyrz   r\   r[   baseUrlr]   r{   r   writeFrequencyrb   saveMessagessessionStrategyrr   sessionPeerPrefixFrW   rX   rZ   r^   peerNamer_   ra   rc   rd   contextTokensrf   dialecticReasoningLevelre   rg   dialecticDynamic)r   rj   dialecticMaxCharsrh   rl   messageMaxCharsrk   rn   dialecticMaxInputCharsrm   ro   
recallModer*   rp   initOnSessionStartrq   observationModer8   r9   observationrv   )rs   rt   rv   rw   rx    )r    r'   r"   loggerdebugr   jsonloads	read_textJSONDecodeErrorOSErrorwarningr   r3   r   r   r   ri   	TypeError
ValueErrorr   r7   r2   r@   rT   )r}   rW   r   r~   pathrw   e
host_block_explicitly_configuredr   r_   rZ   r\   r]   host_enabledroot_enabledr`   raw_wfrc   	host_savera   rs   host_prefixrt   s                           r   from_global_configz%HonchoClientConfig.from_global_config   su    5 3 5 53133{{}} 	4LLMtTTT<<]<333	4*T^^W^==>>CC$g. 	4 	4 	4NNGqQQQ<<]<33333333	4 ggg&&,"11-DD
 "&j!1!1!OSWWY5G5G45O NN;'' ww{## 	 NN8$$ wwx   	 NN8$$ 0wwx  0z~~.// 	 NN=)) 4ww}l33 	 GGI wwz""z~~/44::<< 	 	 "~~i00wwy))#"GG%"GG 7.h//G NN+,, ww'(( 	
	*),VOO:& 	* 	* 	*!&kkOOO	* NN>22	%.%:		X\@]@] NN,-- ;ww(/:: 	 !nn%899&2KK,e44 	
 s F
 F
 F
F
"F
 GF
 $	F

 XF
 !nnZ00GCGGJ4G4GF
 GF
 GF
 (-F
 ,OF
 &>>/::Vcggo>V>VF
 899 77455F
" ,122*++   #F
, !$233 77.//! ! !-F
6 "011 77,--  7F
@ '*788 77344' ' 'AF
J /|,, 77<((  KF
T #0344,--# # # #UF
h 9011 L77,--L!7JII]  
 #+NN#455 Pww011P%;N		 
 }--G1G1G sF
B . 3WWZ,,"8KF
 F
 F
 F
 F	
s0   '(B C"&1CC"C"K" " LLcwdc                    ddl }	 |                    g ddd| d          }|j        dk    r+t          |j                                                  j        S n# t          |j        f$ r Y nw xY wdS )zBReturn the git repo root directory name, or None if not in a repo.r   N)gitz	rev-parsez--show-toplevelT   )capture_outputtextr   timeout)	
subprocessrun
returncoder   stdoutr   namer   TimeoutExpired)r   r   roots      r   _git_repo_namez!HonchoClientConfig._git_repo_name  s     		>>777#$C "  D !##DK--//0055 $23 	 	 	D	ts   AA A-,A-session_title
session_idc                v   ddl }|st          j                    }| j                            |          }|r|S |rH|                    dd|                              d          }|r| j        r| j        r| j         d| S |S | j	        dk    r|r| j        r| j        r| j         d| S |S | j	        dk    rE| 
                    |          pt          |          j        }| j        r| j        r| j         d| S |S | j	        dv r0t          |          j        }| j        r| j        r| j         d| S |S | j        S )u  Resolve Honcho session name.

        Resolution order:
          1. Manual directory override from sessions map
          2. Hermes session title (from /title command)
          3. per-session strategy — Hermes session_id ({timestamp}_{hex})
          4. per-repo strategy — git repo root directory name
          5. per-directory strategy — directory basename
          6. global strategy — workspace name
        r   Nz[^a-zA-Z0-9_-]-per-sessionzper-repo)rr   r   )rer   getcwdrv   r   subr   rt   r^   rs   r   r   r   rX   )selfr   r   r   r   manual	sanitizedbases           r   resolve_session_namez'HonchoClientConfig.resolve_session_name  s     				 	)++C ""3'' 	M  	!0#}EEKKCPPI !+ ; ;"n::y:::    M11j1' 8DN 8.77:777  J..&&s++=tCyy~D' 2DN 2.114111K  $DDD99>D' 2DN 2.114111K   r(   )r   N)rX   r   rW   rY   r   rV   )NN)rW   rY   r   r   r   rV   )r   r   r   rY   )NNN)r   rY   r   rY   r   rY   r   rY   )*__name__
__module____qualname____doc__r   rW   __annotations__rX   rZ   r\   r]   r^   r_   r`   ra   rc   rd   rf   rg   rj   rl   rn   ro   rp   rq   rB   rC   rD   rE   rs   rt   r   rI   rv   rw   rx   classmethodr   r   staticmethodr   r   r   r(   r   rV   rV      s        HHD L    G#K####H I    GGM ")O((((!%N%%%% &+**** #""""""""" #""""%*****
  K
 #('''' *)))) !O     $$$$$M"""""+++++ %%%%%$uT:::H::::%555C5555 #('''' %
 
 
 
 [
&   #'d
 d
 d
 d
 [d
L    \" $(!%	7! 7! 7! 7! 7! 7! 7!r(   rV   zHoncho | None_honcho_clientconfigHonchoClientConfig | Noner   c                   t           t           S | t                                          } | j        s| j        st          d          	 ddlm} n# t          $ r t          d          w xY w| j        }|sw	 ddl	m
}  |            }|                    di           }t          |t                    r*|                    dd	                                          pd}n# t          $ r Y nw xY w|r"t                               d
|| j                   n&t                               d| j        | j                   |od|v pd|v pd|v }|rg| j        pi }|                    d          pi                     | j        i           }t+          |                    d                    }	|	r| j        nd}
n| j        }
| j        |
| j        d}|r||d<    |di |a t           S )zGet or create the Honcho client singleton.

    When no config is provided, attempts to load ~/.honcho/config.json
    first, falling back to environment variables.
    NzHoncho API key not found. Get your API key at https://app.honcho.dev, then run 'hermes honcho setup' or set HONCHO_API_KEY. For local instances, set HONCHO_BASE_URL instead.r   r
   zThoncho-ai is required for Honcho integration. Install it with: pip install honcho-ai)load_confighonchor]   r   z8Initializing Honcho client (base_url: %s, workspace: %s)z4Initializing Honcho client (host: %s, workspace: %s)	localhostz	127.0.0.1z::1r   r   local)rX   rZ   r\   r   )r   rV   r   rZ   r]   r   r   r   ImportErrorhermes_cli.configr   r   rP   rI   r   r   r   inforX   rW   rw   r3   r\   )r   r   resolved_base_urlr   
hermes_cfg
honcho_cfg	_is_local_raw_host_block_host_has_keyeffective_api_keykwargss               r   get_honcho_clientr     sw    !~#6688> 
&/ 
@
 
 	

!!!!!!! 
 
 
5
 
 	

  	555555$J#"55J*d++ S$.NN:r$B$B$H$H$J$J$Rd! 	 	 	D	  nNPacicvwwwwJFKY_Ylmmm " (( 	&++	&%% 
  +zRxx((.B33FKDD[__X6677.;HFNN"N +$) F
  /.zV%%f%%Ns   A A)6A%C 
C)(C)Nonec                 
    da dS )z7Reset the Honcho client singleton (useful for testing).N)r   r   r(   r   reset_honcho_clientr   2  s     NNNr(   )r   r   )r   r   )r-   r   r   r   )r   r3   r   r3   )rF   r   rG   rH   r   rI   )N)r   r   r   r   )r   r   )(r   
__future__r   r   r   loggingdataclassesr   r   pathlibr   hermes_constantsr   typingr   r	   r   r   	getLoggerr   r   r#   r$   r   r    r'   r/   r0   r2   r7   r?   r>   r@   rO   rT   rV   r   r   r   r   r   r(   r   <module>r      sY     # " " " " "  				  ( ( ( ( ( ( ( (       , , , , , , % % % % % % % % 		8	$	$TY[[9,}<    ,   , ) 444 ; ; ; ;    &}5 '0mVcdd E E E E  D 
  T 	 	    > B! B! B! B! B! B! B! B!J
 !% $ $ $ $N N N N Nb     r(   