
    iԍ                       U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ  ej        e          Zd
ZdZdZ da!de"d<   d Z# ej$        e#           d Z% G d d          Z&dddddddg ddddddddddd gd!d"Z'd#d$ddd%ddg d&d'dd(d)gd!d"Z(d*d+ddg d,d-ddd.dd/d0gd!d"Z)d1d2ddd3ddg d4d5dd6d7gd!d"Z*d8d9ddd:ddd;ddd<ddd=ddd>dd?d@ddAdBddCdDgd!d"Z+dUdHZ,dVdLZ-dVdMZ.dVdNZ/dWdPZ0 G dQ dRe          Z1dXdTZ$dS )Yu9  OpenViking memory plugin — full bidirectional MemoryProvider interface.

Context database by Volcengine (ByteDance) that organizes agent knowledge
into a filesystem hierarchy (viking:// URIs) with tiered context loading,
automatic memory extraction, and session management.

Original PR #3369 by Mibayy, rewritten to use the full OpenViking session
lifecycle instead of read-only search endpoints.

Config via environment variables (profile-scoped via each profile's .env):
  OPENVIKING_ENDPOINT  — Server URL (default: http://127.0.0.1:1933)
  OPENVIKING_API_KEY   — API key (required for authenticated servers)
  OPENVIKING_ACCOUNT   — Tenant account (default: default)
  OPENVIKING_USER      — Tenant user (default: default)
  OPENVIKING_AGENT   — Tenant agent (default: hermes)

Capabilities:
  - Automatic memory extraction on session commit (6 categories)
  - Tiered context: L0 (~100 tokens), L1 (~2k), L2 (full)
  - Semantic search with hierarchical directory retrieval
  - Filesystem-style browsing via viking:// URIs
  - Resource ingestion (URLs, docs, code)
    )annotationsN)Path)AnyDictListOptional)urlparse)url2pathname)MemoryProvider)
tool_errorzhttp://127.0.0.1:1933g      >@)zhttp://zhttps://zgit@zssh://zgit://z$Optional['OpenVikingMemoryProvider']_last_active_providerc                 n    t           } | dS da 	 |                     g            dS # t          $ r Y dS w xY w)zAFire on_session_end for the last active provider on process exit.N)r   on_session_end	Exception)providers    G/home/piyush/.hermes/hermes-agent/plugins/memory/openviking/__init__.py_atexit_commit_sessionsr   ;   s[     %H #####   s   & 
44c                 2    	 ddl } | S # t          $ r Y dS w xY w)zLazy import httpx.r   N)httpxImportError)r   s    r   
_get_httpxr   O   s7       tts    
c                  b    e Zd ZdZ	 	 ddd	ZddZddZddZddZddZ	dd dZ
d!dZd"dZdS )#_VikingClientz-Thin HTTP client for the OpenViking REST API. endpointstrapi_keyaccountuseragentc                   |                     d          | _        || _        |pt          j                            dd          | _        |pt          j                            dd          | _        |pt          j                            dd          | _        t                      | _
        | j
        t          d          d S )N/OPENVIKING_ACCOUNTdefaultOPENVIKING_USEROPENVIKING_AGENThermesz3httpx is required for OpenViking: pip install httpx)rstrip	_endpoint_api_keyosenvironget_account_user_agentr   _httpxr   )selfr   r   r   r   r    s         r   __init__z_VikingClient.__init__[   s    !--R2:>>2F	#R#RIRZ^^,=yII
Krz~~.@(KK ll;STTT     returndictc                    d| j         d}| j        r| j        dk    r
| j        |d<   | j        r| j        dk    r
| j        |d<   | j        r| j        |d<   d| j        z   |d<   |S )	Nzapplication/json)Content-TypezX-OpenViking-Agentr$   zX-OpenViking-AccountzX-OpenViking-Userz	X-API-KeyzBearer Authorization)r0   r.   r/   r*   )r2   hs     r   _headersz_VikingClient._headersf   s     /"&+
 
 = 	6T]i77(,A$%: 	0$*	11%)ZA!"= 	;!]AkN!*T]!:Aor4   pathc                    | j          | S N)r)   )r2   r<   s     r   _urlz_VikingClient._urly   s    .($(((r4   c                Z    |                                  }|                    dd            |S )Nr8   )r;   pop)r2   headerss     r   _multipart_headersz _VikingClient._multipart_headers|   s(    --//ND)))r4   c                v   	 |                                 }n# t          $ r d }Y nw xY w|j        dk    rt          |t                    r|                    d          }t          |t                    rE|                    dd          }|                    d|j                  }t          | d|           |                    d          dk    rt          t          |                    |	                                 t          |t                    r|                    d          dk    r|                    d          }t          |t                    r@|                    dd          }|                    dd	          }t          | d|           t          t          |                    |i S |S )
