
    [j             
         d Z ddlm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	m
Z
mZmZmZ ddlmZ ddlmZ ddlmZ  ej        e          Zdd	d
ddddddidddg ddZddd
dddddddddddgddZddd
ddddd g d!d"dddd#dgddZd$d%d
d&dddig ddZd'd(d
dd)ddd*dd+d,ddd-ddd.dd/g ddZeeeeegZ G d0 d1e          Zd5d4ZdS )6uV  Honcho memory plugin — MemoryProvider for Honcho AI-native memory.

Provides cross-session user modeling with dialectic Q&A, semantic search,
peer cards, and persistent conclusions via the Honcho SDK. Honcho provides AI-native cross-session user
modeling with dialectic Q&A, semantic search, peer cards, and conclusions.

Five tools (profile, search, reasoning, context, conclude) are exposed
through the MemoryProvider interface.

Config: Uses the existing Honcho config chain:
  1. $HERMES_HOME/honcho.json (profile-scoped)
  2. ~/.honcho/config.json (legacy global)
  3. Environment variables
    )annotationsN)AnyCallableDictListOptional)sanitize_context)MemoryProvider)
tool_errorhoncho_profileu  Read or write a peer's CARD — a short, curated list of standing facts about that peer (name, role, preferences, communication style, recurring patterns). This is the cheapest, fastest Honcho call: no query, no LLM, just the current card. Pass `card` to overwrite it; omit `card` to read. An empty read returns a `hint` explaining why (observation disabled, fresh peer, representation still warming up) — that is NOT an error; the card accumulates over time from observed conversation. Related tools: honcho_context for the fuller standing snapshot (card + representation + summary + recent messages); honcho_search to find specific things that were actually said; honcho_reasoning for a synthesized answer to a question.objectstringzaPeer to query. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.)typedescriptionarrayr   zGNew peer card as a list of fact strings. Omit to read the current card.)r   itemsr   )peercard)r   
propertiesrequired)namer   
parametershoncho_searchu2  Hybrid (semantic + keyword) search over a peer's actual message history across ALL past sessions they took part in — not just the current one. Returns RRF-ranked raw message excerpts (what was literally said, including the assistant's own messages about the peer), no LLM synthesis. Cheaper and faster than honcho_reasoning. Use this to recall specific past facts — 'what did I say about X', 'what was the regimen/decision/config we settled on' — and reason over the excerpts yourself. For nuanced questions needing synthesis, use honcho_reasoning instead.uq   What to look for — a topic, keyword, name, or natural-language description of the fact you're trying to recall.integerztApproximate budget for returned excerpts (default 800, max 2000). Larger budgets return more/longer ranked snippets.zWhose history to search. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace. Spans every session that peer took part in.)query
max_tokensr   r   honcho_reasoninguG  Ask Honcho's dialectic agent a natural-language question about a peer and get back a SYNTHESIZED answer. This is the only Honcho tool that runs an LLM: it agentically searches both raw messages and derived conclusions, reasons over them, and writes a prose answer — so it is the slowest and most expensive call (seconds + tokens). Reach for it for nuanced or open-ended questions ('how does this person prefer to receive feedback?', 'what's their relationship to project X?') where you want Honcho to do the synthesis. For a specific fact that was stated, prefer honcho_search (cheap, raw excerpts, you synthesize). For standing profile facts, prefer honcho_profile / honcho_context (no LLM). Pass reasoning_level to control depth: minimal (fast/cheap), low (default), medium, high, max (deep/expensive). Omit for the configured default.zA natural language question.u  Override the default reasoning depth. Omit to use the configured default (typically low).
reasoning_level parameter guide:
- minimal: use ONLY for a single quick factual lookup (e.g. 'what is the user's name'). Honcho hard-caps this tier's output at 250 tokens combined with the model's own hidden reasoning tokens — a multi-part answer can get cut off mid-thought before it even reaches the final-answer phase, especially on models with reasoning/thinking enabled.
- low/medium/high/max: use for anything requiring a synthesized, multi-fact, or summary-style answer (e.g. 'summarize known facts about this peer', 'what are their communication preferences'). These tiers have no output-token cap of their own (fall back to Honcho's 8192-token global default), so they don't have minimal's cutoff failure mode.
  - low: straightforward questions with clear answers
  - medium: multi-aspect questions requiring synthesis across observations
  - high: complex behavioral patterns, contradictions, deep analysis
  - max: thorough audit-level analysis, leave no stone unturned
Default to at least 'low' unless the query is genuinely a single fact lookup.minimallowmediumhighmax)r   r   enum)r   reasoning_levelr   honcho_contextu  Retrieve the standing SNAPSHOT Honcho holds for the current session — session summary, the peer's representation, the peer card, and the most recent messages — in one call. No query, no LLM synthesis (cheaper than honcho_reasoning). Use it to orient yourself on what Honcho currently knows about this conversation and peer. This is a fixed snapshot, not a search: to look up a specific past fact use honcho_search; to ask a question and get a synthesized answer use honcho_reasoning; for just the compact card use honcho_profile.r   honcho_concludeu^  Write, delete, or list CONCLUSIONS — persistent, derived facts about a peer that feeds their long-term profile (card + representation). Use this to record something durable you've learned about the peer (a stable preference, a correction, a standing constraint) so future sessions carry it forward. You MUST pass exactly one of `conclusion` (to create), `delete_id` (to delete), or `list` (to list/search); any other combination is an error. A deletion ID is an opaque server-generated string: first call with `list=true` and optionally `query`, then pass the returned ID as `delete_id`. Deletion exists only for PII removal — for merely wrong facts, write a corrected conclusion instead; Honcho self-heals contradictions over time. This is a WRITE tool: to read the profile use honcho_profile / honcho_context, and to search what was said use honcho_search.zxA factual statement to persist. Provide this when creating a conclusion. Do not send it together with delete_id or list.u   Conclusion ID to delete for PII removal. Provide this when deleting a conclusion. Do not send it together with conclusion or list. Get this id from a prior `list` call — never guess it.booleanzSet to true to list or search stored conclusions (with their ids) instead of creating or deleting one. Do not send together with conclusion or delete_id.z}Optional semantic search query, used only when `list` is true. Omit to list the most recent conclusions instead of searching.ztThe peer the conclusion is ABOUT. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.)
conclusion	delete_idlistr   r   c                     e Zd ZU dZdcdZdddedZedfd
            ZdgdZd Z	d Z
dhdZdidZdjdZdddkdZdidZdgdZdgdZdld Zdfd!Zd"d#dmd%Zdfd&Zdnd(Zd"d#dod)Zd*d+d*d+d*d,d-Zd.ed/<   d0Zd1Zd2Zd3Zd4Zd5Zd6Z d3Z!dgd7Z"dpd9Z#dqd:Z$drd;Z%dsdtd=Z&dudAZ'e(dvdC            Z)dDdEdwdGZ* e+j,        dHe+j-                  Z.e/dxdI            Z0dydLZ1e(dzdO            Z2d{dRZ3d"d#d|dUZ4	 ddd}dZZ5d~d]Z6dd^Z7ddaZ8ddbZ9dS )HonchoMemoryProviderzHHoncho AI-native memory with dialectic Q&A and persistent user modeling.return	List[str]c                    g }	 ddl m}  |            }|                    t          |j                             n# t
          $ r Y nw xY w|S )zHoncho keeps its peer/session config under ~/.honcho when no
        profile-local honcho.json exists (see client.resolve_config_path).   )resolve_global_config_path)clientr2   appendstrparent	Exception)selfpathsr2   
