
    #jA                       U d Z ddlZddlZddlmZ ddlmZmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ  ee e                   Z! e"h d          Z#e"e$         e%d<    ej&        e'          Z(e G d d                      Z)de)defdZ*de$dedz  fdZ+	 	 	 	 	 	 dOde$de$de$dz  de e$         dz  de,e$e$f         dz  de$dz  de$dz  de$dz  de-e,e$ef         e$dz  f         fd Z.d!ed"ede)ddfd#Z/d!ed"ede)ddfd$Z0 e"h d%          Z1e"e$         e%d&<   d!ed"ede)ddfd'Z2d!ed"ede)ddfd(Z3d!ed"ede)ddfd)Z4d!ed"ede)ddfd*Z5d!ed"ede)ddfd+Z6d!ed"ede)ddfd,Z7d!ed"ede)ddfd-Z8	 dPd.e$dz  d/e$dz  d0e9dz  de$dz  fd1Z:d!ed"ede)ddfd2Z;d!ed"ede)ddfd3Z<d!ed"ede)ddfd4Z=d!ed"ede)ddfd5Z>d!ed"ede)ddfd6Z?d!ed"ede)ddfd7Z@d!ed"ede)ddfd8ZAd!ed"ede)ddfd9ZBd!ed"ede)ddfd:ZCd!ed"ede)ddfd;ZDd!ed"ede)ddfd<ZEd!ed"ede)ddfd=ZFd!ed"ede)ddfd>ZGd!ed"ede)ddfd?ZHd!ed"ede)ddfd@ZId!ed"ede)ddfdAZJd!ed"ede)ddfdBZKd!ed"ede)ddfdCZLd!ed"ede)ddfdDZMd!ed"ede)ddfdEZNddddFd"edGe$dHed.e$dz  dIe$dz  dJe,e$ef         dz  de,e$ef         fdKZOd!ed"ede)ddfdLZPd!ed"ede)ddfdMZQd!ed"ede)ddfdNZRdS )QzShared MCP tool implementations for Hindsight.

This module provides the core tool logic used by both:
- mcp_local.py (stdio transport for Claude Code)
- api/mcp.py (HTTP transport for API server)
    N)	dataclass)datetimetimezone)AnyCallable)FastMCP)TypeAdapter)MemoryEngine)DEFAULT_MCP_RECALL_DESCRIPTIONDEFAULT_MCP_RETAIN_DESCRIPTION)
AuditEntryAuditLogger)Budget)VALID_RECALL_FACT_TYPES)TagGroup)OperationValidationError)RequestContext>   recallretainreflectget_bank	list_tags
get_memory
list_bankscreate_bankdelete_banksync_retainupdate_bankget_documentget_operationlist_memoriesclear_memoriesget_bank_statslist_documentsdelete_documentlist_directiveslist_operationscancel_operationcreate_directivedelete_directiveget_mental_modellist_mental_modelscreate_mental_modeldelete_mental_modelupdate_mental_modelrefresh_mental_model
_ALL_TOOLSc                   ,   e Zd ZU dZeg edz  f         ed<   dZeg edz  f         dz  ed<   dZeg edz  f         dz  ed<   dZ	eg edz  f         dz  ed<   dZ
eg ef         dz  ed<   dZeed	<   dZee         dz  ed
<   dZedz  ed<   dZedz  ed<   dS )MCPToolsConfigz)Configuration for MCP tools registration.Nbank_id_resolverapi_key_resolvertenant_id_resolverapi_key_id_resolvermcp_authenticated_resolverFinclude_bank_id_paramtoolsretain_descriptionrecall_description)__name__
__module____qualname____doc__r   str__annotations__r5   r6   r7   r8   boolr9   r:   setr;   r<        _/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/hindsight_api/mcp_tools.pyr3   r3   F   s        33 r3:~.... 9=hr3:~.5<<< ;?S4Z047>>> <@"cDj.1D8??? =AT 2T 9@@@ #(4''' "E3s8d?!!! &*d
)))%)d
)))))rF   r3   configreturnc                    | j         r|                                  nd}| j        r|                                 nd}| j        r|                                 nd}| j        r|                                 nd}t	          ||||          S )zCreate RequestContext with auth details from resolvers.

    This enables tenant auth and usage metering to work with MCP tools by propagating
    the authentication results from the MCP middleware to the memory engine.
    NF)api_key	tenant_id
api_key_idmcp_authenticated)r5   r6   r7   r8   r   )rH   rK   rL   rM   rN   s        rG   _get_request_contextrO   f   s     ,2+BLf%%'''G/5/HR))+++dI171KU++---QUJ?E?`k99;;;fk9Wh   rF   	timestampc                     	 t          j        |                     dd                    S # t          $ r}t          d|  d          |d}~ww xY w)zParse an ISO format timestamp string.

    Args:
        timestamp: ISO format timestamp (e.g., '2024-01-15T10:30:00Z')

    Returns:
        Parsed datetime or None if invalid

    Raises:
        ValueError: If timestamp format is invalid
    Zz+00:00zInvalid timestamp format 'zK'. Expected ISO format like '2024-01-15T10:30:00' or '2024-01-15T10:30:00Z'N)r   fromisoformatreplace
ValueError)rP   es     rG   parse_timestamprW   u   sx    %i&7&7X&F&FGGG   W W W W
 
 	s   '* 
AAAcontentcontexttagsmetadatadocument_idstrategyupdate_modec                    t          |t                    ra	 t          j        |          }t          |t                    r|}n# t          j        t          f$ r Y nw xY wt          |t                    r|g}| |d}	|r>	 t          |          }
|
|	d<   n(# t          $ r}i t          |          fcY d}~S d}~ww xY w|||	d<   |||	d<   |||	d<   |||	d<   |||	d<   |	dfS )	a  Build a content dict for retain operations.

    Args:
        content: The memory content
        context: Category for the memory
        timestamp: Optional ISO timestamp
        tags: Optional tags for scoped visibility filtering
        metadata: Optional key-value metadata to attach to the memory
        document_id: Optional document ID to associate the memory with
        strategy: Optional named retain strategy override (e.g., 'exact', 'verbose')
        update_mode: How to handle existing documents ('replace' or 'append')

    Returns:
        Tuple of (content_dict, error_message). error_message is None if successful.
    )rX   rY   
event_dateNrZ   r[   r\   r]   r^   )	
isinstancerA   jsonloadslistJSONDecodeError	TypeErrorrW   rU   )rX   rY   rP   rZ   r[   r\   r]   r^   parsedcontent_dictparsed_timestamprV   s               rG   build_content_dictrj      sS   8 $ 	Z%%F&$'' $i0 	 	 	D	dC   	6D/67#K#KL 	.y99)9L&& 	 	 	s1vv:	 #V#+Z &1]##+Z &1]#s/   +A AA?B 
B9B4.B94B9mcpmemoryc                 "   |j         ph d}d|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt	          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d	|v rt          | ||           d
|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt          | ||           d|v rt!          | ||           d|v rt#          | ||           d|v rt%          | ||           d|v rt'          | ||           d|v rt)          | ||           d|v rt+          | ||           d|v rt-          | ||           d|v rt/          | ||           d|v rt1          | ||           d|v rt3          | ||           d|v rt5          | ||           d|v rt7          | ||           d|v rt9          | ||           d|v rt;          | ||           t=          | ||           t?          | ||           dS ) zRegister MCP tools on a FastMCP server.

    Args:
        mcp: FastMCP server instance
        memory: MemoryEngine instance
        config: Tool configuration
    >   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r   r   r   r   r   r   r,   r+   r-   r/   r.   r0   r&   r)   r*   r!   r   r$   r   r%   r'   r    r(   r   r   r#   r   r   r"   N) r:   _register_retain_register_sync_retain_register_recall_register_reflect_register_list_banks_register_create_bank_register_list_mental_models_register_get_mental_model_register_create_mental_model_register_update_mental_model_register_delete_mental_model_register_refresh_mental_model_register_list_directives_register_create_directive_register_delete_directive_register_list_memories_register_get_memory_register_list_documents_register_get_document_register_delete_document_register_list_operations_register_get_operation_register_cancel_operation_register_list_tags_register_get_bank_register_get_bank_stats_register_update_bank_register_delete_bank_register_clear_memories_apply_bank_tool_filtering_apply_audit_logging)rk   rl   rH   tools_to_registers       rG   register_mcp_toolsr      s      ) ) )@ $$$ff---)))c66222$$$ff---%%%#vv...(((S&&111)))c66222 000$S&&999..."3777 111%c66::: 111%c66::: 111%c66:::!222&sFF;;; ---!#vv666..."3777..."3777 +++VV444(((S&&111 ,,, ff555***sFF333---!#vv666 ---!#vv666+++VV444..."3777 '''C000&&&3///,,, ff555)))c66222)))c66222,,, ff555sFF333ff-----rF   c                    dt           t                   dz  ffdt          | d          rT| j        | j        fd}fd}t
                              | d|           t
                              | d|           dS t          | d          r	 | j        }|j        fd	}t          |d
|           |j
                                        D ]1\  }}|j        }	||	ffd	}
t
                              |d|
           2dS # t          t          f$ r(}t                              d|            Y d}~dS d}~ww xY wt                              d           dS )zFilter bank-level mcp_enabled_tools from both tools/list and tool invocation.

    Compatible with FastMCP 2.x (_tool_manager pattern) and 3.x (provider pattern).
    rI   Nc                  6  K                                    } | sdS t                    }	j                            | |           d{V }|                    d          }|t          |          nd}	j        }||t          |          nt          }	 |	                    | ||           d{V }n.# t          $ r! t                              dd           |cY S w xY w||k    r1| t          |          t          |          z  }nt          |          }|S )zJReturn the enabled tool set for the current bank, or None if unrestricted.Nmcp_enabled_toolsz3filter_mcp_tools raised, returning unfiltered toolsTexc_info)r4   rO   _config_resolverget_bank_configgetrD   _operation_validator	frozensetr1   filter_mcp_tools	Exceptionloggerwarning)
bank_idrequest_contextbank_cfg
bank_toolsenabled	validator	candidatefilteredrH   rl   s
           rG   _get_enabled_toolsz6_apply_bank_tool_filtering.<locals>._get_enabled_toolsZ  sT     ))++ 	4.v66  0@@/ZZZZZZZZ'/||4G'H'H
6@6L3z???RV /	 .5.A	'***zI!*!;!;G_V_!`!```````   T_cddd 9$$)!(mmc*oo=GG!(mmGs   B4 4(CC
list_toolsc                  j   K    di |  d {V }              d {V |S fd|D             S )Nc                 &    g | ]}|j         v |S rE   )name).0tenabled_sets     rG   
<listcomp>zL_apply_bank_tool_filtering.<locals>._filtered_list_tools.<locals>.<listcomp>  s%    >>>!+(=(=A(=(=(=rF   rE   rE   )kwargsr:   r   r   original_list_toolss     @rG   _filtered_list_toolsz8_apply_bank_tool_filtering.<locals>._filtered_list_tools}  su      --7777777777E 2 2 4 4444444K">>>>u>>>>rF   c                 V   K                 d {V }|| |vrd S  | fi | d {V S NrE   )r   r   r   r   original_get_tools      rG   _filtered_get_toolz6_apply_bank_tool_filtering.<locals>._filtered_get_tool  sg       2 2 4 4444444K&4{+B+Bt**4::6:::::::::rF   get_tool_tool_managerc                     K                 d {V }               d {V | S fd|                                  D             S )Nc                 $    i | ]\  }}|v 	||S rE   rE   )r   kvr   s      rG   
<dictcomp>zK_apply_bank_tool_filtering.<locals>._filtered_get_tools.<locals>.<dictcomp>  s)    OOOAa;>N>N1>N>N>NrF   )items)	all_toolsr   r   original_get_toolss    @rG   _filtered_get_toolsz7_apply_bank_tool_filtering.<locals>._filtered_get_tools  sx      "4"4"6"6666666	$6$6$8$8888888&$$OOOO):):OOOOrF   	get_toolsc                    K                 d {V }|,||vr(t          d| d                                 d           ||            d {V S )NzTool 'z' is not enabled for bank '')rU   r4   )	arguments_name_origr   r   rH   s       rG   _filtered_runz1_apply_bank_tool_filtering.<locals>._filtered_run  s      (:(:(<(<"<"<"<"<"<"<K".53K3K()p%)p)pTZTkTkTmTm)p)p)pqqq!&y!1!11111111rF   runz*Could not apply bank tool filtering (v2): z<Could not apply bank tool filtering: unknown FastMCP version)rD   rA   hasattrr   r   object__setattr__r   r   setattr_toolsr   r   AttributeErrorKeyErrorr   r   )rk   rl   rH   r   r   tool_managerr   r   tooloriginal_runr   rV   r   r   r   r   s    ``         @@@@rG   r   r   T  s"   c#ho       < sL!! 1W!nL	? 	? 	? 	? 	? 	?	; 	; 	; 	; 	; 	; 	3.BCCC3
,>?????	o	&	& W	M,L!-!7P P P P P P L+/BCCC*17799 	? 	?
d#x9=\ 2 2 2 2 2 2 2 ""4>>>>	? 	? ) 	M 	M 	MNNKKKLLLLLLLLL	M 	UVVVVVs   A0D
 
ED>>E>   r   r   r   r   r   r   r"   r%   r(   r)   r*   r-   r.   r/   r0   _AUDITABLE_MCP_TOOLSc           	      N  	 |j         dt          ffd}t          | d          r	 | j        j                                        D ]9\  }}|t          v r+t                              |d |||j	                             :dS # t          t          f$ r(}t                              d|            Y d}~dS d}~ww xY wt          | d          r;t          | dd          		r&d	fd		}t                              | d|           dS dS t                              d
           dS )z7Wrap auditable MCP tool run methods with audit logging.	tool_namec                     | |ffd	}|S )z2Create an audited wrapper for a tool's run method.c           
        K                        |          s ||            d {V S d }t          | t                    r3|                     d          pj        r                                nd }n%t          | d          r|                     d          }t          |d|t          j        t          j
                  t          | t                    rt          |           ndt          |           i          }	  ||            d {V }t          |t                    r||_        n=t          |t                    r
