Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(service): add session status endpoint (#1984)
DavdGaod328f96044d9
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pyindex 810ccd6bf..54ee04199 100644--- a/src/agentscope/app/_router/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -49,6 +49,8 @@ from ._session import (UpdateSessionRequest,ListSessionsResponse,ListMessagesResponse,+ SessionStatus,+ SessionStatusResponse,SessionView,TeamDetailResponse,TeamMemberView,@@ -106,6 +108,8 @@ __all__ = ["UpdateSessionRequest","ListSessionsResponse","ListMessagesResponse",+ "SessionStatus",+ "SessionStatusResponse","SessionView","TeamDetailResponse","TeamMemberView",diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.pyindex 7146e0f7f..7eeba221f 100644--- a/src/agentscope/app/_router/_schema/_session.py+++ b/src/agentscope/app/_router/_schema/_session.py@@ -11,6 +11,7 @@ from ...storage import (SessionRecord,TeamRecord,)+from ..._service import SessionStatusclass TeamMemberView(BaseModel):@@ -186,3 +187,24 @@ class ListMessagesResponse(BaseModel):is_running: bool = Field(description="Whether the session is currently running.",)+++class SessionStatusResponse(BaseModel):+ """Response body for probing a session's high-level status.++ See :class:`~agentscope.app._service.SessionStatus` for the+ semantics of each ``status`` value and the precedence rules used+ to derive it.+ """++ session_id: str = Field(description="The session that was probed.")+ status: SessionStatus = Field(+ description=(+ "The session's unified status. One of ``running`` "+ "(some worker holds the run lease), ``idle`` (no worker, "+ "context clean), ``awaiting_permission`` (no worker, "+ "context parked on HITL tool call), or "+ "``awaiting_external_result`` (no worker, context parked "+ "on external executor)."+ ),+ )diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex cfa15ec36..951d9e783 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -19,6 +19,7 @@ from ._schema import (CreateSessionResponse,ListMessagesResponse,ListSessionsResponse,+ SessionStatusResponse,SessionView,TeamDetailResponse,TeamMemberView,@@ -467,6 +468,67 @@ async def list_messages()+# ----------------------------------------------------------------------+# Status probe: unified session status (cluster liveness + parking state)+# ----------------------------------------------------------------------+++@session_router.get(+ "/{session_id}/status",+ response_model=SessionStatusResponse,+ summary="Probe the session's high-level status",+)+async def get_session_status(+ session_id: str,+ agent_id: str = Query(description="Agent the session belongs to."),+ user_id: str = Depends(get_current_user_id),+ session_service: SessionService = Depends(get_session_service),+) -> SessionStatusResponse:+ """Return the unified :class:`SessionStatus` for a session.++ Ownership validation, cluster-liveness probing, and parked-state+ derivation are all delegated to+ :meth:`SessionService.get_session_status` — see that method for+ the precedence rules that collapse the two orthogonal signals+ (message-bus run lock + persisted context tail) into a single+ four-valued enum.++ Args:+ session_id (`str`):+ The session to probe.+ agent_id (`str`):+ The agent that owns the session (ownership validation).+ user_id (`str`):+ Injected authenticated user ID.+ session_service (`SessionService`):+ Injected session service. Owns both storage and message+ bus dependencies so the composed answer is derived in a+ single layer.++ Returns:+ `SessionStatusResponse`:+ The probed session id and its unified status.++ Raises:+ `HTTPException`: 404 if the session does not exist or does not+ belong to the authenticated user.+ """+ session_status = await session_service.get_session_status(+ user_id,+ agent_id,+ session_id,+ )+ if session_status is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Session '{session_id}' not found.",+ )+ return SessionStatusResponse(+ session_id=session_id,+ status=session_status,+ )++# ----------------------------------------------------------------------# Stream: live SSE connection for session events# ----------------------------------------------------------------------diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.pyindex a6a02c61e..03db5ec1d 100644--- a/src/agentscope/app/_service/__init__.py+++ b/src/agentscope/app/_service/__init__.py@@ -8,7 +8,7 @@ from ._index_worker import IndexWorkerfrom ._knowledge_base import KnowledgeBaseServicefrom ._model import get_modelfrom ._tts_model import get_tts_model-from ._session import SessionService+from ._session import SessionService, SessionStatusfrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjectorfrom ._toolkit import get_toolkit@@ -20,6 +20,7 @@ __all__ = ["IndexWorker","KnowledgeBaseService","SessionService",+ "SessionStatus","SessionProjection","SubagentHitlProjector","get_embedding_model",diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pyindex d364a48d5..3a67d7e85 100644--- a/src/agentscope/app/_service/_session.py+++ b/src/agentscope/app/_service/_session.py@@ -46,6 +46,7 @@ component that touches both in the same call. Storage code neverimports the bus; bus code never imports storage."""import asyncio+from enum import StrEnumfrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import StorageBase@@ -53,6 +54,44 @@ from ..storage._utils import _ensure_team_membersfrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjectorfrom ..._logging import logger+from ...message import ToolCallState+++class SessionStatus(StrEnum):+ """The high-level status of a session, unifying cluster liveness+ (from the message bus) with the durable tool-call parking state+ (from the persisted :class:`~agentscope.state.AgentState.context`).++ Exactly one value applies at any moment — the frontend renders a+ single indicator without having to reconcile multiple boolean+ flags.++ Precedence: ``RUNNING`` is decided first from the distributed+ session-run lock; only when the session is not held by any worker+ do the ``AWAITING_*`` / ``IDLE`` values (derived from the stored+ context tail) apply. This ordering reflects the ground-truth+ hierarchy — while a worker owns the run, the live in-memory state+ supersedes the persisted snapshot, which is by definition stale+ until the run yields.++ Values:+ - ``RUNNING``: a worker somewhere in the cluster currently+ holds the session's run lease on the message bus.+ - ``IDLE``: no worker is running the session, and its+ persisted context is not parked on any pending tool call.+ - ``AWAITING_PERMISSION``: no worker is running the session,+ and the persisted context tail has at least one tool call+ waiting for user permission confirmation (HITL).+ - ``AWAITING_EXTERNAL_RESULT``: no worker is running the+ session, and the persisted context tail has at least one+ tool call dispatched to an external executor and awaiting+ its result (with no peer awaiting permission).+ """++ RUNNING = "running"+ IDLE = "idle"+ AWAITING_PERMISSION = "awaiting_permission"+ AWAITING_EXTERNAL_RESULT = "awaiting_external_result"class SessionService:@@ -93,6 +132,116 @@ class SessionService:self._bus = message_busself._projection = SessionProjection(message_bus)+ # ------------------------------------------------------------------+ # Status+ # ------------------------------------------------------------------++ async def get_session_status(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> SessionStatus | None:+ """Return the unified :class:`SessionStatus` for a session.++ The status collapses two orthogonal signals into a single+ four-valued enum:++ - cluster liveness comes from the distributed session-run lock+ on the shared message bus (Redis in production) — the answer+ is cluster-wide, so any worker in the deployment holding the+ lease yields ``RUNNING`` regardless of which API replica+ serves the caller;+ - the parked state (``AWAITING_PERMISSION`` /+ ``AWAITING_EXTERNAL_RESULT`` / ``IDLE``) is derived from the+ persisted ``AgentState.context`` tail, and only applies when+ no worker owns the run.++ The ``RUNNING`` check is performed **before** loading the+ persisted context: while a worker owns the run, the live+ in-memory state supersedes the stored snapshot, and the parked+ derivation would be stale. This also saves a storage round-trip+ in the hot ``RUNNING`` case.++ .. note::+ The run lease auto-expires after+ ``MessageBusKeys.SESSION_RUN_TTL_SECS`` and is refreshed by+ the owning worker while it is actively producing events, so+ a crashed worker's session flips out of ``RUNNING`` on+ lease expiry.++ Args:+ user_id (`str`):+ The authenticated user id (ownership check).+ agent_id (`str`):+ The agent that owns the session (ownership check).+ session_id (`str`):+ The session to probe.++ Returns:+ `SessionStatus | None`:+ The unified status, or ``None`` if the session does+ not exist or is not owned by the user.+ """+ # RUNNING is checked first: while a worker owns the lease, the+ # persisted context is by definition a stale snapshot, and we+ # save a storage round-trip.+ if await self._bus.is_locked(+ MessageBusKeys.session_lock(session_id),+ ):+ return SessionStatus.RUNNING++ session = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ if session is None:+ return None++ return self._derive_parked_status(session.state.context)++ @staticmethod+ def _derive_parked_status(context: list) -> SessionStatus:+ """Derive the parked :class:`SessionStatus` from a persisted+ ``AgentState.context``.++ Only the tail assistant message is inspected — a paused reply+ can only park pending tool calls at the very end of the+ context. ``AWAITING_PERMISSION`` wins over+ ``AWAITING_EXTERNAL_RESULT`` when both appear on the tail: no+ submitted call can complete while a peer is still awaiting user+ confirmation, so the caller-visible status is dominated by the+ blocker.++ Callers must first ensure the session is not currently held by+ any worker (see :attr:`SessionStatus.RUNNING`) — while a worker+ owns the run, the live in-memory state supersedes the persisted+ snapshot and this function's answer is by definition stale.++ Args:+ context (`list[Msg]`):+ The persisted ``AgentState.context`` list.++ Returns:+ `SessionStatus`:+ One of ``AWAITING_PERMISSION``,+ ``AWAITING_EXTERNAL_RESULT``, or ``IDLE``.+ """+ if not context:+ return SessionStatus.IDLE+ last_msg = context[-1]+ if last_msg.role != "assistant":+ return SessionStatus.IDLE+ tool_calls = last_msg.get_content_blocks("tool_call")+ if not tool_calls:+ return SessionStatus.IDLE+ if any(tc.state == ToolCallState.ASKING for tc in tool_calls):+ return SessionStatus.AWAITING_PERMISSION+ if any(tc.state == ToolCallState.SUBMITTED for tc in tool_calls):+ return SessionStatus.AWAITING_EXTERNAL_RESULT+ return SessionStatus.IDLE+# ------------------------------------------------------------------# Cancel# ------------------------------------------------------------------