
    i                       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Z	ddl
Z	ddlmZmZ ddlmZ ddlmZmZmZmZ ddlmZ ddlmZ  ej        e          Zd	Zd
ZdZdZdZdZ dZ!d
Z"dZ#dZ$ ej%        dej&                  Z' ej%        dej(                  Z) ej%        dej(                  Z*dZ+dVdZ,dWdZ-dXdZ.dYd"Z/dZd$Z0d[d'Z1dXd(Z2d\d*Z3d]d0Z4d^d3Z5dXd4Z6d_d5Z7 G d6 d7          Z8d8d9d:d;d<d=d:d>d=d?d@gdAdBZ9dCdDd:d;dEd=dFdGd=dHdIgdAdBZ:dJdKd:d;dLd=d;dMd=dNdOdBZ;dPdQd:dId;dRd=idOdBZ< G dS dTe          Z=dU Z>dS )`zSupermemory memory plugin using the MemoryProvider interface.

Provides semantic long-term memory with profile recall, semantic search,
explicit memory tools, cleaned turn capture, and session-end conversation ingest.
    )annotationsN)datetimetimezone)Path)AnyDictListOptional)MemoryProvider)
tool_errorhermes
   2   allhybrid)r   memories	documents      @i  z+https://api.supermemory.ai/v4/conversationszG^(ok|okay|thanks|thank you|got it|sure|yes|no|yep|nope|k|ty|thx|np)\.?$z6<supermemory-context>[\s\S]*?</supermemory-context>\s*z<<supermemory-containers>[\s\S]*?</supermemory-containers>\s*a  User-assistant conversation. Format: [role: user]...[user:end] and [role: assistant]...[assistant:end].

Only extract things useful in future conversations. Most messages are not worth remembering.

Remember lasting personal facts, preferences, routines, tools, ongoing projects, working context, and explicit requests to remember something.

Do not remember temporary intents, one-time tasks, assistant actions, implementation details, or in-progress status.

When in doubt, store less.returndictc                 f    t           ddt          t          t          t          t
          t          dg ddS )NTF )container_tagauto_recallauto_capturemax_recall_resultsprofile_frequencycapture_modesearch_modeentity_contextapi_timeoutenable_custom_container_tagscustom_containerscustom_container_instructions)_DEFAULT_CONTAINER_TAG_DEFAULT_MAX_RECALL_RESULTS_DEFAULT_PROFILE_FREQUENCY_DEFAULT_CAPTURE_MODE_DEFAULT_SEARCH_MODE_DEFAULT_ENTITY_CONTEXT_DEFAULT_API_TIMEOUT     H/home/piyush/.hermes/hermes-agent/plugins/memory/supermemory/__init__.py_default_configr/   8   s5    /97-+1+(-)+  r-   rawstrc                    t          j        dd| pd          }t          j        dd|          }|                    d          pt          S )Nz[^a-zA-Z0-9_]_r   z_+)resubstripr%   )r0   tags     r.   _sanitize_tagr8   I   sC    
&!3	r
2
2C
&S
!
!C99S>>333r-   textc                Z    | st           S |                                 } | d t                   S N)r*   r6   _MAX_ENTITY_CONTEXT_LENGTHr9   s    r.   _clamp_entity_contextr>   O   s/     '&&::<<D+++,,r-   valuer   defaultboolc                    t          | t                    r| S t          | t                    r2|                                                                 }|dv rdS |dv rdS |S )N)true1yesyonT)false0nonoffF)
isinstancerA   r1   r6   lower)r?   r@   lowereds      r.   _as_boolrP   V   sk    % % ++--%%''55546665Nr-   hermes_homec                   t                      }t          |           dz  }|                                r	 t          j        |                    d                    }t          |t                    r1|                    d |	                                D                        n-# t          $ r  t                              d|d           Y nw xY wt          |                    dt                                                              }|r|nt          |d<   t#          |                    d	          d          |d	<   t#          |                    d
          d          |d