d|i|_        nt          |t                    r	d|i|_        |t          j        t          j
                  |_                            |           S # t          j        t          j
                  |_                            |           w xY w)Nr   r   rk   rawaction	transportr   
started_atrequestr   text)
is_enabledra   dictr   r4   r   r   r   nowr   utcrA   responserd   ended_atlog_fire_and_forget)r   r   r   r   entryresultaudit_loggerrH   s         rG   _audited_runzB_apply_audit_logging.<locals>._wrap_tool_run.<locals>._audited_run  s     **511 ."U9---------G)T** 3#--	22vTZTk7uv7N7N7P7P7PquE** 3#--	22#<55+5i+F+FcYUTWXaTbTbLc  E8$uY////////fd++ 6%+ENN-- 6&-v%6ENN,, 6&,f%5EN!)hl!;!;007777 "*hl!;!;007777s   =A,F" ":GrE   )r   r   r   r   rH   s      rG   _wrap_tool_runz,_apply_audit_logging.<locals>._wrap_tool_run  s5     1: 	8 	8 	8 	8 	8 	8 	8> rF   r   r   z(Could not apply MCP audit logging (v2): Nr   	call_toolc           
        K   | t           vs                    |           s | |fi | d {V S d }t          |t                    r2|                    d          pj        r                                nd }t          | d|t          j        t          j
                  t          |t                    rt          |          ni           }	  | |fi | d {V }dt          |          d d         i|_        |t          j        t          j
                  |_                            |           S # t          j        t          j
                  |_                            |           w xY w)Nr   rk   r   r      )r   r   ra   r   r   r4   r   r   r   r   r   rA   r   r   r   )	r   r   r   r   r   r   r   rH   original_call_tools	         rG   _audited_call_toolz0_apply_audit_logging.<locals>._audited_call_tool  s     333<;R;RSW;X;X3!3!3D)!N!Nv!N!NNNNNNNNi.. 'mmI66 5;5LV//111RV  ###'|HL99/9)T/J/JRDOOOPR  <#5#5dI#P#P#P#PPPPPPPF&.FETE0B%CEN!%-\(,%?%?EN 44U;;;; &.\(,%?%?EN 44U;;;;s   /D8 8:E2z:Could not apply MCP audit logging: unknown FastMCP versionr   )r   rA   r   r   r   r   r   r   r   r   r   r   r   r   getattr)
rk   rl   rH   r   r   r   rV   r   r   r   s
     `     @@rG   r   r     s    & 3L"# " " " " " " "H sO$$ )U	K!/6<<>> T T
d///&&tUNN44R4RSSST T ) 	K 	K 	KNNIaIIJJJJJJJJJ	K	j	!	! !U$S+t<< 	E< < < < < < < <4 sK1CDDDDD9	E 	E< 	STTTTTs   AB B=B88B=c                    j         pt          }j        r|                     |          	 	 	 	 	 	 	 	 ddt          dt          dt          dz  dt
          t                   dz  dt          t          t          f         dz  d	t          dz  d
t          dz  dt          dz  dt          dz  dt          ffd            }dS |                     |          	 	 	 	 	 	 	 ddt          dt          dt          dz  dt
          t                   dz  dt          t          t          f         dz  d	t          dz  dt          dz  dt          dz  dt          ffd            }dS )zRegister the retain tool.descriptiongeneralNrX   rY   rP   rZ   r[   r\   r   r]   r^   rI   c	           
      $  K   |p                                 }	|	dddS t          | |||||||          \  }
}|rd|dS t                    }	                     |	|
g|           d{V }dd|                    d          d	S # t
          $ r9}t                              d
|            dt          |          dcY d}~S d}~wt          $ r;}t          
                    d| d           dt          |          dcY d}~S d}~ww xY w)a<  
            Args:
                content: The fact/memory to store (be specific and include relevant details)
                context: Category for the memory (e.g., 'preferences', 'work', 'hobbies', 'family'). Default: 'general'
                timestamp: When this event/fact occurred (ISO format, e.g., '2024-01-15T10:30:00Z'). Useful for timeline tracking.
                tags: Optional tags for scoped visibility filtering (e.g., ['project:alpha', 'user:123'])
                metadata: Optional key-value metadata to attach (e.g., {'source': 'slack', 'channel': 'general'})
                document_id: Optional document ID to associate this memory with
                bank_id: Optional bank to store in (defaults to session bank). Use for cross-bank operations.
                strategy: Optional named retain strategy (e.g., 'exact' for verbatim storage). Strategies are defined in the bank config.
                update_mode: How to handle existing documents with the same document_id. 'replace' (default) or 'append' (concatenates new content to existing).
            NerrorNo bank_id configuredstatusmessager   contentsr   acceptedMemory storage initiatedoperation_idr   r   r   Retain rejected: Error storing memory: Tr   r4   rj   rO   submit_async_retainr   r   r   r   rA   r   r   )rX   rY   rP   rZ   r[   r\   r   r]   r^   target_bankrh   r   r   r   rV   rH   rl   s                  rG   r   z _register_retain.<locals>.retain  s     0 ">V%<%<%>%>K"")6MNNN"4)T8[(T_# #L%  =")e<<<26::O>%99'*^$3  :           )9$*JJ~$>$>  
 , > > >6166777")c!ff======== > > >9a99DIII")c!ff========>s0   7B	 	
D.CDD0D
D
Dc           
         K                                    }|dddS t          | |||||||          \  }	}
|
rd|
dS t                    }	                     ||	g|           d{V }dd|                    d          d	S # t
          $ r9}t                              d
|            dt          |          dcY d}~S d}~wt          $ r;}t          
                    d| d           dt          |          dcY d}~S d}~ww xY w)a  
            Args:
                content: The fact/memory to store (be specific and include relevant details)
                context: Category for the memory (e.g., 'preferences', 'work', 'hobbies', 'family'). Default: 'general'
                timestamp: When this event/fact occurred (ISO format, e.g., '2024-01-15T10:30:00Z'). Useful for timeline tracking.
                tags: Optional tags for scoped visibility filtering (e.g., ['project:alpha', 'user:123'])
                metadata: Optional key-value metadata to attach (e.g., {'source': 'slack', 'channel': 'general'})
                document_id: Optional document ID to associate this memory with
                strategy: Optional named retain strategy (e.g., 'exact' for verbatim storage). Strategies are defined in the bank config.
                update_mode: How to handle existing documents with the same document_id. 'replace' (default) or 'append' (concatenates new content to existing).
            Nr   r   r   r   r   r   r   r   r   r  Tr   r  )rX   rY   rP   rZ   r[   r\   r]   r^   r  rh   r   r   r   rV   rH   rl   s                 rG   r   z _register_retain.<locals>.retainS  s     , !1133K"")6MNNN"4)T8[(T_# #L%  =")e<<<26::O>%99'*^$3  :           )9$*JJ~$>$>  
 , > > >6166777")c!ff======== > > >9a99DIII")c!ff========>s0   7B 
D.C?DD0DDD)r   NNNNNNNr   NNNNNN)r;   r   r9   r   rA   rd   r   )rk   rl   rH   r   r   s    ``  rG   rn   rn     s   +M/MK# l>	k	*	* %$(%).2&*"&#'&*3	> 3	>3	>3	> Tz3	> s)d"	3	>
 38nt+3	> t3	> 4Z3	> Dj3	> t3	> 3	> 3	> 3	> 3	> 3	> 3	> 
+	*3	> 3	> 3	>n 
k	*	* %$(%).2&*#'&*1	> 1	>1	>1	> Tz1	> s)d"	1	>
 38nt+1	> t1	> Dj1	> t1	> 1	> 1	> 1	> 1	> 1	> 1	> 
+	*1	> 1	> 1	>rF   c                 b   j         r|                                 	 	 	 	 	 	 	 ddt          dt          dt          dz  dt          t                   dz  dt          t          t          f         dz  dt          dz  d	t          dz  d
t          dz  dt          ffd            }dS |                                 	 	 	 	 	 	 ddt          dt          dt          dz  dt          t                   dz  dt          t          t          f         dz  dt          dz  d
t          dz  dt          ffd            }dS )zMRegister the sync_retain tool (synchronous retain that waits for completion).r   NrX   rY   rP   rZ   r[   r\   r   r]   rI   c           	      >  K   |p                                 }|dddS t          | ||||||          \  }	}
|
rd|
dS t                    }	                     ||	g||	                    dd                     d{V }d |D             }dd	|d
S # t
          $ r9}t                              d|            dt          |          dcY d}~S d}~wt          $ r;}t          
                    d| d           dt          |          dcY d}~S d}~ww xY w)ar  Store information to long-term memory and wait for completion.

            Unlike retain (which is asynchronous), this tool blocks until the memory
            is fully stored and immediately available for recall.

            Args:
                content: The fact/memory to store (be specific and include relevant details)
                context: Category for the memory (e.g., 'preferences', 'work', 'hobbies', 'family'). Default: 'general'
                timestamp: When this event/fact occurred (ISO format, e.g., '2024-01-15T10:30:00Z'). Useful for timeline tracking.
                tags: Optional tags for scoped visibility filtering (e.g., ['project:alpha', 'user:123'])
                metadata: Optional key-value metadata to attach (e.g., {'source': 'slack', 'channel': 'general'})
                document_id: Optional document ID to associate this memory with
                bank_id: Optional bank to store in (defaults to session bank). Use for cross-bank operations.
                strategy: Optional named retain strategy (e.g., 'exact' for verbatim storage). Strategies are defined in the bank config.
            Nr   r   r   r]   r   r   r   r]   c                     g | ]	}|D ]}|
S rE   rE   r   batchuids      rG   r   z>_register_sync_retain.<locals>.sync_retain.<locals>.<listcomp>  %    GGGeGG#cGGGGrF   	completedMemory stored successfullyr   r   
memory_idsSync retain rejected: Error in sync retain: Tr   r4   rj   rO   retain_batch_asyncpopr   r   r   rA   r   r   )rX   rY   rP   rZ   r[   r\   r   r]   r  rh   r   r   r   r  rV   rH   rl   s                  rG   r   z*_register_sync_retain.<locals>.sync_retain  s     4 ">V%<%<%>%>K"")6MNNN"4WgyRVX`bmow"x"xL% =")e<<<26::O>%88'*^$3)--j$??	  9           HGvGGG
);",  
 , > > >;;;<<<")c!ff======== > > >9a99DIII")c!ff========>s1   AB 
D .CDD!0DDDc           	      :  K                                    }|dddS t          | ||||||          \  }}	|	rd|	dS t                    }
	                     ||g|
|                    dd                     d{V }d |D             }dd	|d
S # t
          $ r9}t                              d|            dt          |          dcY d}~S d}~wt          $ r;}t          
                    d| d           dt          |          dcY d}~S d}~ww xY w)a  Store information to long-term memory and wait for completion.

            Unlike retain (which is asynchronous), this tool blocks until the memory
            is fully stored and immediately available for recall.

            Args:
                content: The fact/memory to store (be specific and include relevant details)
                context: Category for the memory (e.g., 'preferences', 'work', 'hobbies', 'family'). Default: 'general'
                timestamp: When this event/fact occurred (ISO format, e.g., '2024-01-15T10:30:00Z'). Useful for timeline tracking.
                tags: Optional tags for scoped visibility filtering (e.g., ['project:alpha', 'user:123'])
                metadata: Optional key-value metadata to attach (e.g., {'source': 'slack', 'channel': 'general'})
                document_id: Optional document ID to associate this memory with
                strategy: Optional named retain strategy (e.g., 'exact' for verbatim storage). Strategies are defined in the bank config.
            Nr   r   r   r]   r	  c                     g | ]	}|D ]}|
S rE   rE   r  s      rG   r   z>_register_sync_retain.<locals>.sync_retain.<locals>.<listcomp>  r  rF   r  r  r  r  r  Tr   r  )rX   rY   rP   rZ   r[   r\   r]   r  rh   r   r   r   r  rV   rH   rl   s                 rG   r   z*_register_sync_retain.<locals>.sync_retain  s     0 !1133K"")6MNNN"4WgyRVX`bmow"x"xL% =")e<<<26::O>%88'*^$3)--j$??	  9           HGvGGG
);",  
 , > > >;;;<<<")c!ff======== > > >9a99DIII")c!ff========>s1   AB 
