
    Yj|X                    N   d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	 ddl
Z
ddlmZmZmZmZmZ ddlmZ dd	lmZmZmZmZmZmZmZmZ dd
lmZmZ ddlm Z 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, ddl-m.Z.  ej/        e0          Z1dddZ2 G d dee&          Z3dS )zSync Honcho client.    )annotationsN)Mapping)AnyLiteral)	BaseModel
ConfigDictFieldPrivateAttrvalidate_call   	HonchoAio)MessageResponse
PeerConfigPeerResponseQueueStatusResponseSessionConfigurationSessionResponseWorkspaceConfigurationWorkspaceResponse)PeerBaseSessionBase)AsyncHonchoHTTPClientHonchoHTTPClientroutes)Message)MetadataConfigMixin)SyncPagePeerSession)
resolve_idzhttp://localhost:8000zhttps://api.honcho.dev)local
productionc                      e Zd ZU dZ ed          Z eddd          Zded	<    e	d
          Z
ded<    e	d
          Zded<    e	            Zded<    e	d
          Zded<    e	            Zded<    e	            Zded<    e	d          Zded<   ed{d            Zed|d            Zd Zd}dZd}dZd~d Zdd#Zdd%Ze edd&'          fdd*            Zed}d+            Zedd-            Zedd/            Z e ed01          2          d
d
 ed
d3'           ed
dd           ed
d4d56           ed
d4d78          d
d
 ed
d9'          f	d fdI            ZddJZ ddKZ!e edddL          f ed
dM'           ed
dN'          dOddT            Z"	 dddWZ#e edddX          f ed
dY'           ed
dZ'          dOdd]            Z$	 ddd_Z%	 dddaZ&e edddb          fddc            Z'e edddd           ed
de'           edfddgdhi          fddn            Z( e ed01          2          	 	 	 dddu            Z) e ed01          2          	 	 dddx            Z*d}dyZ+d}dzZ, xZ-S )Honchoa  
    Main client for the Honcho SDK.

    Provides access to peers, sessions, and workspace operations with configuration
    from environment variables or explicit parameters. This is the primary entry
    point for interacting with the Honcho conversational memory platform.

    Attributes:
        workspace_id: Workspace ID for scoping operations
        metadata: Cached metadata for this workspace. May be stale if not recently
            fetched. Call get_metadata() for fresh data.
        configuration: Cached configuration for this workspace. May be stale if not
            recently fetched. Call get_configuration() for fresh data.
    allow)extra.r   z#Workspace ID for scoping operations)
min_lengthdescriptionstrworkspace_idN)defaultdict[str, object] | None	_metadataWorkspaceConfiguration | None_configurationr   _httpzAsyncHonchoHTTPClient | None_async_httpdict[str, Any]_http_config	_base_urlFbool_workspace_ensuredreturnc                    | j         S )zTCached metadata for this workspace. May be stale. Use get_metadata() for fresh data.)r0   selfs    T/home/ubuntu/.hermes/hermes-agent/venv/lib/python3.11/site-packages/honcho/client.pymetadatazHoncho.metadataI        ~    c                    | j         S )z^Cached configuration for this workspace. May be stale. Use get_configuration() for fresh data.)r2   r<   s    r>   configurationzHoncho.configurationN   s     ""rA   c                    | j         S N)r3   r<   s    r>   _get_http_clientzHoncho._get_http_clientT   s
    zrA   c                (    t          j                    S rE   )r   