global_cfgs       @/home/ice/.hermes/hermes-agent/plugins/memory/honcho/__init__.pybackup_pathsz!HonchoMemoryProvider.backup_paths   ss     	::::::3355JLLZ.//0000 	 	 	D	s   7< 
A	A	Nquery_rewriterOptional[Callable[[str], str]]c                ,   d | _         d | _        d| _        || _        d| _        t          j                    | _        d | _        d | _	        d| _
        d | _        t          j                    | _        d| _        d| _        d| _        d| _        d| _        d| _        d | _        d| _        d| _        d	| _        d	| _        d
| _        d	| _        d| _        d| _        d | _        d | _        d | _        t          j                    | _        d| _         d| _!        d S )N hybridr   Fz
every-turnr1   Tr"           )"_manager_config_session_key_query_rewriter_prefetch_result	threadingLock_prefetch_lock_prefetch_thread_sync_thread_recall_mode_base_context_cache_base_context_lock_turn_count_query_rewrite_enabled_injection_frequency_context_cadence_dialectic_cadence_dialectic_depth_dialectic_depth_levels_reasoning_heuristic_reasoning_level_cap_last_context_turn_last_dialectic_turn_prefetch_thread_started_at_prefetch_result_fired_at_dialectic_empty_streak_session_initialized_lazy_init_kwargs_lazy_init_session_id_init_thread
_init_lock_init_error_cron_skipped)r8   r=   s     r;   __init__zHonchoMemoryProvider.__init__   s'   - "'n..<@8<$ 37 "+."2"2 &+#$0! !"# !9=$*.!)/!"&$(! 36(.2&,-$ %*!1548"8<#.** #    r5   c                    dS )Nhoncho r8   s    r;   r   zHonchoMemoryProvider.name*  s    xrg   boolc                    	 ddl m} |                                }|j        ot	          |j        p|j                  S # t          $ r Y dS w xY w)z0Check if Honcho is configured. No network calls.r   )HonchoClientConfigF)plugins.memory.honcho.clientrn   from_global_configenabledrl   api_keybase_urlr7   )r8   rn   cfgs      r;   is_availablez!HonchoMemoryProvider.is_available.  sj    	GGGGGG$7799C;D4(Cs|#D#DD 	 	 	55	s   ;> 
AAc                $   ddl }ddl}ddlm}  ||          dz  }i }|                                r4	  |j        |                                          }n# t          $ r Y nw xY w|                    |           ddl	m
}  |||d           dS )zDWrite config to $HERMES_HOME/honcho.json (Honcho SDK native format).r   N)Pathzhoncho.json)atomic_json_writei  )mode)jsonospathlibrw   existsloads	read_textr7   updateutilsrx   )	r8   valueshermes_homerz   r{   rw   config_pathexistingrx   s	            r;   save_configz HonchoMemoryProvider.save_config7  s    			      d;''-7 	%4:k&;&;&=&=>>   +++++++xe<<<<<<s   "A 
A$#A$c                    ddddddddd	gS )
Nrr   zHoncho API keyTHONCHO_API_KEYzhttps://app.honcho.dev)keyr   secretenv_varurlbaseUrlz!Honcho base URL (for self-hosted))r   r   rj   rk   s    r;   get_config_schemaz&HonchoMemoryProvider.get_config_schemaG  s6    .>$[k  uM  N  N.QRR
 	
rg   r   configdictNonec                T    ddl }ddlm}  ||                                           dS )z:Run the full Honcho setup wizard after provider selection.r   N)	cmd_setup)typesplugins.memory.honcho.clir   SimpleNamespace)r8   r   r   r   r   s        r;   
post_setupzHonchoMemoryProvider.post_setupM  s?    777777	%''))*****rg   
session_idc                   	 |                     dd          }|                     dd          }|dv s|dk    r%t                              d||           d| _        d	S d
dlm}m} d
dlm} |	                                }|j
        r|j        s#|j        st                              d           d	S || _        |j        | _        t                              d| j                   |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        t9          dt;          |j        d                    | _        |j         | _!        |j"        | _#        |j$        | j%        v r|j$        | _&        tO          |          | _(        || _)         | j*        ||fi || _+        | j        dk    r9|j,        r| -                                 d	S t                              d           d	S | .                    d           d	S # t^          $ r t                              d           Y d	S t`          $ r-}	t          1                    d|	           d	| _2        Y d	}	~	d	S d	}	~	ww xY w)zInitialize Honcho session manager.

        Handles cron guards, recall configuration, session resolution,
        memory migration, and optional dialectic prewarming.
        agent_contextr@   platformcli>   cronflushr   zBHoncho skipped: cron/flush context (agent_context=%s, platform=%s)TNr   )rn   get_honcho_clientHonchoSessionManageru)   Honcho not configured — plugin inactivezHoncho recall_mode: %sr1      toolsuG   Honcho tools-only mode — deferring session init until first tool callg?wait_timeoutu3   honcho-ai package not installed — plugin inactivezHoncho init failed: %s)3getloggerdebugre   ro   rn   r   plugins.memory.honcho.sessionr   rp   rq   rr   rs   rE   recall_moderN   injection_frequencyrS   context_cadencerT   dialectic_cadencerU   query_rewriterR   first_turn_base_wait_FIRST_TURN_BASE_TIMEOUTfirst_turn_dialectic_wait_FIRST_TURN_DIALECTIC_CAPr#   mindialectic_depthrV   dialectic_depth_levelsrW   reasoning_heuristicrX   reasoning_level_cap_LEVEL_ORDERrY   r   r`   ra   _resolve_session_keyrF   init_on_session_start_ensure_session_start_session_init_backgroundImportErrorr7   warningrD   )
r8   r   kwargsr   r   rn   r   r   rt   es
             r;   