D.CDD0DDDr  )r   NNNNN)r9   r   rA   rd   r   )rk   rl   rH   r   s    `` rG   ro   ro     s    # p>	 %$(%).2&*"&#'5	> 5	>5	>5	> Tz5	> s)d"	5	>
 38nt+5	> t5	> 4Z5	> Dj5	> 5	> 5	> 5	> 5	> 5	> 5	> 
5	> 5	> 5	>r 
 %$(%).2&*#'3	> 3	>3	>3	> Tz3	> s)d"	3	>
 38nt+3	> t3	> Dj3	> 3	> 3	> 3	> 3	> 3	> 3	> 
3	> 3	> 3	>rF   c                    j         pt          }j        r|                     |          	 	 	 	 	 	 	 	 ddt          dt
          dt          d	t          t                   dz  d
t          t                   dz  dt          dt          t                   dz  dt          dz  dt          dz  dt          t          z  ffd            }dS |                     |          	 	 	 	 	 	 	 ddt          dt
          dt          d	t          t                   dz  d
t          t                   dz  dt          dt          t                   dz  dt          dz  dt          ffd            }dS )zRegister the recall tool.r   r   highNanyquery
max_tokensbudgettypesrZ   
tags_match
tag_groupsquery_timestampr   rI   c	                   K   	 |p                                 }	|	dS ||t          d          t          j        t          j        t          j        d}
|
                    |                                t          j                  }||nt          t                    }|	| |||t                    d}|
||d<   ||d<   |t                              |          |d<   |t          |          |d	<    j        di | d{V }|                    d
          S # t           $ rK}t"                              d|            t'          j        t+          |          g d          cY d}~S d}~wt          $ r}d| dcY d}~S d}~wt,          $ r/}t"                              d| d           d| dcY d}~S d}~ww xY w)a>  
            Args:
                query: Natural language search query (e.g., "user's food preferences", "what projects is user working on")
                max_tokens: Maximum tokens to return in results (default: 4096)
                budget: Search budget - 'low', 'mid', or 'high' (default: 'high'). Higher budgets search more thoroughly.
                types: Fact types to include (e.g., ['world', 'experience']). Default: all types.
                tags: Optional tags to filter results by (e.g., ['project:alpha']). Mutually exclusive with tag_groups.
                tags_match: How to match tags - 'any' (match any tag) or 'all' (match all tags). Default: 'any'
                tag_groups: Compound tag filter using boolean groups (AND-ed together). Each group is a leaf
                    {"tags": [...], "match": "any_strict"} or compound {"and": [...]}, {"or": [...]}, {"not": {...}}.
                    Example: [{"not": {"tags": ["closeout"], "match": "any_strict"}}] excludes memories tagged closeout.
                    Mutually exclusive with tags.
                query_timestamp: Temporal context for the query (ISO format, e.g., '2024-01-15T10:30:00Z'). Helps retrieve time-relevant memories.
                bank_id: Optional bank to search in (defaults to session bank). Use for cross-bank operations.
            NError: No bank_id configuredX'tags' and 'tag_groups' are mutually exclusive. Use 'tag_groups' for compound filtering.lowmidr  r   r  	fact_typer  r  r   rZ   r!  r"  question_date   indentRecall rejected: r   results{"error": "z", "results": []}Error searching: Tr   rE   )r4   rU   r   LOWMIDHIGHr   lowerrd   r   rO   _TAG_GROUP_LIST_ADAPTERvalidate_pythonrW   recall_asyncmodel_dump_jsonr   r   r   rb   dumpsrA   r   r   )r  r  r  r   rZ   r!  r"  r#  r   r  
budget_mapbudget_enum
fact_typesrecall_kwargsrecall_resultrV   rH   rl   s                   rG   r   z _register_recall.<locals>.recall  sJ     6(<%B)@)@)B)B&99#
(>$r   &,Z
FKXX
(nnV\\^^V[II&+&7UUTBY=Z=Z
  +"!+)",';F'C'C1 1 #,0M&)2<M,/)2I2Y2YZd2e2eM,/".5D_5U5UM/2&9f&9&J&JM&J&J J J J J J J$44A4>>>+ D D D6166777zCFFr"B"BCCCCCCCC < < <;a;;;;;;;;; < < <444tDDD;a;;;;;;;;;<sH   D C>D 
G(A E.(G.G;F GG$F=7G=Gc                   K   	                                  }|dg dS ||t          d          t          j        t          j        t          j        d}	|	                    |                                t          j                  }
||nt          t                    }|| ||
|t                    d}|
||d<   ||d<   |t                              |          |d	<   |t          |          |d
<    j        di | d{V }|                                S # t           $ r9}t"                              d|            t'          |          g dcY d}~S d}~wt          $ r}t'          |          g dcY d}~S d}~wt(          $ r;}t"                              d| d           t'          |          g dcY d}~S d}~ww xY w)a  
            Args:
                query: Natural language search query (e.g., "user's food preferences", "what projects is user working on")
                max_tokens: Maximum tokens to return in results (default: 4096)
                budget: Search budget - 'low', 'mid', or 'high' (default: 'high'). Higher budgets search more thoroughly.
                types: Fact types to include (e.g., ['world', 'experience']). Default: all types.
                tags: Optional tags to filter results by (e.g., ['project:alpha']). Mutually exclusive with tag_groups.
                tags_match: How to match tags - 'any' (match any tag) or 'all' (match all tags). Default: 'any'
                tag_groups: Compound tag filter using boolean groups (AND-ed together). Each group is a leaf
                    {"tags": [...], "match": "any_strict"} or compound {"and": [...]}, {"or": [...]}, {"not": {...}}.
                    Example: [{"not": {"tags": ["closeout"], "match": "any_strict"}}] excludes memories tagged closeout.
                    Mutually exclusive with tags.
                query_timestamp: Temporal context for the query (ISO format, e.g., '2024-01-15T10:30:00Z'). Helps retrieve time-relevant memories.
            Nr   r1  r&  r'  r*  rZ   r!  r"  r,  r0  r4  Tr   rE   )r4   rU   r   r5  r6  r7  r   r8  rd   r   rO   r9  r:  rW   r;  
model_dumpr   r   r   rA   r   r   )r  r  r  r   rZ   r!  r"  r#  r  r>  r?  r@  rA  rB  rV   rH   rl   s                  rG   r   z _register_recall.<locals>.recallK  sA     2(8$5577&%<LLL#
(>$r   &,Z
FKXX
(nnV\\^^V[II&+&7UUTBY=Z=Z
  +"!+)",';F'C'C1 1 #,0M&)2<M,/)2I2Y2YZd2e2eM,/".5D_5U5UM/2&9f&9&J&JM&J&J J J J J J J$//111+ 8 8 86166777!$QB77777777 8 8 8!$QB77777777 8 8 8444tDDD!$QB777777778sG   D C<D 
G'.EGG(E?9G?G0G<GG)r   r  NNr  NNN)r   r  NNr  NN)r<   r   r9   r   rA   intrd   r   )rk   rl   rH   r   r   s    ``  rG   rp   rp     s   +M/MK# J8	k	*	* # &*%)#,0*."&B	< B	<B	<B	< B	< 9t#	B	<
 s)d"B	< B	< T
T)B	< !4ZB	< 4ZB	< 4ZB	< B	< B	< B	< B	< B	< 
+	*B	< B	< B	<L 
k	*	* # &*%)#,0*.@	8 @	8@	8@	8 @	8 9t#	@	8
 s)d"@	8 @	8 T
T)@	8 !4Z@	8 @	8 @	8 @	8 @	8 @	8 @	8 
+	*@	8 @	8 @	8rF   c                    j         r|                                 	 	 	 	 	 	 	 ddt          dt          dz  dt          dt          d	t          dz  d
t
          t                   dz  dt          dt          dz  dt          ffd            }dS |                                 	 	 	 	 	 	 ddt          dt          dz  dt          dt          d	t          dz  d
t
          t                   dz  dt          dt          ffd            }dS )zRegister the reflect tool.Nr(  r   r  r  rY   r  r  response_schemarZ   r!  r   rI   c                 2  K   	 |p                                 }|dS t          j        t          j        t          j        d}	|	                    |                                t          j                  }
|| |
||t                    d}|||d<   |
||d<   ||d<    j        di | d{V }t          j
        |                    d	                    }|t          |d
          r
|j        |d
<   t          j        |d	          S # t          $ rJ}t                               d|            t          j        dt%          |          i          cY d}~S d}~wt&          $ r/}t                               d| d           d| dcY d}~S d}~ww xY w)a  
            Generate thoughtful analysis by synthesizing stored memories with the bank's personality.

            WHEN TO USE THIS TOOL:
            Use reflect when you need reasoned analysis, not just fact retrieval. This tool
            thinks through the question using everything the bank knows and its personality traits.

            EXAMPLES OF GOOD QUERIES:
            - "What patterns have emerged in how I approach debugging?"
            - "Based on my past decisions, what architectural style do I prefer?"
            - "What might be the best approach for this problem given what you know about me?"
            - "How should I prioritize these tasks based on my goals?"

            HOW IT DIFFERS FROM RECALL:
            - recall: Returns raw facts matching your search (fast lookup)
            - reflect: Reasons across memories to form a synthesized answer (deeper analysis)

            Use recall for "what did I say about X?" and reflect for "what should I do about X?"

            Args:
                query: The question or topic to reflect on
                context: Optional context about why this reflection is needed
                budget: Search budget - 'low', 'mid', or 'high' (default: 'low')
                max_tokens: Maximum tokens for the response (default: 4096)
                response_schema: Optional JSON schema for structured output. When provided, the response includes a 'structured_output' field.
                tags: Optional tags to filter memories by (e.g., ['project:alpha'])
                tags_match: How to match tags - 'any' (match any tag) or 'all' (match all tags). Default: 'any'
                bank_id: Optional bank to reflect in (defaults to session bank). Use for cross-bank operations.
            Nr%  r'  r   r  r  rY   r  r   rG  rZ   r!  r-  r.  structured_outputReflect rejected: r   Error reflecting: Tr   r3  z", "text": ""}rE   )r4   r   r5  r6  r7  r   r8  rO   reflect_asyncrb   rc   r<  r   rJ  r=  r   r   r   rA   r   r   )r  rY   r  r  rG  rZ   r!  r   r  r>  r?  reflect_kwargsreflect_resultresult_datarV   rH   rl   s                  rG   r   z"_register_reflect.<locals>.reflect  s     P!9%B)@)@)B)B&99%+Z
FKXX
(nnV\\^^VZHH  +")&",';F'C'C2 2 #.8GN#45#-1N6*3=N<0';v';'M'Mn'M'M!M!M!M!M!M!M"j)G)Gq)G)Q)QRR".7>K^3_3_.7E7WK 34z+a8888+ 5 5 57A77888z7CFF"344444444 9 9 95!55EEE8a8888888889s5   D C+D 
F?EFF'$FFFc                   K   	                                  }|dddS t          j        t          j        t          j        d}|                    |                                t          j                  }	|| |	||t                    d}
|||
d<   |
||
d<   ||
d	<    j        di |
 d{V }|	                                }|t          |d
          r
|j        |d
<   |S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt           $ r;}t                              d| d           t          |          ddcY d}~S d}~ww xY w)a~  
            Generate thoughtful analysis by synthesizing stored memories with the bank's personality.

            WHEN TO USE THIS TOOL:
            Use reflect when you need reasoned analysis, not just fact retrieval. This tool
            thinks through the question using everything the bank knows and its personality traits.

            EXAMPLES OF GOOD QUERIES:
            - "What patterns have emerged in how I approach debugging?"
            - "Based on my past decisions, what architectural style do I prefer?"
            - "What might be the best approach for this problem given what you know about me?"
            - "How should I prioritize these tasks based on my goals?"

            HOW IT DIFFERS FROM RECALL:
            - recall: Returns raw facts matching your search (fast lookup)
            - reflect: Reasons across memories to form a synthesized answer (deeper analysis)

            Use recall for "what did I say about X?" and reflect for "what should I do about X?"

            Args:
                query: The question or topic to reflect on
                context: Optional context about why this reflection is needed
                budget: Search budget - 'low', 'mid', or 'high' (default: 'low')
                max_tokens: Maximum tokens for the response (default: 4096)
                response_schema: Optional JSON schema for structured output. When provided, the response includes a 'structured_output' field.
                tags: Optional tags to filter memories by (e.g., ['project:alpha'])
                tags_match: How to match tags - 'any' (match any tag) or 'all' (match all tags). Default: 'any'
            Nr    )r   r   r'  rI  rG  rZ   r!  rJ  rK  r   rL  Tr   rE   )r4   r   r5  r6  r7  r   r8  rO   rM  rD  r   rJ  r   r   r   rA   r   r   )r  rY   r  r  rG  rZ   r!  r  r>  r?  rN  rO  rP  rV   rH   rl   s                 rG   r   z"_register_reflect.<locals>.reflect  s     L!5$5577&%<bIII%+Z