workspacesr<   s    r>   _get_fetch_routezHoncho._get_fetch_routeW   s     """rA   c                4    t          j        | j                  S rE   )r   	workspacer-   r<   s    r>   _get_update_routezHoncho._get_update_routeZ   s     1222rA   c                    d| j         iS )Nidr-   r<   s    r>   _get_fetch_bodyzHoncho._get_fetch_body]   s    d'((rA   data+tuple[dict[str, object], dict[str, object]]c                r    t          j        |          }|j        pi |j                            d          fS )NTexclude_none)r   model_validater?   rC   
model_dumpr=   rQ   rK   s      r>   _parse_responsezHoncho._parse_response`   sG     &4T::	!'R)@)K)K *L *
 *
 
 	
rA   r   c                   |                                                      |                                 |                                           }t	          j        |          }|j        pi | _        |j        | _	        | j	        S )z
        Get configuration from the server and update the cache.

        Returns:
            A WorkspaceConfiguration object containing the configuration settings.
        body)
rF   postrI   rP   r   rV   r?   r0   rC   r2   rX   s      r>   get_configurationzHoncho.get_configurationi   s|     $$&&++!!##$*>*>*@*@ , 
 
 &4T::	"+1r'5""rA   zConfiguration to set)r+   rC   Nonec                    |                                                      |                                 d|                    d          i           || _        dS )z
        Set configuration on the server and update the cache.

        Args:
            configuration: A WorkspaceConfiguration object with configuration settings.
        rC   TrT   r[   N)rF   putrL   rW   r2   )r=   rC   s     r>   set_configurationzHoncho.set_configurationx   se     	##""$$!=#;#;#;#N#NO 	$ 	
 	
 	
 ,rA   c                    | j         S )zThe base URL of the Honcho API.)r7   r<   s    r>   base_urlzHoncho.base_url   r@   rA   r   c                J    | j         t          di | j        | _         | j         S )z/Lazily create and return the async HTTP client.N )r4   r   r6   r<   s    r>   _async_http_clientzHoncho._async_http_client   s/     #4IIt7HIIDrA   r   c                     t          |           S )a  
        Access async versions of all Honcho methods.

        Returns an HonchoAio view that provides async versions of all methods
        while sharing state with this Honcho instance.

        Example:
            ```python
            honcho = Honcho(workspace_id="my-workspace")

            # Async operations
            peer = await honcho.aio.peer("user-123")
            async for p in honcho.aio.peers():
                print(p.id)
            ```
        r   r<   s    r>   aioz
Honcho.aio   s    $ rA   T)arbitrary_types_allowed)configzBase URL for the Honcho APIr   zTimeout in seconds)gtr+   zMaximum number of retries)ger+   zCustom HTTP clientapi_key
str | Noneenvironment%Literal['local', 'production'] | Nonerd   timeoutfloat | Nonemax_retries
int | Nonedefault_headersMapping[str, str] | Nonedefault_queryMapping[str, object] | Nonehttp_clienthttpx.Client | Nonec
                   |pt          j        dd          }
t                                          |
           |pt          j        d          }|r|}n0|rt          |         }n t          j        dt          d                   }|| _        ||d}|||d	<   |||d
<   |t          |          |d<   |t          |          |d<   t          |          | _        |	|	|d<   t          di || _	        dS )a  
        Initialize the Honcho client.

        Args:
            api_key:
                API key for authentication. If not provided, will attempt to
                read from HONCHO_API_KEY environment variable
            environment:
                Environment to use (local or production)
            base_url:
                Base URL for the Honcho API. If not provided, will attempt to
                read from HONCHO_URL environment variable or default to the
                production API URL
            workspace_id:
                Workspace ID to use for operations. If not provided, will
                attempt to read from HONCHO_WORKSPACE_ID environment variable
                or default to "default"
            timeout:
                Optional custom timeout for the HTTP client.
            max_retries:
                Optional custom maximum number of retries for the HTTP client.
            default_headers:
                Optional custom default headers for the HTTP client.
            default_query:
                Optional custom default query parameters for the HTTP client.
            http_client:
                Optional custom httpx client.
        HONCHO_WORKSPACE_IDr.   rO   HONCHO_API_KEY
HONCHO_URLr%   )rd   rn   Nrr   rt   rv   rx   rz   rf   )
osgetenvsuper__init__ENVIRONMENTSr7   dictr6   r   r3   )r=   rn   rp   rd   r-   rr   rt   rv   rx   rz   resolved_workspace_idresolved_api_keyresolved_base_urlhttp_kwargs	__class__s                 r>   r   zHoncho.__init__   sE   ` !- !
	!91
 1
 	&;<<< #Abi0@&A&A  	T ( 	T ,[ 9 "	,\8R S S* *''
 '

 %,K	"")4K&&-1/-B-BK)*$+/+>+>K( !--")4K&%4444


rA   c                    | j         rdS | j                            t          j                    d| j        i           d| _         dS )ad  
        Ensure the workspace exists on the server.

        The Honcho API uses get-or-create semantics for workspaces via
        `POST /v3/workspaces`. This SDK uses that endpoint once per client
        instance to guarantee that subsequent workspace-scoped calls (peers,
        sessions, queue status, etc.) operate on an existing workspace.
        NrN   r[   T)r9   r3   r]   r   rH   r-   r<   s    r>   _ensure_workspacezHoncho._ensure_workspace  sK     " 	F
)++49J2KLLL"&rA   c                   K   | j         rdS | j                            t          j                    d| j        i           d{V  d| _         dS )z
        Async version of `_ensure_workspace`.

        This performs the same get-or-create call, but via the async HTTP client
        used by `honcho.aio`.
        NrN   r[   T)r9   rg   r]   r   rH   r-   r<   s    r>   _ensure_workspace_asynczHoncho._ensure_workspace_async  s|       " 	F%**tT->&? + 
 
 	
 	
 	
 	
 	
 	
 	
 #'rA   zUnique identifier for the peerzqOptional metadata dictionary to associate with this peer. If set, will get/create peer immediately with metadata.zaOptional configuration to set for this peer. If set, will get/create peer immediately with flags.r?   rC   rN   r?   PeerConfig | Noner    c               (    t          || ||          S )a  
        Get or create a peer with the given ID.

        Creates a Peer object that can be used to interact with the specified peer.
        This method does not make an API call unless `configuration` or `metadata` is
        provided.

        Args:
            id: Unique identifier for the peer within the workspace. Should be a
                stable identifier that can be used consistently across sessions.
            metadata: Optional metadata dictionary to associate with this peer.
                If set, will get/create peer immediately with metadata.
            configuration: Optional configuration to set for this peer.
                If set, will get/create peer immediately with flags.

        Returns:
            A Peer object that can be used to send messages, join sessions, and
            query the peer's knowledge representations

        Raises:
            ValidationError: If the peer ID is empty or invalid
        rC   r?   r   r=   rN   r?   rC   s       r>   peerzHoncho.peer!  s    L BMHMMMMrA   filtersSyncPage[PeerResponse, Peer]c                                                         j                            t          j         j                  rdind          }d fdd fdt          |t                    S )a  
        Get all peers in the current workspace.

        Makes an API call to retrieve all peers that have been created or used
        within the current workspace. Returns a paginated result that transforms
        inner client Peer objects to SDK Peer objects as they are consumed.

        Returns:
            A SyncPage of Peer objects representing all peers in the workspace
        r   Nr[   r   r   r:   r    c                H    t          | j        | j        | j                  S Nr   )r    rN   r?   rC   )r   r=   s    r>   	transformzHoncho.peers.<locals>.transform\  s-    "0	   rA   pageintr   c                    j                             t          j        j                  rdind d| i          }t          |t                    S Nr   r   )r\   query)r3   r]   r   
peers_listr-   r   r   r   	next_data
fetch_nextr   r=   r   s     r>   r   z Honcho.peers.<locals>.fetch_nextd  s]    
!$"344-4>i))$tn (  I
 I|Y
KKKrA   )r   r   r:   r    )r   r   r:   r   )r   r3   r]   r   r   r-   r   r   r=   r   rQ   r   r   s   `` @@r>   peerszHoncho.peersI  s     	   zd/00)0:)W%%d  
 

	 	 	 	 	 		L 	L 	L 	L 	L 	L 	L 	L 	L lIzBBBrA   z!Unique identifier for the sessionzwOptional metadata dictionary to associate with this session. If set, will get/create session immediately with metadata.zgOptional configuration to set for this session. If set, will get/create session immediately with flags.SessionConfiguration | Noner"   c               (    t          || ||          S )a  
        Get or create a session with the given ID.

        Creates a Session object that can be used to manage conversations between
        multiple peers. This method does not make an API call unless `configuration` or
        `metadata` is provided.

        Args:
            id: Unique identifier for the session within the workspace. Should be a
                stable identifier that can be used consistently to reference the
                same conversation
            metadata: Optional metadata dictionary to associate with this session.
                If set, will get/create session immediately with metadata.
            configuration: Optional configuration to set for this session.
                If set, will get/create session immediately with flags.

        Returns:
            A Session object that can be used to add peers, send messages, and
            manage conversation context

        Raises:
            ValidationError: If the session ID is empty or invalid
        r   r!   r   s       r>   sessionzHoncho.sessionn  s    N r4}xPPPPrA   "SyncPage[SessionResponse, Session]c                                                         j                            t          j         j                  rdind          }d fdd fdt          |t                    S )aL  
        Get all sessions in the current workspace.

        Makes an API call to retrieve all sessions that have been created within
        the current workspace.

        Returns:
            A SyncPage of Session objects representing all sessions in the workspace.
            Returns an empty page if no sessions exist
        r   Nr[   r   r   r:   r"   c                H    t          | j        | j        | j                  S r   )r"   rN   r?   rC   )r   r=   s    r>   r   z"Honcho.sessions.<locals>.transform  s.    
 )%3	   rA   r   r   r   c                    j                             t          j        j                  rdind d| i          }t          |t                    S r   )r3   r]   r   sessions_listr-   r   r   r   s     r>   r   z#Honcho.sessions.<locals>.fetch_next  s]    
$T%677-4>i))$tn (  I
 I	:NNNrA   )r   r   r:   r"   )r   r   r:   r   )r   r3   r]   r   r   r-   r   r   r   s   `` @@r>   sessionszHoncho.sessions  s     	   z !233)0:)W%%d  
 

	 	 	 	 	 		O 	O 	O 	O 	O 	O 	O 	O 	O oy*EEErA    SyncPage[WorkspaceResponse, str]c                      j                             t          j                    rdind          }ddd fdt	          |t
                    S )z
        Get all workspace IDs from the Honcho instance.

        Makes an API call to retrieve all workspace IDs that the authenticated
        user has access to.

        Returns:
            A paginated SyncPage of workspace ID strings
        r   Nr[   rK   r   r:   r,   c                    | j         S rE   )rN   )rK   s    r>   r   z$Honcho.workspaces.<locals>.transform  s
    <rA   r   r   r   c                    j                             t          j                    rdind d| i          }t	          |t
                    S r   r3   r]   r   workspaces_listr   r   r   s     r>   r   z%Honcho.workspaces.<locals>.fetch_next  sY    
&((-4>i))$tn (  I
 I'8)ZPPPrA   )rK   r   r:   r,   )r   r   r:   r   r   r   s   `` @@r>   rH   zHoncho.workspaces  s     z"$$)0:)W%%d  
 

	  	  	  	 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q /JGGGrA   zID of the workspace to deletec                ^    | j                             t          j        |                     dS )z
        Delete a workspace.

        Makes an API call to delete the specified workspace. This action cannot be undone.

        Args:
            workspace_id: The ID of the workspace to delete
        N)r3   deleter   rK   )r=   r-   s     r>   delete_workspacezHoncho.delete_workspace  s+     	
&*<8899999rA   zThe search query to usezFilters to scope the search
   d   zNumber of results to return)r.   rm   ler+   r   limitr   list[Message]c                    |                                   | j                            t          j        | j                  |||d          }d |D             S )aC  
        Search for messages in the current workspace.

        Makes an API call to search for messages in the current workspace.

        Args:
            query: The search query to use
            filters: Filters to scope the search. See [search filters documentation](https://docs.honcho.dev/v3/documentation/core-concepts/features/using-filters).
            limit: Number of results to return (1-100, default: 10)

        Returns:
            A list of Message objects representing the search results.
            Returns an empty list if no messages are found.
        )r   r   r   r[   c                Z    g | ](}t          j        t          j        |                    )S rf   )r   from_api_responser   rV   ).0items     r>   
<listcomp>z!Honcho.search.<locals>.<listcomp>	  s>     
 
 
 %o&DT&J&JKK
 
 
rA   )r   r3   r]   r   workspace_searchr-   )r=   r   r   r   rQ   s        r>   searchzHoncho.search  so    2 	   z#D$566 WuEE  
 

 

 
 
 	
rA   observerstr | PeerBase | Nonesenderr   str | SessionBase | Noner   c                H   |                                   t          |          }t          |          }t          |          }i }|r||d<   |r||d<   |r||d<   | j                            t	          j        | j                  |r|nd          }t          j        |          S )a  
        Get the queue processing status, optionally scoped to an observer, sender, and/or session.

        Args:
            observer: Optional observer (ID string or Peer object) to scope the status check
            sender: Optional sender (ID string or Peer object) to scope the status check
            session: Optional session (ID string or Session object) to scope the status check
        observer_id	sender_id
session_idN)r   )	r   r#   r3   getr   workspace_queue_statusr-   r   rV   )	r=   r   r   r   resolved_observer_idresolved_sender_idresolved_session_idr   rQ   s	            r>   queue_statuszHoncho.queue_status  s     	   )(33'//(11 " 	8#7E-  	4!3E+ 	6"5E,z~~)$*;<< *%%d  
 
 #1$777rA   str | PeerBaseobservedc                    |                                   t          |          }t          |          }|rt          |          n|}| j                            t	          j        | j                  |||dd           dS )a  
        Schedule a dream task for memory consolidation.

        Dreams are background processes that consolidate observations into higher-level
        insights and update peer cards. This method schedules a dream task for immediate
        processing.

        Args:
            observer: The observer peer (ID string or Peer object) whose perspective
                to use for the dream.
            session: Optional session (ID string or Session object) to scope the dream to.
            observed: Optional observed peer (ID string or Peer object). If not provided,
                defaults to the observer (self-reflection).
        omni)r   r   r   
dream_typer[   N)r   r#   r3   r]   r   workspace_schedule_dreamr-   )r=   r   r   r   r   r   resolved_observed_ids          r>   schedule_dreamzHoncho.schedule_dream0  s    * 	   )(33(11$,FJx   2F 	 	
+D,=>>001$	  	 	
 	
 	
 	
 	
rA   c                (    d| j          d| j         dS )z
        Return a string representation of the Honcho client.

        Returns:
            A string representation suitable for debugging
        zHoncho(workspace_id='z', base_url='z'))r-   r7   r<   s    r>   __repr__zHoncho.__repr__V  s%     WD$5VVDNVVV	
rA   c                    d| j          dS )z
        Return a human-readable string representation of the Honcho client.

        Returns:
            A string showing the workspace ID
        zHoncho Client (workspace: )rO   r<   s    r>   __str__zHoncho.__str__a  s     AD,=@@@@rA   )r:   r/   )r:   r1   )r:   r,   )r:   r5   )rQ   r5   r:   rR   )r:   r   )rC   r   r:   r_   )r:   r   )r:   r   )rn   ro   rp   rq   rd   ro   r-   ro   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r:   r_   )r:   r_   )rN   r,   r?   r/   rC   r   r:   r    rE   )r   r/   r:   r   )rN   r,   r?   r/   rC   r   r:   r"   )r   r/   r:   r   )r   r/   r:   r   )r-   r,   r:   r_   )r   r,   r   r/   r   r   r:   r   )NNN)r   r   r   r   r   r   r:   r   )NN)r   r   r   r   r   r   r:   r_   ).__name__
__module____qualname____doc__r   model_configr	   r-   __annotations__r
   r0   r2   r3   r4   r6   r7   r9   propertyr?   rC   rF   rI   rL   rP   rY   r^   r   rb   rd   rg   ri   r   r   r   r   r   r   r   rH   r   r   r   r   r   r   __classcell__)r   s   @r>   r'   r'   *   s          :G,,,L9  L    
 +6+d*C*C*CICCCC4?K4M4M4MNMMMM)kmmE++++0;D0I0I0IKIIII#.;==L0000 []]I""""*{59999999   X # # # X#
  # # # #3 3 3 3) ) ) )
 
 
 