<   	 t%          dt'          dt)          |                    dt*                                                  |d<   n# t          $ r t*          |d<   Y nw xY w	 t%          dt'          dt)          |                    dt,                                                  |d<   n# t          $ r t,          |d<   Y nw xY w|                    d          dk    rdnd|d<   t          |                    dt.                                                                                              }|t2          v r|nt.          |d<   t5          t          |                    dt6                                        |d<   	 t%          dt'          dt9          |                    dt:                                                  |d<   n# t          $ r t:          |d<   Y nw xY wt#          |                    d          d          |d<   |                    dg           }t          |t<                    rd |D             |d<   ng |d<   t          |                    dd                                                    |d<   |S )Nsupermemory.jsonutf-8encodingc                    i | ]
\  }}|||S r;   r,   ).0kvs      r.   
<dictcomp>z,_load_supermemory_config.<locals>.<dictcomp>i   s    MMM1q}q!}}}r-   zFailed to parse %sTexc_infor   r   r         r   i  r   r   
everythingr   r   r    g      ?g      .@r!   r"   Fr#   c                J    g | ] }|t          t          |                    !S r,   )r8   r1   )rX   ts     r.   
<listcomp>z,_load_supermemory_config.<locals>.<listcomp>   s,    &Z&Z&ZXY&Z}SVV'<'<&Z&Z&Zr-   r$   r   )r/   r   existsjsonloads	read_textrM   r   updateitems	Exceptionloggerdebugr1   getr%   r6   rP   maxminintr&   r'   r)   rN   _VALID_SEARCH_MODESr>   r*   floatr+   list)rQ   configconfig_pathr0   raw_tagraw_search_moderaw_containerss          r.   _load_supermemory_configry   b   s   F{##&88K K	K*[22G2DDEEC#t$$ OMM		MMMNNN 	K 	K 	KLL-{TLJJJJJ	K
 &**_.DEEFFLLNNG)0Lgg6LF?$VZZ%>%>EEF=%fjj&@&@$GGF>C'*1c"c&**EY[v:w:w6x6x.y.y'z'z#$$ C C C'B#$$$CA&)!Sc&**EXZt:u:u6v6v-w-w&x&x"## A A A&@"###A-3ZZ-G-G<-W-W\\]bF>&**]4HIIJJPPRRXXZZO/>BU/U/UOO[oF=4SDTVm9n9n5o5oppF5 #CT5MSg9h9h3i3i)j)j k k} 5 5 5 4}5 .6fjjA_6`6`bg-h-hF)*ZZ 3R88N.$'' )&Z&Zn&Z&Z&Z"##&("#.1&**=\^`2a2a.b.b.h.h.j.jF*+MsK   A.B% %'CC'AF/ /GG
AH H)(H)&AL. .MMvaluesNonec                   t          |          dz  }i }|                                rS	 t          j        |                    d                    }t          |t                    r|}n# t          $ r i }Y nw xY w|                    |            |	                    t          j
        |dd          dz   d           d S )NrS   rT   rU      T)indent	sort_keys
)r   rd   re   rf   rg   rM   r   rj   rh   
write_textdumps)rz   rQ   ru   existingr0   s        r.   _save_supermemory_configr      s    {##&88KH 	*[22G2DDEEC#t$$  	 	 	HHH	OOF4:hqDIIIDP[bcccccs   ?A* *A98A9c                    |                                  }t          j        d|          rdS t          j        d|          rdS t          j        d|          rdS dS )Nzprefer|like|love|hate|want
preferencezdecided|will use|going withdecisionz\bis\b|\bare\b|\bhas\b|\bhave\bfactother)rN   r4   search)r9   rO   s     r.   _detect_categoryr      sb    jjllG	y.88 |	y/99 z	y3W== v7r-   iso_timestampc                   	 t          j        |                     dd                    }t          j        t          j                  }||z
                                  }|dk     rdS |dk     rt          |dz             dS |dk     rt          |dz             d	S |d
k     rt          |dz             dS |j        |j        k    r|	                    d          S |	                    d          S # t          $ r Y dS w xY w)NZz+00:00i  zjust nowi  <   zm agoiQ zh agoi:	 zd agoz%d %bz%d %b %Yr   )r   fromisoformatreplacenowr   utctotal_secondsrp   yearstrftimerj   )r   dtr   secondss       r.   _format_relative_timer      s   #M$9$9#x$H$HIIl8<((8**,,T>>:T>>'B,''....U??'D.))0000V'E/**11117ch;;w'''{{:&&&   rrs0   A#C2 'C2 C2 C2 8$C2 C2 2
D ?D static_factsrs   dynamic_factssearch_resultstuple[list, list, list]c                   t                      }g g g }}}| pg D ]2}|r.||vr*|                    |           |                    |           3|pg D ]2}|r.||vr*|                    |           |                    |           3|pg D ]H}|                    dd          }	|	r.|	|vr*|                    |	           |                    |           I|||fS )Nmemoryr   )setaddappendrm   )
r   r   r   seen
out_staticout_dynamic
out_searchr   itemr   s
             r.   _deduplicate_recallr      s   55D*,b"ZJ" $ $ 	$D$$HHTNNNd#### % % 	%D$$HHTNNNt$$$$" $ $(B'' 	$fD((HHVd###{J..r-   max_resultsrp   c           	     6   t          | ||          \  }}}|d |         }|d |         }|d |         }|s|s|sdS g }|r5|                    dd                    d |D                       z              |r5|                    dd                    d |D                       z              |rHg }|D ]}	|	                    dd          }