FKXX
(nnV\\^^VZHH  +")&",';F'C'C2 2 #.8GN#45#-1N6*3=N<0';v';'M'Mn'M'M!M!M!M!M!M!M,7799".7>K^3_3_.7E7WK 34""+ ) ) )7A77888Q((((((( 5 5 55!55EEE!$Q444444445s5   C$ CC$ $
E).-D!E)!E).0E$E)$E))Nr(  r   NNr  N)Nr(  r   NNr  )r9   r   rA   rE  r   rd   )rk   rl   rH   r   s    `` rG   rq   rq     s    # V5	 #'"+/%)#"&H	9 H	9H	94ZH	9 H	9 	H	9
 "D[H	9 s)d"H	9 H	9 4ZH	9 H	9 H	9 H	9 H	9 H	9 H	9 
H	9 H	9 H	9X 
 #'"+/%)#F	5 F	5F	54ZF	5 F	5 	F	5
 "D[F	5 s)d"F	5 F	5 F	5 F	5 F	5 F	5 F	5 F	5 
F	5 F	5 F	5rF   c                 Z    |                                  dt          ffd            }dS )zRegister the list_banks tool.rI   c                    K   	                      t                               d{V } t          j        d| id          S # t          $ rK}t
                              d|            t          j        t          |          g d          cY d}~S d}~wt          $ r/}t
          	                    d| d	
           d| dcY d}~S d}~ww xY w)a)  
        List all available memory banks.

        Use this tool to discover what memory banks exist in the system.
        Each bank is an isolated memory store (like a separate "brain").

        Returns:
            JSON list of banks with their IDs, names, dispositions, and missions.
        r   Nbanksr-  r.  Operation rejected: )r   rV  zError listing banks: Tr   r3  z", "banks": []})
r   rO   rb   r=  r   r   r   rA   r   r   )rV  rV   rH   rl   s     rG   r   z(_register_list_banks.<locals>.list_banks.  s     	6 ++<PQW<X<X+YYYYYYYYE:w.q9999' 	> 	> 	>NN5!55666:A<<======== 	6 	6 	6LL444tLDDD5!555555555	6s1   A A 
CA BCC#$CCCNr   rA   )rk   rl   rH   r   s    `` rG   rr   rr   +  sL     	XXZZ6c 6 6 6 6 6 6 Z6 6 6rF   c           
          |                                  ddt          dt          dz  dt          dz  dt          ffd            }dS )zRegister the create_bank tool.Nr   r   missionrI   c                   K   	 t                    }                    | |           d{V }||<                    | |||           d{V                      | |           d{V }d|v r3t          |d         d          r|d                                         |d<   t          j        |d          S # t          $ rJ}t          	                    d|            t          j        d	t          |          i          cY d}~S d}~wt          $ r/}t                              d
| d           d| dcY d}~S d}~ww xY w)a  
        Create a new memory bank or get an existing one.

        Memory banks are isolated stores - each one is like a separate "brain" for a user/agent.
        Banks are auto-created with default settings if they don't exist.

        Args:
            bank_id: Unique identifier for the bank (e.g., 'user-123', 'agent-alpha')
            name: Optional human-friendly name for the bank
            mission: Optional mission describing who the agent is and what they're trying to accomplish
        rU  N)r   rZ  r   dispositionrD  r-  r.  rW  r   zError creating bank: Tr   r3  "})rO   get_bank_profiler   r   rD  rb   r=  r   r   r   rA   r   r   )r   r   rZ  r   profilerV   rH   rl   s         rG   r   z*_register_create_bank.<locals>.create_bankG  s     	)26::O"33G_3]]]]]]]]G 7#6((#$3	 )          !' 7 7Q` 7 a aaaaaaa ''GGM4JL,Y,Y')0)?)J)J)L)L&:ga0000' 	1 	1 	1NN5!55666:wA/00000000 	) 	) 	)LL444tLDDD(!(((((((((	)s0   B8B> >
E	?DE	E	$E>E	E	NNrX  )rk   rl   rH   r   s    `` rG   rs   rs   D  sp     	XXZZ%) %)3 %)cDj %)#PT* %)`c %) %) %) %) %) %) Z%) %) %)rF   r   source_queryr  c                     | |                                  sdS ||                                 sdS ||dk     s|dk    rd| S dS )zJValidate mental model inputs, returning an error message or None if valid.Nzname cannot be emptyzsource_query cannot be empty   i    z-max_tokens must be between 256 and 8192, got )stripr   ra  r  s      rG   _validate_mental_model_inputsrf  p  sg     

%%(:(:(<(<--:#3#3zD7H7HKzKKK4rF   c           
      N   j         rT|                                 	 	 	 d	dt          t                   dz  dt          dt          dz  dt          ffd            }dS |                                 	 	 d
dt          t                   dz  dt          dt          ffd            }dS )z%Register the list_mental_models tool.NfullrZ   detailr   rI   c                   K   	 |p                                 }|dS                     || |t                               d{V }t          j        d|idt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d	| d
           d| dcY d}~S d}~ww xY w)a  
            List mental models (pinned reflections) for a memory bank.

            Mental models are living documents that stay current by periodically re-running
            a source query through reflect. Use them to maintain up-to-date summaries,
            preferences, or synthesized knowledge.

            Args:
                tags: Optional tags to filter by (returns models matching any tag)
                detail: Detail level - 'metadata' (names/tags only), 'content' (adds content/config), 'full' (includes reflect_response). Default: 'full'
                bank_id: Optional bank to list from (defaults to session bank). Use for cross-bank operations.
            Nz/{"error": "No bank_id configured", "items": []}r   rZ   ri  r   r   r-  r/  defaultrW  r   Error listing mental models: Tr   r3  ", "items": []})r4   r,   rO   rb   r=  rA   r   r   r   r   r   )rZ   ri  r   r  modelsrV   rH   rl   s         rG   r,   z8_register_list_mental_models.<locals>.list_mental_models  sQ     $:%B)@)@)B)B&LL%88'!$8$@$@	  9           z7F"3AsKKKK+ 5 5 59a99:::z7CFF"344444444 : : :@Q@@4PPP9a999999999:5   A) A	A) )
C43?B82C48C4$C/)C4/C4c                   K   	                                  }|dg dS                     || |t                               d{V }d|iS # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r;}t                              d| d	
           t          |          g dcY d}~S d}~ww xY w)a>  
            List mental models (pinned reflections) for this memory bank.

            Mental models are living documents that stay current by periodically re-running
            a source query through reflect. Use them to maintain up-to-date summaries,
            preferences, or synthesized knowledge.

            Args:
                tags: Optional tags to filter by (returns models matching any tag)
                detail: Detail level - 'metadata' (names/tags only), 'content' (adds content/config), 'full' (includes reflect_response). Default: 'full'
            Nr   r   r   rk  r   rW  r   rn  Tr   )	r4   r,   rO   r   r   r   rA   r   r   )rZ   ri  r  rp  rV   rH   rl   s        rG   r,   z8_register_list_mental_models.<locals>.list_mental_models  s<      6$5577&%<rJJJ%88'!$8$@$@	  9            ((+ ) ) )9a99:::Q((((((( 6 6 6@Q@@4PPP!$Q"5555555564   A /A 
C-BCC0C
CC)Nrh  N)Nrh  )r9   r   rd   rA   r   )rk   rl   rH   r,   s    `` rG   rt   rt     s     # J6	%) "&"	: "	:s)d""	:"	: 4Z"	: 	"	: "	: "	: "	: "	: "	: 
"	: "	: "	:L 
%)  	6  	6s)d" 	6 	6  	6  	6  	6  	6  	6  	6 
 	6  	6  	6rF   c           
         j         rE|                                 	 	 d	dt          dt          dt          dz  dt          ffd            }dS |                                 	 d
dt          dt          dt          ffd            }dS )z#Register the get_mental_model tool.rh  Nmental_model_idri  r   rI   c                 (  K   	 |p                                 }|dS                     || |t                               d{V }|t          j        dd|  d| di          S t          j        |dt
          	          S # t          $ rJ}t                              d
|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d           d| dcY d}~S d}~ww xY w)a$  
            Get a specific mental model by ID.

            Returns the mental model with the requested detail level. Use list_mental_models
            first to discover available model IDs.

            Args:
                mental_model_id: The ID of the mental model to retrieve
                detail: Detail level - 'metadata' (names/tags only), 'content' (adds content/config), 'full' (includes reflect_response). Default: 'full'
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            N"{"error": "No bank_id configured"}r   rv  ri  r   r   Mental model '' not found in bank 'r   r-  rl  rW  Error getting mental model: Tr   r3  r]  )r4   r+   rO   rb   r=  rA   r   r   r   r   r   )rv  ri  r   r  modelrV   rH   rl   s         rG   r+   z4_register_get_mental_model.<locals>.get_mental_model  s{     "-%B)@)@)B)B&??$55'$3!$8$@$@	 6         =:w0u0u0ugr0u0u0u&vwwwz%3????+ 5 5 59a99:::z7CFF"344444444 - - -?A??$OOO,a,,,,,,,,,-s;   B A
B *B 
D?CDD"$DDDc                   K   	                                  }|ddiS                     || |t                               d{V }|dd|  d| diS |S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d	| d
           dt          |          icY d}~S d}~ww xY w)a  
            Get a specific mental model by ID.

            Returns the mental model with the requested detail level. Use list_mental_models
            first to discover available model IDs.

            Args:
                mental_model_id: The ID of the mental model to retrieve
                detail: Detail level - 'metadata' (names/tags only), 'content' (adds content/config), 'full' (includes reflect_response). Default: 'full'
            Nr   r   ry  rz  r{  r   rW  r|  Tr   )	r4   r+   rO   r   r   r   rA   r   r   )rv  ri  r  r}  rV   rH   rl   s        rG   r+   z4_register_get_mental_model.<locals>.get_mental_model  sV     )$5577&#%<==$55'$3!$8$@$@	 6         =#%jo%j%j\g%j%j%jkk+ ) ) )9a99:::Q((((((( ) ) )?A??$OOOQ((((((()s:   A 8A A 
C$-BCC$/CCC)rh  N)rh  r9   r   rA   r   )rk   rl   rH   r+   s    `` rG   ru   ru     s     # L)	 !"&#	- #	- #	-#	- 4Z#	- 	#	- #	- #	- #	- #	- #	- 
#	- #	- #	-N 
 !!	) !	) !	)!	) !	) !	) !	) !	) !	) !	) 
!	) !	) !	)rF   c                    j         ru|                                 	 	 	 	 	 ddt          dt          dt          dz  dt          t                   dz  dt          d	t
          d
t          dz  dt          ffd            }dS |                                 	 	 	 	 ddt          dt          dt          dz  dt          t                   dz  dt          d	t
          dt          ffd            }dS )z&Register the create_mental_model tool.N   Fr   ra  rv  rZ   r  #trigger_refresh_after_consolidationr   rI   c                    K   	 |p                                 }|dS t          | ||          }|rt          j        d|i          S t	                    }	d|i}
                    || |d||||
|		  	         d{V }                    ||d         |		           d{V }t          j        |d         |d
         dd|  dd          S # t          $ rJ}t          	                    d|            t          j        dt          |          i          cY d}~S d}~wt          $ r-}t          j        dt          |          i          cY d}~S d}~wt          $ r/}t                              d| d           d| dcY d}~S d}~ww xY w)a&  
            Create a new mental model (pinned reflection).

            A mental model is a living document generated by running the source_query through
            reflect. The content is auto-generated asynchronously - use the returned operation_id
            to track progress.

            EXAMPLES:
            - name="Coding Preferences", source_query="What coding patterns and tools does the user prefer?"
            - name="Project Goals", source_query="What are the user's current project goals and priorities?"
            - name="Communication Style", source_query="How does the user prefer to communicate?"

            Args:
                name: Human-readable name for the mental model
                source_query: The query to run through reflect to generate content
                mental_model_id: Optional custom ID (alphanumeric lowercase with hyphens). Auto-generated if not provided.
                tags: Optional tags for scoped visibility filtering
                max_tokens: Maximum tokens for generated content (256-8192, default: 2048)
                trigger_refresh_after_consolidation: If True, automatically refresh this model after memory consolidation. Default: False
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  re  r   refresh_after_consolidationGenerating content...	r   r   ra  rX   rv  rZ   r  triggerr   idr   rv  r   r   createdrz  5' created. Content is being generated asynchronously.rv  r   r   r   rW  Error creating mental model: Tr   r3  r]  )r4   rf  rb   r=  rO   r-   !submit_async_refresh_mental_modelr   r   r   rA   rU   r   r   )r   ra  rv  rZ   r  r  r   r  validation_errorr   r  r}  r   rV   rH   rl   s                 rG   r-   z:_register_create_mental_model.<locals>.create_mental_model)  s[     >1-%B)@)@)B)B&??#@LZ$ $ $  $ C:w0@&ABBB"6v">">8:]^ %88'!-3$3)#$3 9 
 
 
 
 
 
 
 
  &GG'$)$K$3  H           z+0;(.~(>"+#oD#o#o#o	    , 5 5 59a99:::z7CFF"344444444 5 5 5z7CFF"344444444 - - -@Q@@4PPP,a,,,,,,,,,-sM   C )C 	BC 