# # # #  1631
 1
 1
, , , , ],$    X       X     X& ]**TBBBCCC #=A$uT7TUUU#(5Q,Q$
 $
 $
 !&dq>R S S S"'%Q$?#
 #
 #
 5959+052,
 ,
 ,
W5 W5 W5 W5 W5 W5 DCW5r' ' ' '' ' ' '  %A+K
 
 
%N .3U L.
 .
 .
 ,15{,
 ,
 ,
%N %N %N %N %N ]%NP 37#C #C #C #C #CJ  %A+N
 
 
&Q .3U R.
 .
 .
 6;U B6
 6
 6
&Q &Q &Q &Q &Q ]&QR 37#F #F #F #F #FL 37H H H H H<  "EA+J
 
 
: : : : ]:   U31:STTT,1E;-
 -
 -
 U12O
 
 
 
  
  
  
 ] 
D ]**TBBBCCC +/(,,0	8 8 8 8 DC8B ]**TBBBCCC -1*.	#
 #
 #
 #
 DC#
J	
 	
 	
 	
A A A A A A A ArA   r'   )4r   
__future__r   loggingr   collections.abcr   typingr   r   httpxpydanticr   r   r	   r
   r   ri   r   	api_typesr   r   r   r   r   r   r   r   baser   r   httpr   r   r   messager   mixinsr   
paginationr   r   r    r   r"   utilsr#   	getLoggerr   loggerr   r'   rf   rA   r>   <module>r      s     " " " " " "  				 # # # # # #          M M M M M M M M M M M M M M      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ( ' ' ' ' ' ' ' A A A A A A A A A A       ' ' ' ' ' '                              		8	$	$ %* ~A ~A ~A ~A ~AY+ ~A ~A ~A ~A ~ArA   