Ni  errorcode
HTTP_ERRORmessagez: statusOPENVIKING_ERRORr   )
jsonr   status_code
isinstancer6   r-   textRuntimeErrorr   raise_for_status)r2   respdatarE   rF   rH   s         r   _parse_responsez_VikingClient._parse_response   s   	99;;DD 	 	 	DDD	 s""$%% 2))eT** = 99V\::D#ii	49==G&$';';'';';<<<88H%%00&s4yy111!!###dD!! 	*dhhx&8&8G&C&CHHW%%E%&& 9yy);<<))Ir22"d#7#7g#7#7888s4yy)))<Is    &&c                     | j         j        |                     |          f|                                 t          d|}|                     |          S )NrB   timeout)r1   r-   r?   r;   _TIMEOUTrS   )r2   r<   kwargsrQ   s       r   r-   z_VikingClient.get   sY    t{IIdOO
%)]]__h
 
JP
 
 ##D)))r4   Npayloadc                     | j         j        |                     |          f|pi |                                 t          d|}|                     |          S )N)rK   rB   rV   )r1   postr?   r;   rW   rS   )r2   r<   rY   rX   rQ   s        r   r[   z_VikingClient.post   sa    t{IIdOO
")-R
 
 &
 
 ##D)))r4   	file_pathr   c                   t          j        |j                  d         pd}|                    d          5 }| j                            |                     d          d|j        ||fi|                                 t                    }d d d            n# 1 swxY w Y   | 	                    |          }|
                    di           }|
                    dd	          }|st          d
          |S )Nr   zapplication/octet-streamrbz/api/v1/resources/temp_uploadfile)filesrB   rV   resulttemp_file_idr   z2OpenViking temp upload did not return temp_file_id)	mimetypes
guess_typenameopenr1   r[   r?   rC   rW   rS   r-   rO   )r2   r\   	mime_typefrQ   rR   ra   rb   s           r   upload_temp_filez_VikingClient.upload_temp_file   s+   (88;Y?Y	^^D!! 	Q;##		9::	9=>//11 	 $  D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ##D))(B''zz."55 	USTTTs   ABBBboolc                    	 | j                             |                     d          |                                 d          }|j        dk    S # t
          $ r Y dS w xY w)Nz/health      @rU      F)r1   r-   r?   r;   rL   r   )r2   rQ   s     r   healthz_VikingClient.health   sn    	;??		)$$dmmoos #  D #s** 	 	 	55	s   AA 
AA)r   r   r   r   )
r   r   r   r   r   r   r   r   r    r   )r5   r6   )r<   r   r5   r   )r<   r   r5   r6   r>   )r<   r   rY   r6   r5   r6   )r\   r   r5   r   r5   rj   )__name__
__module____qualname____doc__r3   r;   r?   rC   rS   r-   r[   ri   rn    r4   r   r   r   X   s        7757AC	U 	U 	U 	U 	U   &) ) ) )   
   :* * * ** * * * *         r4   r   viking_searchzSemantic search over the OpenViking knowledge base. Returns ranked results with viking:// URIs for deeper reading. Use mode='deep' for complex queries that need reasoning across multiple sources, 'fast' for simple lookups.objectstringzSearch query.)typedescription)autofastdeepzSearch depth (default: auto).)rx   enumry   zDViking URI prefix to scope search (e.g. 'viking://resources/docs/').integerzMax results (default: 10).)querymodescopelimitr   )rx   
propertiesrequired)re   ry   
parametersviking_readu   Read content at a viking:// URI. Three detail levels:
  abstract — ~100 token summary (L0)
  overview — ~2k token key points (L1)
  full — complete content (L2)