|
s|	                    d          }|	                    d	          p|	                    d
          pd}g }t	          |          }|r|                    d| d           |H	 |                    dt          t          |          dz             d           n# t          $ r Y nw xY wd                    |          }|                    d| d|
                                            |r+|                    dd                    |          z              |sdS d}d                    |          }d| d| dS )Nr   ## User Profile (Persistent)
r   c              3      K   | ]	}d | V  
dS - Nr,   rX   r   s     r.   	<genexpr>z+_format_prefetch_context.<locals>.<genexpr>   s)      DeDeUY[$[[DeDeDeDeDeDer-   ## Recent Context
c              3      K   | ]	}d | V  
dS r   r,   r   s     r.   r   z+_format_prefetch_context.<locals>.<genexpr>   s(      9[9[$+t++9[9[9[9[9[9[r-   r   
similarity
updated_at	updatedAt[]d   z%] r   z## Relevant Memories
zThe following is background context from long-term memory. Use it silently when relevant. Do not force memories into the conversation.

z<supermemory-context>
z
</supermemory-context>)	r   r   joinrm   r   roundrr   rj   r6   )r   r   r   r   staticsdynamicsr   sectionslinesr   r   r   updatedprefix_bitsrelprefixintrobodys                     r.   _format_prefetch_contextr      s    3L-Q_ ` `GXvl{l#G%HL[L!F 8 F rH g8499DeDe]dDeDeDe;e;eefff ]-		9[9[RZ9[9[9[0[0[[\\\ I 	9 	9DXXh++F ,//Jhh|,,K0E0EKGK'00C /"":s:::...%&&'M5z1B1BS1H+I+I'M'M'MNNNN    DXXk**FLL/f//v//55778888 	IOO4tyy7G7GGHHH r	7 
 ;;x  DNUNNNNNNs   ?6E66
FFc                    t                               d| pd          } t                              d|           } |                                 S Nr   )_CONTEXT_STRIP_REr5   _CONTAINERS_STRIP_REr6   r=   s    r.   _clean_text_for_capturer      s>      TZR00D##B--D::<<r-   c                x    t          t                              | pd                                                    S r   )rA   _TRIVIAL_REmatchr6   r=   s    r.   _is_trivial_messager     s.    !!4:2"4"4"6"677888r-   c                  r    e Zd Zd%d&dZd'd
d	d	dd(dZdd	d	dd)dZd'd	dd*dZd	dd+d Zd	dd,d!Zd-d$Z	d	S )._SupermemoryClientr   api_keyr1   timeoutrr   r   r   c                    ddl m} || _        || _        |t          v r|nt
          | _        || _         |||d          | _        d S )Nr   )Supermemory)r   r   max_retries)	supermemoryr   _api_key_container_tagrq   r)   _search_mode_timeout_client)selfr   r   r   r   r   s         r.   __init__z_SupermemoryClient.__init__  s_    ++++++++6:M+M+MKKSg"{7GQRSSSr-   Nr   )r    r   	custom_idcontentmetadataOptional[dict]r    Optional[str]r   r   r   c                   |p| j         }|                                |gd}|r||d<   |rt          |          |d<   |r||d<    | j        j        j        di |}dt          |dd          iS )N)r   container_tagsr   r    r   idr   r,   )r   r6   r>   r   r   r   getattr)	r   r   r   r    r   r   r7   kwargsresults	            r.   
add_memoryz_SupermemoryClient.add_memory  s     2t2}}"e"
 "
  	*!)F: 	M'<^'L'LF#$ 	,"+F;+'+55f55gfdB//00r-      )limitr   r   queryr   rp   
list[dict]c                  |p| j         }|p| j        }|||d}|t          v r||d<    | j        j        j        di |}g }	t          |dd           pg D ]{}
|	                    t          |
dd          t          |
dd          pdt          |
dd           t          |
dd           pt          |
d	d           t          |
d
d           d           ||	S )N)qr   r   r   resultsr   r   r   r   r   r   r   )r   r   r   r   r   r,   )r   r   rq   r   r   r   r   r   )r   r   r   r   r   r7   moder   responser   r   s              r.   search_memoriesz"_SupermemoryClient.search_memories"  s    2t2/d/',sU!S!S&&&$(F=!/4<&/99&99Xy$77=2 	 	DNNdD"--!$"55;%dL$??%dL$??c74Q\^bCcCc#D*d;;      r-   r   c          
        |p| j         }d|i}|r||d<    | j        j        di |}t          |dd           }t          |dd           pt          |dd           }|rt          |dg           pg ng }|rt          |dg           pg ng }	t          |dd           p|pg }
g }t	          |
t
                    r|