initializezHonchoMemoryProvider.initializeS  s   <	!"JJ;;Mzz*e44H 111X5G5Ga*H6 6 6%)"ZZZZZZZZJJJJJJ$7799C; s{ cl HIIIDL #DLL143DEEE(+(?D%$'$7D!&)&;D#*-*;D',/,DD)-0-JD*$'3s/BA+F+F$G$GD!+.+ED((+(?D%&$*;;;,/,C)
 &*&\\D")3D& 9 9#z T TV T TD  G++, ((***Ffggg//S/AAAAA 	P 	P 	PLLNOOOOOO 	! 	! 	!NN3Q777 DMMMMMMM	!s8   AH AH 0D*H H 8H $I-7	I- "I((I-c                    |                     d          }|                     d          }|                    |||          p|pdS )z<Resolve the Honcho session key without touching the network.session_titlegateway_session_key)r   r   r   hermes-default)r   resolve_session_name)r8   rt   r   r   r   r   s         r;   r   z)HonchoMemoryProvider._resolve_session_key  s`    

?33$jj)>??$$+%$7 %    
    	
rg   rC   r   r   floatc               `     j         s j        rdS  j        r j        dS  j        5   j         s j        r	 ddd           dS  j        r' j                                        r	 ddd           dS  j        r j        	 ddd           dS  j        t           j                   j        pdd fd}t          j
        |dd           _         j                                         |d	k    r j                            |
           ddd           dS # 1 swxY w Y   dS )a  Start Honcho session initialization in a daemon thread.

        This keeps Hermes CLI/gateway startup responsive when Honcho is down,
        slow, or its database is unhealthy. The thread may still take the SDK
        timeout path, but it cannot block agent construction or first prompt
        assembly. ``wait_timeout`` lets fast/mock initializations finish before
        returning while still failing open for slow backends.
        Nr   r.   r   c                     	  j         fi  d _        d _        d_        d S # t          $ rA} t          |           _        d _        t                              d|            Y d } ~ d S d } ~ ww xY w)Nr@   z)Honcho background session init failed: %s)	_do_session_initr`   ra   rd   r7   r5   rD   r   r   )r   rt   init_kwargsinit_session_idr8   s    r;   _runzAHonchoMemoryProvider._start_session_init_background.<locals>._run  s    S)D)#NN+NNN-1D*15D.')D$$$  S S S'*1vvD$$(DMNN#NPQRRRRRRRRRSs   $) 
A46A//A4Tzhoncho-session-inittargetdaemonr   r   timeoutr.   r   )re   r_   rE   r`   rc   rb   is_aliver   ra   rI   Threadstartjoin)r8   r   r   rt   r   r   s   `  @@@r;   r   z3HonchoMemoryProvider._start_session_init_background  s0     	!: 	F| 	t5=F_ 	= 	=! T%> 	= 	= 	= 	= 	= 	= 	= 	=   T%6%?%?%A%A 		= 	= 	= 	= 	= 	= 	= 	=
 < 4#9#A	= 	= 	= 	= 	= 	= 	= 	= ,Ct566K"8L<LO	S 	S 	S 	S 	S 	S 	S 	S 	S !* 0*! ! !D
 ##%%%a!&&|&<<<=	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	=s$   D#	!D#7D#BD##D'*D'c           	     b    ddl m} ddlm}  ||          } ||||j        |                    d          pd|                    d          pd           _          j        ||fi | _        t          
                    d j                    j                             j                  }	 |j        sl|j        d	k    radd
lm} t!           |            dz            }	 j                             j        |	           t          
                    d j                   n+|j        d	k    r t          
                    d j                   n2# t$          $ r%}
t          
                    d|
           Y d}
~
nd}
~
ww xY w j        dv r j         j        stdd fd}t-          j                     _        t3          j        |dd          }|                                 | _        t          
                    d j                   nt          
                    d           d _        dS )zBShared session initialization logic for both eager and lazy paths.r   )r   r   user_idNuser_id_alt)ri   r   context_tokensruntime_user_peer_nameruntime_user_peer_name_altzHoncho session key resolved: %szper-session)get_hermes_homememoriesz:Honcho memory file migration attempted for new session: %sz_Honcho memory file migration skipped: per-session strategy creates a fresh session per run (%s)z(Honcho memory file migration skipped: %s>   rA   contextzcSummarize what you know about this user. Focus on preferences, current projects, and working style.r.   r   c                    	                      d          } nC# t          $ r6}t                              d|           xj        dz  c_        Y d }~d S d }~ww xY w| rQ|                                 r=j        5  | _        d_        d d d            n# 1 swxY w Y   d_	        d_        d S xj        dz  c_        d S )NFuse_query_rewritez#Honcho dialectic prewarm failed: %sr1   r   
_run_dialectic_depthr7   r   r   r^   striprK   rH   r]   r[   )rexc_prewarm_queryr8   s     r;   _prewarm_dialecticzAHonchoMemoryProvider._do_session_init.<locals>._prewarm_dialectic  s9    55*e 6   %   %JCPPP44944  :QWWYY :!0 ? ?45D1=>D:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 561784444494444s&    
A+AA;BBBTzhoncho-prewarm-dialecticr   z0Honcho dialectic prewarm started for session: %szEHoncho generic dialectic prewarm skipped: awaiting first user messager   )ro   r   r   r   r   r   rD   r   rF   r   r   get_or_createmessagessession_strategyhermes_constantsr   r5   migrate_memory_filesr7   rN   rG   rR   time	monotonicr\   rI   r   r   rL   r_   )r8   rt   r   r   r   r   r3   sessionr   mem_dirr   r   prewarm_threadr   s   `            @r;   r   z%HonchoMemoryProvider._do_session_init  s   BBBBBBFFFFFF""3'',,-#)::i#8#8#@D'-zz-'@'@'HD
 
 
 6D5c:PPPP68IJJJ ---d.?@@	H# 	(<(M(M<<<<<<oo//*<==2243DgNNNY[_[lmmmm%66u%    	H 	H 	HLLCQGGGGGGGG	H
  555#+43N+Q 
: : : : : : :$ 48>3C3C0!*!1-3" " "
 $$&&&(6%OQUQbcccc[   %)!!!s   2BE 
F E;;F c                   | j         r	| j        rdS | j        rdS | j        r| j                                        rdS | j        r| j        dS 	  | j        | j        | j        pdfi | j         d| _        d| _        | j         duS # t          $ r4}d| _         d| _        t                              d|           Y d}~dS d}~ww xY w)zLazily initialize the Honcho session (for tools-only mode).

        Returns True if the manager is ready, False otherwise.
        TFNr   z#Honcho lazy session init failed: %s)rD   r_   re   rb   r   rE   r`   r   ra   r7   r   r   )r8   r   s     r;   r   z$HonchoMemoryProvider._ensure_session(  s   
 = 	T6 	4 	5 	!2!;!;!=!= 	5| 	t5=5	!D!*>.>  (   &*D")-D&=,, 	 	 	 DM(-D%NN@!DDD55555		s   6B 
C)B==Cc                v    | j         r| j        sdS | j        rdS | j        o| j                                         S )a  Return whether a manager/session key can be used safely.

        Background initialization sets ``_manager`` before the blocking
        get-or-create call completes, so ``_session_initialized`` guards real
        async startup. Tests and legacy direct construction may inject a ready
        manager/session key without setting that flag; allow that only when no
        init thread is currently in flight.
        FT)rD   rF   r_   rb   r   rk   s    r;   _session_readyz#HonchoMemoryProvider._session_readyF  sM     } 	D$5 	5$ 	4%F$*;*D*D*F*FGGrg   ctxc                   g }|                     dd          }|r|                    d|            |                     dd          }|r|                    d|            |                     dd          }|r|                    d|            |                     dd          }|r|                    d	|            |                     d