Start with abstract/overview, only use full when you need details.zviking:// URI to read.)abstractoverviewfullz!Detail level (default: overview).)urilevelr   viking_browseu   Browse the OpenViking knowledge store like a filesystem.
  list — show directory contents
  tree — show hierarchy
  stat — show metadata for a URItreeliststatzBrowse action.zaViking URI path (default: viking://). Examples: 'viking://resources/', 'viking://user/memories/'.)actionr<   r   viking_rememberzExplicitly store a fact or memory in the OpenViking knowledge base. Use for important information the agent should remember long-term. The system automatically categorizes and indexes the memory.zThe information to remember.)
preferenceentityeventcasepatternz)Memory category (default: auto-detected).)contentcategoryr   viking_add_resourcea  Add a remote URL or local file/directory to the OpenViking knowledge base. Remote resources must be public http(s), git, or ssh URLs. Local files are uploaded first using OpenViking temp_upload. The system automatically parses, indexes, and generates summaries.z/Remote URL or local file/directory path to add.z0Why this resource is relevant (improves search).z/Optional target viking:// URI for the resource.z6Optional parent viking:// URI. Cannot be used with to.z8Optional processing instruction for semantic extraction.booleanz+Whether to wait for processing to complete.numberz%Timeout in seconds when wait is true.)urlreasontoparentinstructionwaitrV   r   dir_pathr   r5   c                   t          t          j                              dt          j                    j         dz  }t          j        |dt          j                  5 }| 	                    d          D ]c}|
                                rMt          |                    |                                         dd          }|                    ||           d	 ddd           n# 1 swxY w Y   |S )	z8Create a temporary zip file containing a directory tree.openviking_upload_z.zipw*\r"   )arcnameN)r   tempfile
gettempdiruuiduuid4hexzipfileZipFileZIP_DEFLATEDrglobis_filer   relative_toreplacewrite)r   zip_pathzipfr\   r   s        r   _zip_directoryr   P  s   H'))**-X$*,,BR-X-X-XXH	3(<	=	= 7!,, 	7 	7I  "" 7i33H==>>FFtSQQ

9g
666	77 7 7 7 7 7 7 7 7 7 7 7 7 7 7
 Os   A:C%%C),C)valuer   rj   c                    t          |           dk    o/| d                                         o| d         dk    o	| d         dv S )N   r      :   )r"   r   )lenisalphar   s    r   _is_windows_absolute_pathr   [  sO    E

a 	$!H	$!HO	$ !H#	r4   c                6    |                      t                    S r>   )
startswith_REMOTE_RESOURCE_PREFIXESr   s    r   _is_remote_resource_sourcer   d  s    5666r4   c                    | rd| v sd| v rdS t          |           rdS t          |           rdS |                     d          pd| v pd| v S )N
FT)r"   z./z../z~/z.\z..\z~\r"   r   )r   r   r   r   s    r   _is_local_path_referencer   h  sx     DEMMTU]]u!%(( u '' tGHH 	%<	5=r4   
Path | strc                    t          |           }|j        dvrd|  S t          t          |j                                                            S )N)r   	localhostz Unsupported non-local file URI: )r	   netlocr   r
   r<   
expanduser)r   parseds     r   _path_from_file_urir   v  sM    c]]F}---7#777V[))**55777r4   c                      e Zd ZdZd Zed/d            Zd0dZd Zd1dZ	d/dZ
ddd2dZddd3dZddd4dZd5dZd6dZd7dZd8d Zd9d!Zed:d$            Zed;d&            Zd<d(Zd=d)Zd=d*Zd=d+Zd=d,Zd=d-Zd.S )>OpenVikingMemoryProviderz:Full bidirectional memory via OpenViking context database.c                    d | _         d| _        d| _        d| _        d| _        d | _        d| _        t          j                    | _	        d | _
        d S )Nr   r   )_clientr)   r*   _session_id_turn_count_sync_thread_prefetch_result	threadingLock_prefetch_lock_prefetch_threadr2   s    r   r3   z!OpenVikingMemoryProvider.__init__  sU    048< "'n..<@r4   r5   r   c                    dS )N