D ]}t	          |t                    r|                    |           -|                    t          |d	d
          t          |dd           pt          |dd           t          |dd           d           ||	|dS )Nr   r   profiler   searchResultsstaticdynamicr   r   r   r   r   r   )r   r   r   )r   r   r   r,   )r   r   r   r   rM   rs   r   r   )r   r   r   r7   r   r   profile_datasearch_datar   r   raw_resultsr   r   s                r.   get_profilez_SupermemoryClient.get_profile6  s   2t2"13!7 	 F3K'4<'11&11xD99h(8$??k78UdfjCkCk>JRx44:PR@LT',	266<"RTk9d;;P{Pbk4(( 		#  dD)) "))$////"))")$""="=&-dL$&G&G&k7SWYdfjKkKk&-dL$&G&G+ +    
 !WWWWr-   	memory_idr{   c               Z    |p| j         }| j        j                            ||           d S )N)r   r   )r   r   r   forget)r   r   r   r7   s       r.   forget_memoryz _SupermemoryClient.forget_memoryO  s3    2t2$$39$EEEEEr-   c               
   |                      |d|          }|sdddS |d         }|                    dd          }|sdd	dS |                     ||
           |                    d          pdd d         }dd| d|dS )Nr   r   r   Fz#No matching memory found to forget.)successmessager   r   r   zBest matching memory has no id.r   r   r   Tz	Forgot: "")r  r  r   )r   rm   r  )r   r   r   r   targetr   previews          r.   forget_by_queryz"_SupermemoryClient.forget_by_queryS  s    &&uA]&SS 	X$1VWWWJJtR((	 	T$1RSSS9MBBB::h''-2tt4,B,B,B,B)TTTr-   
session_idmessagesc                T   t          j        ||| j        gd                              d          }t          j                            t          |d| j         ddd          }t          j        	                    || j
        dz   	          5  	 d d d            d S # 1 swxY w Y   d S )
N)conversationIdr  containerTagsrT   zBearer zapplication/json)AuthorizationzContent-TypePOST)dataheadersmethod   r   )re   r   r   encodeurllibrequestRequest_CONVERSATIONS_URLr   urlopenr   )r   r  r  payloadreqs        r.   ingest_conversationz&_SupermemoryClient.ingest_conversation_  s
   *( "12
 
   6'??	 	
 n$$!:4=!:!: 2   % 
 
 ^##C1B#CC 	 		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   BB!$B!)r   )r   r1   r   rr   r   r1   r   r1   r;   )r   r1   r   r   r    r1   r   r   r   r   r   r   )
r   r1   r   rp   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r1   r   r   r   r{   )r   r1   r   r   r   r   )r  r1   r  r   r   r{   )
__name__
__module____qualname__r   r   r   r   r  r  r   r,   r-   r.   r   r     s       T T T T T1)+D.21 1 1 1 1 1" ;<7;59     (X37X X X X X X2 OS F F F F F F MQ 
U 
U 
U 
U 
U 
U     r-   r   supermemory_storez+Store an explicit memory for future recall.objectstringzThe memory content to store.typedescriptionz)Optional metadata attached to the memory.)r   r   r   )r(  
propertiesrequired)namer)  
parameterssupermemory_searchz/Search long-term memory by semantic similarity.zWhat to search for.integerz#Maximum results to return, 1 to 20.)r   r   r   supermemory_forgetz3Forget a memory by exact id or by best-match query.zExact memory id to delete.z(Query used to find the memory to forget.)r   r   )r(  r*  supermemory_profilez<Retrieve persistent profile facts and recent memory context.z-Optional query to focus the profile response.c                      e Zd Zd Zed-d            Zd.dZd Zd Zd/dZ	d0dZ
d-dZddd1dZddd2dZd3dZd4dZd5dZd6d#Zd7d$Zd8d%Zd8d&Zd8d'Zd8d(Zd9d+Zd,S ):SupermemoryMemoryProviderc                   t                      | _        d| _        d | _        t          | _        d| _        d| _        d| _        t          j
                    | _        d | _        d | _        d | _        d| _        d| _        t"          | _        t&          | _        t*          | _        t.          | _        t2          | _        t6          | _        d| _        d| _        d| _        d| _         g | _!        d| _"        g | _#        d S )Nr   r   TF)$r/   _configr   r   r%   r   _session_id_turn_count_prefetch_result	threadingLock_prefetch_lock_prefetch_thread_sync_thread_write_thread_auto_recall_auto_capturer&   _max_recall_resultsr'   _profile_frequencyr(   _capture_moder)   r   r*   _entity_contextr+   _api_timeout_hermes_home_write_enabled_active_enable_custom_containers_custom_containers_custom_container_instructions_allowed_containersr   s    r.   r   z"SupermemoryMemoryProvider.__init__  s    &((594 "'n..<@8<9= !#> "<2060").&-/.0+.0   r-   r   r1   c                    dS )Nr   r,   rM  s    r.   r,  zSupermemoryMemoryProvider.name  s    }r-   rA   c                    t           j                            dd          }|sdS 	 t          d           dS # t          $ r Y dS w xY w)NSUPERMEMORY_API_KEYr   Fr   T)osenvironrm   