d          }|r|                    d|            |sdS d                    |          S )zEFormat the prefetch context dict into a readable system prompt block.summaryr@   z## Session Summary
representationz## User Representation
r   z## User Peer Card
ai_representationz## AI Self-Representation
ai_cardz## AI Identity Card


)r   r4   r   )r8   r   partsr   repr   ai_repr   s           r;   _format_first_turn_contextz/HonchoMemoryProvider._format_first_turn_contextU  s9    '')R(( 	;LL999:::gg&++ 	;LL9C99:::wwvr"" 	7LL5t55666,b11 	ALL?v??@@@'')R(( 	<LL:::;;; 	2{{5!!!rg   c                    | j         rdS | j        r| j        s	| j        sdS | j        dk    rd}n| j        dk    rd}nd}|S )u  Return system prompt text, adapted by recall_mode.

        Returns only the mode header and tool instructions — static text
        that doesn't change between turns (prompt-cache friendly).
        Live context (representation, card) is injected via prefetch().
        r@   r   u   # Honcho Memory
Active (context-injection mode). Relevant user context is automatically injected before each turn. No memory tools are available — context is managed automatically.r   u  # Honcho Memory
Active (tools-only mode). Use honcho_profile for a quick factual snapshot, honcho_search for raw excerpts, honcho_context for raw peer context, honcho_reasoning for synthesized answers (pass reasoning_level minimal/low/medium/high/max — you pick the depth per call), honcho_conclude to save facts about the user. No automatic context injection — you must use tools to access memory.u  # Honcho Memory
Active (hybrid mode). Relevant context is auto-injected AND memory tools are available. Use honcho_profile for a quick factual snapshot, honcho_search for raw excerpts, honcho_context for raw peer context, honcho_reasoning for synthesized answers (pass reasoning_level minimal/low/medium/high/max — you pick the depth per call), honcho_conclude to save facts about the user.)re   rD   rF   rE   rN   )r8   headers     r;   system_prompt_blockz(HonchoMemoryProvider.system_prompt_blockr  s      	2} 	D$5 	< r	))) F '))Z F@  rg   r@   )r   r   c               t
     j         rdS  j        dk    rdS d} j        dk    ra j        }t	           j        dd          }|t          |t          d|                    }t          j	                    t          d|          z   } 
                                sm                                  |A j        }|8|                    t          d|t          j	                    z
                        
                                sdS  j        dk    o
 j        dk    }                               r-                                 }|r                     |          ndS g }	|s j        5   j        du }
|
rd _         j         _         j        }ddd           n# 1 swxY w Y   |
r  j        ri d fd}t-          j        |dd          }|                                 |$t          d|t          j	                    z
            nd}|                    |                               d          }|r_ j                             j                                        |          }|r( j        5  | _        ddd           n# 1 swxY w Y   |}n/|                                rt<                              d|           |
sg j        r` j                             j                  }|r?                     |          }|r( j        5  | _        ddd           n# 1 swxY w Y   |}|r|	                     |            j!        5  tE           j#                  }ddd           n# 1 swxY w Y   |r j$        dk    r j         _$         j$        dk    r%r" j%        }t	           j        dd          }|t          |t          d|                    } &                                r  j'        }||                    |           nv|} j        d fd}t          j	                     _(        t-          j        |dd          }|                                 | _'         j'                            |            j'        r4 j'                                        rt<                              d|                                            }|r)|)                                r|	                     |           |	sdS d                    |	          }                     |          }|S )u  Return base context (representation + card) plus dialectic supplement.

        Assembles two layers:
        1. Base context from peer.context() — cached, refreshed on context_cadence
        2. Dialectic supplement — cached, refreshed on dialectic_cadence

        Returns empty in tools-only mode and respects the configured injection
        frequency and context budget.
        r@   r   Nr1   r   rC   r   
first-turnr.   r   c                 
   	 j                             j        pd           pi } | d<   | r"j                             j        |            d S d S # t          $ r&}t
                              d|           Y d }~d S d }~ww xY w)Nr   z)Honcho first-turn base context failed: %s)rD   get_prefetch_contextrF   set_context_resultr7   r   r   )r   r   _ctx_holderr   r8   s     r;   _fetch_basez2HonchoMemoryProvider.prefetch.<locals>._fetch_base  s    U"m@@ -u}     .1E* U M<<T=NPSTTTTTU U$ U U U%PRSTTTTTTTTTUs   AA 
BA==BTzhoncho-base-firstr   r   uV   Honcho first-turn base context still running after %.1fs — will surface on next turnrB   c                    	                                } nC# t          $ r6}t                              d|           xj        dz  c_        Y d }~d S d }~ww xY w| rQ|                                 r=j        5  | _        _        d d d            n# 1 swxY w Y   _	        d_        d S xj        dz  c_        d S )Nz&Honcho first-turn dialectic failed: %sr1   r   r   )r   r   	_fired_atr   r8   s     r;   _run_first_turnz6HonchoMemoryProvider.prefetch.<locals>._run_first_turn"  s<    55e<<$   %MsSSS44944  :QWWYY :!0 G G45D1=FD:G G G G G G G G G G G G G G G 5>1784444494444&    
A+AA9BBBzhoncho-prefetch-firstuS   Honcho first-turn dialectic still running after %.1fs — will surface on next turnr   r   )*re   rN   rQ   r   getattrrE   r   r#   r   r   r   r   rb   r   rS   _is_trivial_prompt_consume_pending_dialectic_truncate_to_budgetrP   rO   rZ   rD   rI   r   r   r   pop_context_resultrF   r  r   r   r   r4   rK   rl   rH   r[   r   _thread_is_liverL   r\   r   )r8   r   r   first_turn_base_deadline	base_waitrequest_timeoutrb   
_skip_basereadyr   _first_base_fetchbase_contextr  _bt
_base_wait_ctx	formatted	fresh_ctx_prewarm_landed	_dia_wait_live_first_turn_timeoutr  first_turn_threaddialectic_resultresultr  r  s   ``                        @@r;   prefetchzHonchoMemoryProvider.prefetch  s4     	2 ''2#' q  5I%dlItDDO*	3sO+D+DEE	'+~'7'7#c9:M:M'M$""$$ 
	//111'3#0+ %% #C)ADNDTDT)T U U &    &&(( r %5N$:JQ:N 	
 ""5)) 	D3355E6;C4++E222C  ;	+ ( 8 8$($<$D!$ ?/1D,.2.>D+#78 8 8 8 8 8 8 8 8 8 8 8 8 8 8 ! $T] $/1	U 	U 	U 	U 	U 	U 	U 	U  &&t:M   		 0; 58H8HHIII 
 ,,,"u-- M44T5FGGG $ ? ? E EI  1!4 A A7@D4A A A A A A A A A A A A A A A'0\\^^ LL45?   % 1 1 M<<T=NOO	 1 $ ? ?	 J JI  1!4 A A7@D4A A A A A A A A A A A A A A A'0 +\***   	: 	:"4#899O	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	9t8D@@(,(8D%$,,, 6I%dlItDDO*	3sO+D+DEE	##%% H-$JJyJ111&/# ,	: : : : : : : :" 48>3C3C0$-$4*4>U% % %! "'')))(9%%**3F*GGG$ )>)G)G)I)I 0    ::<< 	+ 0 6 6 8 8 	+LL)*** 	2U##))&11sH   .&F  F$'F$=JJJL**L.1L.M66M:=M:c                >   | j         5  | j        }| j        }d| _        d| _        ddd           n# 1 swxY w Y   | j        | j        z  }|r8|dk    r2| j        |z
  |k    r$t                              d|| j        |           dS |r|                                r|ndS )zPop any pending dialectic result, applying the stale-discard guard.

        Returns an empty string when no result is ready or the pending result
        is older than the configured cadence window.
        r@   rB   Nr   zKHoncho pending dialectic discarded as stale: fired_at=%d, turn=%d, limit=%d)	rK   rH   r]   rU   _STALE_RESULT_MULTIPLIERrQ   r   r   r   )r8   r(  fired_atstale_limits       r;   r  z/HonchoMemoryProvider._consume_pending_dialecticP  s      	2 	2#45H$&D!-1D*		2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 -0MM 	A43Ch3NR]2]2]LL$%-t/?   2$4Z9I9O9O9Q9QZXZZs   155textc                    | j         r| j         j        s|S | j         j        dz  }t          |          |k    r|S |d|         }|                    d          }||dz  k    r
|d|         }|dz   S )z9Truncate text to fit within context_tokens budget if set.   N g?u    …)rE   r   lenrfind)r8   r/  budget_chars	truncated
last_spaces        r;   r  z(HonchoMemoryProvider._truncate_to_budgetf  s    | 	4<#> 	K|2Q6t99$$K,'	__S))
s***!+:+.I6!!rg   c                    j         rdS  j        dk    rdS                                  rs                                  dS                                rdS  j        dk    p j         j        z
   j        k    } j        dk    rb|r` j         _        	  j	        
                     j                   n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w                                 rt                              d           dS                                  } j         j        z
  |k     r7t                              d| j         j         j         j        z
             dS  j         fd}t)          j                     _        t/          j        |d	d
          }|                                 | _        dS )zFire background prefetch threads for the upcoming turn.

        Context and dialectic refreshes have independent cadence controls.
        Nr   r1   r  z"Honcho context prefetch failed: %sz=Honcho dialectic prefetch skipped: prior thread still runningzhHoncho dialectic prefetch skipped: effective cadence %d (base %d, empty streak %d), turns since last: %dc                    	                                } nC# t          $ r6}t                              d|           xj        dz  c_        Y d }~d S d }~ww xY w| rQ|                                 r=j        5  | _        _        d d d            n# 1 swxY w Y   _	        d_        d S xj        dz  c_        d S )NzHoncho prefetch failed: %sr1   r   r   )r)  r   r  r   r8   s     r;   r   z1HonchoMemoryProvider.queue_prefetch.<locals>._run  s+   22599   91===,,1,,  2&,,.. 2( ? ?,2D)5>D2? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -6)/0,,,,,1,,,,r  Tzhoncho-prefetchr   )re   rN   r   r   r  rT   rQ   rZ   rS   rD   prefetch_contextrF   r7   r   r   r  _effective_cadencer[   rU   r^   r   r   r\   rI   r   r   rL   )	r8   r   r   context_duer   	effectiver   prefetch_threadr  s	   ``      @r;   queue_prefetchz#HonchoMemoryProvider.queue_prefetcht  sG   
  	F''F""$$ 	E 	//111F ""5)) 	F !Q& U 4#::t?TT 	 $444&*&6D#F..t/@%HHHH F F FA1EEEEEEEEF !! 	LLXYYYF ++--	t88IEELLC42D4P 4#<<	   F $		2 	2 	2 	2 	2 	2 	2  ,0>+;+;(#*+<
 
 
 	 /s    B; ;