F?DFF)"EFF$FFFc                   K   	                                  }|ddiS t          | ||          }|rd|iS t                    }d|i}	                    || |d||||	|	  	         d{V }
                    ||
d         |	           d{V }|
d         |d
         dd|  ddS # t
          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r}dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)a  
            Create a new mental model (pinned reflection).

            A mental model is a living document generated by running the source_query through
            reflect. The content is auto-generated asynchronously - use the returned operation_id
            to track progress.

            EXAMPLES:
            - name="Coding Preferences", source_query="What coding patterns and tools does the user prefer?"
            - name="Project Goals", source_query="What are the user's current project goals and priorities?"
            - name="Communication Style", source_query="How does the user prefer to communicate?"

            Args:
                name: Human-readable name for the mental model
                source_query: The query to run through reflect to generate content
                mental_model_id: Optional custom ID (alphanumeric lowercase with hyphens). Auto-generated if not provided.
                tags: Optional tags for scoped visibility filtering
                max_tokens: Maximum tokens for generated content (256-8192, default: 2048)
                trigger_refresh_after_consolidation: If True, automatically refresh this model after memory consolidation. Default: False
            Nr   r   re  r  r  r  r  r  r   r  rz  r  r  rW  r  Tr   )r4   rf  rO   r-   r  r   r   r   rA   rU   r   r   )r   ra  rv  rZ   r  r  r  r  r   r  r}  r   rV   rH   rl   s                rG   r-   z:_register_create_mental_model.<locals>.create_mental_model}  s,     :-)$5577&#%<==#@LZ$ $ $  $ 7#%566"6v">">8:]^$88'!-3$3)#$3 9 
 
 
 
 
 
 
 
  &GG'$)$K$3  H           (-T{$*>$:'kkkk	   , ) ) )9a99:::Q((((((( ) ) )Q((((((( ) ) )@Q@@4PPPQ((((((()sL   B) B) A1B) )
E3-C& E&E3D	E	E/EEE)NNr  FN)NNr  F)r9   r   rA   rd   rE  rC   r   )rk   rl   rH   r-   s    `` rG   rv   rv   $  s    # `)	 +/%)"8="&O	- O	-O	-O	- !4ZO	- s)d"	O	-
 O	- 26O	- 4ZO	- O	- O	- O	- O	- O	- O	- 
O	- O	- O	-f 
 +/%)"8=I	) I	)I	)I	) !4ZI	) s)d"	I	)
 I	) 26I	) I	) I	) I	) I	) I	) I	) 
I	) I	) I	)rF   c                    j         r|                                 	 	 	 	 	 	 ddt          dt          dz  dt          dz  dt          dz  dt          t                   dz  dt
          dz  dt          dz  d	t          ffd
            }dS |                                 	 	 	 	 	 ddt          dt          dz  dt          dz  dt          dz  dt          t                   dz  dt
          dz  d	t          ffd            }dS )z&Register the update_mental_model tool.Nrv  r   ra  r  rZ   r  r   rI   c           	        K   	 |p                                 }|dS t          |||          }|rt          j        d|i          S || ||||t	                    d}	|d|i|	d<    j        di |	 d{V }
|
t          j        dd|  d	| d
i          S t          j        |
dt                    S # t          $ rJ}t          	                    d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t                              d| d           d| dcY d}~S d}~ww xY w)aP  
            Update a mental model's metadata.

            Changes the name, source query, or tags of an existing mental model.
            To regenerate the content, use refresh_mental_model after updating the source query.

            Args:
                mental_model_id: The ID of the mental model to update
                name: New name (leave None to keep current)
                source_query: New source query (leave None to keep current)
                max_tokens: New max tokens for content generation (256-8192, leave None to keep current)
                tags: New tags (leave None to keep current)
                trigger_refresh_after_consolidation: If set, update whether this model auto-refreshes after consolidation
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  re  r   r   rv  r   ra  r  rZ   r   r  r  rz  r{  r   r-  rl  rW  Error updating mental model: Tr   r3  r]  rE   )r4   rf  rb   r=  rO   r/   rA   r   r   r   r   r   )rv  r   ra  r  rZ   r  r   r  r  update_kwargsr}  rV   rH   rl   s               rG   r/   z:_register_update_mental_model.<locals>.update_mental_model  s     2 -%B)@)@)B)B&??#@LZ$ $ $  $ C:w0@&ABBB  +'6 $0", ';F'C'C1 1 7B0MOr/sM),8f8II=IIIIIIII=:w0u0u0ugr0u0u0u&vwwwz%3????+ 5 5 59a99:::z7CFF"344444444 - - -@Q@@4PPP,a,,,,,,,,,-sA   B7 )B7 	AB7 B7 7
E?D EE$D=7E=Ec           	         K   	                                  }|ddiS t          |||          }|rd|iS || ||||t                    d}|d|i|d<    j        di | d{V }	|	dd|  d	| d
iS |	S # t          $ r8}
t
                              d|
            dt          |
          icY d}
~
S d}
~
wt          $ r:}
t
          	                    d|
 d           dt          |
          icY d}
~
S d}
~
ww xY w)a  
            Update a mental model's metadata.

            Changes the name, source query, or tags of an existing mental model.
            To regenerate the content, use refresh_mental_model after updating the source query.

            Args:
                mental_model_id: The ID of the mental model to update
                name: New name (leave None to keep current)
                source_query: New source query (leave None to keep current)
                max_tokens: New max tokens for content generation (256-8192, leave None to keep current)
                tags: New tags (leave None to keep current)
                trigger_refresh_after_consolidation: If set, update whether this model auto-refreshes after consolidation
            Nr   r   re  r  r  r  rz  r{  r   rW  r  Tr   rE   )
r4   rf  rO   r/   r   r   r   rA   r   r   )rv  r   ra  r  rZ   r  r  r  r  r}  rV   rH   rl   s              rG   r/   z:_register_update_mental_model.<locals>.update_mental_model  s     . )$5577&#%<==#@LZ$ $ $  $ 7#%566  +'6 $0", ';F'C'C1 1 7B0MOr/sM),8f8II=IIIIIIII=#%jo%j%j\g%j%j%jkk+ ) ) )9a99:::Q((((((( ) ) )@Q@@4PPPQ((((((()s?   A9 A9 ?A9 7A9 9
C=-B60C=6C=/C82C=8C=NNNNNN)NNNNN)r9   r   rA   rE  rd   rC   r   )rk   rl   rH   r/   s    `` rG   rw   rw     s    # v)	  $'+%)%)?C"&8	- 8	- 8	-*8	- *8	- d
	8	-
 s)d"8	- 268	- 4Z8	- 8	- 8	- 8	- 8	- 8	- 8	- 
8	- 8	- 8	-x 
  $'+%)%)?C6	) 6	) 6	)*6	) *6	) d
	6	)
 s)d"6	) 266	) 6	) 6	) 6	) 6	) 6	) 6	) 
6	) 6	) 6	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )z&Register the delete_mental_model tool.Nrv  r   rI   c                   K   	 |p                                 }|dS                     || t                               d{V }|st          j        dd|  d| di          S t          j        d| d	          S # t
          $ rJ}t                              d