__import__rj   )r   r   s     r.   is_availablez&SupermemoryMemoryProvider.is_available  s_    *..!6;; 	5	}%%%4 	 	 	55	s   7 
AAc                    dddddddgS )Nr   zSupermemory API keyTrP  zhttps://supermemory.ai)keyr)  secretr+  env_varurlr,   rM  s    r.   get_config_schemaz+SupermemoryMemoryProvider.get_config_schema  s3    
 .Ctae  sH  Qi  j  j
 	
r-   c                    t          |pi           }d|v r%t          t          |d                             |d<   d|v r%t          t          |d                             |d<   t	          ||           d S )Nr   r    )r   r8   r1   r>   r   )r   rz   rQ   	sanitizeds       r.   save_configz%SupermemoryMemoryProvider.save_config  s    2&&	i'')6s9_;U7V7V)W)WIo&y((*?IN^D_@`@`*a*aI&' K88888r-   r  r{   c                :   ddl m} |                    d          pt           |                      | _        || _        d| _        t          | j                  | _        t          j
                            dd          | _        t          j
                            dd                                          }|p| j        d         }|                    dd	          }t          |                    d
|                    | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        d         | _        | j        gt7          | j                  z   | _        |                    dd          }|dv| _        t=          | j                  | _        d | _         | j        rj	 tC          | j        | j        | j        | j                  | _         d S # tD          $ r. tF          $                    dd           d| _        d | _         Y d S w xY wd S )Nr   )get_hermes_homerQ   rP  r   SUPERMEMORY_CONTAINER_TAGr   agent_identityr@   z
{identity}r   r   r   r   r   r   r    r!   r"   r#   r$   agent_context)cronflushsubagent)r   r   r   r   z!Supermemory initialization failedTr\   F)%hermes_constantsr_  rm   r1   rF  r6  r7  ry   r5  rQ  rR  r   r6   r8   r   r   r?  r@  rA  rB  rC  r   rD  rE  rI  rJ  rK  rs   rL  rG  rA   rH  r   r   rj   rk   warning)r   r  r   r_  env_tagrv   identityrb  s           r.   
initializez$SupermemoryMemoryProvider.initialize  st   444444"JJ}55O__=N=N9O9O%/0ABB
'<bAA *..!<bAAGGII:T\/:::.	::+GOOL(,S,STT L7!\.9#'<0D#E "&,/B"C!\.9 L7#|,<= L7 *.6T)U&"&,/B"C.2l;Z.[+$($7#84@W;X;X#X 

?B77+3PPDM**< 	$
$1 M -"&"5 $ 1	       $ $ $BTRRR$#$	$ 	$s   2,I   4JJturn_numberrp   r  c                0    t          |d          | _        d S )Nr   )rn   r7  )r   rk  r  r   s       r.   on_turn_startz'SupermemoryMemoryProvider.on_turn_start  s    {A..r-   c                N   | j         sdS dd| j         ddg}| j        rs| j        rld                    | j                  }|                    d| d           |                    d           | j        r|                    d	| j                    d	                    |          S )
Nr   z# SupermemoryzActive. Container: .zvUse supermemory_search, supermemory_store, supermemory_forget, and supermemory_profile for explicit memory operations., z5
Multi-container mode enabled. Available containers: zPass an optional container_tag to supermemory_search, supermemory_store, supermemory_forget, and supermemory_profile to target a specific container.r   )rH  r   rI  rJ  r   rL  r   rK  )r   r   tags_strs      r.   system_prompt_blockz-SupermemoryMemoryProvider.system_prompt_block  s    | 	28$"5888 E

 ) 	Id.E 	Iyy!9::HLL]RZ]]]^^^LL  p  q  q  q2 IG$"EGGHHHyyr-   r   )r  r   c                  | j         r"| j        r| j        r|                                sdS 	 | j                            |d d                   }| j        dk    p| j        | j        z  dk    }t          |r|d         ng |r|d         ng |d         | j        	          }|S # t          $ r  t                              d
d           Y dS w xY w)Nr      )r   r^   r   r   r   r   )r   r   r   r   zSupermemory prefetch failedTr\   )rH  r?  r   r6   r   r7  rB  r   rA  rj   rk   rl   )r   r   r  r   include_profilecontexts         r.   prefetchz"SupermemoryMemoryProvider.prefetch"  s   | 	4#4 	DL 	PUP[P[P]P] 	2	l..U4C4[.AAG".!3h8H4Kb8bfg8gO.2AIWX..r4CKgi00&'78 4	  G N 	 	 	LL6LFFF22	s   A4B" "&CCuser_contentassistant_contentc               D     j         r j        r j        r j        sd S t	          |          }t	          |          }|r|sd S  j        dk    rCt          |          t          k     st          |          t          k     rd S t          |          rd S d| d| dddd fd} j	        r4 j	        
                                r j	                            d	
           d  _	        t          j        |dd           _	         j	                                         d S )Nr   z[role: user]