C*C%%C*baser   r    ))r1   r   )   r   )rA  r1   )r   r   )r   r1   )r   rA  zdict[tuple[int, int], str]_PROPORTIONAL_LEVELSr   x   i  g       @rA     g      @c                *   | j         r| j                                         sdS | j        r| j        j        r| j        j        nd}t	          j                    | j        z
  }||| j        z  k    r&t          	                    d||| j        z             dS dS )zThread-alive guard that treats threads older than the stale
        threshold as dead, so a hung Honcho request can't block new fires.Fg       @uS   Honcho prefetch thread age %.1fs exceeds stale threshold %.1fs — treating as deadT)
rL   r   rE   r   r   r   r\   _STALE_THREAD_MULTIPLIERr   r   )r8   r   ages      r;   r  z$HonchoMemoryProvider._thread_is_live  s     $ 	D,A,J,J,L,L 	5+/<YDL<PY4<''VYn!AA48888LL-.17T=Z3Z   5trg   intc                    | j         dk    r| j        S | j        | j         z   }| j        | j        z  }t          ||          S )uB   Cadence plus empty-streak backoff, capped at _BACKOFF_MAX × base.r   )r^   rU   _BACKOFF_MAXr   )r8   widenedceilings      r;   r;  z'HonchoMemoryProvider._effective_cadence  sI    '1,,**)D,HH)D,==7G$$$rg   c                    d}| j         r4| j                                         rt          j                    | j        z
  }| j        | j        | j        | j        | 	                                |du|dS )zIn-process snapshot of dialectic liveness state for diagnostics.

        Returns current turn, last successful dialectic turn, pending-result
        fire turn, empty streak, effective cadence, and thread status.
        N)
turn_countlast_dialectic_turnpending_result_fired_atempty_streakeffective_cadencethread_alivethread_age_seconds)
rL   r   r   r   r\   rQ   r[   r]   r^   r;  )r8   
thread_ages     r;   liveness_snapshotz&HonchoMemoryProvider.liveness_snapshot  s     
  	MT%:%C%C%E%E 	M))D,LLJ*#'#<'+'E 8!%!8!8!:!:&d2",
 
 	
rg   c                6   | j         r|s|S || j        vr|S t          |          }|| j        k     rd}n|| j        k     rd}nd}| j                            |          }| j                            | j                  }| j        t          ||z   |                   S )zScale `base` up by query length, clamped at reasoning_level_cap.

        Char-count heuristic: +1 at >=120 chars, +2 at >=400.
        r   r1   rA  )rX   r   r3  _HEURISTIC_LENGTH_MEDIUM_HEURISTIC_LENGTH_HIGHindexrY   r   )r8   r@  r   nbumpbase_idxcap_idxs          r;   _apply_reasoning_heuristicz/HonchoMemoryProvider._apply_reasoning_heuristic  s    
 ( 	 	Kt(((KJJt,,,DD,,,DDD$**400#))$*CDD X_g!>!>??rg   pass_idxc                   | j         r%|t          | j                   k     r| j         |         S | j        r| j        j        nd}| j                            | j        |f          }||dk    r|                     ||          S |S )ut  Resolve reasoning level for a given pass index.

        Precedence:
          1. dialecticDepthLevels (explicit per-pass) — wins absolutely
          2. _PROPORTIONAL_LEVELS table (depth>1 lighter-early passes)
          3. Base level = dialecticReasoningLevel, optionally scaled by the
             reasoning heuristic when the mapping falls through to 'base'
        r    Nr@  )rW   r3  rE   dialectic_reasoning_levelrB  r   rV   r_  )r8   r`  r   r@  mappings        r;   _resolve_pass_levelz(HonchoMemoryProvider._resolve_pass_level&  s     ' 	:Hs4;W7X7X,X,X/99:>,Q66E+//1F0QRR?g//224???rg   prior_results	list[str]is_coldc                    |dk    r|r	 dS 	 dS |dk    r|r|d         nd}d| dS d	t          |          dk    r|d         nd
 dt          |          dk    r|d         nd
 dS )a  Build the prompt for a given dialectic pass.

        Pass 0: cold start (general user query) or warm (session-scoped).
        Pass 1: self-audit / targeted synthesis against gaps from pass 0.
        Pass 2: reconciliation / contradiction check across prior passes.
        r   zWho is this person? What are their preferences, goals, and working style? Focus on facts that would help an AI assistant be immediately useful.zGiven what's been discussed in this session so far, what context about this user is most relevant to the current conversation? Prioritize active context over biographical facts.r1   r@   z Given this initial assessment:

z

What gaps remain in your understanding that would help going forward? Synthesize what you actually know about the user's current state and immediate needs, grounded in evidence from recent sessions.z Prior passes produced:

Pass 1:
z(empty)z


Pass 2:
z

Do these assessments cohere? Reconcile any contradictions and produce a final, concise synthesis of what matters most for the current conversation.)r3  )r8   r`  re  rg  priors        r;   _build_dialectic_promptz,HonchoMemoryProvider._build_dialectic_prompt8  s     q== 7 S 
 ]])6>M"%%BE4U 4 4 4003M0B0BQ0F0FM!,,I0 003M0B0BQ0F0FM!,,I0 0 0rg   r)  c                :   | r%t          |                                           dk     rdS d| v rJd| v sDd| v s@t          j        d| t          j                  s t          j        d| t          j                  rdS t          |                                           d	k    S )