|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d           d| dcY d}~S d}~ww xY w)a6  
            Delete a mental model.

            Permanently removes a mental model and its generated content.

            Args:
                mental_model_id: The ID of the mental model to delete
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r  r   rz  r{  r   deletedr   rv  rW  Error deleting mental model: Tr   r3  r]  )r4   r.   rO   rb   r=  r   r   r   rA   r   r   )rv  r   r  r  rV   rH   rl   s        rG   r.   z:_register_delete_mental_model.<locals>.delete_mental_modelK  s}     -%B)@)@)B)B&?? & : :'$3$8$@$@ !; ! !      
  x:w0u0u0ugr0u0u0u&vwwwzY?"["[\\\+ 5 5 59a99:::z7CFF"344444444 - - -@Q@@4PPP,a,,,,,,,,,-s;   B  A	B  )B   
D
?C	DD$D DDc                   K   	                                  }|ddiS                     || t                               d{V }|sdd|  d| diS d| d	S # t          $ r8}t                              d
|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)z
            Delete a mental model.

            Permanently removes a mental model and its generated content.

            Args:
                mental_model_id: The ID of the mental model to delete
            Nr   r   r  rz  r{  r   r  r  rW  r  Tr   )	r4   r.   rO   r   r   r   rA   r   r   )rv  r  r  rV   rH   rl   s       rG   r.   z:_register_delete_mental_model.<locals>.delete_mental_modelo  s`     )$5577&#%<== & : :'$3$8$@$@ !; ! !      
  l#%jo%j%j\g%j%j%jkk"+PPP+ ) ) )9a99:::Q((((((( ) ) )@Q@@4PPPQ((((((()s:   A 7A A 
C &-BC C &/CC C r   r  )rk   rl   rH   r.   s    `` rG   rx   rx   F  s     # D)	 #'	- 	- 	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-F 
	) 	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )z'Register the refresh_mental_model tool.Nrv  r   rI   c                 ^  K   	 |p                                 }|dS                     || t                               d{V }t          j        |d         dd|  dd          S # t
          $ rJ}t                              d	|            t          j        d
t          |          i          cY d}~S d}~wt          $ r-}t          j        d
t          |          i          cY d}~S d}~wt          $ r/}t                              d| d           d| dcY d}~S d}~ww xY w)a  
            Refresh a mental model by re-running its source query.

            Schedules an async task to re-run the source query through reflect and update the
            mental model's content with fresh results. Use this after adding new memories or
            when the mental model's content may be stale.

            Args:
                mental_model_id: The ID of the mental model to refresh
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r  r   queued!Refresh queued for mental model ''.r   r   r   rW  r   Error refreshing mental model: Tr   r3  r]  )r4   r  rO   rb   r=  r   r   r   rA   rU   r   r   )rv  r   r  r   rV   rH   rl   s        rG   r0   z<_register_refresh_mental_model.<locals>.refresh_mental_model  s      -%B)@)@)B)B&??%GG'$3$8$@$@  H          
 z(.~(>"*#Z#Z#Z#Z    , 5 5 59a99:::z7CFF"344444444 5 5 5z7CFF"344444444 - - -BqBBTRRR,a,,,,,,,,,-sG   A, AA, ,
D,6?B;5D,;D,"C0*D,0D,=$D'!D,'D,c                   K   	                                  }|ddiS                     || t                               d{V }|d         dd|  dd	S # t          $ r8}t                              d
|            dt          |          icY d}~S d}~wt          $ r}dt          |          icY d}~S d}~wt          $ r:}t          	                    d| d           dt          |          icY d}~S d}~ww xY w)a  
            Refresh a mental model by re-running its source query.

            Schedules an async task to re-run the source query through reflect and update the
            mental model's content with fresh results. Use this after adding new memories or
            when the mental model's content may be stale.

            Args:
                mental_model_id: The ID of the mental model to refresh
            Nr   r   r  r   r  r  r  r  rW  r  Tr   )
r4   r  rO   r   r   r   rA   rU   r   r   )rv  r  r   rV   rH   rl   s       rG   r0   z<_register_refresh_mental_model.<locals>.refresh_mental_model  s     )$5577&#%<==%GG'$3$8$@$@  H           %+>$:&V?VVV  
 , ) ) )9a99:::Q((((((( ) ) )Q((((((( ) ) )BqBBTRRRQ((((((()sF   A :A 
D$-BDD$B:4D:D/C<6D<Dr   r  )rk   rl   rH   r0   s    `` rG   ry   ry     s     # R)	 #''	- '	- '	-4Z'	- '	- '	- '	- '	- '	- '	- 
'	- '	- '	-V 
#	) #	)#	) #	) #	) #	) #	) #	) 
#	) #	) #	)rF   c           
      N   j         rT|                                 	 	 	 d	dt          t                   dz  dt          dt          dz  dt          ffd            }dS |                                 	 	 d
dt          t                   dz  dt          dt
          ffd            }dS )z"Register the list_directives tool.NTrZ   active_onlyr   rI   c                   K   	 |p                                 }|dS                     || |t                               d{V }t          j        d|idt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d	| d
           d| dcY d}~S d}~ww xY w)a  
            List directives for a memory bank.

            Directives are instructions that guide how the memory engine processes and
            responds to queries. They influence reflect behavior and memory organization.

            Args:
                tags: Optional tags to filter by
                active_only: If True, only return active directives (default: True)
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rZ   r  r   r   r-  rl  rW  r   Error listing directives: Tr   r3  ro  )r4   r&   rO   rb   r=  rA   r   r   r   r   r   )rZ   r  r   r  
directivesrV   rH   rl   s         rG   r&   z2_register_list_directives.<locals>.list_directives  sQ     ":%B)@)@)B)B&??#)#9#9 +$8$@$@	 $: $ $      
 z7J"73OOOO+ 5 5 59a99:::z7CFF"344444444 : : :=!==MMM9a999999999:rq  c                   K   	                                  }|dg dS                     || |t                               d{V }d|iS # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r;}t                              d| d	
           t          |          g dcY d}~S d}~ww xY w)a  
            List directives for this memory bank.

            Directives are instructions that guide how the memory engine processes and
            responds to queries. They influence reflect behavior and memory organization.

            Args:
                tags: Optional tags to filter by
                active_only: If True, only return active directives (default: True)
            Nr   rs  r  r   rW  r   r  Tr   )	r4   r&   rO   r   r   r   rA   r   r   )rZ   r  r  r  rV   rH   rl   s        rG   r&   z2_register_list_directives.<locals>.list_directives  s<     6$5577&%<rJJJ#)#9#9 +$8$@$@	 $: $ $      
  ,,+ ) ) )9a99:::Q((((((( 6 6 6=!==MMM!$Q"555555556rt  )NTN)NT)r9   r   rd   rA   rC   r   )rk   rl   rH   r&   s    `` rG   rz   rz     s     # H6	%) $"&!	: !	:s)d"!	:!	: 4Z!	: 	!	: !	: !	: !	: !	: !	: 
!	: !	: !	:J 
%) $	6 	6s)d"	6	6 	6 	6 	6 	6 	6 	6 
	6 	6 	6rF   c                    j         rj|                                 	 	 	 	 ddt          dt          dt          dt          dt
          t                   dz  d	t          dz  d
t          ffd            }dS |                                 	 	 	 ddt          dt          dt          dt          dt
          t                   dz  d
t          ffd            }dS )z#Register the create_directive tool.r   TNr   rX   priority	is_activerZ   r   rI   c                   K   	 |p	                                 }|dS 
                    || ||||t          	                     d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)a]  
            Create a new directive for a memory bank.

            Directives guide how the memory engine processes queries and generates reflections.

            Args:
                name: Human-readable name for the directive
                content: The directive content/instructions
                priority: Priority level (higher = more important, default: 0)
                is_active: Whether the directive is active (default: True)
                tags: Optional tags for filtering
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r   rX   r  r  rZ   r   r-  rl  rW  r   Error creating directive: Tr   r3  r]  )r4   r)   rO   rb   r=  rA   r   r   r   r   r   )r   rX   r  r  rZ   r   r  	directiverV   rH   rl   s            rG   r)   z4_register_create_directive.<locals>.create_directive@  sU     ,-%B)@)@)B)B&??"("9"9#%'$8$@$@ #: # #      	 z)AsCCCC+ 5 5 59a99:::z7CFF"344444444 - - -=!==MMM,a,,,,,,,,,-5   A* A
A* *
C54?B93C59C5$C0*C50C5c                   K   	                                  }|ddiS 	                    || ||||t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	a  
            Create a new directive for this memory bank.

            Directives guide how the memory engine processes queries and generates reflections.

            Args:
                name: Human-readable name for the directive
                content: The directive content/instructions
                priority: Priority level (higher = more important, default: 0)
                is_active: Whether the directive is active (default: True)
                tags: Optional tags for filtering
            Nr   r   r  rW  r  Tr   )	r4   r)   rO   r   r   r   rA   r   r   )
r   rX   r  r  rZ   r  r  rV   rH   rl   s
           rG   r)   z4_register_create_directive.<locals>.create_directiven  s;     ()$5577&#%<=="("9"9#%'$8$@$@ #: # #      	 ! + ) ) )9a99:::Q((((((( ) ) )=!==MMMQ((((((()4   A 0A 
C-BCC/C	CC)r   TNN)r   TN)r9   r   rA   rE  rC   rd   r   )rk   rl   rH   r)   s    `` rG   r{   r{   ;  sF    # X)	 "%)"&)	- )	-)	-)	- )	- 	)	-
 s)d")	- 4Z)	- )	- )	- )	- )	- )	- )	- 
)	- )	- )	-Z 
 "%)'	) '	)'	)'	) '	) 	'	)
 s)d"'	) '	) '	) '	) '	) '	) '	) 
'	) '	) '	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )z#Register the delete_directive tool.Ndirective_idr   rI   c                   K   	 |p                                 }|dS                     || t                               d{V }|st          j        dd|  di          S t          j        d| d          S # t
          $ rJ}t                              d	|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d
| d           d| dcY d}~S d}~ww xY w)a%  
            Delete a directive.

            Permanently removes a directive from the memory bank.

            Args:
                directive_id: The ID of the directive to delete
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r   Directive '' not foundr  r   r  rW  Error deleting directive: Tr   r3  r]  )r4   r*   rO   rb   r=  r   r   r   rA   r   r   )r  r   r  r  rV   rH   rl   s        rG   r*   z4_register_delete_directive.<locals>.delete_directive  st     -%B)@)@)B)B&?? & 7 7 $8$@$@ !8 ! !      
  Z:w0Wl0W0W0W&XYYYzY"U"UVVV+ 5 5 59a99:::z7CFF"344444444 - - -=!==MMM,a,,,,,,,,,-s;   A= AA= &A= =
D?CDD$D=DDc                   K   	                                  }|ddiS                     || t                               d{V }|sdd|  diS d| dS # t          $ r8}t                              d	|            dt          |          icY d}~S d}~wt          $ r:}t                              d
| d           dt          |          icY d}~S d}~ww xY w)z
            Delete a directive.

            Permanently removes a directive from this memory bank.

            Args:
                directive_id: The ID of the directive to delete
            Nr   r   rU  r  r  r  r  rW  r  Tr   )	r4   r*   rO   r   r   r   rA   r   r   )r  r  r  rV   rH   rl   s       rG   r*   z4_register_delete_directive.<locals>.delete_directive  sW     )$5577&#%<== & 7 7 $8$@$@ !8 ! !      
  N#%L<%L%L%LMM"+\JJJ+ ) ) )9a99:::Q((((((( ) ) )=!==MMMQ((((((()s:   A 4A A 
C#-BCC#/CCCr   r  )rk   rl   rH   r*   s    `` rG   r|   r|     s     # D)	 #'	- 	-	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-F 
	)	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                 n   j         r\|                                 	 	 	 	 	 ddt          dz  dt          dz  dt          dt          dt          dz  d	t          ffd
            }dS |                                 	 	 	 	 ddt          dz  dt          dz  dt          dt          d	t          f
fd            }dS )z Register the list_memories tool.Nd   r   typeqlimitoffsetr   rI   c           
        K   	 |p                                 }|dS 	                    || |||t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)aV  
            Browse stored memories with optional filtering.

            Lists memory units (facts) stored in the bank. Unlike recall, this is a direct
            browse/search without relevance ranking.

            Args:
                type: Filter by fact type: 'world', 'experience', or 'opinion'
                q: Optional text search query to filter memories
                limit: Maximum number of results (default: 100)
                offset: Pagination offset (default: 0)
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r+  search_queryr  r  r   r-  rl  rW  r   Error listing memories: Tr   r3  r]  )r4   list_memory_unitsrO   rb   r=  rA   r   r   r   r   r   )
r  r  r  r  r   r  r   rV   rH   rl   s
           rG   r!   z._register_list_memories.<locals>.list_memories  sR     *-%B)@)@)B)B&??%77"!"!$8$@$@  8           z&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -;;;dKKK,a,,,,,,,,,-rq  c           
        K   	                                  }|ddiS                     || |||t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	a  
            Browse stored memories with optional filtering.

            Lists memory units (facts) stored in the bank. Unlike recall, this is a direct
            browse/search without relevance ranking.

            Args:
                type: Filter by fact type: 'world', 'experience', or 'opinion'
                q: Optional text search query to filter memories
                limit: Maximum number of results (default: 100)
                offset: Pagination offset (default: 0)
            Nr   r   r  rW  r  Tr   )	r4   r  rO   r   r   r   rA   r   r   )	r  r  r  r  r  r   rV   rH   rl   s	          rG   r!   z._register_list_memories.<locals>.list_memories  s7     &)$5577&#%<==%77"!"!$8$@$@  8           + ) ) )9a99:::Q((((((( ) ) );;;dKKKQ((((((()s4   A /A 
C-BCC/CCC)NNr  r   N)NNr  r   r9   r   rA   rE  r   )rk   rl   rH   r!   s    `` rG   r}   r}     s2    # T)	# "&'	- '	-*'	-Tz'	- '	- 	'	-
 4Z'	- '	- '	- '	- '	- '	- '	- 
'	- '	- '	-V 
# 	%	) %	)*%	)Tz%	) %	) 	%	)
 %	) %	) %	) %	) %	) %	) 
%	) %	) %	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )zRegister the get_memory tool.N	memory_idr   rI   c                    K   	 |p                                 }|dS                     || t                               d{V }|t          j        dd|  di          S t          j        |dt
                    S # t          $ rJ}t                              d	|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d
| d           d| dcY d}~S d}~ww xY w)a>  
            Get a specific memory by ID.

            Returns the full memory unit including content, metadata, and timestamps.

            Args:
                memory_id: The ID of the memory to retrieve
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r   Memory 'r  r-  rl  rW  Error getting memory: Tr   r3  r]  )r4   get_memory_unitrO   rb   r=  rA   r   r   r   r   r   )r  r   r  r   rV   rH   rl   s        rG   r   z(_register_get_memory.<locals>.get_memoryG  so     -%B)@)@)B)B&??%55$8$@$@  6          
 >:w0Q90Q0Q0Q&RSSSz&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -9a99DIII,a,,,,,,,,,-;   B AB &B 
D?CDD$DDDc                   K   	                                  }|ddiS                     || t                               d{V }|dd|  diS |S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d	
           dt          |          icY d}~S d}~ww xY w)z
            Get a specific memory by ID.

            Returns the full memory unit including content, metadata, and timestamps.

            Args:
                memory_id: The ID of the memory to retrieve
            Nr   r   rU  r  r  rW  r  Tr   )	r4   r  rO   r   r   r   rA   r   r   )r  r  r   rV   rH   rl   s       rG   r   z(_register_get_memory.<locals>.get_memoryk  sJ     )$5577&#%<==%55$8$@$@  6          
 >#%F	%F%F%FGG+ ) ) )9a99:::Q((((((( ) ) )9a99DIIIQ((((((():   A 4A A 
C -BCC /CCCr   r  )rk   rl   rH   r   s    `` rG   r~   r~   B  s     # D)	 #'	- 	-	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-F 
	)	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c           
      "   j         rI|                                 	 	 	 d	dt          dz  dt          dt          dz  dt          ffd            }dS |                                 	 	 d
dt          dz  dt          dt          ffd            }dS )z!Register the list_documents tool.Nr  r  r  r   rI   c                   K   	 |p                                 }|dS                     || |t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)a  
            List documents in a memory bank.

            Documents are containers for related memories (e.g., a conversation transcript,
            a meeting notes file). Memories created with a document_id are grouped under that document.

            Args:
                q: Optional search query to filter documents
                limit: Maximum number of results (default: 100)
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r  r  r   r-  rl  rW  r   Error listing documents: Tr   r3  r]  )r4   r$   rO   rb   r=  rA   r   r   r   r   r   r  r  r   r  r   rV   rH   rl   s         rG   r$   z0_register_list_documents.<locals>.list_documents  sL     "-%B)@)@)B)B&??%44!"$8$@$@	  5           z&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -<<<tLLL,a,,,,,,,,,-5   A' AA' '
C21?B60C26C2$C-'C2-C2c                   K   	                                  }|ddiS                     || |t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	a  
            List documents in this memory bank.

            Documents are containers for related memories (e.g., a conversation transcript,
            a meeting notes file). Memories created with a document_id are grouped under that document.

            Args:
                q: Optional search query to filter documents
                limit: Maximum number of results (default: 100)
            Nr   r   r  rW  r  Tr   )	r4   r$   rO   r   r   r   rA   r   r   r  r  r  r   rV   rH   rl   s        rG   r$   z0_register_list_documents.<locals>.list_documents  s1     )$5577&#%<==%44!"$8$@$@	  5           + ) ) )9a99:::Q((((((( ) ) )<<<tLLLQ((((((()4   A -A 
C-B
C
C/CCCNr  NNr  r  )rk   rl   rH   r$   s    `` rG   r   r     s     # H)	 "&!	- !	-Tz!	-!	- 4Z!	- 	!	- !	- !	- !	- !	- !	- 
!	- !	- !	-J 
 	) 	)Tz	)	) 	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )zRegister the get_document tool.Nr\   r   rI   c                    K   	 |p                                 }|dS                     | |t                               d{V }|t          j        dd|  di          S t          j        |dt
                    S # t          $ rJ}t                              d	|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d
| d           d| dcY d}~S d}~ww xY w)a7  
            Get a specific document by ID.

            Returns document metadata and associated memory information.

            Args:
                document_id: The ID of the document to retrieve
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r   
Document 'r  r-  rl  rW  Error getting document: Tr   r3  r]  )r4   r   rO   rb   r=  rA   r   r   r   r   r   r\   r   r  r   rV   rH   rl   s        rG   r   z,_register_get_document.<locals>.get_document  so     -%B)@)@)B)B&??%22$8$@$@  3          
 >:w0U[0U0U0U&VWWWz&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -;;;dKKK,a,,,,,,,,,-r  c                   K   	                                  }|ddiS                     | |t                               d{V }|dd|  diS |S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d	
           dt          |          icY d}~S d}~ww xY w)z
            Get a specific document by ID.

            Returns document metadata and associated memory information.

            Args:
                document_id: The ID of the document to retrieve
            Nr   r   rU  r  r  rW  r  Tr   )	r4   r   rO   r   r   r   rA   r   r   r\   r  r   rV   rH   rl   s       rG   r   z,_register_get_document.<locals>.get_document	  sJ     )$5577&#%<==%22$8$@$@  3          
 >#%J+%J%J%JKK+ ) ) )9a99:::Q((((((( ) ) );;;dKKKQ((((((()r  r   r  )rk   rl   rH   r   s    `` rG   r   r     s     # D)	 #'	- 	-	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-F 
	)	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )z"Register the delete_document tool.Nr\   r   rI   c                   K   	 |p                                 }|dS                     | |t                               d{V }t          j        d| d|t
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d	| d
           d| dcY d}~S d}~ww xY w)aF  
            Delete a document and its associated memories.

            Permanently removes a document and all memories linked to it.

            Args:
                document_id: The ID of the document to delete
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r  r   r\   rm  rW  r   Error deleting document: Tr   r3  r]  )r4   r%   rO   rb   r=  rA   r   r   r   r   r   r  s        rG   r%   z2_register_delete_document.<locals>.delete_document.	  sV     -%B)@)@)B)B&??%55$8$@$@  6          
 zY{"]"]V\"]gjkkkk+ 5 5 59a99:::z7CFF"344444444 - - -<<<tLLL,a,,,,,,,,,-r  c                   K   	                                  }|ddiS                     | |t                               d{V }d| d|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d	
           dt          |          icY d}~S d}~ww xY w)z
            Delete a document and its associated memories.

            Permanently removes a document and all memories linked to it.

            Args:
                document_id: The ID of the document to delete
            Nr   r   rU  r  r  rW  r  Tr   )	r4   r%   rO   r   r   r   rA   r   r   r  s       rG   r%   z2_register_delete_document.<locals>.delete_documentP	  s<     )$5577&#%<==%55$8$@$@  6          
 #,KRR6RR+ ) ) )9a99:::Q((((((( ) ) )<<<tLLLQ((((((()s4   A 1A 
C-BCC/C
CCr   r  )rk   rl   rH   r%   s    `` rG   r   r   )	  s     # @)	 #'	- 	-	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-B 
	)	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c           
      "   j         rI|                                 	 	 	 d	dt          dz  dt          dt          dz  dt          ffd            }dS |                                 	 	 d
dt          dz  dt          dt          ffd            }dS )z"Register the list_operations tool.N   r   r  r   rI   c                   K   	 |p                                 }|dS                     || |t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)a  
            List async operations for a memory bank.

            Operations track background tasks like retain processing, mental model refresh, etc.

            Args:
                status: Filter by status: 'pending', 'running', 'completed', 'failed', 'cancelled'
                limit: Maximum number of results (default: 20)
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r   r  r   r-  rl  rW  r   Error listing operations: Tr   r3  r]  )r4   r'   rO   rb   r=  rA   r   r   r   r   r   )r   r  r   r  r   rV   rH   rl   s         rG   r'   z2_register_list_operations.<locals>.list_operationsy	  sL      -%B)@)@)B)B&??%55!$8$@$@	  6           z&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -=!==MMM,a,,,,,,,,,-r  c                   K   	                                  }|ddiS                     || |t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	a\  
            List async operations for this memory bank.

            Operations track background tasks like retain processing, mental model refresh, etc.

            Args:
                status: Filter by status: 'pending', 'running', 'completed', 'failed', 'cancelled'
                limit: Maximum number of results (default: 20)
            Nr   r   r  rW  r  Tr   )	r4   r'   rO   r   r   r   rA   r   r   )r   r  r  r   rV   rH   rl   s        rG   r'   z2_register_list_operations.<locals>.list_operations	  s1     )$5577&#%<==%55!$8$@$@	  6           + ) ) )9a99:::Q((((((( ) ) )=!==MMMQ((((((()r  )Nr  N)Nr  r  )rk   rl   rH   r'   s    `` rG   r   r   t	  s     # F)	!%"& 	-  	-$J 	- 	- 4Z 	- 	 	-  	-  	-  	-  	-  	- 
 	-  	-  	-H 
!%	) 	)$J	)	) 	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )z Register the get_operation tool.Nr   r   rI   c                   K   	 |p                                 }|dS                     || t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)aS  
            Get the status of an async operation.

            Check progress of background tasks like retain processing or mental model refresh.

            Args:
                operation_id: The ID of the operation to check
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r-  rl  rW  r   Error getting operation: Tr   r3  r]  )r4   get_operation_statusrO   rb   r=  rA   r   r   r   r   r   r   r   r  r   rV   rH   rl   s        rG   r    z._register_get_operation.<locals>.get_operation	  sI     -%B)@)@)B)B&??%:: $8$@$@  ;          
 z&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -<<<tLLL,a,,,,,,,,,-5   A& AA& &
C10?B5/C15C1$C,&C1,C1c                   K   	                                  }|ddiS                     || t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	z
            Get the status of an async operation.

            Check progress of background tasks like retain processing or mental model refresh.

            Args:
                operation_id: The ID of the operation to check
            Nr   r   rU  rW  r  Tr   )	r4   r  rO   r   r   r   rA   r   r   r   r  r   rV   rH   rl   s       rG   r    z._register_get_operation.<locals>.get_operation	  s.     )$5577&#%<==%:: $8$@$@  ;          
 + ) ) )9a99:::Q((((((( ) ) )<<<tLLLQ((((((()4   A ,A 
C-B	C	C/CCCr   r  )rk   rl   rH   r    s    `` rG   r   r   	  s     # @)	 #'	- 	-	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-B 
	)	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                     j         r=|                                 	 ddt          dt          dz  dt          ffd            }dS |                                 dt          dt          ffd            }dS )z#Register the cancel_operation tool.Nr   r   rI   c                   K   	 |p                                 }|dS                     || t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)z
            Cancel a pending or running async operation.

            Args:
                operation_id: The ID of the operation to cancel
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r-  rl  rW  r   Error cancelling operation: Tr   r3  r]  )r4   r(   rO   rb   r=  rA   r   r   r   r   r   r  s        rG   r(   z4_register_cancel_operation.<locals>.cancel_operation
  sI     -%B)@)@)B)B&??%66 $8$@$@  7          
 z&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -?A??$OOO,a,,,,,,,,,-r  c                   K   	                                  }|ddiS                     || t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	z
            Cancel a pending or running async operation.

            Args:
                operation_id: The ID of the operation to cancel
            Nr   r   rU  rW  r  Tr   )	r4   r(   rO   r   r   r   rA   r   r   r  s       rG   r(   z4_register_cancel_operation.<locals>.cancel_operation+
  s.     )$5577&#%<==%66 $8$@$@  7          
 + ) ) )9a99:::Q((((((( ) ) )?A??$OOOQ((((((()r  r   r  )rk   rl   rH   r(   s    `` rG   r   r   
  s     # <)	 #'	- 	-	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-> 
	)	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c           
      "   j         rI|                                 	 	 	 d	dt          dz  dt          dt          dz  dt          ffd            }dS |                                 	 	 d
dt          dz  dt          dt          ffd            }dS )zRegister the list_tags tool.Nr  r  r  r   rI   c                   K   	 |p                                 }|dS                     || |t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)a  
            List tags used in a memory bank.

            Tags are used to organize and filter memories, directives, and mental models.

            Args:
                q: Optional pattern to filter tags (e.g., 'project:*')
                limit: Maximum number of results (default: 100)
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  patternr  r   r-  rl  rW  r   Error listing tags: Tr   r3  r]  )r4   r   rO   rb   r=  rA   r   r   r   r   r   r  s         rG   r   z&_register_list_tags.<locals>.list_tagsR
  sL      -%B)@)@)B)B&??%//$8$@$@	  0           z&C@@@@+ 5 5 59a99:::z7CFF"344444444 - - -7A77$GGG,a,,,,,,,,,-r  c                   K   	                                  }|ddiS                     || |t                               d{V }|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d           dt          |          icY d}~S d}~ww xY w)	a2  
            List tags used in this memory bank.

            Tags are used to organize and filter memories, directives, and mental models.

            Args:
                q: Optional pattern to filter tags (e.g., 'project:*')
                limit: Maximum number of results (default: 100)
            Nr   r   r  rW  r  Tr   )	r4   r   rO   r   r   r   rA   r   r   r  s        rG   r   z&_register_list_tags.<locals>.list_tagsw
  s1     )$5577&#%<==%//$8$@$@	  0           + ) ) )9a99:::Q((((((( ) ) )7A77$GGGQ((((((()r  r  r  r  )rk   rl   rH   r   s    `` rG   r   r   M
  s     # F)	 "& 	-  	-Tz 	- 	- 4Z 	- 	 	-  	-  	-  	-  	-  	- 
 	-  	-  	-H 
 	) 	)Tz	)	) 	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                     j         r6|                                 	 ddt          dz  dt          ffd            }dS |                                 dt          ffd            }dS )zRegister the get_bank tool.Nr   rI   c                 T  K   	 | p                                 }|dS                     |t                               d{V }d|v r3t          |d         d          r|d                                         |d<   t          j        |dt                    S # t          $ rJ}t          
                    d|            t          j        d	t          |          i          cY d}~S d}~wt          $ r/}t                              d
| d           d| dcY d}~S d}~ww xY w)z
            Get the profile of a memory bank.

            Returns bank metadata including name, disposition, and mission.

            Args:
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r\  rD  r-  rl  rW  r   Error getting bank: Tr   r3  r]  )r4   r^  rO   r   rD  rb   r=  rA   r   r   r   r   r   )r   r  r_  rV   rH   rl   s       rG   r   z$_register_get_bank.<locals>.get_bank
  s     -%B)@)@)B)B&?? & 7 7$8$@$@ !8 ! !       !G++8NP\0]0]+-4]-C-N-N-P-PGM*z'!SAAAA+ 5 5 59a99:::z7CFF"344444444 - - -7A77$GGG,a,,,,,,,,,-s5   B A<B 
D'&?C+%D'+D'8$D"D'"D'c                    K   	                                  } | ddiS                     | t                               d{V }d|v r3t          |d         d          r|d                                         |d<   |S # t
          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t          
                    d| d	
           dt          |          icY d}~S d}~ww xY w)z
            Get the profile of this memory bank.

            Returns bank metadata including name, disposition, and mission.
            Nr   r   rU  r\  rD  rW  r  Tr   )r4   r^  rO   r   rD  r   r   r   rA   r   r   )r  r_  rV   rH   rl   s      rG   r   z$_register_get_bank.<locals>.get_bank
  sf     )$5577&#%<== & 7 7$8$@$@ !8 ! !       !G++8NP\0]0]+-4]-C-N-N-P-PGM*+ ) ) )9a99:::Q((((((( ) ) )7A77$GGGQ((((((()s5   B A"B 
D-B?9D?D/D;DDr   r  )rk   rl   rH   r   s    `` rG   r   r   
  s     # ;)	"&	- 	-4Z	-	- 	- 	- 	- 	- 	- 
	- 	- 	-@ 
	) 	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                 r    |                                  	 ddt          dz  dt          ffd            }dS )z3Register the get_bank_stats tool (multi-bank only).Nr   rI   c                   K   	 | p                                 }|dS                     |t                               d{V }t          j        |dt
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d| d	
           d| dcY d}~S d}~ww xY w)z
        Get statistics for a memory bank.

        Returns counts of nodes, links, and other metrics.

        Args:
            bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
        Nrx  rU  r-  rl  rW  r   zError getting bank stats: Tr   r3  r]  )r4   r#   rO   rb   r=  rA   r   r   r   r   r   r   r  r   rV   rH   rl   s       rG   r#   z0_register_get_bank_stats.<locals>.get_bank_stats
  sF     	)!>V%<%<%>%>K";;!00 4V < < 1        F :fQ<<<<' 	1 	1 	1NN5!55666:wA/00000000 	) 	) 	)LL9a99DLIII(!(((((((((	)s5   A% AA% %
C0/?B4.C04C0$C+%C0+C0r   rX  )rk   rl   rH   r#   s    `` rG   r   r   
  sa     	XXZZ") )t)	) ) ) ) ) ) Z) ) )rF   r   rZ  config_updatesr  r   rZ  r  c                  K   ||                      |||           d{V  |rt          |          ni }|	d|vr||d<   |r"| j                            |||           d{V  |                     ||           d{V S )u  Shared implementation for update_bank MCP tool variants.

    Args:
        name: Display name (stored in banks table).
        mission: Deprecated alias for reflect_mission — mapped into config_updates.
        config_updates: Arbitrary config overrides passed to config_resolver.update_bank_config().
            Supports all configurable fields (retain_mission, disposition_*, etc.).
            The config resolver validates keys and rejects non-configurable/credential fields.
    N)r   r   reflect_missionrU  )r   r   r   update_bank_configr^  )rl   r  r   r   rZ  r  effective_configs          rG   _do_update_bankr  
  s      &   + ! 
 
 	
 	
 	
 	
 	
 	
 	
 @N'UtN';';';SU08HHH.5*+ i%88FVXghhhhhhhhh ((o(VVVVVVVVVrF   c                    j         ri|                                 	 	 	 	 d	dt          dz  dt          dz  dt          t          t          f         dz  dt          dz  dt          f
fd            }dS |                                 	 	 	 d
dt          dz  dt          dz  dt          t          t          f         dz  dt          ffd            }dS )zRegister the update_bank tool.Nr   rZ  r  r   rI   c                   K   	 |p                                 }|dS t          |t                    | ||           d{V }t          j        |dt
                    S # t          t          f$ rJ}t          	                    d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t                              d| d	
           d| dcY d}~S d}~ww xY w)a  
            Update a memory bank's configuration.

            Updates the bank's name and/or any bank-level configuration fields.
            Only provided fields will be updated; omitted fields remain unchanged.

            Args:
                name: Human-friendly display name for the bank.
                mission: Deprecated alias for config_updates.reflect_mission.
                config_updates: Dictionary of configuration fields to update. Supports all
                    bank-configurable fields including:
                    - reflect_mission: Mission/context for Reflect operations.
                    - retain_mission: Steers what gets extracted during retain().
                    - retain_extraction_mode: 'concise' (default), 'verbose', or 'custom'.
                    - retain_custom_instructions: Custom extraction prompt (active when mode is 'custom').
                    - retain_chunk_size: Maximum token size for each content chunk.
                    - retain_chunk_batch_size: Number of chunks to process in parallel.
                    - enable_observations: Toggle observation consolidation after retain().
                    - observations_mission: Controls observation synthesis rules.
                    - disposition_skepticism: Critical evaluation level (1-5).
                    - disposition_literalism: Literal vs. abstract interpretation (1-5).
                    - disposition_empathy: Emotional context consideration (1-5).
                    - entity_labels: Controlled vocabulary for entity classification.
                    - entities_allow_free_form: Allow labels outside entity_labels.
                    - recall_include_chunks: Include raw chunks in recall results.
                    - recall_max_tokens: Max tokens for recall results.
                    - mcp_enabled_tools: Tool allowlist for this bank.
                    Any configurable field name is accepted (use Python field names).
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  r  r-  rl  rW  r   Error updating bank: Tr   r3  r]  )r4   r  rO   rb   r=  rA   r   rU   r   r   r   r   )	r   rZ  r  r   r  r   rV   rH   rl   s	          rG   r   z*_register_update_bank.<locals>.update_bank&  sR     J-%B)@)@)B)B&??.(00##1            z&C@@@@,j9 5 5 59a99:::z7CFF"344444444 - - -8Q884HHH,a,,,,,,,,,-s5   A# AA# #C54?B93C59C5$C0*C50C5c                   K   	                                  }|ddiS t          |t                    | ||           d{V }|S # t          t          f$ r8}t
                              d|            dt          |          icY d}~S d}~wt          $ r:}t
          	                    d| d           dt          |          icY d}~S d}~ww xY w)	a  
            Update this memory bank's configuration.

            Updates the bank's name and/or any bank-level configuration fields.
            Only provided fields will be updated; omitted fields remain unchanged.

            Args:
                name: Human-friendly display name for the bank.
                mission: Deprecated alias for config_updates.reflect_mission.
                config_updates: Dictionary of configuration fields to update. Supports all
                    bank-configurable fields including:
                    - reflect_mission: Mission/context for Reflect operations.
                    - retain_mission: Steers what gets extracted during retain().
                    - retain_extraction_mode: 'concise' (default), 'verbose', or 'custom'.
                    - retain_custom_instructions: Custom extraction prompt (active when mode is 'custom').
                    - retain_chunk_size: Maximum token size for each content chunk.
                    - retain_chunk_batch_size: Number of chunks to process in parallel.
                    - enable_observations: Toggle observation consolidation after retain().
                    - observations_mission: Controls observation synthesis rules.
                    - disposition_skepticism: Critical evaluation level (1-5).
                    - disposition_literalism: Literal vs. abstract interpretation (1-5).
                    - disposition_empathy: Emotional context consideration (1-5).
                    - entity_labels: Controlled vocabulary for entity classification.
                    - entities_allow_free_form: Allow labels outside entity_labels.
                    - recall_include_chunks: Include raw chunks in recall results.
                    - recall_max_tokens: Max tokens for recall results.
                    - mcp_enabled_tools: Tool allowlist for this bank.
                    Any configurable field name is accepted (use Python field names).
            Nr   r   r  rW  r  Tr   )
r4   r  rO   r   rU   r   r   rA   r   r   )r   rZ  r  r  r   rV   rH   rl   s         rG   r   z*_register_update_bank.<locals>.update_bankb  s7     F)$5577&#%<==.(00##1            ,j9 ) ) )9a99:::Q((((((( ) ) )8Q884HHHQ((((((()s4   A	 )A	 	C-BCC/C	CC)NNNNNNN)r9   r   rA   r   r   )rk   rl   rH   r   s    `` rG   r   r   !  s2    # t)	#"&48"&	7	- 7	-*7	-4Z7	- !cNT17	- 4Z	7	-
 7	- 7	- 7	- 7	- 7	- 7	- 
7	- 7	- 7	-v 
#"&485	) 5	)*5	)4Z5	) !cNT15	) 	5	) 5	) 5	) 5	) 5	) 5	) 
5	) 5	) 5	)rF   c                     j         r6|                                 	 ddt          dz  dt          ffd            }dS |                                 dt          ffd            }dS )zRegister the delete_bank tool.Nr   rI   c                   K   	 | p                                 }|dS                     |t                               d{V }t          j        d|d|t
                    S # t          $ rJ}t                              d|            t          j        dt          |          i          cY d}~S d}~wt          $ r/}t          
                    d	| d
           d| dcY d}~S d}~ww xY w)ac  
            Delete a memory bank and all its data.

            WARNING: This permanently deletes the bank and all its memories, documents,
            mental models, directives, and other data. This action cannot be undone.

            Args:
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  rU  r  r   r   r  rW  r   Error deleting bank: Tr   r3  r]  r4   r   rO   rb   r=  rA   r   r   r   r   r   r  s       rG   r   z*_register_delete_bank.<locals>.delete_bank  sS     -%B)@)@)B)B&??%11$8$@$@  2           zY;"Y"YRX"Ycfgggg+ 5 5 59a99:::z7CFF"344444444 - - -8Q884HHH,a,,,,,,,,,-rq  c                    K   	                                  } | ddiS                     | t                               d{V }d| d|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d| d	
           dt          |          icY d}~S d}~ww xY w)z
            Delete this memory bank and all its data.

            WARNING: This permanently deletes the bank and all its memories, documents,
            mental models, directives, and other data. This action cannot be undone.
            Nr   r   rU  r  r  rW  r  Tr   	r4   r   rO   r   r   r   rA   r   r   )r  r   rV   rH   rl   s      rG   r   z*_register_delete_bank.<locals>.delete_bank  s9     )$5577&#%<==%11$8$@$@  2           #,NNvNN+ ) ) )9a99:::Q((((((( ) ) )8Q884HHHQ((((((()r  r   r  )rk   rl   rH   r   s    `` rG   r   r     s     # 9)	"&	- 	-4Z	-	- 	- 	- 	- 	- 	- 
	- 	- 	-> 
	)4 	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   c                    j         rA|                                 	 	 ddt          dz  dt          dz  dt          ffd            }dS |                                 	 ddt          dz  dt          ffd            }dS )	z!Register the clear_memories tool.Nr  r   rI   c                   K   	 |p                                 }|dS                     || dt                               d{V }t          j        d|d|t
                    S # t          $ rJ}t                              d|            t          j        d	t          |          i          cY d}~S d}~wt          $ r/}t          
                    d
| d           d| dcY d}~S d}~ww xY w)a  
            Clear all memories from a bank without deleting the bank itself.

            Optionally filter by fact type to only clear specific kinds of memories.

            Args:
                type: Optional fact type filter: 'world', 'experience', or 'opinion'. If not specified, clears all.
                bank_id: Optional bank (defaults to session bank). Use for cross-bank operations.
            Nrx  Fr+  delete_bank_profiler   clearedr  r  rW  r   Error clearing memories: Tr   r3  r]  r  )r  r   r  r   rV   rH   rl   s        rG   r"   z0_register_clear_memories.<locals>.clear_memories  sY     -%B)@)@)B)B&??%11"(-$8$@$@	  2           zY;"Y"YRX"Ycfgggg+ 5 5 59a99:::z7CFF"344444444 - - -<<<tLLL,a,,,,,,,,,-s5   A+ AA+ +
C65?B:4C6:C6$C1+C61C6c                   K   	                                  }|ddiS                     || dt                               d{V }d|d|S # t          $ r8}t                              d|            dt          |          icY d}~S d}~wt          $ r:}t                              d	| d
           dt          |          icY d}~S d}~ww xY w)a:  
            Clear all memories from this bank without deleting the bank itself.

            Optionally filter by fact type to only clear specific kinds of memories.

            Args:
                type: Optional fact type filter: 'world', 'experience', or 'opinion'. If not specified, clears all.
            Nr   r   Fr"  r$  r  rW  r%  Tr   r  )r  r  r   rV   rH   rl   s       rG   r"   z0_register_clear_memories.<locals>.clear_memories  s?     )$5577&#%<==%11"(-$8$@$@	  2           #,NNvNN+ ) ) )9a99:::Q((((((( ) ) )<<<tLLLQ((((((()s4   A 2A 
C-B	CC/CCCr`  r   r  )rk   rl   rH   r"   s    `` rG   r   r     s     # B)	#"&	- 	-*	-4Z	- 	- 	- 	- 	- 	- 	- 
	- 	- 	-D 
