Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: expose session(must_exist) and session_exists() on public API (#321)

ponsde094005377972
diff --git a/openviking/async_client.py b/openviking/async_client.py
index ce69b65c6..f351a6cc3 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -94,14 +94,29 @@ class AsyncOpenViking:
# ============= Session methods =============
- def session(self, session_id: Optional[str] = None) -> Session:
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Session:
"""
Create a new session or load an existing one.
Args:
session_id: Session ID, creates a new session (auto-generated ID) if None
+ must_exist: If True and session_id is provided, raises NotFoundError
+ when the session does not exist.
+ If session_id is None, must_exist is ignored.
"""
- return self._client.session(session_id)
+ return self._client.session(session_id, must_exist=must_exist)
+
+ async def session_exists(self, session_id: str) -> bool:
+ """Check whether a session exists in storage.
+
+ Args:
+ session_id: Session ID to check
+
+ Returns:
+ True if the session exists, False otherwise
+ """
+ await self._ensure_initialized()
+ return await self._client.session_exists(session_id)
async def create_session(self) -> Dict[str, Any]:
"""Create a new session."""
diff --git a/openviking/client/local.py b/openviking/client/local.py
index b5ff6ef70..1e24757be 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -11,6 +11,7 @@ from openviking.server.identity import RequestContext, Role
from openviking.service import OpenVikingService
from openviking_cli.client.base import BaseClient
from openviking_cli.session.user_id import UserIdentifier
+from openviking_cli.utils import run_async
class LocalClient(BaseClient):
@@ -327,24 +328,40 @@ class LocalClient(BaseClient):
"""Check service health."""
return True # Local service is always healthy if initialized
- def session(self, session_id: Optional[str] = None) -> Any:
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
"""Create a new session or load an existing one.
Args:
session_id: Session ID, creates a new session if None
+ must_exist: If True and session_id is provided, raises NotFoundError
+ when the session does not exist.
+ If session_id is None, must_exist is ignored.
Returns:
Session object
+
+ Raises:
+ NotFoundError: If must_exist=True and the session does not exist.
"""
- from openviking.session import Session
-
- return Session(
- viking_fs=self._service.viking_fs,
- vikingdb_manager=self._service.vikingdb_manager,
- session_compressor=self._service.session_compressor,
- user=self._user,
- session_id=session_id,
- )
+ session = self._service.sessions.session(self._ctx, session_id)
+ if must_exist and session_id:
+ if not run_async(session.exists()):
+ from openviking_cli.exceptions import NotFoundError
+
+ raise NotFoundError(session_id, "session")
+ return session
+
+ async def session_exists(self, session_id: str) -> bool:
+ """Check whether a session exists in storage.
+
+ Args:
+ session_id: Session ID to check
+
+ Returns:
+ True if the session exists, False otherwise
+ """
+ session = self._service.sessions.session(self._ctx, session_id)
+ return await session.exists()
def get_status(self) -> Any:
"""Get system status.
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index c440e9d73..9e58eb2af 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -28,9 +28,13 @@ class SyncOpenViking:
run_async(self._async_client.initialize())
self._initialized = True
- def session(self, session_id: Optional[str] = None) -> "Session":
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> "Session":
"""Create new session or load existing session."""
- return self._async_client.session(session_id)
+ return self._async_client.session(session_id, must_exist=must_exist)
+
+ def session_exists(self, session_id: str) -> bool:
+ """Check whether a session exists in storage."""
+ return run_async(self._async_client.session_exists(session_id))
def create_session(self) -> Dict[str, Any]:
"""Create a new session."""
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 4520e8691..3bb877a5c 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -251,14 +251,33 @@ class BaseClient(ABC):
...
@abstractmethod
- def session(self, session_id: Optional[str] = None) -> Any:
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
"""Create a new session or load an existing one.
Args:
session_id: Session ID, creates a new session if None
+ must_exist: If True and session_id is provided, raises NotFoundError
+ when the session does not exist instead of silently
+ returning a fresh empty session.
+ If session_id is None, must_exist is ignored.
Returns:
Session object
+
+ Raises:
+ NotFoundError: If must_exist=True and the session does not exist.
+ """
+ ...
+
+ @abstractmethod
+ async def session_exists(self, session_id: str) -> bool:
+ """Check whether a session exists in storage.
+
+ Args:
+ session_id: Session ID to check
+
+ Returns:
+ True if the session exists, False otherwise
"""
...
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index f468e6f6f..e3cad61e1 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -783,22 +783,46 @@ class AsyncHTTPClient(BaseClient):
# ============= New methods for BaseClient interface =============
- def session(self, session_id: Optional[str] = None) -> Any:
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
"""Create a new session or load an existing one.
Args:
session_id: Session ID, creates a new session if None
+ must_exist: If True and session_id is provided, raises NotFoundError
+ when the session does not exist.
+ If session_id is None, must_exist is ignored.
Returns:
Session object
+
+ Raises:
+ NotFoundError: If must_exist=True and the session does not exist.
"""
from openviking.client.session import Session
if not session_id:
result = run_async(self.create_session())
session_id = result.get("session_id", "")
+ elif must_exist:
+ # get_session() raises NotFoundError (via _handle_response) for 404.
+ run_async(self.get_session(session_id))
return Session(self, session_id, self._user)
+ async def session_exists(self, session_id: str) -> bool:
+ """Check whether a session exists in storage.
+
+ Args:
+ session_id: Session ID to check
+
+ Returns:
+ True if the session exists, False otherwise
+ """
+ try:
+ await self.get_session(session_id)
+ return True
+ except NotFoundError:
+ return False
+
def get_status(self) -> Dict[str, Any]:
"""Get system status.
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index 1629f4fb6..d9b329c84 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -53,9 +53,22 @@ class SyncHTTPClient:
# ============= session =============
- def session(self, session_id: Optional[str] = None) -> Any:
- """Create new session or load existing session."""
- return self._async_client.session(session_id)
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
+ """Create a new session or load an existing one.
+
+ Args:
+ session_id: Session ID, creates a new session if None
+ must_exist: If True and session_id is provided, raises NotFoundError
+ when the session does not exist.
+
+ Returns:
+ Session object
+ """
+ return self._async_client.session(session_id, must_exist=must_exist)
+
+ def session_exists(self, session_id: str) -> bool:
+ """Check whether a session exists in storage."""
+ return run_async(self._async_client.session_exists(session_id))
def create_session(self) -> Dict[str, Any]:
"""Create a new session."""
diff --git a/tests/session/test_session_lifecycle.py b/tests/session/test_session_lifecycle.py
index 1f8e827c0..a3258ef1b 100644
--- a/tests/session/test_session_lifecycle.py
+++ b/tests/session/test_session_lifecycle.py
@@ -70,3 +70,51 @@ class TestSessionLoad:
assert hasattr(session, "uri")
assert hasattr(session, "messages")
assert hasattr(session, "session_id")
+
+
+class TestSessionMustExist:
+ """Test session(must_exist=True) raises when session does not exist."""
+
+ async def test_must_exist_raises_for_nonexistent(self, client: AsyncOpenViking):
+ """must_exist=True should raise NotFoundError for an unknown session_id."""
+ import pytest
+
+ from openviking_cli.exceptions import NotFoundError
+
+ with pytest.raises(NotFoundError):
+ client.session(session_id="definitely_not_a_real_session", must_exist=True)
+
+ async def test_must_exist_succeeds_after_create(self, client: AsyncOpenViking):
+ """must_exist=True should succeed for a session created via create_session()."""
+ result = await client.create_session()
+ existing_id = result["session_id"]
+
+ session = client.session(session_id=existing_id, must_exist=True)
+ assert session.session_id == existing_id
+
+ async def test_must_exist_false_default_accepts_unknown_id(self, client: AsyncOpenViking):
+ """Default must_exist=False should silently accept any session_id (backward compat)."""
+ session = client.session(session_id="fabricated_id_abc")
+ await session.load()
+ assert session.session_id == "fabricated_id_abc"
+
+
+class TestSessionExists:
+ """Test session_exists() convenience method."""
+
+ async def test_session_exists_true_after_create(self, client: AsyncOpenViking):
+ """session_exists() should return True for a created session."""
+ result = await client.create_session()
+ session_id = result["session_id"]
+
+ assert await client.session_exists(session_id) is True
+
+ async def test_session_exists_false_for_unknown(self, client: AsyncOpenViking):
+ """session_exists() should return False for an unknown session_id."""
+ assert await client.session_exists("definitely_not_a_real_session") is False
+
+ async def test_session_exists_true_after_add_message(
+ self, session_with_messages: Session, client: AsyncOpenViking
+ ):
+ """session_exists() should return True for a session that has messages."""
+ assert await client.session_exists(session_with_messages.session_id) is True