zCheck if a dialectic pass returned enough signal to skip further passes.

        Heuristic: a response longer than 100 chars with some structure
        (section headers, bullets, or an ordered list) is considered sufficient.
        d   F
z##u   •z^[*-] z
^\s*\d+\. Ti,  )r3  r   research	MULTILINE)r)  s    r;   _signal_sufficientz'HonchoMemoryProvider._signal_sufficient_  s      	V\\^^,,s2256>>FNNyFBL99 y==  46<<>>""S((rg   Tr   r   c                  | j         r| j        sdS | j         }g }d}|ri| j        rb| j        r[	 |                     |                                          }n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wt          | j
                  D ]7}d |D             }|dk    r|p|                     d||          }	n|r>|                     |d                   r#t                              d| j
        |            n|s;t                              d| j
        |           |p|                     d||          }	n|                     |||          }	|                     ||	          }
t                              d
| j
        ||
|           | j                             | j        |	|
d          }|                    |pd           9t!          |          D ]}|r|                                r|c S dS )u[  Execute up to dialecticDepth .chat() calls with conditional bail-out.

        Cold start (no base context): general user-oriented query.
        Warm session (base context exists): session-scoped query.
        Each pass is conditional — bails early if prior pass returned strong signal.
        Returns the best (usually last) result.
        r@   z Honcho query rewriter failed: %sNc                >    g | ]}||                                 |S rj   )r   ).0r   s     r;   
<listcomp>z=HonchoMemoryProvider._run_dialectic_depth.<locals>.<listcomp>  s*    CCC11CCQCCCrg   r   ri  zCHoncho dialectic depth %d: pass %d skipped, prior signal sufficientuY   Honcho dialectic depth %d: pass %d has no non-empty prior — falling back to base prompt)r   z5Honcho dialectic depth %d: pass %d, level=%s, cold=%suser)r%   r   )rD   rF   rO   rR   rG   r   r7   r   r   rangerV   rk  rr  rd  dialectic_queryr4   reversed)r8   r   r   rg  resultsrewritten_queryr   ire  promptlevelr)  r   s                r;   r   z)HonchoMemoryProvider._run_dialectic_depths  s    } 	D$5 	2.. 	F!< 	FAU 	FF"&"6"6u"="="C"C"E"E F F F?EEEEEEEEF t,--  	)  	)ACCCCCMAvv( D,H,H}g- -
 ! T%<%<]2=N%O%O LL!f!%!6; ; ;E$ ULL "?@D@UWXZ Z Z, 0L0L='1 1FF "99!]GTTF,,Qe,<<ELLP.5'C C C ]22!6 % 3  F
 NN6<R(((( '"" 	 	A QWWYY rs   'A 
B B  Bz^(yes|no|ok|okay|sure|thanks|thank you|y|n|yep|nope|yeah|nah|continue|go ahead|do it|proceed|got it|cool|nice|great|done|next|lgtm|k)$c                    |sdS |                                 }|sdS |                    d          rdS | j                            |          rdS dS )zFReturn True if the prompt is too trivial to warrant context injection.T/F)r   
startswith_TRIVIAL_PROMPT_REmatch)clsr/  strippeds      r;   r  z'HonchoMemoryProvider._is_trivial_prompt  si      	4::<< 	4s## 	4!''11 	4urg   turn_numbermessagec                    || _         dS )z;Track turn count for cadence and injection_frequency logic.N)rQ   )r8   r  r  r   s       r;   on_turn_startz"HonchoMemoryProvider.on_turn_start  s    &rg   contentlimitc                l   t          |           |k    r| gS d}t          |          }g }| }d}|r|r|n||z
  }t          |          |k    r|                    |r|n||z              n|d|         }|                    d          }	|	|dz  k     r |                    d          }	|	dk    r|	dz  }	|	|dz  k     r|                    d	          }	|	|dz  k     r|}	|d|	                                         }
||	d                                         }|s||
z   }
|                    |
           d
}||S )aR  Split content into chunks that fit within the Honcho message limit.

        Splits at paragraph boundaries when possible, falling back to
        sentence boundaries, then word boundaries. Each continuation
        chunk is prefixed with "[continued] " so Honcho's representation
        engine can reconstruct the full message.
        z[continued] TNr   g333333?z. r   rA  r2  F)r3  r4   r4  rstriplstrip)r  r  prefix
prefix_lenchunks	remainingfirstr=  segmentcutchunks              r;   _chunk_messagez#HonchoMemoryProvider._chunk_message  s}    w<<5  9[[
	 	!&>EJ,>I9~~**5Hiify6HIII

+G --''CY_$$mmD))!881HCY_$$mmC((Y_$$dsdO**,,E!#$$..00I 'MM%   E1  	4 rg   r   Dict[str, Any]c                ^   | j         }g }||dk    r=t          t          |dd                    }t          t          |dd                    }n<t          t          |dd                    }t          t          |dd                    }|s|s|                    d| d	           t          | d
d          }t          | dd          }|t	          d|          k     r|                    d| d| d           |s|                    d           ddd                    |          z   dz   dS )u  Build a diagnostic hint when honcho_profile returns an empty card.

        A literal "No profile facts available yet." tells the model nothing
        about WHY.  The model then often surfaces it to the user as a cryptic
        error.  This hint enumerates the likely causes so the model can
        explain the situation (or retry with a different peer).

        Ordered by likelihood for a typical deployment:
          1. Observation is disabled for this peer
          2. Card hasn't accumulated yet (fresh peer, not enough dialectic
             cycles — dialectic cadence runs every N turns)
          3. Self-hosted Honcho backend doesn't support peer cards
             (honcho-ai server < 3.x)
        Nrw  user_observe_meTuser_observe_othersai_observe_meai_observe_othersz"observation is disabled for peer 'z+' (user_observe_me/ai_observe_me in config)rU   r1   rQ   r   rA  zthis session has only zh turn(s); peer cards accumulate as the dialectic layer reasons over conversation history (cadence every z	 turn(s))u   peer card has no facts yet — Honcho's dialectic layer builds this over time from observed turns; self-hosted Honcho < 3.x does not support peer cards at allzNo profile facts available yet.zThis is not an error.  z; zf.  Try honcho_reasoning for a synthesized answer, or honcho_search to query raw conversation excerpts.)r)  hint)rE   rl   r  r4   r#   r   )r8   r   rt   reasons