z
[user:end]

[role: assistant]
z
[assistant:end]r   conversation_turn)sourcer(  c                     	 j                              j                   d S # t          $ r  t                              dd           Y d S w xY w)Nr   r    zSupermemory sync_turn failedTr\   )r   r   rD  rj   rk   rl   )r   r   r   s   r.   _runz1SupermemoryMemoryProvider.sync_turn.<locals>._runG  so    L''(SWSg'hhhhh L L L;dKKKKKKLs   "' &AA       @r  Tzsupermemory-syncr	  daemonr,  )rH  r@  rG  r   r   rC  len_MIN_CAPTURE_LENGTHr   r=  is_aliver   r9  Threadstart)	r   rx  ry  r  
clean_userclean_assistantr  r   r   s	   `      @@r.   	sync_turnz#SupermemoryMemoryProvider.sync_turn3  s   | 	4#5 	T=P 	X\Xd 	F,\::
12CDD 	 	F&&:!444O8L8LOb8b8b":.. EZ E E"1E E E 	 '0CDD	L 	L 	L 	L 	L 	L 	L  	0!2!;!;!=!= 	0""3"/// %,DL^___!!!!!r-   r  List[Dict[str, Any]]c           	        | j         r| j        r| j        r| j        sd S g }|pg D ]f}|                    d          }|dvrt          t          |                    dd                              }|r|                    ||d           g|sd S t          |          dk    r/t          |d                             dd                    dk     rd S 	 | j        	                    | j        |           d S # t          j        j        $ r  t                              d	d
           Y d S t          $ r  t                              d	d
           Y d S w xY w)Nrole)user	assistantr   r   )r  r   r^   r   r_   z!Supermemory session ingest failedTr\   )rH  rG  r   r6  rm   r   r1   r   r  r   r  error	HTTPErrorrk   rg  rj   )r   r  cleanedr  r  r   s         r.   on_session_endz(SupermemoryMemoryProvider.on_session_endS  s   | 	4#6 	dl 	RVRb 	F~2 	C 	CG;;v&&D000-c'++i2L2L.M.MNNG CAABBB 	Fw<<1WQZ^^Ir%B%B!C!Cb!H!HF	OL,,T-=wGGGGG|% 	O 	O 	ONN>NNNNNNN 	O 	O 	ONN>NNNNNNN	Os    C5 50E(%EEactionr	  r   c                r     j         r j        r j        sd S |dk    spd                                sd S  fd} j        r4 j                                        r j                            d           d  _        t          j        |dd           _         j        	                                 d S )	Nr   r   c                     	 j                                                              dddj                   d S # t          $ r  t
                              dd           Y d S w xY w)Nhermes_memoryexplicit_memory)r|  r	  r(  r~  z"Supermemory on_memory_write failedTr\   )r   r   r6   rD  rj   rk   rl   )r   r   r	  s   r.   r  z7SupermemoryMemoryProvider.on_memory_write.<locals>._runo  s    R''MMOO(76Sdee#'#7 (     
  R R RADQQQQQQRs   8= &A'&A'r  r  Fzsupermemory-memory-writer  )
rH  rG  r   r6   r>  r  r   r9  r  r  )r   r  r	  r   r  s   ` `` r.   on_memory_writez)SupermemoryMemoryProvider.on_memory_writei  s    | 	4#6 	dl 	FU??7=b"7"7"9"9?F	R 	R 	R 	R 	R 	R 	R  	1$"4"="="?"? 	1##C#000!&-T%Nhiii  """""r-   c                    dD ]P}t          | |d           }|r*|                                r|                    d           t          | |d            Qd S )N)r<  r=  r>  r   r  )r   r  r   setattr)r   	attr_namethreads      r.   shutdownz"SupermemoryMemoryProvider.shutdown  sn    N 	+ 	+IT9d33F )&//++ )C(((D)T****		+ 	+r-   argsr   r   c                   | j         sdS t          |                    d          pd                                          }|sdS t	          |          }|| j        vr-t          d| dd                    | j                             |S )a  Validate and resolve container_tag from tool call args.

        Returns None (use primary) if multi-container is disabled or no tag provided.
        Returns the validated tag if it's in the allowed list.
        Raises ValueError if the tag is not whitelisted.
        Nr   r   zContainer tag 'z' is not allowed. Allowed: rp  )rI  r1   rm   r6   r8   rL  