#	) 	)*	)	) 	) 	) 	) 	) 	) 
	) 	) 	)rF   r  r  )Sr@   rb   loggingdataclassesr   r   r   typingr   r   fastmcpr   pydanticr	   hindsight_apir
   hindsight_api.configr   r   hindsight_api.engine.auditr   r   "hindsight_api.engine.memory_enginer   $hindsight_api.engine.response_modelsr    hindsight_api.engine.search.tagsr   hindsight_api.extensionsr   hindsight_api.modelsr   rd   r9  r   r1   rA   rB   	getLoggerr=   r   r3   rO   rW   r   tuplerj   r   r   r   r   rn   ro   rp   rq   rr   rs   rE  rf  rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r  r   r   r   rE   rF   rG   <module>r6     s(       ! ! ! ! ! ! ' ' ' ' ' ' ' '                                   & & & & & &        ? > > > > > > > 5 5 5 5 5 5 H H H H H H 5 5 5 5 5 5 = = = = = = / / / / / /%+d8n55  'Y     
IcN      D 
	8	$	$ * * * * * * * *> N    s x$    0 !!&*"": ::: Tz: s)d
	:
 38nt#: t: Dj: t: 4S>3:%&: : : :zJ.	J.J. J. 
	J. J. J. J.ZUWG UW\ UW> UW^b UW UW UW UWp (1y  ( ( in   *QUg QU| QU^ QUX\ QU QU QU QUhp>' p>< p> p>TX p> p> p> p>fs>w s> s>n s>Y] s> s> s> s>lN8' N8< N8 N8TX N8 N8 N8 N8bY57 Y5L Y5. Y5UY Y5 Y5 Y5 Y5x6g 6| 6^ 6X\ 6 6 6 62))w )) ))n ))Y] )) )) )) ))Z X\
 