observe_meobserve_otherscadenceturns           r;   _empty_profile_hintz(HonchoMemoryProvider._empty_profile_hint  s    l?v~~!'#/@$"G"GHH
!%gc3H$&O&O!P!P!'#"E"EFF
!%gc3F&M&M!N!N . A A A A  
 $ 4a88t]A..#a//!!NN5 5 5")5 5 5    	NN5   8)))G$$%DD
 
 	
rg   user_contentassistant_contentc               \     j         rdS  j        dk    r                                 sdS                                  s                                  dS  j        r j        j        ndt          |pd                                          t          |pd                                           fd} j        r4 j        	                                r j        
                    d           t          j        |dd	
           _         j                                         dS )zRecord the conversation turn in Honcho (non-blocking).

        Messages exceeding the Honcho API limit (default 25k chars) are
        split into multiple messages with continuation markers.
        Nr   ia  r@   c                    	 j                             j                  }                               D ]}|                     d|                                         D ]}|                     d|           j                             |            d S # t          $ r&}t                              d|           Y d }~d S d }~ww xY w)Nrw  	assistantzHoncho sync_turn failed: %s)	rD   r   rF   r  add_message_flush_sessionr7   r   r   )r   r  r   clean_assistant_contentclean_user_content	msg_limitr8   s      r;   _syncz-HonchoMemoryProvider.sync_turn.<locals>._syncB  s    ?-55d6GHH!001CYOO 7 7E''6666!001H)TT < <E''U;;;;,,W55555 ? ? ?:A>>>>>>>>>?s   BB 