openvikingrt   r   s    r   re   zOpenVikingMemoryProvider.name  s    |r4   rj   c                Z    t          t          j                            d                    S )z=Check if OpenViking endpoint is configured. No network calls.OPENVIKING_ENDPOINT)rj   r+   r,   r-   r   s    r   is_availablez%OpenVikingMemoryProvider.is_available  s    BJNN#899:::r4   c           	     N    dddt           ddddddd	d
ddddddddddddddgS )Nr   zOpenViking server URLTr   )keyry   r   r$   env_varr   z3OpenViking API key (leave blank for local dev mode)OPENVIKING_API_KEY)r   ry   secretr   r   z[OpenViking tenant account ID ([default], used when local mode, OPENVIKING_API_KEY is empty)r$   r#   )r   ry   r$   r   r   zdOpenViking user ID within the account ([default], used when local mode, OPENVIKING_API_KEY is empty)r%   r    zMOpenViking agent ID within the account ([hermes], useful in multi-agent mode)r'   r&   )_DEFAULT_ENDPOINTr   s    r   get_config_schemaz*OpenVikingMemoryProvider.get_config_schema  s     "6 ,0  !T/	  !|$/	    F$,	  n#-	 5 
  	
r4   
session_idNonec                   t           j                            dt                    | _        t           j                            dd          | _        t           j                            dd          | _        t           j                            dd          | _        t           j                            dd          | _        || _	        d	| _
        	 t          | j        | j        | j        | j        | j        
          | _        | j                                        s't                              d| j                   d | _        n1# t           $ r$ t                              d           d | _        Y nw xY w| ad S )Nr   r   r   r#   r$   r%   r&   r'   r   r   r   r    z(OpenViking server at %s is not reachableu2   httpx not installed — OpenViking plugin disabled)r+   r,   r-   r   r)   r*   r.   r/   r0   r   r   r   r   rn   loggerwarningr   r   )r2   r   rX   s      r   
initializez#OpenVikingMemoryProvider.initialize  s:   (=?PQQ
';R@@
';YGGZ^^$5yAA
jnn%7BB%
	 (DJdk  DL <&&(( $I4>ZZZ# 	  	  	 NNOPPPDLLL	  !%s   A2E +E/.E/c                j   | j         sdS 	 | j                             dddi          }|                    dg           }t          |t                    rt	          |          nd}|dk    rdS d| j         d	S # t          $ r0}t                              d
|           d| j         dcY d }~S d }~ww xY w)Nr   /api/v1/fs/lsr   	viking://paramsra   r   z.# OpenViking Knowledge Base
Active. Endpoint: z
Use viking_search to find information, viking_read for details (abstract/overview/full), viking_browse to explore.
Use viking_remember to store facts, viking_add_resource to index URLs/docs.z)OpenViking system_prompt_block failed: %szU
Use viking_search, viking_read, viking_browse, viking_remember, viking_add_resource.)	r   r-   rM   r   r   r)   r   r   r   )r2   rQ   ra   childrenes        r   system_prompt_blockz,OpenVikingMemoryProvider.system_prompt_block  s   | 	2	<##OUK<P#QQDXXh++F&0&>&>Es6{{{AH1}}r^%)^^ ^ ^  	 	 	NNFJJJ8%)^8 8 8     	s$   A A8 -
A8 8
B2%B-'B2-B2r   )r   r   c                   | j         r4| j                                         r| j                             d           | j        5  | j        }d| _        ddd           n# 1 swxY w Y   |sdS d| S )z5Return prefetched results from the background thread.rl   rV   r   Nz## OpenViking Context
)r   is_alivejoinr   r   )r2   r   r   ra   s       r   prefetchz!OpenVikingMemoryProvider.prefetch  s      	4T%:%C%C%E%E 	4!&&s&333  	' 	'*F$&D!	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	'  	21111s   AA"%A"c                     j         rsdS  fd}t          j        |dd           _         j                                         dS )z6Fire a background search to pre-load relevant context.Nc                    	 t          j        j        j        j        j                  } |                     ddd          }|                    di           }g }dD ]}|                    |g           }|d d         D ]f}|                    dd	          }|                    d
d	          }|                    dd          }	|r |                    d|	dd| d| d           g|r<j	        5  d
                    |          _        d d d            d S # 1 swxY w Y   d S d S # t          $ r&}
t                              d|
           Y d }