*
+.:
JMPT*
4Z
 
 
 
$M6g M6| M6^ M6`d M6 M6 M6 M6`O)G O)\ O)> O)^b O) O) O) O)dc)w c) c)n c)ae c) c) c) c)Ly)w y) y)n y)ae y) y) y) y)xG)w G) G)n G)ae G) G) G) G)TU) U) U)~ U)bf U) U) U) U)zK67 K6L K6. K6]a K6 K6 K6 K6\[)G [)\ [)> [)^b [) [) [) [)|G)G G)\ G)> G)^b G) G) G) G)^W) W), W) W)[_ W) W) W) W)tG)g G)| G)^ G)X\ G) G) G) G)^K)' K)< K) K)\` K) K) K) K)\G) G) G)~ G)Z^ G) G) G) G)TC)7 C)L C). C)]a C) C) C) C)VI)7 I)L I). I)]a I) I) I) I)XC) C), C) C)[_ C) C) C) C)L?)G ?)\ ?)> ?)^b ?) ?) ?) ?)NI)W I)l I)N I)W[ I) I) I) I)X>)G >)\ >)> >)VZ >) >) >) >)B)' )< ) )\` ) ) ) )L ,0#W #W #W#W#W $#W
 *#W 4Z#W cNT)#W 
#s(^#W #W #W #WLw)w w) w)n w)Y] w) w) w) w)t<)w <) <)n <)Y] <) <) <) <)~E)' E)< E) E)\` E) E) E) E) E) E)rF   