ValueErrorr   )r   r  r7   r\  s       r.   _resolve_tool_container_tagz5SupermemoryMemoryProvider._resolve_tool_container_tag  s     - 	4$((?++1r2288:: 	4!#&&	D444B) B B IId&>??B B   r-   c                p   | j         st          t          t          t          gS ddd                    | j                   d| j         dd}g }t          t          t          t          fD ]N}t          j	        t          j
        |                    }||d         d         d	<   |                    |           O|S )
Nr&  z!Optional container tag. Allowed: rp  z. Defaults to primary (z).r'  r-  r*  r   )rI  STORE_SCHEMASEARCH_SCHEMAFORGET_SCHEMAPROFILE_SCHEMAr   rL  r   re   rf   r   r   )r   container_paramschemasbaseschemas        r.   get_tool_schemasz*SupermemoryMemoryProvider.get_tool_schemas  s    - 	P -OO  StyyIa?b?b  S  S{  |O  S  S  S
 
 !=-P 	# 	#DZ
4 0 011FBQF< .?NN6""""r-   c                   t          |                    d          pd                                          }|st          d          S 	 |                     |          }n3# t
          $ r&}t          t          |                    cY d }~S d }~ww xY w|                    d          pi }t          |t                    si }|                    dt          |                     d|d<   	 | j
                            ||| j        |          }|d d	         t          |          d	k    rd
ndz   }d|                    dd          |d}|r||d<   t          j        |          S # t           $ r}t          d|           cY d }~S d }~ww xY w)Nr   r   zcontent is requiredr   r(  hermes_toolr|  )r   r    r   P   z...Tr   )savedr   r
  r   zFailed to store memory: )r1   rm   r6   r   r  r  rM   r   
setdefaultr   r   r   rD  r  re   r   rj   )	r   r  r   r7   excr   r   r
  resps	            r.   _tool_storez%SupermemoryMemoryProvider._tool_store  s   dhhy))/R006688 	53444	(22488CC 	( 	( 	(c#hh''''''''	(88J''-2(D)) 	HF$4W$=$=>>>*	@\,,WxX\Xl|,  A  AFcrcls7||b/@/@eebIG-1D"9M9MZa#b#bD ,(+_%:d### 	@ 	@ 	@>>>????????	@s=   	A 
B)B
B
B)A9E# #
F	-F>F	F	c                   t          |                    d          pd                                          }|st          d          S 	 |                     |          }n3# t
          $ r&}t          t          |                    cY d }~S d }~ww xY w	 t          dt          dt          |                    dd          pd                              }n# t          $ r d}Y nw xY w	 | j
                            |||          }g }|D ]}|                    d	d          |                    d
d          d}	|                    d          :	 t          t          |d                   dz            |	d<   n# t          $ r Y nw xY w|                    |	           |t          |          d}
|r||
d<   t!          j        |
          S # t          $ r}t          d|           cY d }~S d }~ww xY w)Nr   r   zquery is requiredr^   r_   r   r   r  r   r   )r   r   r   r   )r   countr   zSearch failed: )r1   rm   r6   r   r  r  rn   ro   rp   rj   r   r   r   rr   r   r  re   r   )r   r  r   r7   r  r   r   	formattedr   entryr  s              r.   _tool_searchz&SupermemoryMemoryProvider._tool_search  sO   DHHW%%+,,2244 	31222	(22488CC 	( 	( 	(c#hh''''''''	(	3r3txx';';'@q#A#ABBCCEE 	 	 	EEE		7l225UX2YYGI ( (/3xxb/A/AdhhW_acNdNd(e(e88L))5.3E$|:L4M4MPS4S.T.Tl++$     ''''/83y>>#R#RD ,(+_%:d### 	7 	7 	755566666666	7su   	A 
B)B
B
BAC C$#C$(A%G
 (E76G
 7
FG
 FAG
 

G0G+%G0+G0c                   t          |                    d          pd                                          }t          |                    d          pd                                          }|s|st          d          S 	 |                     |          }n3# t
          $ r&}t          t          |                    cY d }~S d }~ww xY w	 |r3| j                            ||           t          j	        d|d          S t          j	        | j        
                    ||                    S # t          $ r}t          d|           cY d }~S d }~ww xY w)	Nr   r   r   zProvide either id or queryr   T)	forgottenr   zForget failed: )r1   rm   r6   r   r  r  r   r  re   r   r  rj   )r   r  r   r   r7   r  s         r.   _tool_forgetz&SupermemoryMemoryProvider._tool_forget  sz   ,"--3355	DHHW%%+,,2244 	< 	<:;;;	(22488CC 	( 	( 	(c#hh''''''''	(	7 H**9C*HHHzI"F"FGGG:dl::5PS:TTUUU 	7 	7 	755566666666	7sB   B 
C!C<CC4D.  -D. .
E8E	EEc                V   t          |                    d          pd                                          pd }	 |                     |          }n3# t          $ r&}t          t          |                    cY d }~S d }~ww xY w	 | j                            ||          }g }|d         r;|                    dd	                    d |d         D                       z              |d         r;|                    d	d	                    d
 |d         D                       z              d	                    |          t          |d                   t          |d                   d}|r||d<   t          j        |          S # t          $ r}t          d|           cY d }~S d }~ww xY w)Nr   r   )r   r   r   r   r   c              3      K   | ]	}d | V  
dS r   r,   r   s     r.   r   z:SupermemoryMemoryProvider._tool_profile.<locals>.<genexpr>  s*      LwLw]a[RV[[LwLwLwLwLwLwr-   r   r   c              3      K   | ]	}d | V  
dS r   r,   r   s     r.   r   z:SupermemoryMemoryProvider._tool_profile.<locals>.<genexpr>  s)      AmAmRV+t++AmAmAmAmAmAmr-   r   )r   static_countdynamic_countr   zProfile failed: )r1   rm   r6   r  r  r   r   r   r   r   r  re   r   rj   )r   r  r   r7   r  r   r   r  s           r.   _tool_profilez'SupermemoryMemoryProvider._tool_profile  s   DHHW%%+,,2244<	(22488CC 	( 	( 	(c#hh''''''''	(	8l..U#.NNGHx  y @499LwLwelmuevLwLwLwCwCw wxxxy! o 5		AmAmZabkZlAmAmAm8m8m mnnn!;;x00 #GH$5 6 6!$WY%7!8!8$ $D
  ,(+_%:d### 	8 	8 	866677777777	8s<   A 
B A;5B ;B C=F 
F(F#F(#F(	tool_nameDict[str, Any]c                8   | j         r| j        st          d          S |dk    r|                     |          S |dk    r|                     |          S |dk    r|                     |          S |dk    r|                     |          S t          d|           S )NzSupermemory is not configuredr$  r.  r0  r1  zUnknown tool: )rH  r   r   r  r  r  r  )r   r  r  r   s       r.   handle_tool_callz*SupermemoryMemoryProvider.handle_tool_call  s    | 	?4< 	?=>>>+++##D))),,,$$T***,,,$$T***---%%d+++6966777r-   N)r   r1   )r   rA   )r  r1   r   r{   )rk  rp   r  r1   r   r{   )r   r1   r  r1   r   r1   )rx  r1   ry  r1   r  r1   r   r{   )r  r  r   r{   )r  r1   r	  r1   r   r1   r   r{   )r   r{   )r  r   r   r   )r   r  )r  r   r   r1   )r  r1   r  r  r   r1   )r!  r"  r#  r   propertyr,  rT  rZ  r]  rj  rm  rr  rw  r  r  r  r  r  r  r  r  r  r  r  r,   r-   r.   r3  r3    s       1 1 1:    X   
 
 
9 9 9-$ -$ -$ -$^/ / / /         9;      " Y[ " " " " " "@O O O O,# # # #,+ + + +   (    @ @ @ @.7 7 7 7<7 7 7 7"8 8 8 808 8 8 8 8 8r-   r3  c                H    |                      t                                 d S r;   )register_memory_providerr3  )ctxs    r.   registerr    s#      !:!<!<=====r-   )r   r   )r0   r1   r   r1   )r9   r1   r   r1   )r?   r   r@   rA   r   rA   )rQ   r1   r   r   )rz   r   rQ   r1   r   r{   )r   r1   r   r1   )r   rs   r   rs   r   rs   r   r   )
r   rs   r   rs   r   rs   r   rp   r   r1   )r9   r1   r   rA   )?__doc__
__future__r   re   loggingrQ  r4   r9  urllib.errorr  urllib.requestr   r   pathlibr   typingr   r   r	   r
   agent.memory_providerr   tools.registryr   	getLoggerr!  rk   r%   r&   r'   r(   r)   rq   r+   r  r<   r  compile
IGNORECASEr   DOTALLr   r   r*   r/   r8   r>   rP   ry   r   r   r   r   r   r   r   r   r  r  r  r  r3  r  r,   r-   r.   <module>r     s    # " " " " "   				 				             ' ' ' ' ' ' ' '       , , , , , , , , , , , , 0 0 0 0 0 0 % % % % % %		8	$	$!      9   ! B bjNM  BJ=ry   "rzCRY  !    "4 4 4 4- - - -	 	 	 	+ + + +\d d d d      (/ / / /&*O *O *O *OZ   9 9 9 9h h h h h h h hX  @ (9WXX!):eff
 
 K   !D&7LMM'8]^^
 
 I   !H#4PQQ&7abb
 
 
 
 "Qh7fgg
 	 	o8 o8 o8 o8 o8 o8 o8 o8d> > > > >r-   