~
d S d }
~
ww xY w)Nr   /api/v1/search/find   )r   top_kra   )memories	resourcesr   r   r   r   scorer   z- [z.2f] z ()r   zOpenViking prefetch failed: %s)r   r)   r*   r.   r/   r0   r[   r-   appendr   r   r   r   r   debug)clientrQ   ra   partsctx_typeitemsitemr   r   r  r   r   r2   s              r   _runz5OpenVikingMemoryProvider.queue_prefetch.<locals>._run  s$   B&NDM M
$+   {{#8"; ;   (B// 9 P PH"JJx44E %bqb	 P P"hhub11#'88J#;#; $! 4 4# P!LL)Nu)N)N)NH)N)N)N)N)NOOOP  A, A A04		%0@0@-A A A A A A A A A A A A A A A A A AA A  B B B=qAAAAAAAAABs<   C3D- 6DD- D""D- %D"&D- -
E7EETzopenviking-prefetchtargetdaemonre   )r   r   Threadr   start)r2   r   r   r  s   ``  r   queue_prefetchz'OpenVikingMemoryProvider.queue_prefetch  s    | 	5 	F	B 	B 	B 	B 	B 	B4 !* 0+@!
 !
 !
 	##%%%%%r4   user_contentassistant_contentc               ,     j         sdS  xj        dz  c_         fd} j        r4 j                                        r j                            d           t          j        |dd           _         j                                         dS )	zDRecord the conversation turn in OpenViking's session (non-blocking).Nr   c                 l   	 t          j        j        j        j        j                  } j        }|                     d| ddd d         d           |                     d| ddd d         d           d S # t          $ r&}t          
                    d|           Y d }~d S d }~ww xY w)	Nr   /api/v1/sessions/	/messagesr     )roler   	assistantzOpenViking sync_turn failed: %s)r   r)   r*   r.   r/   r0   r   r[   r   r   r  )r  sidr   r  r2   r  s      r   _syncz1OpenVikingMemoryProvider.sync_turn.<locals>._sync$  s   C&NDM M
$+   & >>>>"+ETE2A A   
 >>>>'0$7A A       C C C>BBBBBBBBBCs   A>B 
B3B..B3      @r   Tzopenviking-syncr  )r   r   r   r   r   r   r  r  )r2   r  r  r   r"  s   ```  r   	sync_turnz"OpenVikingMemoryProvider.sync_turn  s    | 	FA	C 	C 	C 	C 	C 	C 	C,  	0!2!;!;!=!= 	0""3"///%,,=
 
 
 	!!!!!r4   messagesList[Dict[str, Any]]c                   | j         sdS | j        r4| j                                        r| j                            d           | j        dk    rdS 	 | j                             d| j         d           t                              d| j        | j                   dS # t          $ r&}t          
                    d|           Y d}~dS d}~ww xY w)	zCommit the session to trigger memory extraction.

        OpenViking automatically extracts 6 categories of memories:
        profile, preferences, entities, events, cases, and patterns.
        Ng      $@r   r   r  z/commitz*OpenViking session %s committed (%d turns)z$OpenViking session commit failed: %s)r   r   r   r   r   r[   r   r   infor   r   )r2   r%  r   s      r   r   z'OpenVikingMemoryProvider.on_session_endB  s     | 	F
  	1!2!;!;!=!= 	1""4"000q  F	FLK$2BKKKLLLKKDdFVX\Xhiiiii 	F 	F 	FNNA1EEEEEEEEE	Fs   A	B 
C(C		Cr   r  r   c                      j         r|dk    ssdS  fd}t          j        |dd          }|                                 dS )zAMirror built-in memory writes to OpenViking as explicit memories.addNc            	     "   	 t          j        j        j        j        j                  } |                     dj         dddd d dgd	           d S # t          $ r&}t          
                    d