C&CC      @r   Tzhoncho-syncr   )re   rN   r   r   rE   message_max_charsr	   r   rM   r   r   rI   r   r   )r8   r  r  r   r  r  r  r  s   `    @@@r;   	sync_turnzHonchoMemoryProvider.sync_turn0  s_     	F''0C0C0E0E'F""$$ 	//111F6:lMDL22	-l.@bAAGGII"23D3J"K"K"Q"Q"S"S		? 		? 		? 		? 		? 		? 		? 		?  	0!2!;!;!=!= 	0""3"///%,M
 
 
 	!!!!!rg   actionr   metadataOptional[Dict[str, Any]]c                4    |dk    s|dk    ssdS  j         rdS  j        dk    r                                 sdS                                  s                                  dS  fd}t	          j        |dd          }|                                 dS )	ai  Mirror built-in user profile writes as Honcho conclusions.

        ``metadata`` is accepted for compatibility with the write-origin
        work landed in main (commit 6a957a74); it's not yet threaded into
        the Honcho conclusion payload.  Left as a follow-up so this PR
        stays focused on the 7-PR consolidation and its review follow-ups.
        addrw  Nr   c                     	 j                             j                   d S # t          $ r&} t                              d|            Y d } ~ d S d } ~ ww xY w)NzHoncho memory mirror failed: %s)rD   create_conclusionrF   r7   r   r   )r   r  r8   s    r;   _writez4HonchoMemoryProvider.on_memory_write.<locals>._writel  st    C//0A7KKKKK C C C>BBBBBBBBBCs    % 
AAATzhoncho-memwriter   )re   rN   r   r   rI   r   r   )r8   r  r   r  r  r  ts   `  `   r;   on_memory_writez$HonchoMemoryProvider.on_memory_writeT  s     U??f..g.F 	F''0C0C0E0E'F""$$ 	//111F	C 	C 	C 	C 	C 	C F4>OPPP						rg   r   List[Dict[str, Any]]c                   | j         rdS | j        sdS | j        s"| j        r| j                                        rdS | j        r4| j                                        r| j                            d           	 | j                                         dS # t          $ r&}t          
                    d|           Y d}~dS d}~ww xY w)z4Flush all pending messages to Honcho on session end.Ng      $@r   z#Honcho session-end flush failed: %s)re   rD   r_   rb   r   rM   r   	flush_allr7   r   r   )r8   r   r   s      r;   on_session_endz#HonchoMemoryProvider.on_session_endu  s     	F} 	F( 	T-> 	4CTC]C]C_C_ 	F 	1!2!;!;!=!= 	1""4"000	CM##%%%%% 	C 	C 	CLL>BBBBBBBBB	Cs   8B 
CB>>Cc                V    | j         rg S | j        dk    rg S t          t                    S )ziReturn tool schemas, respecting recall_mode.

        Context-only mode exposes no Honcho tools.
        r   )re   rN   r+   ALL_TOOL_SCHEMASrk   s    r;   get_tool_schemasz%HonchoMemoryProvider.get_tool_schemas  s6    
  	I	))I$%%%rg   	tool_nameargsc                   | j         rt          d          S | j        sR| j        r(| j                                        rt          d          S |                                 st          d          S | j        r| j        st          d          S 	 |dk    r|                    dd          }|                    d          }|r[| j        	                    | j        ||	          }|t          d          S t          j        dt          |           d|d          S | j                            | j        |	          }|s't          j        |                     |                    S t          j        d|i          S |dk    r|                    d          pd                                }|st          d          S t!          t#          |                    dd                    d          }	|                    dd          }| j                            | j        ||	|          }|st          j        ddi          S t          j        d|i          S |dk    r|                    d          pd                                }|st          d          S |                    dd          }|                    d          }
| j                            | j        ||
|d          }| j        | _        t          j        d|pdi          S |dk    rq|                    dd          }| j                            | j        |	          }|st          j        ddi          S g }|                    d           r|                    d!|d                      |                    d"          r|                    d#|d"                     |                    d          r|                    d$|d                     |                    d%          rG|d%         }d&                    d' |d(d
         D                       }|                    d)|            t          j        dd*                    |          pd+i          S |d,k    r|                    d-          pd                                }|                    d.d                                          }t3          |                    d/                    }|                    dd          }t3          |          }t3          |          }t5          |||g          d0k    rt          d1          S |                    d          pd                                }|r|st          d2          S |r:| j                            | j        |pd
|3          }t          j        d4|i          S |rQ| j                            | j        ||	          }|rt          j        dd5| d6i          S t          d7| d8          S | j                            | j        ||	          }|rt          j        dd9| d:| i          S t          d;          S t          d<|           S # t<          $ r;}t>                               d=||           t          d>| d?|           cY d
}~S d
}~ww xY w)@zFHandle a Honcho tool call, with lazy session init for tools-only mode.z$Honcho is not active (cron context).z8Honcho session is still initializing; try again shortly.z(Honcho session could not be initialized.z&Honcho is not active for this session.r   r   rw  r   )r   NzFailed to update peer card.zPeer card updated (z facts).)r)  r   r)  r   r   r@   z!Missing required parameter: queryr   i   i  )r   r   zNo relevant context found.r   r%   F)r%   r   apply_injection_capzNo result from Honcho.r&   zNo context available yet.r   z## Summary
r   z## Representation
z## Card
recent_messagesrn  c              3  N   K   | ] }d |d          d|d         dd          V  !dS )z  [rolez] r  N   rj   )ru  ms     r;   	<genexpr>z8HonchoMemoryProvider.handle_tool_call.<locals>.<genexpr>  sX       ( ( @ai??1Y<+=??( ( ( ( ( (rg   z## Recent messages
r   zNo context available.r'   r*   r)   r+   r1   z?Exactly one of conclusion, delete_id, or list must be provided.z&query is only valid when list is true.)r   r   conclusionszConclusion z	 deleted.zFailed to delete conclusion .zConclusion saved for z: zFailed to save conclusion.zUnknown tool: zHoncho tool %s failed: %szHoncho z	 failed: )!re   r   r_   rb   r   r   rD   rF   r   set_peer_cardrz   dumpsr3  get_peer_cardr  r   r   rH  search_contextry  rQ   r[   get_session_contextr4   r   rl   sumlist_conclusionsdelete_conclusionr  r7   r   error)r8   r  r  r   r   card_updater)  r   r   r   r%   r   r   msgsmsg_strr*   r)   	list_modehas_delete_idhas_conclusionr  okr   s                          r;   handle_tool_callz%HonchoMemoryProvider.handle_tool_call  sb    	FDEEE( 	N  ^T%6%?%?%A%A ^!"\]]]'')) N!"LMMM} 	HD$5 	HFGGGc	A,,,xx//"hhv.. o!]889JK^b8ccF~)*GHHH:1\s6{{1\1\1\fl&m&mnnn}2243D42PP F:d&>&>t&D&DEEEz8T"2333o--'**0b7799 K%&IJJJ TXXlC%@%@!A!A4HH
xx//55%u$ 6    P:x1M&NOOOz8V"4555000'**0b7799 K%&IJJJxx//"&((+<"="=66%u$3(- 7   -1,<)z8V-O7O"PQQQ...xx//m778IPT7UU O:x1L&MNNN779%% BLL!@I!@!@AAA77+,, PLL!Ns;K7L!N!NOOO776?? <LL!:S[!:!:;;;77,-- C01D"ii ( (!%bcc( ( (  G LL!A!A!ABBBz8V[[-?-?-ZCZ"[\\\///!XXk228b??AA	!XXlB77==??
 &!1!122	xx// $Y!%j!1!1~yABBaGG%&ghhh'**0b7799 P P%&NOOO D"&-"@"@)$T #A # #K  :}k&BCCC  S889JI\`8aaB Z#z85W95W5W5W*XYYY%&QY&Q&Q&QRRR]44T5F
Y]4^^ `:x1]1]1]Q[1]1]&^___!">???:y::;;; 	A 	A 	ALL4iCCC?	??A??@@@@@@@@	As   A%Y> 4'Y> A	Y> &Y> <?Y> <BY> >Y> ?Y> A2Y> AY> D!Y> ?CY> ;Y> ;Y> 
?Y> 
Y> ?Y> Y> ,Y> >
[0Z>8[>[c                :   | j         | j        fD ].}|r*|                                r|                    d           /| j        rT| j        r | j                                        r| j        r/	 | j                                         d S # t          $ r Y d S w xY wd S d S )Nr  r   )	rL   rM   r   r   rD   rb   r_   r  r7   )r8   r  s     r;   shutdownzHonchoMemoryProvider.shutdown  s    '):; 	$ 	$A $QZZ\\ $s###= 	$"3 	8I8R8R8T8T 	]a]v 	'')))))   	 	 	 	s   -B 
BB)r.   r/   )N)r=   r>   )r.   r5   )r.   rl   )r   r5   r   r   r.   r   )r   r5   r.   r   )r   r5   r.   r5   )r   r   r.   r   )r   r   r.   r5   )r   r5   r   r5   r.   r5   )r/  r5   r.   r5   )r   r5   r   r5   r.   r   )r.   rH  )r.   r   )r@  r5   r   r5   r.   r5   )r@   )r`  rH  r   r5   r.   r5   )r`  rH  re  rf  rg  rl   r.   r5   )r)  r5   r.   rl   )r   r5   r   rl   r.   r5   )r/  r5   r.   rl   )r  rH  r  r5   r.   r   )r  r5   r  rH  r.   rf  )r   r5   r.   r  )r  r5   r  r5   r   r5   r.   r   )
r  r5   r   r5   r  r5   r  r  r.   r   )r   r  r.   r   )r.   r  )r  r5   r  r   r.   r5   r   ):__name__
__module____qualname____doc__r<   rf   propertyr   ru   r   r   r   r   r   r   r   r   r   r  r  r*  r  r  r?  rB  __annotations__r   rX  rY  rF  r,  rJ  r   r   r  r;  rV  r_  rd  rk  staticmethodrr  r   ro  compile
IGNORECASEr  classmethodr  r  r  r  r  r  r  r  r  r  rj   rg   r;   r-   r-      sT        RR   +# +# +# +# +#Z    X   = = = 
 
 
+ + + +B! B! B! B!H
 
 
 
 GJ ,= ,= ,= ,= ,= ,=\S) S) S) S)j   <H H H H" " " ":) ) ) )V 9; q q q q q qf[ [ [ [," " " " ?A L0 L0 L0 L0 L0 L0j 
8 
8 
 
 
 
 ?L  #   #  ! L" #   % % % %
 
 
 
&@ @ @ @(    $% % % %N ) ) ) \)& MQ : : : : : :~ $	U
     [' ' ' ' * * * \*X7
 7
 7
 7
r Y[ "" "" "" "" "" ""R .2    BC C C C 	& 	& 	& 	&qA qA qA qAf	 	 	 	 	 	rg   r-   r.   r   c                X    ddl m} |                     t          |                     dS )z,Register Honcho as a memory provider plugin.r   )rewrite_memory_query)r=   N)plugins.memory.query_rewriter  register_memory_providerr-   )r   r  s     r;   registerr    sE    AAAAAA  ,@AAA    rg   r   )r  
__future__r   rz   loggingro  rI   r   typingr   r   r   r   r   agent.memory_managerr	   agent.memory_providerr
   tools.registryr   	getLoggerr  r   PROFILE_SCHEMASEARCH_SCHEMAREASONING_SCHEMACONTEXT_SCHEMACONCLUDE_SCHEMAr  r-   r  rj   rg   r;   <module>r      sk    # " " " " "   				      6 6 6 6 6 6 6 6 6 6 6 6 6 6 1 1 1 1 1 1 0 0 0 0 0 0 % % % % % %		8	$	$ 
	,  !  C 
   (+h 

 

   B 	(  !  S 
 "  V 
 !  y 
 
 I!  D 	O  != 
 !#, DCC3   8 !  C A$
 $
J IO( (!9 9 x 	+    C 
 	 	 2 	"  !  Z 
 !  ] 
 "  { 
 !  _ 
 !  V #
 
, 1 #+ +\ #M3C^Ude _ _ _ _ _> _ _ _L)     rg   