|           Y d }~d S d }~ww xY w)Nr   r  r  r   rN   u   [Memory note — r  rx   rN   r  r  z#OpenViking memory mirror failed: %s)r   r)   r*   r.   r/   r0   r[   r   r   r   r  )r  r   r   r2   r  s     r   _writez8OpenVikingMemoryProvider.on_memory_write.<locals>._write_  s    G&NDM M
$+   K0@KKK"!'1XV1X1Xw1X1XYYN N       G G GBAFFFFFFFFFGs   AA 
B(B		BTzopenviking-memwriter  )r   r   r  r  )r2   r   r  r   r.  ts   ` ``  r   on_memory_writez(OpenVikingMemoryProvider.on_memory_writeZ  su    | 	vgF	G 	G 	G 	G 	G 	G 	G" F4>STTT						r4   c                B    t           t          t          t          t          gS r>   )SEARCH_SCHEMAREAD_SCHEMABROWSE_SCHEMAREMEMBER_SCHEMAADD_RESOURCE_SCHEMAr   s    r   get_tool_schemasz)OpenVikingMemoryProvider.get_tool_schemass  s    {M?L_``r4   	tool_nameargsr6   c                   | j         st          d          S 	 |dk    r|                     |          S |dk    r|                     |          S |dk    r|                     |          S |dk    r|                     |          S |dk    r|                     |          S t          d|           S # t          $ r&}t          t          |                    cY d }~S d }~ww xY w)NzOpenViking server not connectedru   r   r   r   r   zUnknown tool: )	r   r   _tool_search
_tool_read_tool_browse_tool_remember_tool_add_resourcer   r   )r2   r8  r9  rX   r   s        r   handle_tool_callz)OpenVikingMemoryProvider.handle_tool_callv  s   | 	A?@@@	&O++((...m++t,,,o--((...///**4000333..t444:y::;;; 	& 	& 	&c!ff%%%%%%%%	&s:   B1 B1 B1 )B1 B1 B1 1
C!;CC!C!c                    | j         | j        fD ].}|r*|                                r|                    d           /t          | u rd ad S d S )Nr#  r   )r   r   r   r   r   )r2   r/  s     r   shutdownz!OpenVikingMemoryProvider.shutdown  si    #T%:; 	$ 	$A $QZZ\\ $s### !D(($(!!! )(r4   rQ   r   c                b    t          | t                    rd| v r|                     d          S | S )zEReturn OpenViking payload body regardless of wrapped/unwrapped shape.ra   )rM   r6   r-   )rQ   s    r   _unwrap_resultz'OpenVikingMemoryProvider._unwrap_result  s7     dD!! 	&h$&6&688H%%%r4   r   c                z    | s| S dD ]3}|                      |          r| dt          |                    pdc S 4| S )zGMap pseudo summary files to their parent directory URI for L0/L1 reads.)z/.abstract.mdz/.overview.mdz	/.read.mdz	/.full.mdNr   )endswithr   )r   suffixs     r   _normalize_summary_uriz/OpenVikingMemoryProvider._normalize_summary_uri  s`      	JR 	: 	:F||F## :>c&kk\>*9k999:
r4   bool | Nonec                   	 | j                             dd|i          }n# t          $ r Y dS w xY w|                     |          }t	          |t
                    rd|v r"t          |                    d                    S d|v r"t          |                    d                    S |                    d          dk    rd	S |                    d          d
k    rdS dS )a   Probe fs/stat to decide if a URI is a directory.

        Returns True/False when the server answers cleanly, and None when the
        probe itself fails (network error, unexpected shape). Callers should
        treat None as "unknown" and fall back to the exception-based path.
        /api/v1/fs/statr   r   NisDiris_dirrx   dirTr_   F)r   r-   r   rD  rM   r6   rj   )r2   r   rQ   ra   s       r   _is_directory_uriz*OpenVikingMemoryProvider._is_directory_uri  s    	<##$5ucl#KKDD 	 	 	44	$$T**fd## 	&  FJJw//0006!!FJJx00111zz&!!U**tzz&!!V++uts   ! 
//c           	        |                     dd          }|st          d          S d|i}|                     dd          }|dk    r||d<   |                     d          r|d         |d<   |                     d          r|d         |d	<   | j                            d
|          }|                     di           }g }dD ]}|                     |g           }	|	D ]}
|
                     d          }||nd}|
                     dd          |                    d          |t          |d          nd|
                     dd          d}|
                     d          rd |
d         d d         D             |d<   |                    ||f           |                    d d           d |D             }t          j	        ||                     dt          |                    dd          S )Nr   r   zquery is requiredr   rz   r   
target_urir   r  r  ra   )r  r  skillsr  g        r   sr   r   )r   rx   r  r   	relationsc                8    g | ]}|                     d           S )r   )r-   ).0rs     r   
<listcomp>z9OpenVikingMemoryProvider._tool_search.<locals>.<listcomp>  s"    'T'T'Te'T'T'Tr4   relatedc                    | d         S )Nr   rt   )xs    r   <lambda>z7OpenVikingMemoryProvider._tool_search.<locals>.<lambda>  s
    !A$ r4   T)r   reversec                    g | ]\  }}|S rt   rt   )rV  _entrys      r   rX  z9OpenVikingMemoryProvider._tool_search.<locals>.<listcomp>  s    :::xq%U:::r4   total)resultsra  Fensure_ascii)r-   r   r   r[   r(   roundr
  sortrK   dumpsr   )r2   r9  r   rY   r   rQ   ra   scored_entriesr  r  r  	raw_score
sort_scorer`  	formatteds                  r   r;  z%OpenVikingMemoryProvider._tool_search  sH   "%% 	31222#*E"2xx''6>>"GFO88G 	2$(MGL!88G 	-#G}GG|  !6@@(B'' ; 	; 	;HJJx,,E ; ; HHW--	*3*?YYS
88E2..$OOC004=4IU9a000s $R 8 8	  88K(( U'T'Td;>OPRQRPR>S'T'T'TE)$%%z5&9::::; 	===::>:::	z ZZY88
 
    	r4   c                t   |                     dd          }|st          d          S |                     dd          }|dv }|r|                     |          n|}d}|r#||k    r|                     |          }|du r|}d}d	}|s|d
k    rd}n|dk    rd}	 | j                             |d|i          }	n;# t
          $ r. |r||k    s|r | j                             d	d|i          }	d}Y nw xY w|                     |	          }
t          |
t                    r|
}nDt          |
t                    r-|
                     dd          p|
                     dd          }nd}d}|dk    rd}n|d
k    rd}t          |          |k    r|d |         dz   }||||d}|rd|d<   t          j        |d          S )Nr   r   zuri is requiredr   r   )r   r   FTz/api/v1/content/readr   z/api/v1/content/abstractz/api/v1/content/overviewr   r   rN   i@  r  i  z8

[... truncated, use a more specific URI or full level])r   resolved_urir   r   zcontent/readfallbackrc  )r-   r   rH  rO  r   r   rD  rM   r   r6   r   rK   rg  )r2   r9  r   r   summary_levelrm  used_fallbackrM  r   rQ   ra   r   max_lenrY   s                 r   r<  z#OpenVikingMemoryProvider._tool_read  s]   hhub!! 	1/000*--!99 <IQt223777c  	%\S00++C00F" $ * 	6
""5*$$5	!<##He\5J#KKDD 	! 	! 	! ! LC$7$7=$7<##$:E3<#PPD MMM	! $$T**fc"" 	GG%% 	jjB//I6::fb3I3IGGG JGGj  Gw<<'!!hwh'*ffG (	
 
  	1"0GJz'6666s   B7 75C/.C/c           
        |                     dd          }|                     dd          }dddd}|                     |d          }| j                             |d	|i
          }|                     |          }|dv rx|}t          |t                    rA|                     d          p+|                     d          p|                     d          pg }t          |t
                    r
g }	|d d         D ]}
|
                     d	d          }|
                     d          p4|
                     d          p|r|                    dd          d         nd}t          |
                     d          p-|
                     d          p|
                     d          dk              }|	                    |||rdnd|
                     dd          d           t          j
        ||	dd          S t          j
        |d          S ) Nr   r   r<   r   z/api/v1/fs/treer   rK  r   r   r   )r   r   entriesr  r   2   r   rel_pathre   r"   r   rL  rM  rx   rN  r_   r   )re   r   rx   r   )r<   rs  Frc  )r-   r   rD  rM   r6   r   rsplitrj   r
  rK   rg  )r2   r9  r   r<   endpoint_mapr   rQ   ra   raw_entriesrs  r   r   re   rM  s                 r   r=  z%OpenVikingMemoryProvider._tool_browse0  s!   (F++xx,, !2?Teff##FO<<|%??$$T** %%% K&$'' k$jj33jvzz'7J7JjfjjYcNdNdjhj+t,, Z$SbS) 	 	A%%r**C55,,hfh\_Bg#**SRSBTBTUWBXBXegD!!%%.."]AEE(OO"]quuV}}X]G]^^FNN $")/ ;V$%EE*b$9$9	$ $     z4G"D"DSXYYYYz&u5555r4   c                   |                     dd          }|st          d          S |                     dd          }d| }|rd| d| }| j                            d| j         d	d
d|dgd           t          j        ddd          S )Nr   r   zcontent is requiredr   z[Remember] u   [Remember — r  r  r  r   rN   r,  r-  storedzAMemory recorded. Will be extracted and indexed on session commit.)rI   rH   )r-   r   r   r[   r   rK   rg  )r2   r9  r   r   rN   s        r   r>  z'OpenVikingMemoryProvider._tool_rememberP  s    ((9b)) 	53444 88J++&W&& 	:9H9999DId.>III..L
 L
 	 	 	 zZ
 
   	r4   c                R   |                     dd          }|st          d          S |                     d          r$|                     d          rt          d          S i }dD ]}||v r||         dvr||         ||<   t          |          }t          |          rd }ny|j        d	k    r4t          |          }t          |t                    rt          |          S n:|j        rt          |          sd }n!t          |          
                                }d }	 ||                                r|                                r|j        |d
<   t          |          }|}nL|                                r|j        |d
<   |}n+t          d|           |r|                    d           S S | j                            |          |d<   nEt'          |          r+t          d|           |r|                    d           S S ||d<   n||d<   | j                            d|          }	|	                     di           }
|r|                    d           n# |r|                    d           w w xY wt+          j        d|
                     dd          ddd          S )Nr   r   zurl is requiredr   r   z%Cannot specify both 'to' and 'parent')r   r   r   r   r   rV   )Nr   r_   source_namez!Unsupported local resource path: T)
missing_okrb   z$Local resource path does not exist: r<   z/api/v1/resourcesra   addedroot_urizLResource queued for processing. Use viking_search after a moment to find it.)rI   r  rH   Frc  )r-   r   r	   r   schemer   rM   r   r   r   r   existsrM  re   r   r   unlinkr   ri   r   r[   rK   rg  )r2   r9  r   rY   r   
parsed_urlsource_pathcleanup_pathupload_pathrQ   ra   s              r   r?  z+OpenVikingMemoryProvider._tool_add_resourceh  s1   hhub!! 	1/00088D>> 	Gdhhx00 	GEFFF"$O 	) 	)Cd{{tCy
::#Cyc]]
%c** 		1KK&((-c22K+s++ /!+.../ 	1'@'E'E 	1KKs))..00K'+	5&%%'' *"))++ U1<1A.'5k'B'B&2$,,.. U1<1A.&1)*Sc*S*STT  5##t#44445 /3l.K.KK.X.XGN++-c22 *%&RS&R&RSS  5##t#44445 '*GFOO"%<$$%8'BBDXXh++F 5##t#444  5##t#44445 z

:r22e
 
 	   	s   A8I 0>I <I I8N)r5   r   ro   )r   r   r5   r   )r   r   r   r   r5   r   )r   r   r   r   r5   r   )r  r   r  r   r   r   r5   r   )r%  r&  r5   r   )r   r   r  r   r   r   r5   r   )r5   r&  )r8  r   r9  r6   r5   r   r5   r   )rQ   r   r5   r   )r   r   r5   r   )r   r   r5   rI  )r9  r6   r5   r   )rp   rq   rr   rs   r3   propertyre   r   r   r   r   r   r  r$  r   r0  r7  r@  rB  staticmethodrD  rH  rO  r;  r<  r=  r>  r?  rt   r4   r   r   r     s1       DD	A 	A 	A    X; ; ; ;!
 !
 !
F% % % %2   6 9; 	2 	2 	2 	2 	2 	2 ?A "& "& "& "& "& "&H Y[ #" #" #" #" #" #"JF F F F0   2a a a a& & & &&) ) ) )    \    \   .( ( ( (TG7 G7 G7 G7R6 6 6 6@   08 8 8 8 8 8r4   r   r   c                H    |                      t                                 dS )z0Register OpenViking as a memory provider plugin.N)register_memory_providerr   )ctxs    r   registerr    s#      !9!;!;<<<<<r4   )r   r   r5   r   )r   r   r5   rj   )r   r   r5   r   r  )2rs   
__future__r   atexitrK   loggingrc   r+   r   r   r   r   pathlibr   typingr   r   r   r   urllib.parser	   urllib.requestr
   agent.memory_providerr   tools.registryr   	getLoggerrp   r   r   rW   r   r   __annotations__r   r  r   r   r2  r3  r4  r5  r6  r   r   r   r   r   r   rt   r4   r   <module>r     s    0 # " " " " "        				              , , , , , , , , , , , , ! ! ! ! ! ! ' ' ' ' ' ' 0 0 0 0 0 0 % % % % % %		8	$	$+ O  ?C  B B B B
 
 
 ' ( ( (  j j j j j j j jd 	7 &GG *B*B*B> 
 !e  (8TUU
 
 I  6 	M $5MNN *J*J*JB 
 
 G
 
 . 	-  !*B*B*B/ 
 !  C 	
 	
 J  2 	G
  (9WXX LLLJ 
 
 K  , "	M $5fgg Q 
 !P 
 !W 
 !Y 
 "L 
 !F -
 
6 G; ' ' T      7 7 7 7   8 8 8 8_ _ _ _ _~ _ _ _L= = = = = =r4   