Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(app): standard operating procedures at the service layer (#2617)
DavdGao9298a3728fd3
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex 4b4d5ea03..6cd0ae7a3 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -24,6 +24,7 @@ from ._router import (schedule_router,session_router,skill_router,+ sop_router,workspace_router,)from ._types import AgentMiddlewareFactory, AgentToolFactory, SubAgentTemplate@@ -396,6 +397,7 @@ def create_app(schedule_router,session_router,skill_router,+ sop_router,workspace_router,model_router,tts_model_router,diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.pyindex 779e08c83..3b9e2e866 100644--- a/src/agentscope/app/_lifespan.py+++ b/src/agentscope/app/_lifespan.py@@ -22,6 +22,7 @@ from ._service import (KnowledgeBaseService,ResourceAccessService,SessionService,+ SOPService,WorkspaceService,)@@ -183,6 +184,20 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:workspace_manager=workspace_manager,)+ # On the stack so its detached advances stop before storage closes.+ sop_service = await stack.enter_async_context(+ SOPService(+ storage=storage,+ workspace_manager=workspace_manager,+ message_bus=message_bus,+ chat=chat_service,+ session_service=app.state.session_service,+ ),+ )+ app.state.sop_service = sop_service+ # So a turn resuming a step carries its run on.+ chat_service.sop_service = sop_service+app.state.workspace_service = WorkspaceService(storage=storage,workspace_manager=workspace_manager,diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.pyindex 5444501d9..ca07e67b7 100644--- a/src/agentscope/app/_router/__init__.py+++ b/src/agentscope/app/_router/__init__.py@@ -12,6 +12,7 @@ from ._mcp import mcp_routerfrom ._schedule import schedule_routerfrom ._session import session_routerfrom ._skill import skill_router+from ._sop import sop_routerfrom ._model import model_routerfrom ._tts_model import tts_model_routerfrom ._workspace import workspace_router@@ -31,5 +32,6 @@ __all__ = ["schedule_router","session_router","skill_router",+ "sop_router","workspace_router",]diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pyindex 5bb04b786..7f5232bf4 100644--- a/src/agentscope/app/_router/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -40,6 +40,16 @@ from ._schedule import (ScheduleSessionsResponse,UpdateScheduleRequest,)+from ._sop import (+ CreateSOPRequest,+ CreateSOPResponse,+ ListSOPRunsResponse,+ ListSOPsResponse,+ SOPSchemaResponse,+ StartSOPRunRequest,+ SubmitVerdictRequest,+ UpdateSOPRequest,+)from ._agent import (AgentSchemaResponse,AgentSchemaV2Response,@@ -110,6 +120,14 @@ __all__ = ["MCPClientStatus","ToolInfo",# Agent+ "CreateSOPRequest",+ "CreateSOPResponse",+ "ListSOPRunsResponse",+ "ListSOPsResponse",+ "SOPSchemaResponse",+ "StartSOPRunRequest",+ "SubmitVerdictRequest",+ "UpdateSOPRequest","AgentSchemaResponse","AgentSchemaV2Response","ListAgentsResponse",diff --git a/src/agentscope/app/_router/_schema/_sop.py b/src/agentscope/app/_router/_schema/_sop.pynew file mode 100644index 000000000..1781b549e--- /dev/null+++ b/src/agentscope/app/_router/_schema/_sop.py@@ -0,0 +1,70 @@+# -*- coding: utf-8 -*-+"""Request / response schemas for the SOP router."""+from pydantic import BaseModel, Field++from ...storage import SOPData, SOPRecord, SOPRunRecord+from ....message import Msg+++class SOPSchemaResponse(BaseModel):+ """The JSON Schema a procedure's editor is built from."""++ schema_: dict = Field(+ alias="schema",+ description="JSON Schema of ``SOPData``, ``$defs`` included.",+ )+++class CreateSOPRequest(BaseModel):+ """Request body for creating a procedure."""++ data: SOPData = Field(description="The procedure to store.")+++class CreateSOPResponse(BaseModel):+ """Response body after creating a procedure."""++ sop_id: str = Field(description="Server-assigned procedure identifier.")+++class UpdateSOPRequest(BaseModel):+ """Request body for replacing a procedure's contents."""++ data: SOPData = Field(description="The procedure as it should now read.")+++class ListSOPsResponse(BaseModel):+ """Response body listing the caller's procedures."""++ sops: list[SOPRecord] = Field(description="The procedures.")+ total: int = Field(description="How many there are.")+++class StartSOPRunRequest(BaseModel):+ """Request body for starting a run."""++ inputs: list[Msg] = Field(+ default_factory=list,+ description="What the run is started with, read by its first step.",+ )+++class ListSOPRunsResponse(BaseModel):+ """Response body listing runs."""++ runs: list[SOPRunRecord] = Field(description="The runs, newest first.")+ total: int = Field(description="How many were returned.")+++class SubmitVerdictRequest(BaseModel):+ """Request body for a person's verdict on a step."""++ step_index: int = Field(+ ge=0,+ description="Which step is being judged, by its position.",+ )+ passed: bool = Field(description="Whether the attempt is accepted.")+ message: str = Field(+ default="",+ description="Why it was refused, handed to the author verbatim.",+ )diff --git a/src/agentscope/app/_router/_sop.py b/src/agentscope/app/_router/_sop.pynew file mode 100644index 000000000..01b838c19--- /dev/null+++ b/src/agentscope/app/_router/_sop.py@@ -0,0 +1,454 @@+# -*- coding: utf-8 -*-+"""SOP router — procedures, their runs, and the verdicts people file.++A tool call parked in a step's session is answered through ``POST /chat``+like any other; answering either kind is what carries the run on.+"""+from fastapi import APIRouter, Depends, HTTPException, Query, status++from ..deps import (+ get_current_user_id,+ get_sop_service,+ get_storage,+)+from ._schema import (+ CreateSOPRequest,+ CreateSOPResponse,+ ListSOPRunsResponse,+ ListSOPsResponse,+ SOPSchemaResponse,+ StartSOPRunRequest,+ SubmitVerdictRequest,+ UpdateSOPRequest,+)+from .._service import SOPService+from ..storage import (+ ChatModelConfig,+ SOPData,+ SOPRecord,+ SOPRunRecord,+ StorageBase,+)+from ..storage._model._sop import _session_agents+from ...sop import SOPPhase++sop_router = APIRouter(+ prefix="/sop",+ tags=["sop"],+ responses={404: {"description": "Not found"}},+)+++async def _require_sop(+ storage: StorageBase,+ user_id: str,+ sop_id: str,+) -> SOPRecord:+ """Fetch a procedure the caller owns, or answer 404."""+ record = await storage.get_sop(user_id, sop_id)+ if record is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"SOP {sop_id!r} not found.",+ )+ return record+++async def _require_run(+ storage: StorageBase,+ user_id: str,+ sop_run_id: str,+) -> SOPRunRecord:+ """Fetch a run the caller owns, or answer 404."""+ record = await storage.get_sop_run(user_id, sop_run_id)+ if record is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"SOP run {sop_run_id!r} not found.",+ )+ return record+++@sop_router.get(+ "/schema",+ response_model=SOPSchemaResponse,+ summary="The schema a procedure's editor is built from",+)+async def get_sop_schema() -> SOPSchemaResponse:+ """Return :class:`SOPData`'s JSON Schema, unflattened.++ Kept with ``$defs``: the verifier union's discriminator mapping+ points into them, and no model ever reads this schema.++ Returns:+ `SOPSchemaResponse`:+ The schema.+ """+ return SOPSchemaResponse(schema=SOPData.model_json_schema())+++@sop_router.get(+ "/",+ response_model=ListSOPsResponse,+ summary="List procedures",+)+async def list_sops(+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> ListSOPsResponse:+ """Return the caller's procedures.++ Args:+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend.++ Returns:+ `ListSOPsResponse`:+ Every procedure the caller owns.+ """+ records = await storage.list_sops(user_id)+ return ListSOPsResponse(sops=records, total=len(records))+++@sop_router.post(+ "/",+ response_model=CreateSOPResponse,+ status_code=status.HTTP_201_CREATED,+ summary="Create a procedure",+)+async def create_sop(+ body: CreateSOPRequest,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> CreateSOPResponse:+ """Store a new procedure.++ Args:+ body (`CreateSOPRequest`):+ The procedure to store.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend.++ Returns:+ `CreateSOPResponse`:+ The server-assigned identifier.++ Raises:+ `HTTPException`:+ 422 if a run of it could not open its sessions.+ """+ _reject_unconfigured_sessions(body.data)+ record = SOPRecord(user_id=user_id, data=body.data)+ await storage.upsert_sop(user_id, record)+ return CreateSOPResponse(sop_id=record.id)+++@sop_router.get(+ "/runs",+ response_model=ListSOPRunsResponse,+ summary="List runs",+)+async def list_sop_runs(+ sop_id: str+ | None = Query(+ default=None,+ description="Only runs of this procedure.",+ ),+ phase: SOPPhase+ | None = Query(+ default=None,+ description="Only runs standing here — ``awaiting`` is the one "+ "worth asking for.",+ ),+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> ListSOPRunsResponse:+ """Return the caller's runs, newest first.++ Args:+ sop_id (`str | None`):+ Narrow to one procedure.+ phase (`SOPPhase | None`):+ Narrow to one phase.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend.++ Returns:+ `ListSOPRunsResponse`:+ The matching runs.+ """+ records = await storage.list_sop_runs(user_id, sop_id, phase)+ return ListSOPRunsResponse(runs=records, total=len(records))+++@sop_router.get(+ "/runs/{sop_run_id}",+ response_model=SOPRunRecord,+ summary="Read one run",+)+async def get_sop_run(+ sop_run_id: str,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> SOPRunRecord:+ """Return one run and where it stands.++ Args:+ sop_run_id (`str`):+ The run to read.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend.++ Returns:+ `SOPRunRecord`:+ The run. Where it stands is its state's ``phase``.+ """+ return await _require_run(storage, user_id, sop_run_id)+++@sop_router.delete(+ "/runs/{sop_run_id}",+ status_code=status.HTTP_204_NO_CONTENT,+ summary="Delete a run",+)+async def delete_sop_run(+ sop_run_id: str,+ user_id: str = Depends(get_current_user_id),+ service: SOPService = Depends(get_sop_service),+) -> None:+ """Delete one run and the conversations it opened.++ Args:+ sop_run_id (`str`):+ The run to delete.+ user_id (`str`):+ Injected authenticated user id.+ service (`SOPService`):+ Injected SOP service.+ """+ if not await service.delete_run(user_id, sop_run_id):+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"SOP run {sop_run_id!r} not found.",+ )+++@sop_router.post(+ "/runs/{sop_run_id}/verdict",+ response_model=SOPRunRecord,+ summary="File a person's verdict on a step",+)+async def submit_verdict(+ sop_run_id: str,+ body: SubmitVerdictRequest,+ user_id: str = Depends(get_current_user_id),+ service: SOPService = Depends(get_sop_service),+) -> SOPRunRecord:+ """Answer a step that was waiting on a person.++ Returns once the verdict is recorded; the run carries on in the+ background.++ Args:+ sop_run_id (`str`):+ The run being judged.+ body (`SubmitVerdictRequest`):+ Which step, and what was decided.+ user_id (`str`):+ Injected authenticated user id.+ service (`SOPService`):+ Injected SOP service.++ Returns:+ `SOPRunRecord`:+ The run with the verdict recorded on it.++ Raises:+ `HTTPException`:+ 404 if there is no such run or step, 409 if the step is+ not waiting on a person.+ """+ try:+ updated = await service.record_verdict(+ user_id,+ sop_run_id,+ body.step_index,+ body.passed,+ body.message,+ )+ except KeyError as exc:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=str(exc).strip("'"),+ ) from exc+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(exc),+ ) from exc+ service.advance_later(user_id, sop_run_id)+ return updated+++@sop_router.get(+ "/{sop_id}",+ response_model=SOPRecord,+ summary="Read one procedure",+)+async def get_sop(+ sop_id: str,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> SOPRecord:+ """Return one procedure.++ Args:+ sop_id (`str`):+ The procedure to read.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend.++ Returns:+ `SOPRecord`:+ The procedure.+ """+ return await _require_sop(storage, user_id, sop_id)+++@sop_router.patch(+ "/{sop_id}",+ response_model=SOPRecord,+ summary="Replace a procedure's contents",+)+async def update_sop(+ sop_id: str,+ body: UpdateSOPRequest,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+) -> SOPRecord:+ """Rewrite a procedure; runs keep the copy they started with.++ Args:+ sop_id (`str`):+ The procedure to update.+ body (`UpdateSOPRequest`):+ The procedure as it should now read.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend.++ Returns:+ `SOPRecord`:+ The procedure as stored.++ Raises:+ `HTTPException`:+ 422 if a run of it could not open its sessions.+ """+ record = await _require_sop(storage, user_id, sop_id)+ _reject_unconfigured_sessions(body.data)+ record.data = body.data+ return await storage.upsert_sop(user_id, record)+++@sop_router.delete(+ "/{sop_id}",+ status_code=status.HTTP_204_NO_CONTENT,+ summary="Delete a procedure and its runs",+)+async def delete_sop(+ sop_id: str,+ user_id: str = Depends(get_current_user_id),+ service: SOPService = Depends(get_sop_service),+) -> None:+ """Delete a procedure, every run of it, and their sessions.++ Args:+ sop_id (`str`):+ The procedure to delete.+ user_id (`str`):+ Injected authenticated user id.+ service (`SOPService`):+ Injected SOP service.+ """+ if not await service.delete_sop(user_id, sop_id):+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"SOP {sop_id!r} not found.",+ )+++@sop_router.post(+ "/{sop_id}/runs",+ response_model=SOPRunRecord,+ status_code=status.HTTP_201_CREATED,+ summary="Start a run",+)+async def start_sop_run(+ sop_id: str,+ body: StartSOPRunRequest,+ user_id: str = Depends(get_current_user_id),+ service: SOPService = Depends(get_sop_service),+) -> SOPRunRecord:+ """Open a run of a procedure and set it going in the background.++ Args:+ sop_id (`str`):+ The procedure to run.+ body (`StartSOPRunRequest`):+ What the run is started with.+ user_id (`str`):+ Injected authenticated user id.+ service (`SOPService`):+ Injected SOP service.++ Returns:+ `SOPRunRecord`:+ The opened run, before it has got anywhere.+ """+ try:+ run = await service.create_run(user_id, sop_id, body.inputs)+ except KeyError as exc:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"SOP {sop_id!r} not found.",+ ) from exc+ service.advance_later(user_id, run.id)+ return run+++def _reject_unconfigured_sessions(data: SOPData) -> None:+ """Refuse a procedure a run could not open its sessions from.++ Not a model validator, so stored runs still load if model configs+ change shape."""+ try:+ agents = _session_agents(data.steps)+ missing = sorted(set(agents) - set(data.session_settings))+ if missing:+ raise ValueError(+ f"These conversations are used but never configured: "+ f"{', '.join(missing)}.",+ )+ for settings in data.session_settings.values():+ ChatModelConfig.model_validate(settings.chat_model_config)+ if settings.fallback_chat_model_config:+ ChatModelConfig.model_validate(+ settings.fallback_chat_model_config,+ )+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=str(exc),+ ) from excdiff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.pyindex 060cfc2f0..200a6faea 100644--- a/src/agentscope/app/_service/__init__.py+++ b/src/agentscope/app/_service/__init__.py@@ -24,6 +24,7 @@ from ._tts_model import get_tts_modelfrom ._session import SessionService, SessionStatusfrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjector+from ._sop import SessionSOPStep, SOPServicefrom ._toolkit import get_toolkitfrom ._download_token import sign_download_token, verify_download_tokenfrom ._workspace import GitStatus, WorkspaceService, WorkspaceStatus@@ -44,6 +45,8 @@ __all__ = ["KnowledgeBaseView","MCPRenderError","ResourceAccessService",+ "SessionSOPStep",+ "SOPService","SessionService","SessionStatus","SessionProjection",diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 895230f23..c0b67860e 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -37,18 +37,21 @@ from ..storage import (SessionNaming,SessionRecord,ChannelOrigin,+ SOPOrigin,)from ..storage._utils import _resolve_team_leaderfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..workspace_manager import WorkspaceManagerBasefrom ..middleware import (InboxMiddleware,+ SOPStepSubmitMiddleware,StateChangeMiddleware,ToolOffloadMiddleware,TeamMemberLoopMiddleware,)from ...middleware import TTSMiddleware, RAGMiddlewarefrom ...rag import KnowledgeBase+from ...sop import SOPPhasefrom .._types import (AgentMiddlewareFactory,AgentToolFactory,@@ -60,6 +63,7 @@ from ._model import get_modelfrom ._tts_model import get_tts_modelfrom ._toolkit import get_toolkitfrom ._session_projection import SessionProjection+from ._sop import SOPServicefrom ._projectors import SubagentHitlProjectorfrom ..._logging import logger@@ -249,6 +253,9 @@ class ChatService:passself._extra_agent_tools = extra_agent_toolsself._channel_clients = channel_clients+ self.sop_service: SOPService | None = None+ """Carries a procedure on after a turn resumes one of its steps.+ Set by the lifespan, since a SOP service is built on this one."""self._sub_agent_templates = custom_subagent_templatesself._agent_cls = custom_agent_cls or Agentself._projection = SessionProjection(message_bus)@@ -268,6 +275,7 @@ class ChatService:| ExternalExecutionResultEvent| UserInterruptEvent| None = None,+ sop_dispatch: str | None = None,) -> None:"""Drive a chat run to completion.@@ -307,9 +315,18 @@ class ChatService:- ``UserInterruptEvent``: abort a parked reply — theagent closes pending tool calls with interruptedresults and ends the reply (Case B, no reasoning).+ sop_dispatch (`str | None`, optional):+ ``"<run id>:<step index>"`` when a SOP run dispatched+ this turn, which gives it a submit tool."""try:- await self._run_impl(user_id, session_id, agent_id, input_msg)+ await self._run_impl(+ user_id,+ session_id,+ agent_id,+ input_msg,+ sop_dispatch,+ )except Exception as e:logger.exception("ChatService.run failed for user_id=%s session_id=%s "@@ -770,6 +787,7 @@ class ChatService:| ExternalExecutionResultEvent| UserInterruptEvent| None,+ sop_dispatch: str | None = None,) -> None:"""The actual chat-run body; wrapped by :meth:`run` for errorswallowing. Separated so the try/except doesn't bury the@@ -780,6 +798,10 @@ class ChatService:otherwise a waiter can assemble an agent from a snapshot that thepreceding holder replaces before releasing the lock."""+ # The run to carry on after the lock, if this turn resumed a step.+ resumed_sop_run_id: str | None = None+ interrupted = False+async with self._message_bus.acquire_lock(MessageBusKeys.session_lock(session_id),ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,@@ -828,6 +850,21 @@ class ChatService:),)worker_name = agent_record.data.name+ if (+ isinstance(session_record.origin, SOPOrigin)+ and sop_dispatch is None+ and isinstance(+ input_msg,+ (UserConfirmResultEvent, ExternalExecutionResultEvent),+ )+ ):+ # Only an answer to the step's parked call resumes it.+ sop_dispatch = await self._parked_dispatch(+ user_id,+ session_id,+ )+ if sop_dispatch is not None:+ resumed_sop_run_id = session_record.origin.sop_run_id# -------------------------------------------------------------# 1b. Resolve the team identity ONCE, before anything that@@ -957,6 +994,11 @@ class ChatService:),)+ # Only a turn the run asked for must end in a submission;+ # a person chatting in the same session must not.+ if sop_dispatch is not None:+ middlewares.append(SOPStepSubmitMiddleware())+if self._extra_agent_middlewares is not None:factory_args: tuple = (user_id, agent_id, session_id)if self._middlewares_take_workspace:@@ -1054,6 +1096,7 @@ class ChatService:sub_agent_templates=self._sub_agent_templates,team_role=team_ctx.role if team_ctx else None,channel_tools=channel_tools,+ sop_dispatch=sop_dispatch,)# -------------------------------------------------------------@@ -1403,6 +1446,11 @@ class ChatService:):reply_msgs.append(reply_msg)+ interrupted = any(+ msg.finished_reason is ReplyFinishedReason.INTERRUPTED+ for msg in reply_msgs+ )+# All persistence in a single coroutine, shielded from# outer cancellation. Must complete BEFORE the session# lock is released — otherwise another worker could@@ -1471,6 +1519,59 @@ class ChatService:trigger_text,)+ # Detached, since the rest of the run can be many turns; an+ # interrupted turn leaves the run where it is.+ if (+ resumed_sop_run_id is not None+ and not interrupted+ and self.sop_service is not None+ ):+ self.sop_service.advance_later(user_id, resumed_sop_run_id)++ async def _parked_dispatch(+ self,+ user_id: str,+ session_id: str,+ ) -> str | None:+ """The claim of a step parked on this session, if still valid.++ Valid only while the step is parked on this session's half.++ Args:+ user_id (`str`):+ The owner user id.+ session_id (`str`):+ The session whose claim to read.++ Returns:+ `str | None`:+ ``"<run id>:<step index>"``, or ``None``.+ """+ claim = await self._message_bus.registry_get(+ MessageBusKeys.sop_dispatch(session_id),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ )+ if claim is None:+ return None+ sop_run_id, _, step_index = claim.rpartition(":")+ run = await self._storage.get_sop_run(user_id, sop_run_id)+ index = int(step_index)+ if (+ run is None+ or index >= len(run.state.steps)+ or run.state.steps[index].phase is not SOPPhase.AWAITING+ ):+ return None+ step = run.definition.steps[index]+ ref = (+ step.executor+ if run.state.steps[index].submission is None+ else getattr(step.verifier, "agent", None)+ )+ if ref is None or run.sessions.get(ref.session_key) != session_id:+ return None+ return claim+async def _project_event(self,user_id: str,diff --git a/src/agentscope/app/_service/_sop.py b/src/agentscope/app/_service/_sop.pynew file mode 100644index 000000000..f33643467--- /dev/null+++ b/src/agentscope/app/_service/_sop.py@@ -0,0 +1,642 @@+# -*- coding: utf-8 -*-+"""Running a stored procedure, one ``ChatService`` turn per step half.++A step's result is read back from the run state, where its agent's+submit tool wrote it.+"""+import asyncio+from typing import Any, AsyncGenerator, Awaitable, Callable, Self++from ..storage import (+ AgentVerifier,+ ChatModelConfig,+ HumanVerifier,+ SessionConfig,+ SOPOrigin,+ SOPRunRecord,+ SOPStepDataV1,+ SOPWorkspaceGrain,+ StorageBase,+)+from ..storage._model._sop import _session_agents+from .._tool import SubmitVerdict+from ..message_bus import MessageBus, MessageBusKeys+from ..workspace_manager import WorkspaceManagerBase+from ..._logging import logger+from ._session import SessionService, SessionStatus+from ...event import (+ ExternalExecutionResultEvent,+ UserConfirmResultEvent,+ UserInterruptEvent,+)+from ...message import Msg, TextBlock, UserMsg+from ..._utils._common import _generate_id+from ...sop import (+ SOP,+ SOPEngine,+ SOPPhase,+ SOPRunState,+ SOPStepBase,+ SOPStepRunState,+)+from ...permission import PermissionContext, PermissionMode+from ...state import AgentState++_PARKED = (+ SessionStatus.AWAITING_PERMISSION,+ SessionStatus.AWAITING_EXTERNAL_RESULT,+)+++class SessionSOPStep(SOPStepBase):+ """One milestone, worked on in ordinary chat sessions.++ One call hands one turn to the executor's or the reviewer's session,+ chosen by whether anything has been handed over yet.+ """++ def __init__(+ self,+ data: SOPStepDataV1,+ index: int,+ user_id: str,+ sop_run_id: str,+ sessions: dict[str, str],+ chat: Any,+ storage: StorageBase,+ message_bus: MessageBus,+ persist: Callable[[], Awaitable[None]],+ ) -> None:+ """Bind the step to the run it belongs to.++ Args:+ data (`SOPStepDataV1`):+ The milestone as the procedure describes it.+ index (`int`):+ Its position in the run.+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run this step is part of.+ sessions (`dict[str, str]`):+ The run's session ids, by session key.+ chat (`ChatService`):+ Where a turn is actually taken.+ storage (`StorageBase`):+ Application storage.+ message_bus (`MessageBus`):+ Holds the dispatch claim of a parked turn.+ persist (`Callable[[], Awaitable[None]]`):+ Writes the whole run state.+ """+ super().__init__(data.subject, data.description, data.max_attempts)+ self._data = data+ self._index = index+ self._user_id = user_id+ self._sop_run_id = sop_run_id+ self._sessions = sessions+ self._chat = chat+ self._storage = storage+ self._message_bus = message_bus+ self._persist = persist++ async def reply_stream( # pylint: disable=invalid-overridden-method+ self,+ inputs: Msg+ | list[Msg]+ | UserConfirmResultEvent+ | UserInterruptEvent+ | ExternalExecutionResultEvent+ | None,+ state: SOPStepRunState,+ ) -> AsyncGenerator[Any, None]:+ """Hand one turn to one session and read back what it filed.++ Yields nothing: the agent publishes into its own session.+ """+ for event in ():+ yield event++ verifier = self._data.verifier+ reviewing = state.submission is not None+ if not reviewing:+ ref, opening = self._data.executor, self._brief(state)+ elif verifier is None:+ # A step that only had to happen.+ self.record(state, True)+ return+ elif isinstance(verifier, HumanVerifier):+ # The person's verdict is filed via ``record_verdict``.+ state.phase = SOPPhase.AWAITING+ return+ else:+ ref, opening = verifier.agent, self._question(state, verifier)++ session_id = self._sessions[ref.session_key]+ if state.phase is SOPPhase.AWAITING:+ # Still parked on a tool call, which a new brief can't answer.+ session = await self._storage.get_session(+ self._user_id,+ ref.agent_id,+ session_id,+ )+ if session is not None and (+ SessionService.derive_parked_status(session.state.context)+ in _PARKED+ ):+ return++ state.phase = SOPPhase.RUNNING+ # Before the turn, since its submit tool reads the stored state.+ await self._persist()++ dispatch = f"{self._sop_run_id}:{self._index}"+ try:+ await self._chat.run(+ self._user_id,+ session_id,+ ref.agent_id,+ opening,+ sop_dispatch=dispatch,+ )++ stored = await self._storage.get_sop_run(+ self._user_id,+ self._sop_run_id,+ )+ if stored is None:+ # Deleted mid-turn; nothing left to record against.+ state.phase = SOPPhase.FAILED+ return+ filed = stored.state.steps[self._index]+ state.submission = filed.submission+ verdicts = list(filed.verifications)++ if len(verdicts) > len(state.verifications):+ state.verifications = verdicts+ if verdicts[-1].passed:+ state.phase = SOPPhase.COMPLETED+ else:+ state.submission = None+ state.phase = SOPPhase.PENDING+ return++ if not reviewing and state.submission is not None:+ # Handed over; the same step is judged on the next pass.+ state.phase = SOPPhase.RUNNING+ return++ session = await self._storage.get_session(+ self._user_id,+ ref.agent_id,+ session_id,+ )+ if session is not None and (+ SessionService.derive_parked_status(session.state.context)+ in _PARKED+ ):+ state.phase = SOPPhase.AWAITING+ return++ self.record(+ state,+ False,+ "The reviewer ended its turn without a verdict."+ if reviewing+ else "Your turn ended without submitting anything, so the "+ "step has nothing to show for it.",+ "sop",+ )+ finally:+ # A parked turn keeps its claim for the chat turn that+ # resumes it; any other ending releases the session.+ if state.phase is SOPPhase.AWAITING:+ await self._message_bus.registry_set(+ MessageBusKeys.sop_dispatch(session_id),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ dispatch,+ )+ else:+ await self._message_bus.registry_drop(+ MessageBusKeys.sop_dispatch(session_id),+ )++ def _brief(self, state: SOPStepRunState) -> list[Msg]:+ """What the author is asked at the start of an attempt."""+ text = (+ f"<system-reminder>You are running one step of the SOP.\n\n"+ f"## {self.subject}\n\n{self.description}\n"+ )+ if state.verifications:+ text += (+ f"\nYour last attempt was not accepted:\n"+ f"{state.verifications[-1].message}\n"+ )+ text += "</system-reminder>"+ return [UserMsg(name="sop", content=text), *state.given]++ def _question(+ self,+ state: SOPStepRunState,+ verifier: AgentVerifier,+ ) -> list[Msg]:+ """What the reviewer is asked, once there is something to judge."""+ text = (+ f"<system-reminder>Judge the work below against what this "+ f"step had to prove.\n\n## {self.subject}\n\n{self.description}"+ )+ if verifier.criteria:+ text += f"\n\n{verifier.criteria}"+ return [+ UserMsg(name="sop", content=text + "</system-reminder>"),+ *state.given,+ UserMsg(+ name="sop",+ content=[+ TextBlock(type="text", text="<submission>"),+ *(state.submission or []),+ TextBlock(type="text", text="</submission>"),+ ],+ ),+ ]+++class SOPService:+ """Start runs of a stored procedure, and carry them forward.++ Enter it as a context manager so detached advances are cancelled+ before storage closes.+ """++ def __init__(+ self,+ storage: StorageBase,+ workspace_manager: WorkspaceManagerBase,+ message_bus: MessageBus,+ chat: Any,+ session_service: SessionService,+ ) -> None:+ """Initialize the service.++ Args:+ storage (`StorageBase`):+ Application storage.+ workspace_manager (`WorkspaceManagerBase`):+ Closes the workspaces a deleted run minted.+ message_bus (`MessageBus`):+ Serialises advances of one run against each other.+ chat (`ChatService`):+ Where each step's turn is taken.+ session_service (`SessionService`):+ Deletes a run's sessions.+ """+ self._storage = storage+ self._workspace_manager = workspace_manager+ self._message_bus = message_bus+ self._chat = chat+ self._session_service = session_service+ # Strong refs to detached advances, by run, so a delete can+ # cancel them.+ self._advancing: dict[str, set[asyncio.Task]] = {}++ async def create_run(+ self,+ user_id: str,+ sop_id: str,+ inputs: list[Msg] | None = None,+ ) -> SOPRunRecord:+ """Open a run with all of its sessions created up front.++ Args:+ user_id (`str`):+ The owner user id.+ sop_id (`str`):+ The procedure to run, copied into the run.+ inputs (`list[Msg] | None`, optional):+ What the first step is given.++ Returns:+ `SOPRunRecord`:+ The opened run, already persisted.++ Raises:+ `KeyError`:+ If the user has no such procedure.+ """+ async with self._message_bus.acquire_lock(+ MessageBusKeys.sop_lock(sop_id),+ ttl_secs=MessageBusKeys.SOP_RUN_TTL_SECS,+ ):+ return await self._open_run(user_id, sop_id, inputs)++ async def _open_run(+ self,+ user_id: str,+ sop_id: str,+ inputs: list[Msg] | None,+ ) -> SOPRunRecord:+ """Open the run, with the procedure's lock already held."""+ sop_record = await self._storage.get_sop(user_id, sop_id)+ if sop_record is None:+ raise KeyError(f"SOP {sop_id!r} not found.")+ data = sop_record.data+ run = SOPRunRecord(+ user_id=user_id,+ sop_id=sop_record.id,+ definition=data,+ state=SOPRunState(+ inputs=inputs or [],+ steps=[SOPStepRunState() for _ in data.steps],+ ),+ )++ agents = _session_agents(data.steps)++ # Minted rather than assigned: ``assign_workspace_id`` may reuse+ # the agent's workspace across runs, breaking the grain.+ shared = _generate_id()+ try:+ for key, agent_id in agents.items():+ settings = data.session_settings[key]+ fallback = settings.fallback_chat_model_config+ workspace_id = (+ shared+ if data.workspace_grain is SOPWorkspaceGrain.RUN+ else _generate_id()+ )+ session = await self._storage.upsert_session(+ user_id=user_id,+ agent_id=agent_id,+ config=SessionConfig(+ workspace_id=workspace_id,+ name=f"{data.name} / {key}",+ chat_model_config=ChatModelConfig(+ **settings.chat_model_config,+ ),+ fallback_chat_model_config=(+ ChatModelConfig(**fallback) if fallback else None+ ),+ ),+ state=AgentState(+ permission_context=PermissionContext(+ mode=PermissionMode(settings.permission_mode),+ ),+ ),+ origin=SOPOrigin(sop_run_id=run.id, session_key=key),+ )+ run.sessions[key] = session.id++ return await self._storage.upsert_sop_run(user_id, run)+ except Exception:+ # Unreachable without the run record, so roll them back.+ for key, session_id in run.sessions.items():+ await self._storage.delete_session(+ user_id,+ agents[key],+ session_id,+ )+ raise++ async def __aenter__(self) -> Self:+ """Enter the service's lifetime."""+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Stop every advance still going, before its storage closes."""+ going = [task for tasks in self._advancing.values() for task in tasks]+ for task in going:+ task.cancel()+ await asyncio.gather(*going, return_exceptions=True)+ self._advancing.clear()++ def advance_later(self, user_id: str, sop_run_id: str) -> None:+ """Advance a run in a detached task; failures are logged.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run to carry on.+ """++ async def _run() -> None:+ try:+ await self.run(user_id, sop_run_id)+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "Advancing SOP run %r failed.",+ sop_run_id,+ )++ task = asyncio.create_task(_run(), name=f"sop-run:{sop_run_id}")+ going = self._advancing.setdefault(sop_run_id, set())+ going.add(task)+ task.add_done_callback(going.discard)++ async def delete_sop(self, user_id: str, sop_id: str) -> bool:+ """Delete a procedure and every run of it.++ Under the procedure's lock, so no run is opened mid-cascade.++ Args:+ user_id (`str`):+ The owner user id.+ sop_id (`str`):+ The procedure to delete.++ Returns:+ `bool`:+ Whether there was one to delete.+ """+ async with self._message_bus.acquire_lock(+ MessageBusKeys.sop_lock(sop_id),+ ttl_secs=MessageBusKeys.SOP_RUN_TTL_SECS,+ ):+ for run in await self._storage.list_sop_runs(+ user_id,+ sop_id=sop_id,+ ):+ await self.delete_run(user_id, run.id)+ return await self._storage.delete_sop(user_id, sop_id)++ async def delete_run(self, user_id: str, sop_run_id: str) -> bool:+ """Delete a run, its sessions, claims and workspaces.++ Local advances are cancelled first, then the rest runs under the+ run's lock so no advance writes the record back afterwards.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run to delete.++ Returns:+ `bool`:+ Whether there was one to delete.+ """+ going = list(self._advancing.get(sop_run_id, ()))+ for task in going:+ task.cancel()+ await asyncio.gather(*going, return_exceptions=True)+ async with self._message_bus.acquire_lock(+ MessageBusKeys.sop_run_lock(sop_run_id),+ ttl_secs=MessageBusKeys.SOP_RUN_TTL_SECS,+ ):+ record = await self._storage.get_sop_run(user_id, sop_run_id)+ if record is None:+ return False+ agents = _session_agents(record.definition.steps)+ workspace_ids = set()+ for key, session_id in record.sessions.items():+ session = await self._storage.get_session(+ user_id,+ agents[key],+ session_id,+ )+ if session is not None:+ workspace_ids.add(session.config.workspace_id)+ # Via the session service, to also cancel and purge.+ await self._session_service.delete_session(+ user_id,+ agents[key],+ session_id,+ )+ await self._message_bus.registry_drop(+ MessageBusKeys.sop_dispatch(session_id),+ )+ deleted = await self._storage.delete_sop_run(user_id, sop_run_id)+ # Minted for this run alone, so nobody else closes them.+ for workspace_id in workspace_ids:+ await self._workspace_manager.close(workspace_id)+ return deleted++ async def record_verdict(+ self,+ user_id: str,+ sop_run_id: str,+ step_index: int,+ passed: bool,+ message: str = "",+ ) -> SOPRunRecord:+ """File a person's verdict on a step waiting for one.++ Under the run's lock, so an advance cannot overwrite it.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run being judged.+ step_index (`int`):+ Which step, by its position.+ passed (`bool`):+ Whether the attempt is accepted.+ message (`str`, defaults to `""`):+ Why it was refused.++ Returns:+ `SOPRunRecord`:+ The run with the verdict recorded on it.++ Raises:+ `KeyError`:+ If the user has no such run, or it has no such step.+ `ValueError`:+ If that step is not judged by a person, or not waiting.+ """+ async with self._message_bus.acquire_lock(+ MessageBusKeys.sop_run_lock(sop_run_id),+ ttl_secs=MessageBusKeys.SOP_RUN_TTL_SECS,+ ):+ record = await self._storage.get_sop_run(user_id, sop_run_id)+ if record is None:+ raise KeyError(f"SOP run {sop_run_id!r} not found.")+ if not 0 <= step_index < len(record.definition.steps):+ raise KeyError(+ f"Step {step_index} is not part of this run.",+ )+ step = record.definition.steps[step_index]+ if not isinstance(step.verifier, HumanVerifier):+ raise ValueError(+ f"Step {step_index} is not judged by a person.",+ )+ if record.state.steps[step_index].phase is not SOPPhase.AWAITING:+ raise ValueError(+ f"Step {step_index} is not waiting to be judged.",+ )++ # The same tool an agent reviewer calls.+ await SubmitVerdict(+ storage=self._storage,+ user_id=user_id,+ sop_run_id=sop_run_id,+ step_index=step_index,+ verifier=user_id,+ )(passed=passed, message=message)++ updated = await self._storage.get_sop_run(user_id, sop_run_id)++ if updated is None:+ raise KeyError(f"SOP run {sop_run_id!r} not found.")+ return updated++ async def run(self, user_id: str, sop_run_id: str) -> SOPRunState:+ """Carry a run on until it finishes, fails, or waits on someone.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run to drive.++ Returns:+ `SOPRunState`:+ How the run stands now.++ Raises:+ `KeyError`:+ If the user has no such run.+ """+ async with self._message_bus.acquire_lock(+ MessageBusKeys.sop_run_lock(sop_run_id),+ ttl_secs=MessageBusKeys.SOP_RUN_TTL_SECS,+ ):+ return await self._advance(user_id, sop_run_id)++ async def _advance(self, user_id: str, sop_run_id: str) -> SOPRunState:+ """Drive the run, with its lock already held."""+ record = await self._storage.get_sop_run(user_id, sop_run_id)+ if record is None:+ raise KeyError(f"SOP run {sop_run_id!r} not found.")++ state = record.state++ async def _persist() -> None:+ await self._storage.update_sop_run(user_id, sop_run_id, state)++ engine = SOPEngine(+ SOP(+ name=record.definition.name,+ description=record.definition.description,+ steps=[+ SessionSOPStep(+ data=step,+ index=index,+ user_id=user_id,+ sop_run_id=sop_run_id,+ sessions=record.sessions,+ chat=self._chat,+ storage=self._storage,+ message_bus=self._message_bus,+ persist=_persist,+ )+ for index, step in enumerate(record.definition.steps)+ ],+ ),+ state,+ )+ async for _ in engine.reply_stream():+ pass+ await _persist()+ return engine.statediff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pyindex 13b434693..5d20760db 100644--- a/src/agentscope/app/_service/_toolkit.py+++ b/src/agentscope/app/_service/_toolkit.py@@ -11,6 +11,8 @@ from typing import Any, Literalfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..message_bus import MessageBusfrom .._tool import (+ SubmitHandover,+ SubmitVerdict,AgentCreate,AgentInvite,TeamCreate,@@ -52,6 +54,7 @@ async def get_toolkit(sub_agent_templates: dict[str, SubAgentTemplate] | None = None,team_role: Literal["leader", "worker"] | None = None,channel_tools: list[ToolBase] | None = None,+ sop_dispatch: str | None = None,) -> Toolkit:"""Assemble the complete :class:`Toolkit` for one chat turn.@@ -120,6 +123,9 @@ optional):team_role (`Literal["leader", "worker"] | None`, optional):The session's team role, resolved once by the caller.``None`` means not in any team.+ sop_dispatch (`str | None`, optional):+ ``"<run id>:<step index>"`` when this turn is a SOP+ step's, which gives it a submit tool.channel_tools (`list[ToolBase] | None`, optional):Platform tools of the originating channel, resolved onceby the caller. ``None`` / empty when channel-less.@@ -220,6 +226,28 @@ time or interval"),)+ # A step's turn gets one submit tool: handover until something has+ # been handed over, verdict after.+ if sop_dispatch is not None:+ sop_run_id, _, step_index = sop_dispatch.rpartition(":")+ run = await storage.get_sop_run(user_id, sop_run_id)+ index = int(step_index)+ if run is not None and index < len(run.state.steps):+ submit_kwargs: dict[str, Any] = {+ "storage": storage,+ "user_id": user_id,+ "sop_run_id": sop_run_id,+ "step_index": index,+ }+ tools.append(+ SubmitHandover(**submit_kwargs)+ if run.state.steps[index].submission is None+ else SubmitVerdict(+ **submit_kwargs,+ verifier=agent_record.data.name,+ ),+ )+# Caller-supplied extras.if extra_factory is not None:tools += await extra_factory(diff --git a/src/agentscope/app/_tool/__init__.py b/src/agentscope/app/_tool/__init__.pyindex 6f87b1f0a..2467388a3 100644--- a/src/agentscope/app/_tool/__init__.py+++ b/src/agentscope/app/_tool/__init__.py@@ -35,12 +35,15 @@ from ._agent_create import AgentCreate, DEFAULT_SUB_AGENT_TEMPLATEfrom ._agent_invite import AgentInvitefrom ._team_create import TeamCreatefrom ._team_delete import TeamDelete+from ._sop_submit import SubmitHandover, SubmitVerdictfrom ._team_say import TeamSay__all__ = ["AgentCreate","AgentInvite","DEFAULT_SUB_AGENT_TEMPLATE",+ "SubmitHandover",+ "SubmitVerdict","TeamCreate","TeamDelete","TeamSay",diff --git a/src/agentscope/app/_tool/_sop_submit.py b/src/agentscope/app/_tool/_sop_submit.pynew file mode 100644index 000000000..8849197e0--- /dev/null+++ b/src/agentscope/app/_tool/_sop_submit.py@@ -0,0 +1,255 @@+# -*- coding: utf-8 -*-+"""The tools a SOP step's agent files its handover or verdict with,+straight into the run state."""+from typing import Any, TYPE_CHECKING++from pydantic import Field++from ...message import TextBlock, ToolResultState+from ...permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from ...sop import SOPPhase, VerificationResult+from ...tool import ToolBase, ToolChunk, ParamsBase++if TYPE_CHECKING:+ from ..storage import StorageBase+++class _SubmitHandoverParams(ParamsBase):+ """Parameters for :class:`SubmitHandover`."""++ handover: str = Field(+ description=(+ "What you are handing to the following steps. They cannot "+ "see this conversation or your tools' output, so anything "+ "they need from it has to be in here. Files are the "+ "exception when the procedure shares one workspace: name "+ "those by path rather than describing them."+ ),+ )+++class _SubmitVerdictParams(ParamsBase):+ """Parameters for :class:`SubmitVerdict`."""++ passed: bool = Field(+ description="Whether the work meets what the step had to prove.",+ )+ message: str = Field(+ default="",+ description=(+ "If it does not pass, exactly what is wrong and what to do "+ "about it. This is handed to the author verbatim on their "+ "next attempt, so name the specific claims, files or values "+ "at fault."+ ),+ )+++class _SOPSubmitBase(ToolBase):+ """Shared plumbing for the two submission tools, bound to one step+ of one run and writing its state directly."""++ name: str+ description: str+ input_schema: dict[str, Any]+ is_concurrency_safe: bool = False+ is_read_only: bool = False+ is_state_injected: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ def __init__(+ self,+ storage: "StorageBase",+ user_id: str,+ sop_run_id: str,+ step_index: int,+ ) -> None:+ """Bind the run this tool writes to.++ Args:+ storage (`StorageBase`):+ Application storage.+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run the calling session belongs to.+ step_index (`int`):+ Which of the run's steps it is working on.+ """+ self._storage = storage+ self._user_id = user_id+ self._sop_run_id = sop_run_id+ self._step_index = step_index++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Always allow — a step only ever carries the tool it needs.++ Args:+ tool_input (`dict[str, Any]`):+ Ignored.+ context (`PermissionContext`):+ Ignored.++ Returns:+ `PermissionDecision`:+ An ``ALLOW`` decision.+ """+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"{self.name} is how a step reports, so it never asks.",+ )++ async def _write(self, apply: Any) -> ToolChunk | None:+ """Apply *apply* to the step and write the run back; returns an+ error chunk if the run is gone, else ``None``."""+ record = await self._storage.get_sop_run(+ self._user_id,+ self._sop_run_id,+ )+ if record is None or self._step_index >= len(record.state.steps):+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"{self.name}: run {self._sop_run_id!r} is no "+ f"longer there to submit to."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ apply(record.state.steps[self._step_index])+ await self._storage.update_sop_run(+ self._user_id,+ self._sop_run_id,+ record.state,+ )+ return None+++class SubmitHandover(_SOPSubmitBase):+ """Hand this step's result to the steps that follow it."""++ name: str = "SubmitHandover"+ description: str = """Hand over the result of this step.++## When to Use This Tool+- You have finished what this step had to achieve. Call this as the \+last thing you do — your turn is not over until you have.++## Important+- The steps after this one cannot see your tool output or this \+conversation, so whatever they need from it has to be in the handover \+text itself. Files are the exception when the procedure shares one \+workspace: leave them there and name them by path.+- Calling this does not mean the work is accepted; it is judged after \+you hand it over, and you may be asked again with a reason.+"""++ input_schema: dict = _SubmitHandoverParams.model_json_schema()++ async def __call__(self, handover: str) -> ToolChunk:+ """Record the handover on this step's run state.++ Args:+ handover (`str`):+ What the following steps are told.++ Returns:+ `ToolChunk`:+ A confirmation, or an error if the run has gone.+ """++ def _apply(step: Any) -> None:+ step.submission = [TextBlock(type="text", text=handover)]++ failure = await self._write(_apply)+ return failure or ToolChunk(+ content=[TextBlock(type="text", text="Handed over.")],+ state=ToolResultState.SUCCESS,+ )+++class SubmitVerdict(_SOPSubmitBase):+ """Accept or refuse the work of the step under review."""++ name: str = "SubmitVerdict"+ description: str = """Decide whether this step's work is accepted.++## When to Use This Tool+- You have read the submission and judged it against what the step had \+to prove. Call this as the last thing you do — your turn is not over \+until you have.++## Important+- A refusal is handed to the author verbatim and is the only thing they \+get to work from, so say what is missing rather than that something is.+- Refusing sends the step back to be attempted again. Do not refuse over \+something the step was never asked to do.+"""++ input_schema: dict = _SubmitVerdictParams.model_json_schema()++ def __init__(self, *args: Any, verifier: str = "", **kwargs: Any) -> None:+ """Bind who the verdict is recorded under.++ Args:+ verifier (`str`, defaults to `""`):+ The reviewing agent's name, recorded on the verdict.+ *args:+ Forwarded to :class:`_SOPSubmitBase`.+ **kwargs:+ Forwarded to :class:`_SOPSubmitBase`.+ """+ super().__init__(*args, **kwargs)+ self._verifier = verifier++ async def __call__(self, passed: bool, message: str = "") -> ToolChunk:+ """File the verdict on this step's current attempt.++ Args:+ passed (`bool`):+ Whether the attempt is accepted.+ message (`str`, defaults to `""`):+ Why it was refused.++ Returns:+ `ToolChunk`:+ A confirmation, or an error if the run has gone.+ """++ def _apply(step: Any) -> None:+ step.verifications.append(+ VerificationResult(+ passed=passed,+ message=message,+ verifier=self._verifier,+ ),+ )+ if passed:+ step.phase = SOPPhase.COMPLETED+ else:+ # Same rule as ``SOPStepBase.record``.+ step.submission = None+ step.phase = SOPPhase.PENDING++ failure = await self._write(_apply)+ return failure or ToolChunk(+ content=[+ TextBlock(+ type="text",+ text="Accepted." if passed else "Sent back.",+ ),+ ],+ state=ToolResultState.SUCCESS,+ )diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.pyindex 9ed62286a..55b6d40ab 100644--- a/src/agentscope/app/deps.py+++ b/src/agentscope/app/deps.py@@ -16,6 +16,7 @@ from ._service import (ChannelService,CredentialBindingService,ChatService,+ SOPService,KnowledgeBaseService,ResourceAccessService,SessionService,@@ -172,6 +173,18 @@ async def get_background_task_manager(return request.app.state.background_task_manager+async def get_sop_service(request: Request) -> SOPService:+ """Return the application-wide SOP service.++ Args:+ request (`Request`): The incoming FastAPI request.++ Returns:+ `SOPService`: The SOP service instance stored in ``app.state``.+ """+ return request.app.state.sop_service++async def get_workspace_manager(request: Request) -> WorkspaceManagerBase:"""Return the application-wide workspace manager.diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.pyindex b5b4f73c1..3ce31cec8 100644--- a/src/agentscope/app/message_bus/_keys.py+++ b/src/agentscope/app/message_bus/_keys.py@@ -145,6 +145,41 @@ class MessageBusKeys: # pylint: disable=too-many-public-methods"""Per-session distributed-lock key."""return cls._SESSION_LOCK.format(sid=session_id)+ # ------------------------------------------------------------------+ # SOP run lock+ # ------------------------------------------------------------------++ _SOP_LOCK = "agentscope:sop:lock:{sid}"++ @classmethod+ def sop_lock(cls, sop_id: str) -> str:+ """Per-procedure lock, held while a run is opened or the procedure+ deleted. Outermost of the three: procedure, run, session."""+ return cls._SOP_LOCK.format(sid=sop_id)++ _SOP_RUN_LOCK = "agentscope:sop_run:lock:{rid}"++ SOP_RUN_TTL_SECS = 600+ """Lock lease for a SOP run (10 minutes), renewed while held."""++ _SOP_DISPATCH_NS = "agentscope:sop:dispatch:{sid}"++ SOP_DISPATCH_FIELD = "step"+ """The only field a dispatch namespace holds."""++ @classmethod+ def sop_dispatch(cls, session_id: str) -> str:+ """Registry namespace holding ``"<run id>:<step index>"`` while a+ step's turn is parked in this session. Per session and unleased,+ since a park can wait on a person indefinitely."""+ return cls._SOP_DISPATCH_NS.format(sid=session_id)++ @classmethod+ def sop_run_lock(cls, sop_run_id: str) -> str:+ """Per-run lock, taken after the procedure's and before any+ session's."""+ return cls._SOP_RUN_LOCK.format(rid=sop_run_id)+# ------------------------------------------------------------------# Session inbox# ------------------------------------------------------------------diff --git a/src/agentscope/app/middleware/__init__.py b/src/agentscope/app/middleware/__init__.pyindex 77e4a05bf..6f058d8f9 100644--- a/src/agentscope/app/middleware/__init__.py+++ b/src/agentscope/app/middleware/__init__.py@@ -3,6 +3,7 @@from ._inbox_middleware import InboxMiddlewarefrom ._protocol import ProtocolMiddlewareBase, AGUIProtocolMiddleware+from ._sop_step_middleware import SOPStepSubmitMiddlewarefrom ._state_change_middleware import StateChangeMiddlewarefrom ._team_member_middleware import TeamMemberLoopMiddlewarefrom ._tool_offload_middleware import ToolOffloadMiddleware@@ -12,6 +13,7 @@ __all__ = ["InboxMiddleware","ProtocolMiddlewareBase","AGUIProtocolMiddleware",+ "SOPStepSubmitMiddleware","StateChangeMiddleware","ToolOffloadMiddleware","TeamMemberLoopMiddleware",diff --git a/src/agentscope/app/middleware/_sop_step_middleware.py b/src/agentscope/app/middleware/_sop_step_middleware.pynew file mode 100644index 000000000..b25b838b8--- /dev/null+++ b/src/agentscope/app/middleware/_sop_step_middleware.py@@ -0,0 +1,169 @@+# -*- coding: utf-8 -*-+"""The middleware that holds a SOP step's agent to its submission."""++import json+from typing import AsyncGenerator, Callable++from ...agent import Agent+from ...event import HintBlockEvent, ReplyEndEvent+from ...message import HintBlock, ToolCallBlock, ToolResultBlock+from ...message import ToolResultState+from ...middleware import MiddlewareBase+from ...types import ErrorInfo, ErrorType, ReplyFinishedReason+++class SOPStepSubmitMiddleware(MiddlewareBase):+ """Require a step's agent to end its turn through its submit tool.++ A reply-end with nothing submitted is swallowed with a nudge, and+ failed after ``max_nudges`` so it costs an attempt instead of hanging.+ """++ #: Either ends a step's turn; :func:`get_toolkit` gives an agent one.+ TOOLS = ("SubmitHandover", "SubmitVerdict")++ def __init__(self, max_nudges: int = 3) -> None:+ """Initialize the middleware.++ Args:+ max_nudges (`int`, defaults to `3`):+ How many times one reply may be sent back before it is+ failed instead.+ """+ super().__init__()+ self._max_nudges = max_nudges++ def _submitted(self, agent: "Agent") -> bool:+ """Whether this reply's last tool call was a successful submit.++ Args:+ agent (`Agent`):+ The replying agent.++ Returns:+ `bool`:+ ``True`` when the reply ends on an accepted submission.+ """+ for msg in reversed(agent.state.context):+ if (+ msg.id != agent.state.reply_id+ or msg.role != "assistant"+ or msg.name != agent.name+ ):+ continue++ blocks = msg.get_content_blocks()+ last_call = next(+ (+ block+ for block in reversed(blocks)+ if isinstance(block, ToolCallBlock)+ ),+ None,+ )+ if last_call is None:+ continue+ if last_call.name not in self.TOOLS:+ return False++ result = next(+ (+ block+ for block in blocks+ if isinstance(block, ToolResultBlock)+ and block.id == last_call.id+ ),+ None,+ )+ return (+ result is not None and result.state == ToolResultState.SUCCESS+ )++ return False++ async def on_reply(+ self,+ agent: "Agent",+ input_kwargs: dict,+ next_handler: Callable[..., AsyncGenerator],+ ) -> AsyncGenerator:+ """Discard reply-ends until the submit tool has been called.++ Args:+ agent (`Agent`):+ The replying agent.+ input_kwargs (`dict`):+ The reply arguments, forwarded unchanged.+ next_handler (`Callable[..., AsyncGenerator]`):+ The rest of the middleware chain.++ Yields:+ `AgentEvent | Msg`:+ The inner reply's events, with unsubmitted reply-ends+ replaced by a reminder or an ``ERROR`` ending.+ """+ nudges = 0++ async for event in next_handler(**input_kwargs):+ if not isinstance(event, ReplyEndEvent):+ yield event+ continue++ if self._submitted(agent):+ yield event+ continue++ if event.finished_reason not in (+ ReplyFinishedReason.COMPLETED,+ ReplyFinishedReason.EXCEED_MAX_ITERS,+ ):+ # Interrupted or failed endings cannot be continued.+ yield event+ continue++ if nudges >= self._max_nudges:+ yield ReplyEndEvent(+ session_id=event.session_id,+ reply_id=event.reply_id,+ finished_reason=ReplyFinishedReason.ERROR,+ error=ErrorInfo(+ type=ErrorType.INTERNAL,+ message=(+ f"{agent.name} ended {nudges} replies in a "+ f"row without submitting anything to the "+ f"procedure; giving up on this attempt."+ ),+ ),+ )+ continue++ nudges += 1+ equipped = {+ tool.name+ for group in agent.toolkit.tool_groups+ for tool in group.tools+ } & set(self.TOOLS)+ instruction = (+ f"<system-reminder>Your turn is not over until you call "+ f"`{sorted(equipped)[0] if equipped else self.TOOLS[0]}`. "+ f"Call it now.</system-reminder>"+ )+ # Free one iteration so the agent can actually make the call.+ agent.state.cur_iter = min(+ agent.state.cur_iter,+ agent.react_config.max_iters - 1,+ )++ hint_block = HintBlock(+ hint=instruction,+ source=json.dumps(+ {"label": "System", "sublabel": "Reminder"},+ ),+ )+ agent.state.append_context(agent.name, [hint_block])+ yield HintBlockEvent(+ reply_id=agent.state.reply_id,+ block_id=hint_block.id,+ source=hint_block.source,+ hint=instruction,+ )diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.pyindex b1b8c76e8..aece10a45 100644--- a/src/agentscope/app/storage/__init__.py+++ b/src/agentscope/app/storage/__init__.py@@ -33,6 +33,16 @@ from ._model import (ScheduleSource,ChannelOrigin,TeamOrigin,+ AgentVerifier,+ HumanVerifier,+ SOPAgentRef,+ SOPData,+ SOPOrigin,+ SOPRecord,+ SOPRunRecord,+ SOPStepDataV1,+ SOPVerifier,+ SOPWorkspaceGrain,SkillRecord,ChatModelConfig,TTSModelConfig,@@ -102,6 +112,16 @@ __all__ = ["ScheduleOrigin","ChannelOrigin","TeamOrigin",+ "AgentVerifier",+ "HumanVerifier",+ "SOPAgentRef",+ "SOPData",+ "SOPOrigin",+ "SOPRecord",+ "SOPRunRecord",+ "SOPStepDataV1",+ "SOPVerifier",+ "SOPWorkspaceGrain","SkillRecord","ChatModelConfig","TTSModelConfig",diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.pyindex 6c4027ba4..7fb1fda84 100644--- a/src/agentscope/app/storage/_base.py+++ b/src/agentscope/app/storage/_base.py@@ -19,10 +19,13 @@ from ._model import (SessionConfig,SessionOrigin,SkillRecord,+ SOPRecord,+ SOPRunRecord,TeamRecord,)from ...credential import CredentialBasefrom ...message import Msg+from ...sop import SOPPhase, SOPRunStatefrom ...state import AgentState@@ -798,6 +801,168 @@ class StorageBase(ABC):when older messages exist before the returned page."""+ # ------------------------------------------------------------------+ # SOP persistence+ # ------------------------------------------------------------------++ async def upsert_sop(self, user_id: str, record: SOPRecord) -> SOPRecord:+ """Create or overwrite a procedure.++ Args:+ user_id (`str`):+ The owner user id.+ record (`SOPRecord`):+ The procedure to store.++ Returns:+ `SOPRecord`:+ The stored record, with its timestamps refreshed.+ """+ raise NotImplementedError++ async def get_sop(self, user_id: str, sop_id: str) -> SOPRecord | None:+ """Fetch one procedure; owner-scoped.++ Args:+ user_id (`str`):+ The owner user id.+ sop_id (`str`):+ The procedure id.++ Returns:+ `SOPRecord | None`:+ The record, or ``None`` if the user has no such one.+ """+ raise NotImplementedError++ async def list_sops(self, user_id: str) -> list[SOPRecord]:+ """List the user's procedures.++ Args:+ user_id (`str`):+ The owner user id.++ Returns:+ `list[SOPRecord]`:+ Every procedure the user owns.+ """+ raise NotImplementedError++ async def delete_sop(self, user_id: str, sop_id: str) -> bool:+ """Delete a procedure, every run of it, and their conversations.++ Args:+ user_id (`str`):+ The owner user id.+ sop_id (`str`):+ The procedure id.++ Returns:+ `bool`:+ Whether there was one to delete.+ """+ raise NotImplementedError++ async def upsert_sop_run(+ self,+ user_id: str,+ record: SOPRunRecord,+ ) -> SOPRunRecord:+ """Create or overwrite a run.++ Args:+ user_id (`str`):+ The owner user id.+ record (`SOPRunRecord`):+ The run to store.++ Returns:+ `SOPRunRecord`:+ The stored record, with its timestamps refreshed.+ """+ raise NotImplementedError++ async def get_sop_run(+ self,+ user_id: str,+ sop_run_id: str,+ ) -> SOPRunRecord | None:+ """Fetch one run; owner-scoped.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run id.++ Returns:+ `SOPRunRecord | None`:+ The record, or ``None`` if the user has no such one.+ """+ raise NotImplementedError++ async def list_sop_runs(+ self,+ user_id: str,+ sop_id: str | None = None,+ phase: SOPPhase | None = None,+ ) -> list[SOPRunRecord]:+ """List the user's runs, newest first.++ Args:+ user_id (`str`):+ The owner user id.+ sop_id (`str | None`, optional):+ Only runs of this procedure. ``None`` means all of them.+ phase (`SOPPhase | None`, optional):+ Only runs in this phase. ``None`` means all of them.++ Returns:+ `list[SOPRunRecord]`:+ The matching runs.+ """+ raise NotImplementedError++ async def update_sop_run(+ self,+ user_id: str,+ sop_run_id: str,+ state: SOPRunState,+ sessions: dict[str, str] | None = None,+ ) -> None:+ """Update a run's state (and sessions), leaving its definition.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run id.+ state (`SOPRunState`):+ How the run is going now.+ sessions (`dict[str, str] | None`, optional):+ The run's conversations. ``None`` leaves them as is.++ Raises:+ `KeyError`:+ If the user has no such run.+ """+ raise NotImplementedError++ async def delete_sop_run(self, user_id: str, sop_run_id: str) -> bool:+ """Delete one run and the conversations it opened.++ Args:+ user_id (`str`):+ The owner user id.+ sop_run_id (`str`):+ The run id.++ Returns:+ `bool`:+ Whether there was one to delete.+ """+ raise NotImplementedError+# ------------------------------------------------------------------# Team persistence# ------------------------------------------------------------------diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.pyindex 6d4227fb9..51c959085 100644--- a/src/agentscope/app/storage/_model/__init__.py+++ b/src/agentscope/app/storage/_model/__init__.py@@ -36,8 +36,20 @@ from ._session import (ScheduleOrigin,ChannelOrigin,TeamOrigin,+ SOPOrigin,)from ._skill import SkillRecord+from ._sop import (+ AgentVerifier,+ HumanVerifier,+ SOPAgentRef,+ SOPData,+ SOPRecord,+ SOPRunRecord,+ SOPStepDataV1,+ SOPVerifier,+ SOPWorkspaceGrain,+)from ._team import TeamRecord, TeamData, TeamMemberfrom ._user import UserRecord@@ -71,6 +83,16 @@ __all__ = ["ChannelOrigin","TeamOrigin","SkillRecord",+ "AgentVerifier",+ "HumanVerifier",+ "SOPAgentRef",+ "SOPData",+ "SOPOrigin",+ "SOPRecord",+ "SOPRunRecord",+ "SOPStepDataV1",+ "SOPVerifier",+ "SOPWorkspaceGrain","ChatModelConfig","TTSModelConfig","EmbeddingModelConfig",diff --git a/src/agentscope/app/storage/_model/_channel.py b/src/agentscope/app/storage/_model/_channel.pyindex 9f5414d32..f9e67bded 100644--- a/src/agentscope/app/storage/_model/_channel.py+++ b/src/agentscope/app/storage/_model/_channel.py@@ -108,7 +108,7 @@ class RoutingConfig(BaseModel):class SessionSettings(BaseModel):- """Settings applied when a channel creates an agent session."""+ """Settings for a session a channel or SOP run opens for a user."""chat_model_config: dict[str, Any]"""Model configuration for channel-created sessions. Required — therediff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex 5364d37b8..c7cf207ea 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -79,13 +79,31 @@ class TeamOrigin(BaseModel):type: Literal["team"] = "team"+class SOPOrigin(BaseModel):+ """A session a SOP run opened to hold one of its conversations."""++ type: Literal["sop"] = "sop"++ sop_run_id: str+ """The run that opened it."""++ session_key: str+ """Which of the run's conversations this is."""++# How a session came to exist. Fixed when the session is created and# never rewritten, which is what separates it from# ``SessionRecord.team_id``: team membership is granted by a tool call# inside an existing session and can be revoked, so it is a field of its# own rather than a member of this union.SessionOrigin = Annotated[- Union[UserOrigin, ScheduleOrigin, ChannelOrigin, TeamOrigin],+ Union[+ UserOrigin,+ ScheduleOrigin,+ ChannelOrigin,+ TeamOrigin,+ SOPOrigin,+ ],Field(discriminator="type"),]diff --git a/src/agentscope/app/storage/_model/_sop.py b/src/agentscope/app/storage/_model/_sop.pynew file mode 100644index 000000000..7f2a96a06--- /dev/null+++ b/src/agentscope/app/storage/_model/_sop.py@@ -0,0 +1,180 @@+# -*- coding: utf-8 -*-+"""The SOP storage classes: a procedure's description, and its runs.+A live :class:`~agentscope.sop.SOP` holds agents, so only this is stored."""+from enum import StrEnum+from typing import Annotated, Literal, Union++from pydantic import BaseModel, Field++from ._base import _RecordBase+from ._channel import SessionSettings+from ....sop import SOPRunState+++class SOPWorkspaceGrain(StrEnum):+ """How many workspaces a run gets. Always minted for the run, never+ shared with another run."""++ RUN = "run"+ """One for the whole run, so steps can hand files to each other."""++ PER_SESSION_KEY = "per_session_key"+ """One per session, so no step sees another's files."""+++class SOPAgentRef(BaseModel):+ """Which agent does something, and in which conversation."""++ agent_id: str = Field(description="The agent that does the work.")++ session_key: str = Field(+ description=(+ "Which conversation it does it in; references sharing a key "+ "share one session."+ ),+ )+++class AgentVerifier(BaseModel):+ """A verifier that is itself an agent."""++ type: Literal["agent"] = "agent"++ agent: SOPAgentRef = Field(description="Who judges the work.")++ criteria: str = Field(+ default="",+ description=(+ "What to hold the work to, beyond the step's own description."+ ),+ json_schema_extra={"format": "textarea"},+ )+++class HumanVerifier(BaseModel):+ """A verifier that asks a person and waits for the answer."""++ type: Literal["human"] = "human"++ question: str = Field(+ default="Does this meet what the step had to prove?",+ description="What the person is asked.",+ json_schema_extra={"format": "textarea"},+ )+++# Who judges a step: an agent or a person.+SOPVerifier = Annotated[+ Union[AgentVerifier, HumanVerifier],+ Field(discriminator="type"),+]+++class SOPStepDataV1(BaseModel):+ """One milestone, as :class:`~agentscope.sop.SOPStep` runs it.+ An incompatible change becomes a new model discriminated on+ :attr:`version`."""++ version: Literal["v1"] = "v1"++ subject: str = Field(description="A brief, actionable name.")++ description: str = Field(+ description="What this step must achieve — the destination.",+ )++ executor: SOPAgentRef = Field(description="Who does the work.")++ verifier: SOPVerifier | None = Field(+ default=None,+ description="Who judges it. ``None`` accepts whatever comes back.",+ )++ max_attempts: int = Field(+ default=3,+ gt=0,+ description="How many refusals before the run gives up on it.",+ )+++def _session_agents(steps: list[SOPStepDataV1]) -> dict[str, str]:+ """Map each session key the steps name to its agent.++ Raises:+ `ValueError`:+ If one key is used by two different agents.+ """+ agents: dict[str, str] = {}+ for step in steps:+ refs = [step.executor]+ if isinstance(step.verifier, AgentVerifier):+ refs.append(step.verifier.agent)+ for ref in refs:+ if (+ agents.setdefault(ref.session_key, ref.agent_id)+ != ref.agent_id+ ):+ raise ValueError(+ f"Conversation {ref.session_key!r} is used by more "+ f"than one agent.",+ )+ return agents+++class SOPData(BaseModel):+ """A procedure: its milestones, in order."""++ name: str = Field(description="The name of the procedure.")++ description: str = Field(+ default="",+ description="What the procedure is for.",+ )++ steps: list[SOPStepDataV1] = Field(+ min_length=1,+ description="Its milestones, in the order they must happen.",+ )++ workspace_grain: SOPWorkspaceGrain = Field(+ default=SOPWorkspaceGrain.RUN,+ description="How many workspaces a run of this gets.",+ )++ session_settings: dict[str, SessionSettings] = Field(+ default_factory=dict,+ description=(+ "What each conversation is opened with, keyed by session key."+ ),+ )+++class SOPRecord(_RecordBase):+ """A stored procedure."""++ user_id: str+ """The user id."""++ data: SOPData+ """The procedure."""+++class SOPRunRecord(_RecordBase):+ """One run of a procedure."""++ user_id: str+ """The user id."""++ sop_id: str = Field(frozen=True)+ """The :class:`SOPRecord` this run came from. Frozen, since backends+ index runs under it."""++ definition: SOPData+ """A copy of the procedure at start, so editing it cannot strand+ the run."""++ sessions: dict[str, str] = Field(default_factory=dict)+ """The session id for each :attr:`SOPAgentRef.session_key`."""++ state: SOPRunState = Field(default_factory=SOPRunState)+ """How the run is going."""diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.pyindex 352957780..3f7607820 100644--- a/src/agentscope/app/storage/_redis_storage.py+++ b/src/agentscope/app/storage/_redis_storage.py@@ -25,11 +25,14 @@ from ._model import (ScheduleOrigin,SessionOrigin,SkillRecord,+ SOPRecord,+ SOPRunRecord,TeamRecord,)from ._utils import _dump_with_secretsfrom ...credential import CredentialBasefrom ...message import Msg+from ...sop import SOPPhase, SOPRunStatefrom ...state import AgentStateif TYPE_CHECKING:@@ -114,6 +117,13 @@ class RedisStorage(StorageBase):"agentscope:user:{user_id}:channel:{channel_id}:sessions")+ sop: str = "agentscope:user:{user_id}:sop:{sop_id}"+ sop_index: str = "agentscope:user:{user_id}:sops"+ sop_run: str = "agentscope:user:{user_id}:sop_run:{sop_run_id}"+ sop_run_index: str = "agentscope:user:{user_id}:sop_runs"+ # Per-procedure run index.+ sop_run_sop_index: str = "agentscope:user:{user_id}:sop:{sop_id}:runs"+team: str = "agentscope:user:{user_id}:team:{team_id}"team_index: str = "agentscope:user:{user_id}:teams"@@ -1556,6 +1566,182 @@ class RedisStorage(StorageBase):has_more = start > 0return [Msg.model_validate_json(raw) for raw in raw_list], has_more+ # ------------------------------------------------------------------+ # SOP persistence+ # ------------------------------------------------------------------++ async def upsert_sop(self, user_id: str, record: SOPRecord) -> SOPRecord:+ """Persist a procedure and index it under the user."""+ record.updated_at = datetime.now()+ await self._set_with_ttl(+ self._key(self.key_config.sop, user_id=user_id, sop_id=record.id),+ record.model_dump_json(),+ )+ await self._client.sadd(+ self._key(self.key_config.sop_index, user_id=user_id),+ record.id,+ )+ return record++ async def get_sop(self, user_id: str, sop_id: str) -> SOPRecord | None:+ """Fetch one procedure by id."""+ raw = await self._client.get(+ self._key(self.key_config.sop, user_id=user_id, sop_id=sop_id),+ )+ return SOPRecord.model_validate_json(raw) if raw else None++ async def list_sops(self, user_id: str) -> list[SOPRecord]:+ """Return every procedure in the user's index that still exists."""+ ids = await self._client.smembers(+ self._key(self.key_config.sop_index, user_id=user_id),+ )+ records = []+ for sop_id in ids:+ record = await self.get_sop(user_id, sop_id)+ if record is not None:+ records.append(record)+ return records++ async def delete_sop(self, user_id: str, sop_id: str) -> bool:+ """Delete a procedure and every run of it."""+ for run in await self.list_sop_runs(user_id, sop_id=sop_id):+ await self.delete_sop_run(user_id, run.id)+ await self._client.delete(+ self._key(+ self.key_config.sop_run_sop_index,+ user_id=user_id,+ sop_id=sop_id,+ ),+ )+ await self._client.srem(+ self._key(self.key_config.sop_index, user_id=user_id),+ sop_id,+ )+ deleted = await self._client.delete(+ self._key(self.key_config.sop, user_id=user_id, sop_id=sop_id),+ )+ return bool(deleted)++ async def upsert_sop_run(+ self,+ user_id: str,+ record: SOPRunRecord,+ ) -> SOPRunRecord:+ """Persist a run and index it under the user and its procedure."""+ record.updated_at = datetime.now()+ await self._set_with_ttl(+ self._key(+ self.key_config.sop_run,+ user_id=user_id,+ sop_run_id=record.id,+ ),+ record.model_dump_json(),+ )+ await self._client.sadd(+ self._key(self.key_config.sop_run_index, user_id=user_id),+ record.id,+ )+ await self._client.sadd(+ self._key(+ self.key_config.sop_run_sop_index,+ user_id=user_id,+ sop_id=record.sop_id,+ ),+ record.id,+ )+ return record++ async def get_sop_run(+ self,+ user_id: str,+ sop_run_id: str,+ ) -> SOPRunRecord | None:+ """Fetch one run by id."""+ raw = await self._client.get(+ self._key(+ self.key_config.sop_run,+ user_id=user_id,+ sop_run_id=sop_run_id,+ ),+ )+ return SOPRunRecord.model_validate_json(raw) if raw else None++ async def list_sop_runs(+ self,+ user_id: str,+ sop_id: str | None = None,+ phase: SOPPhase | None = None,+ ) -> list[SOPRunRecord]:+ """Return the user's runs, newest first. ``phase`` is filtered+ after reading, since Redis has no index for it."""+ index_key = (+ self._key(self.key_config.sop_run_index, user_id=user_id)+ if sop_id is None+ else self._key(+ self.key_config.sop_run_sop_index,+ user_id=user_id,+ sop_id=sop_id,+ )+ )+ records = []+ for run_id in await self._client.smembers(index_key):+ record = await self.get_sop_run(user_id, run_id)+ if record is not None and phase in (None, record.state.phase):+ records.append(record)+ return sorted(records, key=lambda _: _.created_at, reverse=True)++ async def update_sop_run(+ self,+ user_id: str,+ sop_run_id: str,+ state: SOPRunState,+ sessions: dict[str, str] | None = None,+ ) -> None:+ """Read-modify-write the run record; raises if absent."""+ record = await self.get_sop_run(user_id, sop_run_id)+ if record is None:+ raise KeyError(f"SOP run {sop_run_id!r} not found.")+ record.state = state+ if sessions is not None:+ record.sessions = sessions+ await self.upsert_sop_run(user_id, record)++ async def delete_sop_run(self, user_id: str, sop_run_id: str) -> bool:+ """Delete one run, its sessions, and both index entries."""+ record = await self.get_sop_run(user_id, sop_run_id)+ if record is None:+ return False+ for session_id in record.sessions.values():+ # Redis keys sessions by id alone; the agent id comes back+ # off the record.+ session = await self.get_session(user_id, "", session_id)+ if session is not None:+ await self.delete_session(+ user_id,+ session.agent_id,+ session_id,+ )+ await self._client.srem(+ self._key(self.key_config.sop_run_index, user_id=user_id),+ sop_run_id,+ )+ await self._client.srem(+ self._key(+ self.key_config.sop_run_sop_index,+ user_id=user_id,+ sop_id=record.sop_id,+ ),+ sop_run_id,+ )+ await self._client.delete(+ self._key(+ self.key_config.sop_run,+ user_id=user_id,+ sop_run_id=sop_run_id,+ ),+ )+ return True+# ------------------------------------------------------------------# Team persistence# ------------------------------------------------------------------diff --git a/src/agentscope/app/storage/_sql/_alembic/versions/0004_sops.py b/src/agentscope/app/storage/_sql/_alembic/versions/0004_sops.pynew file mode 100644index 000000000..8c9647a72--- /dev/null+++ b/src/agentscope/app/storage/_sql/_alembic/versions/0004_sops.py@@ -0,0 +1,96 @@+# -*- coding: utf-8 -*-+"""SOP and SOP run tables.++Revision ID: 0004_sops+Revises: 0003_channels+Create Date: 2026-09-14 00:00:00.000000++Both tables are new; ``phase`` copies the run state's derived phase.+"""+from typing import Sequence, Union++from alembic import op+import sqlalchemy as sa+++# revision identifiers, used by Alembic.+revision: str = "0004_sops"+down_revision: Union[str, None] = "0003_channels"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ """Create the ``sops`` and ``sop_runs`` tables."""+ op.create_table(+ "sops",+ sa.Column("user_id", sa.String(length=255), nullable=False),+ sa.Column("id", sa.String(length=255), nullable=False),+ sa.Column("created_at", sa.DateTime(), nullable=False),+ sa.Column("updated_at", sa.DateTime(), nullable=False),+ sa.Column("payload", sa.JSON(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ )+ with op.batch_alter_table("sops", schema=None) as batch_op:+ for column in ("created_at", "updated_at", "user_id"):+ batch_op.create_index(+ batch_op.f(f"ix_sops_{column}"),+ [column],+ unique=False,+ )++ op.create_table(+ "sop_runs",+ sa.Column("user_id", sa.String(length=255), nullable=False),+ sa.Column("sop_id", sa.String(length=255), nullable=False),+ sa.Column("phase", sa.String(length=16), nullable=False),+ sa.Column("id", sa.String(length=255), nullable=False),+ sa.Column("created_at", sa.DateTime(), nullable=False),+ sa.Column("updated_at", sa.DateTime(), nullable=False),+ sa.Column("payload", sa.JSON(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ )+ with op.batch_alter_table("sop_runs", schema=None) as batch_op:+ for column in (+ "created_at",+ "updated_at",+ "user_id",+ "sop_id",+ "phase",+ ):+ batch_op.create_index(+ batch_op.f(f"ix_sop_runs_{column}"),+ [column],+ unique=False,+ )+ batch_op.create_index(+ "ix_sop_runs_user_sop",+ ["user_id", "sop_id"],+ unique=False,+ )+ batch_op.create_index(+ "ix_sop_runs_user_phase",+ ["user_id", "phase"],+ unique=False,+ )+++def downgrade() -> None:+ """Drop the ``sop_runs`` and ``sops`` tables."""+ with op.batch_alter_table("sop_runs", schema=None) as batch_op:+ batch_op.drop_index("ix_sop_runs_user_phase")+ batch_op.drop_index("ix_sop_runs_user_sop")+ for column in (+ "phase",+ "sop_id",+ "user_id",+ "updated_at",+ "created_at",+ ):+ batch_op.drop_index(batch_op.f(f"ix_sop_runs_{column}"))+ op.drop_table("sop_runs")++ with op.batch_alter_table("sops", schema=None) as batch_op:+ for column in ("user_id", "updated_at", "created_at"):+ batch_op.drop_index(batch_op.f(f"ix_sops_{column}"))+ op.drop_table("sops")diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.pyindex d760a4476..8d0eaa962 100644--- a/src/agentscope/app/storage/_sql/_storage.py+++ b/src/agentscope/app/storage/_sql/_storage.py@@ -34,6 +34,8 @@ from .._model import (SessionConfig,SessionOrigin,SkillRecord,+ SOPRecord,+ SOPRunRecord,TeamRecord,)from .._utils import _dump_with_secrets@@ -50,10 +52,13 @@ from ._tables import (ScheduleRow,SessionRow,SkillRow,+ SOPRow,+ SOPRunRow,TeamRow,)from ....credential import CredentialBasefrom ....message import Msg+from ....sop import SOPPhase, SOPRunStatefrom ....state import AgentStateif TYPE_CHECKING:@@ -1049,6 +1054,158 @@ class AsyncSQLAlchemyStorage(StorageBase):await sess.commit()return ok+ # ------------------------------------------------------------------+ # SOPs+ # ------------------------------------------------------------------++ async def upsert_sop(self, user_id: str, record: SOPRecord) -> SOPRecord:+ """Persist a procedure (create or overwrite)."""+ _ = user_id # scoping is enforced by the caller+ return await self._write_row(SOPRow, record)++ async def get_sop(self, user_id: str, sop_id: str) -> SOPRecord | None:+ """Fetch one procedure; owner-scoped."""+ async with self._session() as sess:+ row = await sess.get(SOPRow, sop_id)+ if row is None or row.user_id != user_id:+ return None+ return _to_record(row, SOPRecord)++ async def list_sops(self, user_id: str) -> list[SOPRecord]:+ """Return the user's procedures."""+ from sqlalchemy import select++ async with self._session() as sess:+ rows = (+ (+ await sess.execute(+ select(SOPRow).where(SOPRow.user_id == user_id),+ )+ )+ .scalars()+ .all()+ )+ return [_to_record(r, SOPRecord) for r in rows]++ async def delete_sop(self, user_id: str, sop_id: str) -> bool:+ """Delete a procedure, its runs and their sessions atomically."""+ from sqlalchemy import select++ async with self._session() as sess:+ row = await sess.get(SOPRow, sop_id)+ if row is None or row.user_id != user_id:+ return False+ runs = (+ (+ await sess.execute(+ select(SOPRunRow).where(+ SOPRunRow.user_id == user_id,+ SOPRunRow.sop_id == sop_id,+ ),+ )+ )+ .scalars()+ .all()+ )+ for run in runs:+ await self._delete_sop_run_impl(sess, user_id, run)+ await sess.delete(row)+ await sess.commit()+ return True++ async def _delete_sop_run_impl(+ self,+ sess: "AsyncSession",+ user_id: str,+ row: Any,+ ) -> None:+ """Delete a run row and the sessions it opened, on *sess*."""+ record = _to_record(row, SOPRunRecord)+ for session_id in record.sessions.values():+ session_row = await sess.get(SessionRow, session_id)+ if session_row is not None:+ await self._delete_session_impl(+ sess,+ user_id,+ session_row.agent_id,+ session_id,+ )+ await sess.delete(row)++ async def upsert_sop_run(+ self,+ user_id: str,+ record: SOPRunRecord,+ ) -> SOPRunRecord:+ """Persist a run (create or overwrite)."""+ _ = user_id # scoping is enforced by the caller+ return await self._write_row(SOPRunRow, record)++ async def get_sop_run(+ self,+ user_id: str,+ sop_run_id: str,+ ) -> SOPRunRecord | None:+ """Fetch one run; owner-scoped."""+ async with self._session() as sess:+ row = await sess.get(SOPRunRow, sop_run_id)+ if row is None or row.user_id != user_id:+ return None+ return _to_record(row, SOPRunRecord)++ async def list_sop_runs(+ self,+ user_id: str,+ sop_id: str | None = None,+ phase: SOPPhase | None = None,+ ) -> list[SOPRunRecord]:+ """Return the user's runs, newest first, filtered in the database."""+ from sqlalchemy import select++ stmt = select(SOPRunRow).where(SOPRunRow.user_id == user_id)+ if sop_id is not None:+ stmt = stmt.where(SOPRunRow.sop_id == sop_id)+ if phase is not None:+ stmt = stmt.where(SOPRunRow.phase == phase.value)+ stmt = stmt.order_by(SOPRunRow.created_at.desc())++ async with self._session() as sess:+ rows = (await sess.execute(stmt)).scalars().all()+ return [_to_record(r, SOPRunRecord) for r in rows]++ async def update_sop_run(+ self,+ user_id: str,+ sop_run_id: str,+ state: SOPRunState,+ sessions: dict[str, str] | None = None,+ ) -> None:+ """Read-modify-write on the payload; raises if absent."""+ async with self._session() as sess:+ row = await sess.get(SOPRunRow, sop_run_id)+ if row is None or row.user_id != user_id:+ raise KeyError(f"SOP run {sop_run_id!r} not found.")+ record = _to_record(row, SOPRunRecord)+ record.state = state+ if sessions is not None:+ record.sessions = sessions+ record.updated_at = _utcnow()+ new_row = _from_record(SOPRunRow, record)+ row.payload = new_row.payload+ row.updated_at = new_row.updated_at+ row.phase = new_row.phase+ await sess.commit()++ async def delete_sop_run(self, user_id: str, sop_run_id: str) -> bool:+ """Delete one run and its sessions in one transaction."""+ async with self._session() as sess:+ row = await sess.get(SOPRunRow, sop_run_id)+ if row is None or row.user_id != user_id:+ return False+ await self._delete_sop_run_impl(sess, user_id, row)+ await sess.commit()+ return True+# ------------------------------------------------------------------# Sessions# ------------------------------------------------------------------diff --git a/src/agentscope/app/storage/_sql/_tables.py b/src/agentscope/app/storage/_sql/_tables.pyindex 21c943b99..9625b6b6f 100644--- a/src/agentscope/app/storage/_sql/_tables.py+++ b/src/agentscope/app/storage/_sql/_tables.py@@ -188,6 +188,52 @@ class SessionRow(_JsonRecordMixin):}+class SOPRow(_JsonRecordMixin):+ """One row per :class:`~agentscope.app.storage.SOPRecord`."""++ __tablename__ = "sops"++ user_id: Mapped[str] = mapped_column(+ String(_ID_LEN),+ nullable=False,+ index=True,+ )++ _indexed_fields = ("user_id",)+++class SOPRunRow(_JsonRecordMixin):+ """One row per :class:`~agentscope.app.storage.SOPRunRecord`."""++ __tablename__ = "sop_runs"++ user_id: Mapped[str] = mapped_column(+ String(_ID_LEN),+ nullable=False,+ index=True,+ )+ sop_id: Mapped[str] = mapped_column(+ String(_ID_LEN),+ nullable=False,+ index=True,+ )+ phase: Mapped[str] = mapped_column(+ String(16),+ nullable=False,+ index=True,+ )++ __table_args__ = (+ Index("ix_sop_runs_user_sop", "user_id", "sop_id"),+ Index("ix_sop_runs_user_phase", "user_id", "phase"),+ )++ _indexed_fields = ("user_id", "sop_id")++ # A copy of the run state's derived phase, for filtering.+ _index_paths: ClassVar[dict[str, str]] = {"phase": "state.phase"}++class ScheduleRow(_JsonRecordMixin):"""One row per :class:`~agentscope.app.storage.ScheduleRecord`."""diff --git a/tests/app_sop_router_test.py b/tests/app_sop_router_test.pynew file mode 100644index 000000000..6c7b6d67c--- /dev/null+++ b/tests/app_sop_router_test.py@@ -0,0 +1,428 @@+# -*- coding: utf-8 -*-+"""Tests for the SOP endpoints, over a real app and fake backends.++No model is ever called: every run here stops at a step a person has to+judge, which is exactly the path the endpoints exist to serve.+"""+import tempfile+from typing import Any+from unittest import IsolatedAsyncioTestCase++import fakeredis.aioredis+from fastapi.testclient import TestClient++from agentscope.app import create_app+from agentscope.app.message_bus import RedisMessageBus+from agentscope.app.storage import RedisStorage+from agentscope.app.workspace_manager import LocalWorkspaceManager+from agentscope.sop import SOPRunState++HEADERS = {"X-User-ID": "alice"}++MODEL = {+ "type": "dashscope",+ "credential_id": "c-1",+ "model": "qwen-max",+ "parameters": {},+}+++def _fake_backends() -> tuple:+ """Build a fakeredis-backed storage and message bus."""+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)++ class _Storage(RedisStorage):+ async def __aenter__(self) -> Any:+ self._client = redis+ return self++ async def aclose(self) -> None:+ self._client = None++ class _Bus(RedisMessageBus):+ async def __aenter__(self) -> Any:+ self._client = redis+ return self++ async def aclose(self) -> None:+ self._client = None++ return _Storage(), _Bus()+++class SOPRouterTest(IsolatedAsyncioTestCase):+ """Procedures, their runs, and the verdicts people file."""++ def setUp(self) -> None:+ """Start an app and register the agent a procedure refers to."""+ # pylint: disable=consider-using-with+ workdir = self.enterContext(tempfile.TemporaryDirectory())+ storage, bus = _fake_backends()+ self._client = self.enterContext(+ TestClient(+ create_app(+ storage=storage,+ message_bus=bus,+ workspace_manager=LocalWorkspaceManager(workdir),+ enable_index_worker=False,+ ),+ ),+ )+ self._agent_id = self._client.post(+ "/agent/",+ json={"name": "modeller", "system_prompt": "hi"},+ headers=HEADERS,+ ).json()["agent_id"]++ def _data(self) -> dict:+ """A one-step procedure a person signs off."""+ return {+ "name": "ship",+ "description": "build one",+ "steps": [+ {+ "subject": "model",+ "description": "make the hull",+ "executor": {+ "agent_id": self._agent_id,+ "session_key": "modeller",+ },+ "verifier": {+ "type": "human",+ "question": "Watertight?",+ },+ },+ ],+ "session_settings": {+ "modeller": {"chat_model_config": MODEL},+ },+ }++ def test_a_procedure_round_trips_through_the_api(self) -> None:+ """Create, read, list, edit, delete."""+ created = self._client.post(+ "/sop/",+ json={"data": self._data()},+ headers=HEADERS,+ )+ self.assertEqual(created.status_code, 201)+ sop_id = created.json()["sop_id"]++ fetched = self._client.get(f"/sop/{sop_id}", headers=HEADERS)+ self.assertEqual(fetched.json()["data"]["name"], "ship")++ listed = self._client.get("/sop/", headers=HEADERS).json()+ self.assertEqual(listed["total"], 1)+ self.assertEqual(listed["sops"][0]["id"], sop_id)++ renamed = dict(self._data(), name="ship faster")+ patched = self._client.patch(+ f"/sop/{sop_id}",+ json={"data": renamed},+ headers=HEADERS,+ )+ self.assertEqual(patched.json()["data"]["name"], "ship faster")++ self.assertEqual(+ self._client.delete(f"/sop/{sop_id}", headers=HEADERS).status_code,+ 204,+ )+ self.assertEqual(+ self._client.get(f"/sop/{sop_id}", headers=HEADERS).status_code,+ 404,+ )++ def test_a_step_naming_an_unconfigured_conversation_is_refused(+ self,+ ) -> None:+ """A run of it could not open that session, so it is caught here."""+ data = self._data()+ data["session_settings"] = {}++ refused = self._client.post(+ "/sop/",+ json={"data": data},+ headers=HEADERS,+ )++ self.assertEqual(refused.status_code, 422)+ self.assertIn("modeller", refused.json()["detail"])++ def test_a_conversation_shared_by_two_agents_is_refused(self) -> None:+ """One session belongs to one agent, so a key cannot name two."""+ data = self._data()+ data["steps"][0]["verifier"] = {+ "type": "agent",+ "agent": {"agent_id": "someone-else", "session_key": "modeller"},+ }++ refused = self._client.post(+ "/sop/",+ json={"data": data},+ headers=HEADERS,+ )++ self.assertEqual(refused.status_code, 422)+ self.assertIn(+ "more than one agent",+ refused.json()["detail"],+ )++ def test_an_invalid_model_config_is_refused(self) -> None:+ """Caught while it is an edit, not when a run opens its sessions."""+ data = self._data()+ data["session_settings"]["modeller"]["chat_model_config"] = {}++ refused = self._client.post(+ "/sop/",+ json={"data": data},+ headers=HEADERS,+ )++ self.assertEqual(refused.status_code, 422)++ def test_a_procedure_with_no_steps_is_refused(self) -> None:+ """A run of one could never reach any phase but pending."""+ data = self._data()+ data["steps"] = []++ refused = self._client.post(+ "/sop/",+ json={"data": data},+ headers=HEADERS,+ )++ self.assertEqual(refused.status_code, 422)++ def test_the_schema_resolves_every_ref_it_names(self) -> None:+ """A tagged union's mapping has to point at something."""+ schema = self._client.get("/sop/schema", headers=HEADERS).json()[+ "schema"+ ]++ self.assertIn("steps", schema["properties"])+ defs = set(schema.get("$defs", {}))+ named = set()++ def _walk(node: Any) -> None:+ """Collect every ``#/$defs/...`` pointer in the schema."""+ if isinstance(node, dict):+ ref = node.get("$ref")+ if isinstance(ref, str) and ref.startswith("#/$defs/"):+ named.add(ref.removeprefix("#/$defs/"))+ mapping = node.get("discriminator", {}).get("mapping", {})+ for target in mapping.values():+ named.add(target.removeprefix("#/$defs/"))+ for value in node.values():+ _walk(value)+ elif isinstance(node, list):+ for value in node:+ _walk(value)++ _walk(schema)+ self.assertIn("AgentVerifier", named)+ self.assertEqual(named - defs, set())++ def test_a_run_opens_its_conversations_and_is_listed(self) -> None:+ """Starting a run returns it before it has got anywhere."""+ sop_id = self._client.post(+ "/sop/",+ json={"data": self._data()},+ headers=HEADERS,+ ).json()["sop_id"]++ started = self._client.post(+ f"/sop/{sop_id}/runs",+ json={"inputs": []},+ headers=HEADERS,+ )+ self.assertEqual(started.status_code, 201)+ run = started.json()+ self.assertEqual(list(run["sessions"]), ["modeller"])+ self.assertEqual(run["sop_id"], sop_id)++ listed = self._client.get(+ "/sop/runs",+ params={"sop_id": sop_id},+ headers=HEADERS,+ ).json()+ self.assertEqual([_["id"] for _ in listed["runs"]], [run["id"]])++ self.assertEqual(+ self._client.get(+ f"/sop/runs/{run['id']}",+ headers=HEADERS,+ ).json()["id"],+ run["id"],+ )++ def test_deleting_a_run_takes_its_sessions_and_reports_a_miss(+ self,+ ) -> None:+ """204 once, 404 after, and nothing left under the agent."""+ sop_id = self._client.post(+ "/sop/",+ json={"data": self._data()},+ headers=HEADERS,+ ).json()["sop_id"]+ run = self._client.post(+ f"/sop/{sop_id}/runs",+ json={"inputs": []},+ headers=HEADERS,+ ).json()+ session_id = run["sessions"]["modeller"]++ other = {"X-User-ID": "bob"}+ self.assertEqual(+ self._client.delete(+ f"/sop/runs/{run['id']}",+ headers=other,+ ).status_code,+ 404,+ )++ self.assertEqual(+ self._client.delete(+ f"/sop/runs/{run['id']}",+ headers=HEADERS,+ ).status_code,+ 204,+ )+ self.assertEqual(+ self._client.delete(+ f"/sop/runs/{run['id']}",+ headers=HEADERS,+ ).status_code,+ 404,+ )+ self.assertEqual(+ self._client.get(+ "/sessions/",+ params={"agent_id": self._agent_id},+ headers=HEADERS,+ ).json()["sessions"],+ [],+ )+ self.assertEqual(session_id, run["sessions"]["modeller"])++ def test_a_verdict_is_refused_on_a_step_nobody_was_asked_about(+ self,+ ) -> None:+ """Nothing has been handed over yet, so there is nothing to judge."""+ sop_id = self._client.post(+ "/sop/",+ json={"data": self._data()},+ headers=HEADERS,+ ).json()["sop_id"]+ run_id = self._client.post(+ f"/sop/{sop_id}/runs",+ json={"inputs": []},+ headers=HEADERS,+ ).json()["id"]++ refused = self._client.post(+ f"/sop/runs/{run_id}/verdict",+ json={"step_index": 0, "passed": True},+ headers=HEADERS,+ )+ self.assertEqual(refused.status_code, 409)++ missing = self._client.post(+ f"/sop/runs/{run_id}/verdict",+ json={"step_index": 9, "passed": True},+ headers=HEADERS,+ )+ self.assertEqual(missing.status_code, 404)++ def test_a_verdict_answers_before_the_run_carries_on(self) -> None:+ """The reply is "recorded", not "and here is where it got to"."""+ sop_id = self._client.post(+ "/sop/",+ json={"data": self._data()},+ headers=HEADERS,+ ).json()["sop_id"]+ run_id = self._client.post(+ f"/sop/{sop_id}/runs",+ json={"inputs": []},+ headers=HEADERS,+ ).json()["id"]++ # Park the step the way a handover would, without a model.+ state = self._run_state(run_id)+ state["steps"][0]["phase"] = "awaiting"+ state["steps"][0]["submission"] = [+ {"type": "text", "text": "a hull"},+ ]+ self._put_run_state(run_id, state)++ answered = self._client.post(+ f"/sop/runs/{run_id}/verdict",+ json={"step_index": 0, "passed": True},+ headers=HEADERS,+ )++ self.assertEqual(answered.status_code, 200)+ self.assertListEqual(+ [+ {k: v for k, v in _.items() if k != "created_at"}+ for _ in answered.json()["state"]["steps"][0]["verifications"]+ ],+ [{"passed": True, "message": "", "verifier": "alice"}],+ )++ def _run_state(self, run_id: str) -> dict:+ """Read a run's state straight back out of the API."""+ return self._client.get(+ f"/sop/runs/{run_id}",+ headers=HEADERS,+ ).json()["state"]++ def _put_run_state(self, run_id: str, state: dict) -> None:+ """Write a run's state back through the storage the app holds."""+ storage = self._client.app.state.storage+ portal = self._client.portal++ async def _write() -> None:+ record = await storage.get_sop_run("alice", run_id)+ record.state = SOPRunState.model_validate(state)+ await storage.upsert_sop_run("alice", record)++ portal.call(_write)++ def test_another_user_sees_none_of_it(self) -> None:+ """Everything is owner-scoped, including the run endpoints."""+ sop_id = self._client.post(+ "/sop/",+ json={"data": self._data()},+ headers=HEADERS,+ ).json()["sop_id"]+ run_id = self._client.post(+ f"/sop/{sop_id}/runs",+ json={"inputs": []},+ headers=HEADERS,+ ).json()["id"]++ other = {"X-User-ID": "bob"}+ self.assertEqual(+ self._client.get("/sop/", headers=other).json()["total"],+ 0,+ )+ self.assertEqual(+ self._client.get(f"/sop/{sop_id}", headers=other).status_code,+ 404,+ )+ self.assertEqual(+ self._client.get(+ f"/sop/runs/{run_id}",+ headers=other,+ ).status_code,+ 404,+ )+ self.assertEqual(+ self._client.post(+ f"/sop/runs/{run_id}/verdict",+ json={"step_index": 0, "passed": True},+ headers=other,+ ).status_code,+ 404,+ )diff --git a/tests/app_sop_service_test.py b/tests/app_sop_service_test.pynew file mode 100644index 000000000..7ed719313--- /dev/null+++ b/tests/app_sop_service_test.py@@ -0,0 +1,918 @@+# -*- coding: utf-8 -*-+"""Tests for :class:`SOPService` and the step that drives it.++The chat service is replaced by a script: each entry says what the+session it is handed does with its turn, written through the same+submit tools a real agent would call. What is under test is the+service's own reasoning — which session gets the turn, what it reads+back, and where the run stops.+"""+import asyncio+from contextlib import AsyncExitStack+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.app._service import ChatService, SessionService, SOPService+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys+from agentscope.app._tool import SubmitHandover, SubmitVerdict+from agentscope.app.storage import (+ AgentData,+ AgentRecord,+ AgentVerifier,+ AsyncSQLAlchemyStorage,+ HumanVerifier,+ SessionSettings,+ SOPAgentRef,+ SOPData,+ SOPRecord,+ SOPStepDataV1,+)+from agentscope.agent import ContextConfig, ReActConfig+from agentscope.message import (+ AssistantMsg,+ ToolCallBlock,+ ToolCallState,+ UserMsg,+)+from agentscope.sop import SOPPhase+++class _Workspaces:+ """A workspace manager that only records what it was asked to close."""++ def __init__(self) -> None:+ """Start out having closed nothing."""+ self.closed: list[str] = []++ async def close(self, workspace_id: str) -> None:+ """Remember the workspace."""+ self.closed.append(workspace_id)+++class _ScriptedChat:+ """A chat service that replays one scripted turn per call.++ A turn writes through the same submit tool a real agent would call,+ and finds its step the way ``get_toolkit`` does — the one the stored+ run says is running.+ """++ def __init__(self, storage: Any, bus: Any, script: list[Any]) -> None:+ """Remember the script, and what it gets asked."""+ self._storage = storage+ self._bus = bus+ self.script = list(script)+ self.asked: list[tuple[str, Any]] = []+ self.dispatched: list[str | None] = []+ self.lying_about: list[str | None] = []+ self.sop_run_id = ""++ async def run(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ input_msg: Any = None,+ sop_dispatch: str | None = None,+ ) -> None:+ """Take one turn, doing whatever the script says it does."""+ _ = agent_id+ self.asked.append((session_id, input_msg))+ self.dispatched.append(sop_dispatch)+ self.lying_about.append(+ await self._bus.registry_get(+ MessageBusKeys.sop_dispatch(session_id),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ ),+ )+ action = self.script.pop(0)+ if action is None:+ return+ if action == "park":+ record = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ record.state.context = [+ AssistantMsg(+ name="ex",+ content=[+ ToolCallBlock(+ type="tool_call",+ id="call-1",+ name="shell",+ input="{}",+ state=ToolCallState.SUBMITTED,+ ),+ ],+ ),+ ]+ await self._storage.upsert_session(+ user_id=user_id,+ agent_id=agent_id,+ config=record.config,+ state=record.state,+ session_id=session_id,+ origin=record.origin,+ )+ return++ record = await self._storage.get_sop_run(user_id, self.sop_run_id)+ index = next(+ i+ for i, step in enumerate(record.state.steps)+ if step.phase is SOPPhase.RUNNING+ )+ tool_cls, kwargs = action+ tool = tool_cls(+ storage=self._storage,+ user_id=user_id,+ sop_run_id=self.sop_run_id,+ step_index=index,+ **({"verifier": "ve"} if tool_cls is SubmitVerdict else {}),+ )+ await tool(**kwargs)+++def _sop(user_id: str, verifier: Any, keys: tuple[str, str]) -> SOPRecord:+ """A one-step procedure with the given verifier and session keys."""+ return SOPRecord(+ user_id=user_id,+ data=SOPData(+ name="ship",+ steps=[+ SOPStepDataV1(+ subject="model",+ description="make the hull",+ executor=SOPAgentRef(agent_id="a-1", session_key=keys[0]),+ verifier=verifier,+ ),+ ],+ session_settings={+ key: SessionSettings(+ chat_model_config={+ "type": "dashscope",+ "credential_id": "c-1",+ "model": "qwen-max",+ "parameters": {},+ },+ )+ for key in set(keys)+ },+ ),+ )+++class SOPServiceTest(IsolatedAsyncioTestCase):+ """End-to-end tests over in-memory SQLite."""++ async def asyncSetUp(self) -> None:+ """Open storage and register the agents a procedure refers to."""+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(+ InMemoryMessageBus(),+ )+ self.storage = await self._stack.enter_async_context(+ AsyncSQLAlchemyStorage(+ "sqlite+aiosqlite:///:memory:",+ create_tables=True,+ ),+ )+ self.sessions = SessionService(self.storage, self.bus)+ for agent_id, name in (("a-1", "ex"), ("a-2", "ve")):+ await self.storage.upsert_agent(+ "user-1",+ AgentRecord(+ id=agent_id,+ user_id="user-1",+ data=AgentData(+ name=name,+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ ),+ )++ async def asyncTearDown(self) -> None:+ """Close storage."""+ await self._stack.aclose()++ async def _drive(self, chat: _ScriptedChat, run_id: str) -> None:+ """Run the service with the scripted chat bound to this run."""+ chat.sop_run_id = run_id+ await SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ chat,+ self.sessions,+ ).run(+ "user-1",+ run_id,+ )++ async def test_a_run_walks_its_step_and_finishes(self) -> None:+ """Work, then judgement, then the run is done."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run(+ "user-1",+ sop.id,+ [UserMsg(name="user", content="go")],+ )++ chat = _ScriptedChat(+ self.storage,+ self.bus,+ [+ (SubmitHandover, {"handover": "a hull"}),+ (SubmitVerdict, {"passed": True}),+ ],+ )+ await self._drive(chat, run.id)++ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(stored.state.phase, SOPPhase.COMPLETED)+ self.maxDiff = None+ self.assertListEqual(+ [_.model_dump(mode="json") for _ in stored.state.steps],+ [+ {+ "phase": "completed",+ "given": [+ {+ "name": "user",+ "content": [+ {+ "type": "text",+ "text": "go",+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ },+ ],+ "role": "user",+ "id": AnyString(),+ "metadata": {},+ "created_at": AnyString(),+ "usage": None,+ "finished_at": AnyString(),+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ },+ ],+ "submission": [+ {+ "type": "text",+ "text": "a hull",+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ },+ ],+ "verifications": [+ {+ "passed": True,+ "message": "",+ "verifier": "ve",+ "created_at": AnyString(),+ },+ ],+ },+ ],+ )+ # The work went to one session and the judging to the other.+ self.assertListEqual(+ [session for session, _ in chat.asked],+ [run.sessions["modeller"], run.sessions["reviewer"]],+ )++ async def test_a_refusal_sends_the_step_back(self) -> None:+ """A refused attempt is retried, and the critique comes with it."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ chat = _ScriptedChat(+ self.storage,+ self.bus,+ [+ (SubmitHandover, {"handover": "a leaky hull"}),+ (SubmitVerdict, {"passed": False, "message": "panel 3 leaks"}),+ (SubmitHandover, {"handover": "a sealed hull"}),+ (SubmitVerdict, {"passed": True}),+ ],+ )+ await self._drive(chat, run.id)++ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(stored.state.phase, SOPPhase.COMPLETED)+ self.assertEqual(len(stored.state.steps[0].verifications), 2)+ self.assertIn("panel 3 leaks", str(chat.asked[2][1]))++ async def test_the_run_gives_up_once_the_attempts_do(self) -> None:+ """Refusals are spent from the step's budget, not forgiven."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ sop.data.steps[0].max_attempts = 2+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ chat = _ScriptedChat(+ self.storage,+ self.bus,+ [+ (SubmitHandover, {"handover": "draft"}),+ (SubmitVerdict, {"passed": False, "message": "no"}),+ ]+ * 2,+ )+ await self._drive(chat, run.id)++ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(stored.state.phase, SOPPhase.FAILED)++ async def test_a_turn_that_submits_nothing_costs_an_attempt(self) -> None:+ """An agent that just stops has produced nothing to go on."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ sop.data.steps[0].max_attempts = 1+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ await self._drive(+ _ScriptedChat(self.storage, self.bus, [None]),+ run.id,+ )++ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(stored.state.phase, SOPPhase.FAILED)+ self.assertListEqual(+ [+ _.model_dump(mode="json")+ for _ in stored.state.steps[0].verifications+ ],+ [+ {+ "passed": False,+ "message": (+ "Your turn ended without submitting anything, so "+ "the step has nothing to show for it."+ ),+ "verifier": "sop",+ "created_at": AnyString(),+ },+ ],+ )++ async def test_a_human_verifier_stops_the_run_until_someone_answers(+ self,+ ) -> None:+ """The verdict is a write, so nothing is dispatched to wait on it."""+ sop = _sop(+ "user-1",+ HumanVerifier(question="Watertight?"),+ ("modeller", "modeller"),+ )+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ chat = _ScriptedChat(+ self.storage,+ self.bus,+ [(SubmitHandover, {"handover": "a hull"})],+ )+ await self._drive(chat, run.id)++ parked = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(parked.state.phase, SOPPhase.AWAITING)+ self.assertEqual(len(chat.asked), 1)++ # Whoever is asked files the verdict through the same tool an+ # agent reviewer would, and the run picks up from that.+ await SubmitVerdict(+ storage=self.storage,+ user_id="user-1",+ sop_run_id=run.id,+ step_index=0,+ verifier="user-1",+ )(passed=True)++ await self._drive(_ScriptedChat(self.storage, self.bus, []), run.id)++ self.assertEqual(+ (await self.storage.get_sop_run("user-1", run.id)).state.phase,+ SOPPhase.COMPLETED,+ )++ async def test_a_turn_is_claimed_only_while_the_run_asked_for_it(+ self,+ ) -> None:+ """What tells a step's turn apart from a person typing."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ chat = _ScriptedChat(+ self.storage,+ self.bus,+ [+ (SubmitHandover, {"handover": "a hull"}),+ (SubmitVerdict, {"passed": True}),+ ],+ )+ await self._drive(chat, run.id)++ # Each turn was told which step it was for.+ self.assertListEqual(chat.dispatched, [f"{run.id}:0", f"{run.id}:0"])+ # And nothing was left lying in the registry while it ran, for+ # a turn the run never asked for to pick up.+ self.assertListEqual(chat.lying_about, [None, None])+ # Nor once the run stops.+ for session_id in run.sessions.values():+ self.assertIsNone(+ await self.bus.registry_get(+ MessageBusKeys.sop_dispatch(session_id),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ ),+ )++ async def test_a_parked_turn_keeps_its_claim(self) -> None:+ """Whoever answers it resumes this attempt and must still submit.++ The answer arrives through the ordinary chat endpoint, not+ through the run, so the claim is the only thing that will still+ be saying this session owes the step a deliverable.+ """+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ await self._drive(+ _ScriptedChat(self.storage, self.bus, ["park"]),+ run.id,+ )++ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(stored.state.phase, SOPPhase.AWAITING)+ self.assertEqual(+ await self.bus.registry_get(+ MessageBusKeys.sop_dispatch(run.sessions["modeller"]),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ ),+ f"{run.id}:0",+ )+ # Nothing was held against the step for parking.+ self.assertListEqual(stored.state.steps[0].verifications, [])++ async def test_leaving_the_service_stops_the_advances_it_started(+ self,+ ) -> None:+ """They outlive their request, so something has to end them."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)++ class _Hanging:+ """A chat service whose turn never comes back."""++ def __init__(self) -> None:+ """Start out uncancelled, with nobody inside yet."""+ self.entered = asyncio.Event()+ self.cancelled = False++ async def run(self, *args: Any, **kwargs: Any) -> None:+ """Wait to be cancelled, and remember that it was."""+ _ = args, kwargs+ self.entered.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ self.cancelled = True+ raise++ chat = _Hanging()+ async with SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ chat,+ self.sessions,+ ) as service:+ run = await service.create_run("user-1", sop.id)+ service.advance_later("user-1", run.id)+ # Waited for rather than slept on: how long an advance+ # takes to reach its turn is the scheduler's business.+ await chat.entered.wait()++ self.assertTrue(chat.cancelled)++ async def test_a_turn_that_raises_still_releases_its_claim(self) -> None:+ """Otherwise the next person to type there inherits the claim."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ class _Failing:+ """A chat service whose turn blows up."""++ async def run(self, *args: Any, **kwargs: Any) -> None:+ """Fail the way an unassemblable agent would."""+ _ = args, kwargs+ raise RuntimeError("no model configured")++ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ _Failing(),+ self.sessions,+ )+ with self.assertRaises(RuntimeError):+ await service.run("user-1", run.id)++ self.assertIsNone(+ await self.bus.registry_get(+ MessageBusKeys.sop_dispatch(run.sessions["modeller"]),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ ),+ )++ async def test_a_verdict_is_refused_unless_the_step_asked_for_one(+ self,+ ) -> None:+ """The two ways a person's verdict does not belong on a step."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ with self.assertRaises(ValueError) as judged:+ await service.record_verdict("user-1", run.id, 0, True)+ self.assertIn("not judged by a person", str(judged.exception))++ with self.assertRaises(KeyError):+ await service.record_verdict("user-1", run.id, 9, True)+ with self.assertRaises(KeyError):+ await service.record_verdict("user-2", run.id, 0, True)++ async def test_deleting_a_run_takes_its_conversations(self) -> None:+ """A session nobody opened is still wakeable, so none is left."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)+ session_id = run.sessions["modeller"]++ self.assertTrue(await self.storage.delete_sop_run("user-1", run.id))++ self.assertIsNone(+ await self.storage.get_session("user-1", "a-1", session_id),+ )+ self.assertEqual(await self.storage.list_sessions("user-1", "a-1"), [])++ async def test_deleting_a_procedure_takes_every_run_conversation(+ self,+ ) -> None:+ """The same cascade, one level up."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ first = await service.create_run("user-1", sop.id)+ second = await service.create_run("user-1", sop.id)++ self.assertTrue(await self.storage.delete_sop("user-1", sop.id))++ for run in (first, second):+ self.assertIsNone(+ await self.storage.get_session(+ "user-1",+ "a-1",+ run.sessions["modeller"],+ ),+ )+ self.assertEqual(await self.storage.list_sop_runs("user-1"), [])++ async def test_one_conversation_per_session_key(self) -> None:+ """A key named twice is one session; two keys are two."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ sop.data.steps.append(+ SOPStepDataV1(+ subject="paint",+ description="give it a livery",+ executor=SOPAgentRef(agent_id="a-1", session_key="modeller"),+ ),+ )+ await self.storage.upsert_sop("user-1", sop)++ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ self.assertEqual(list(run.sessions), ["modeller"])+ session = await self.storage.get_session(+ "user-1",+ "a-1",+ run.sessions["modeller"],+ )+ self.assertEqual(+ session.origin.model_dump(),+ {+ "type": "sop",+ "sop_run_id": run.id,+ "session_key": "modeller",+ },+ )++ async def test_a_reviewer_that_files_no_verdict_costs_an_attempt(+ self,+ ) -> None:+ """Otherwise the reviewer is dispatched again and again, for free."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ sop.data.steps[0].max_attempts = 1+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)++ chat = _ScriptedChat(+ self.storage,+ self.bus,+ [(SubmitHandover, {"handover": "a hull"}), None],+ )+ await self._drive(chat, run.id)++ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertListEqual(+ [+ _.model_dump(mode="json")+ for _ in stored.state.steps[0].verifications+ ],+ [+ {+ "passed": False,+ "message": (+ "The reviewer ended its turn without a verdict."+ ),+ "verifier": "sop",+ "created_at": AnyString(),+ },+ ],+ )+ self.assertEqual(stored.state.phase, SOPPhase.FAILED)+ self.assertEqual(len(chat.asked), 2)++ async def test_a_step_still_parked_is_not_briefed_again(self) -> None:+ """Its agent is waiting for an answer, not for a new brief."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)+ await self._drive(+ _ScriptedChat(self.storage, self.bus, ["park"]),+ run.id,+ )++ chat = _ScriptedChat(self.storage, self.bus, [])+ await self._drive(chat, run.id)++ self.assertListEqual(chat.asked, [])+ stored = await self.storage.get_sop_run("user-1", run.id)+ self.assertEqual(stored.state.phase, SOPPhase.AWAITING)++ async def test_deleting_a_run_through_the_service_cleans_up(self) -> None:+ """Its sessions, its claims and its workspace all go with it."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ workspaces = _Workspaces()+ service = SOPService(+ self.storage,+ workspaces,+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)+ session_id = run.sessions["modeller"]+ session = await self.storage.get_session("user-1", "a-1", session_id)+ await self._drive(+ _ScriptedChat(self.storage, self.bus, ["park"]),+ run.id,+ )++ self.assertTrue(await service.delete_run("user-1", run.id))++ self.assertIsNone(await self.storage.get_sop_run("user-1", run.id))+ self.assertIsNone(+ await self.storage.get_session("user-1", "a-1", session_id),+ )+ self.assertIsNone(+ await self.bus.registry_get(+ MessageBusKeys.sop_dispatch(session_id),+ MessageBusKeys.SOP_DISPATCH_FIELD,+ ),+ )+ self.assertListEqual(+ workspaces.closed,+ [session.config.workspace_id],+ )+ self.assertFalse(await service.delete_run("user-1", run.id))++ async def test_a_run_that_fails_to_open_leaves_no_sessions(self) -> None:+ """Nothing could reach them without the run record."""+ sop = _sop("user-1", None, ("modeller", "modeller"))+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )++ async def _fail(*args: Any, **kwargs: Any) -> None:+ _ = args, kwargs+ raise RuntimeError("storage is down")++ self.storage.upsert_sop_run = _fail+ with self.assertRaises(RuntimeError):+ await service.create_run("user-1", sop.id)++ self.assertEqual(await self.storage.list_sessions("user-1", "a-1"), [])++ async def test_a_parked_claim_holds_only_for_the_half_it_parked(+ self,+ ) -> None:+ """Once handed over, the author's session cannot judge its own work."""+ sop = _sop(+ "user-1",+ AgentVerifier(+ agent=SOPAgentRef(agent_id="a-2", session_key="reviewer"),+ ),+ ("modeller", "reviewer"),+ )+ await self.storage.upsert_sop("user-1", sop)+ service = SOPService(+ self.storage,+ _Workspaces(),+ self.bus,+ None,+ self.sessions,+ )+ run = await service.create_run("user-1", sop.id)+ await self._drive(+ _ScriptedChat(self.storage, self.bus, ["park"]),+ run.id,+ )+ chat = ChatService(+ storage=self.storage,+ workspace_manager=_Workspaces(),+ scheduler_manager=object(),+ background_task_manager=object(),+ message_bus=self.bus,+ resource_access_service=object(),+ )+ # pylint: disable=protected-access+ self.assertEqual(+ await chat._parked_dispatch("user-1", run.sessions["modeller"]),+ f"{run.id}:0",+ )++ # The resumed turn hands over; the step now waits on its reviewer.+ await SubmitHandover(+ storage=self.storage,+ user_id="user-1",+ sop_run_id=run.id,+ step_index=0,+ )(handover="a hull")++ self.assertIsNone(+ await chat._parked_dispatch("user-1", run.sessions["modeller"]),+ )diff --git a/tests/sop_step_middleware_test.py b/tests/sop_step_middleware_test.pynew file mode 100644index 000000000..a1a01d342--- /dev/null+++ b/tests/sop_step_middleware_test.py@@ -0,0 +1,233 @@+# -*- coding: utf-8 -*-+"""Unittests for :class:`SOPStepSubmitMiddleware`.++Driven against a real :class:`Agent` with a mock model and a stand-in+submit tool, so the reasoning-acting loop is genuine while nothing+touches the app service layer.+"""+import itertools+import json+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase++from utils import MockModel++from agentscope.agent import Agent, InjectionConfig, ReActConfig+from agentscope.app.middleware import SOPStepSubmitMiddleware+from agentscope.event import ReplyEndEvent+from agentscope.message import TextBlock, ToolCallBlock, ToolResultState+from agentscope.message import UserMsg+from agentscope.model import ChatResponse+from agentscope.permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from agentscope.tool import ToolBase, ToolChunk, Toolkit+from agentscope.types import ReplyFinishedReason+++class _FakeSubmit(ToolBase):+ """Stand-in for ``SubmitHandover`` — records calls, never writes."""++ name: str = "SubmitHandover"+ description: str = "Hand over the result of this step."+ input_schema: dict = {+ "type": "object",+ "properties": {"handover": {"type": "string"}},+ "required": ["handover"],+ }+ is_concurrency_safe: bool = False+ is_read_only: bool = False+ is_state_injected: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ def __init__(self, state: ToolResultState = ToolResultState.SUCCESS):+ """Answer with the given state every time."""+ super().__init__()+ self.calls: list[dict] = []+ self._state = state++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Always allow."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="allowed",+ )++ async def __call__(self, handover: str) -> ToolChunk:+ """Record the call and answer with the configured state."""+ self.calls.append({"handover": handover})+ return ToolChunk(+ content=[TextBlock(text="handed over")],+ state=self._state,+ )+++class _OtherTool(_FakeSubmit):+ """A non-submit tool, used to invalidate an earlier submission."""++ name: str = "Note"+ description: str = "Write a note."++ async def __call__(self, handover: str) -> ToolChunk:+ """Answer successfully without submitting anything."""+ self.calls.append({"handover": handover})+ return ToolChunk(content=[TextBlock(text="noted")])+++def _text(text: str) -> ChatResponse:+ """A plain text reply — ends the reasoning-acting loop."""+ return ChatResponse(content=[TextBlock(text=text)], is_last=True)+++_CALL_SEQ = itertools.count()+++def _call(tool: str, **kwargs: Any) -> ChatResponse:+ """A single tool call reply; ``input`` is the raw JSON string."""+ return ChatResponse(+ content=[+ ToolCallBlock(+ type="tool_call",+ id=f"call-{tool}-{next(_CALL_SEQ)}",+ name=tool,+ input=json.dumps(kwargs),+ ),+ ],+ is_last=True,+ )+++class SOPStepSubmitMiddlewareTest(IsolatedAsyncioTestCase):+ """The nudge / release / give-up decisions of the middleware."""++ async def asyncSetUp(self) -> None:+ """Build a step agent wired to the middleware."""+ self.model = MockModel()+ self.submit = _FakeSubmit()++ async def _run(+ self,+ responses: list,+ *,+ max_iters: int = 5,+ max_nudges: int = 3,+ extra_tools: list | None = None,+ submit: ToolBase | None = None,+ ) -> list:+ """Drive one reply and return the streamed items."""+ toolkit = Toolkit(+ tools=[submit or self.submit, *(extra_tools or [])],+ )+ self.model.set_responses(responses)+ agent = Agent(+ name="modeller",+ system_prompt="You make hulls.",+ model=self.model,+ toolkit=toolkit,+ react_config=ReActConfig(max_iters=max_iters),+ middlewares=[SOPStepSubmitMiddleware(max_nudges=max_nudges)],+ injection_config=InjectionConfig(inject_runtime_state=False),+ )+ return [_ async for _ in agent.reply_stream(UserMsg("sop", "do it"))]++ @staticmethod+ def _end_events(items: list) -> list[ReplyEndEvent]:+ """The reply-end events that escaped the middleware."""+ return [_ for _ in items if isinstance(_, ReplyEndEvent)]++ async def test_a_successful_submission_ends_the_reply(self) -> None:+ """Nothing is swallowed once the step has something to show."""+ items = await self._run(+ [+ _call("SubmitHandover", handover="a hull"),+ _text("handed over"),+ ],+ )++ self.assertDictEqual(+ {+ "model_calls": self.model.cnt,+ "reasons": [+ _.finished_reason for _ in self._end_events(items)+ ],+ "submissions": self.submit.calls,+ },+ {+ "model_calls": 2,+ "reasons": [ReplyFinishedReason.COMPLETED],+ "submissions": [{"handover": "a hull"}],+ },+ )++ async def test_a_reply_that_submits_nothing_is_sent_back(self) -> None:+ """Then accepted as soon as it submits."""+ items = await self._run(+ [+ _text("all done!"),+ _call("SubmitHandover", handover="a hull"),+ _text("handed over"),+ ],+ )++ self.assertDictEqual(+ {+ "reasons": [+ _.finished_reason for _ in self._end_events(items)+ ],+ "submissions": self.submit.calls,+ },+ {+ "reasons": [ReplyFinishedReason.COMPLETED],+ "submissions": [{"handover": "a hull"}],+ },+ )++ async def test_the_nudges_run_out(self) -> None:+ """An attempt that never submits fails rather than looping."""+ items = await self._run([_text("all done!")] * 6, max_nudges=2)++ ends = self._end_events(items)+ self.assertListEqual(+ [_.finished_reason for _ in ends],+ [ReplyFinishedReason.ERROR],+ )+ self.assertIn("without submitting", ends[0].error.message)+ self.assertListEqual(self.submit.calls, [])++ async def test_a_later_tool_call_undoes_the_submission(self) -> None:+ """Whatever the reply did last is what its turn amounts to."""+ items = await self._run(+ [+ _call("SubmitHandover", handover="a hull"),+ _call("Note", handover="and one more thing"),+ _text("all done!"),+ ],+ max_nudges=0,+ extra_tools=[_OtherTool()],+ )++ self.assertListEqual(+ [_.finished_reason for _ in self._end_events(items)],+ [ReplyFinishedReason.ERROR],+ )++ async def test_a_submission_that_failed_does_not_count(self) -> None:+ """The tool answered, but the step has nothing filed for it."""+ items = await self._run(+ [_call("SubmitHandover", handover="a hull"), _text("done")],+ max_nudges=0,+ submit=_FakeSubmit(state=ToolResultState.ERROR),+ )++ self.assertListEqual(+ [_.finished_reason for _ in self._end_events(items)],+ [ReplyFinishedReason.ERROR],+ )diff --git a/tests/storage_redis_test.py b/tests/storage_redis_test.pyindex 5e0bba412..dd409cd32 100644--- a/tests/storage_redis_test.py+++ b/tests/storage_redis_test.py@@ -6,6 +6,8 @@ from unittest.async_case import IsolatedAsyncioTestCaseimport fakeredis.aioredis+from utils import AnyString+from agentscope.app.storage import (RedisStorage,AgentRecord,@@ -19,6 +21,11 @@ from agentscope.app.storage import (TeamData,TeamMember,TeamRecord,+ SOPAgentRef,+ SOPData,+ SOPRecord,+ SOPRunRecord,+ SOPStepDataV1,)from agentscope.app.storage import MCPRecord, SkillRecordfrom agentscope.credential import OllamaCredential@@ -26,6 +33,7 @@ from agentscope.mcp import HttpMCPConfig, MCPClientfrom agentscope.app.storage import AgentDatafrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.message import UserMsg, AssistantMsg, TextBlock+from agentscope.sop import SOPPhase, SOPRunState, SOPStepRunStatefrom agentscope.state import AgentState@@ -1639,3 +1647,297 @@ class TestChannelSessionIndex(IsolatedAsyncioTestCase):),[],)+++# A procedure needs at least one milestone, so the fixtures that only+# care about the record around it still carry one.+_A_STEP = SOPStepDataV1(+ subject="model",+ description="make the hull",+ executor=SOPAgentRef(agent_id="a-1", session_key="modeller"),+)+++def make_sop_record(user_id: str) -> SOPRecord:+ """A one-step procedure."""+ return SOPRecord(+ user_id=user_id,+ data=SOPData(+ name="ship",+ description="build one",+ steps=[+ SOPStepDataV1(+ subject="model",+ description="make the hull",+ executor=SOPAgentRef(+ agent_id="agent-1",+ session_key="modeller",+ ),+ ),+ ],+ ),+ )+++class TestSOP(IsolatedAsyncioTestCase):+ """Tests for SOP and SOP run CRUD."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.storage = make_storage()+ self.user_id = "user-1"++ async def test_round_trip(self) -> None:+ """A stored procedure comes back whole."""+ record = make_sop_record(self.user_id)+ await self.storage.upsert_sop(self.user_id, record)++ fetched = await self.storage.get_sop(self.user_id, record.id)++ self.maxDiff = None+ self.assertDictEqual(+ fetched.model_dump(mode="json"),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "updated_at": AnyString(),+ "user_id": "user-1",+ "data": {+ "name": "ship",+ "description": "build one",+ "steps": [+ {+ "version": "v1",+ "subject": "model",+ "description": "make the hull",+ "executor": {+ "agent_id": "agent-1",+ "session_key": "modeller",+ },+ "verifier": None,+ "max_attempts": 3,+ },+ ],+ "workspace_grain": "run",+ "session_settings": {},+ },+ },+ )+ self.assertEqual(+ [_.id for _ in await self.storage.list_sops(self.user_id)],+ [record.id],+ )++ async def test_user_isolation(self) -> None:+ """One user's procedures are invisible to another."""+ record = make_sop_record("user-A")+ await self.storage.upsert_sop("user-A", record)++ self.assertEqual(await self.storage.list_sops("user-B"), [])+ self.assertIsNone(await self.storage.get_sop("user-B", record.id))++ async def test_delete(self) -> None:+ """Deleting twice reports the second as a miss."""+ record = make_sop_record(self.user_id)+ await self.storage.upsert_sop(self.user_id, record)++ self.assertTrue(await self.storage.delete_sop(self.user_id, record.id))+ self.assertFalse(+ await self.storage.delete_sop(self.user_id, record.id),+ )+ self.assertEqual(await self.storage.list_sops(self.user_id), [])++ async def test_runs_are_listed_by_procedure_and_phase(self) -> None:+ """The per-procedure index narrows the read; phase filters after."""+ waiting = SOPRunRecord(+ user_id=self.user_id,+ sop_id="sop-1",+ definition=SOPData(name="a", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING)],+ ),+ )+ done = SOPRunRecord(+ user_id=self.user_id,+ sop_id="sop-1",+ definition=SOPData(name="a", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.COMPLETED)],+ ),+ )+ other = SOPRunRecord(+ user_id=self.user_id,+ sop_id="sop-2",+ definition=SOPData(name="b", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING)],+ ),+ )+ for record in (waiting, done, other):+ await self.storage.upsert_sop_run(self.user_id, record)++ self.assertEqual(+ {+ _.id+ for _ in await self.storage.list_sop_runs(+ self.user_id,+ sop_id="sop-1",+ )+ },+ {waiting.id, done.id},+ )+ self.assertEqual(+ {+ _.id+ for _ in await self.storage.list_sop_runs(+ self.user_id,+ phase=SOPPhase.AWAITING,+ )+ },+ {waiting.id, other.id},+ )++ async def test_update_run_writes_state_and_sessions(self) -> None:+ """The hot path rewrites what moves and keeps the snapshot."""+ run = SOPRunRecord(+ user_id=self.user_id,+ sop_id="sop-1",+ definition=SOPData(name="ship", steps=[_A_STEP]),+ state=SOPRunState(steps=[SOPStepRunState()]),+ )+ await self.storage.upsert_sop_run(self.user_id, run)++ await self.storage.update_sop_run(+ self.user_id,+ run.id,+ SOPRunState(steps=[SOPStepRunState(phase=SOPPhase.AWAITING)]),+ sessions={"modeller": "session-1"},+ )++ updated = await self.storage.get_sop_run(self.user_id, run.id)++ self.maxDiff = None+ self.assertDictEqual(+ updated.model_dump(mode="json"),+ {+ "id": run.id,+ "created_at": AnyString(),+ "updated_at": AnyString(),+ "user_id": "user-1",+ "sop_id": "sop-1",+ "definition": {+ "name": "ship",+ "description": "",+ "steps": [+ {+ "version": "v1",+ "subject": "model",+ "description": "make the hull",+ "executor": {+ "agent_id": "a-1",+ "session_key": "modeller",+ },+ "verifier": None,+ "max_attempts": 3,+ },+ ],+ "workspace_grain": "run",+ "session_settings": {},+ },+ "sessions": {"modeller": "session-1"},+ "state": {+ "id": AnyString(),+ "inputs": [],+ "steps": [+ {+ "phase": "awaiting",+ "given": [],+ "submission": None,+ "verifications": [],+ },+ ],+ "created_at": AnyString(),+ "phase": "awaiting",+ },+ },+ )++ with self.assertRaises(KeyError):+ await self.storage.update_sop_run(+ self.user_id,+ "no-such-id",+ SOPRunState(),+ )++ async def test_deleting_a_sop_takes_its_runs_with_it(self) -> None:+ """A run is only readable through the definition it snapshotted."""+ sop = make_sop_record(self.user_id)+ await self.storage.upsert_sop(self.user_id, sop)+ run = SOPRunRecord(+ user_id=self.user_id,+ sop_id=sop.id,+ definition=sop.data,+ )+ await self.storage.upsert_sop_run(self.user_id, run)++ await self.storage.delete_sop(self.user_id, sop.id)++ self.assertIsNone(await self.storage.get_sop_run(self.user_id, run.id))+ self.assertEqual(await self.storage.list_sop_runs(self.user_id), [])++ async def test_deleting_a_run_takes_its_sessions(self) -> None:+ """The run minted them, so none is left behind to be woken."""+ await self.storage.upsert_agent(+ self.user_id,+ make_agent_record(self.user_id),+ )+ agents = await self.storage.list_agents(self.user_id)+ session = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=agents[0].id,+ config=SessionConfig(workspace_id="ws-1"),+ )+ run = SOPRunRecord(+ user_id=self.user_id,+ sop_id="sop-1",+ definition=SOPData(name="ship", steps=[_A_STEP]),+ sessions={"modeller": session.id},+ )+ await self.storage.upsert_sop_run(self.user_id, run)++ self.assertTrue(+ await self.storage.delete_sop_run(self.user_id, run.id),+ )++ self.assertIsNone(+ await self.storage.get_session(+ self.user_id,+ agents[0].id,+ session.id,+ ),+ )++ async def test_a_step_state_subclass_survives_redis(self) -> None:+ """What a step kept beyond the base record is stored, not trimmed."""+ run = SOPRunRecord(+ user_id=self.user_id,+ sop_id="sop-1",+ definition=SOPData(name="ship", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING, call_id="c1")],+ ),+ )+ await self.storage.upsert_sop_run(self.user_id, run)++ fetched = await self.storage.get_sop_run(self.user_id, run.id)++ self.assertDictEqual(+ fetched.state.steps[0].model_dump(mode="json"),+ {+ "phase": "awaiting",+ "given": [],+ "submission": None,+ "verifications": [],+ "call_id": "c1",+ },+ )diff --git a/tests/storage_sql_test.py b/tests/storage_sql_test.pyindex c4ff4623e..2ad2e65c4 100644--- a/tests/storage_sql_test.py+++ b/tests/storage_sql_test.py@@ -44,6 +44,13 @@ from agentscope.app.storage import (ScheduleOrigin,SessionRecord,SkillRecord,+ SOPAgentRef,+ SOPData,+ SOPRecord,+ SOPRunRecord,+ SOPStepDataV1,+ AgentVerifier,+ HumanVerifier,AsyncSQLAlchemyStorage,TeamData,TeamMember,@@ -54,6 +61,7 @@ from agentscope.agent import ContextConfig, ReActConfigfrom agentscope.credential import DashScopeCredentialfrom agentscope.mcp import HttpMCPConfig, MCPClientfrom agentscope.message import AssistantMsg, UserMsg+from agentscope.sop import SOPPhase, SOPRunState, SOPStepRunStatedef _channel_record(@@ -171,6 +179,15 @@ def _mcp_record(user_id: str, name: str = "deepwiki") -> MCPRecord:)+# A procedure needs at least one milestone, so the fixtures that only+# care about the record around it still carry one.+_A_STEP = SOPStepDataV1(+ subject="model",+ description="make the hull",+ executor=SOPAgentRef(agent_id="a-1", session_key="modeller"),+)++class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):"""End-to-end tests for :class:`AsyncSQLAlchemyStorage` overin-memory SQLite."""@@ -488,6 +505,380 @@ class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):)self.assertEqual([m.id for m in listed], [long_msg_id])+ # ------------------------------------------------------------------+ # SOPs+ # ------------------------------------------------------------------++ async def test_sops_round_trip(self) -> None:+ """Upsert / get / list / delete + owner scoping."""+ record = SOPRecord(+ user_id="user-1",+ data=SOPData(+ name="ship",+ description="build one",+ steps=[+ SOPStepDataV1(+ subject="model",+ description="make the hull",+ executor=SOPAgentRef(+ agent_id="agent-1",+ session_key="modeller",+ ),+ verifier=AgentVerifier(+ agent=SOPAgentRef(+ agent_id="agent-2",+ session_key="reviewer",+ ),+ criteria="Every panel has to be watertight.",+ ),+ ),+ SOPStepDataV1(+ subject="paint",+ description="give it a livery",+ executor=SOPAgentRef(+ agent_id="agent-1",+ session_key="modeller",+ ),+ verifier=HumanVerifier(question="Good enough?"),+ ),+ ],+ ),+ )+ await self.storage.upsert_sop("user-1", record)++ fetched = await self.storage.get_sop("user-1", record.id)++ self.maxDiff = None+ self.assertDictEqual(+ fetched.model_dump(mode="json"),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "updated_at": AnyString(),+ "user_id": "user-1",+ "data": {+ "name": "ship",+ "description": "build one",+ "steps": [+ {+ "version": "v1",+ "subject": "model",+ "description": "make the hull",+ "executor": {+ "agent_id": "agent-1",+ "session_key": "modeller",+ },+ "verifier": {+ "type": "agent",+ "agent": {+ "agent_id": "agent-2",+ "session_key": "reviewer",+ },+ "criteria": (+ "Every panel has to be watertight."+ ),+ },+ "max_attempts": 3,+ },+ {+ "version": "v1",+ "subject": "paint",+ "description": "give it a livery",+ "executor": {+ "agent_id": "agent-1",+ "session_key": "modeller",+ },+ "verifier": {+ "type": "human",+ "question": "Good enough?",+ },+ "max_attempts": 3,+ },+ ],+ "workspace_grain": "run",+ "session_settings": {},+ },+ },+ )++ self.assertEqual(+ [_.id for _ in await self.storage.list_sops("user-1")],+ [record.id],+ )+ self.assertEqual(await self.storage.list_sops("user-2"), [])+ self.assertIsNone(await self.storage.get_sop("user-2", record.id))++ self.assertTrue(await self.storage.delete_sop("user-1", record.id))+ self.assertFalse(await self.storage.delete_sop("user-1", record.id))++ async def test_sop_runs_round_trip(self) -> None:+ """A run stores its snapshot, its sessions and the SDK's state."""+ run = SOPRunRecord(+ user_id="user-1",+ sop_id="sop-1",+ definition=SOPData(+ name="ship",+ steps=[+ SOPStepDataV1(+ subject="model",+ description="make the hull",+ executor=SOPAgentRef(+ agent_id="agent-1",+ session_key="modeller",+ ),+ ),+ ],+ ),+ sessions={"modeller": "session-1"},+ state=SOPRunState(steps=[SOPStepRunState()]),+ )+ await self.storage.upsert_sop_run("user-1", run)++ fetched = await self.storage.get_sop_run("user-1", run.id)++ self.maxDiff = None+ self.assertDictEqual(+ fetched.model_dump(mode="json"),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "updated_at": AnyString(),+ "user_id": "user-1",+ "sop_id": "sop-1",+ "definition": {+ "name": "ship",+ "description": "",+ "steps": [+ {+ "version": "v1",+ "subject": "model",+ "description": "make the hull",+ "executor": {+ "agent_id": "agent-1",+ "session_key": "modeller",+ },+ "verifier": None,+ "max_attempts": 3,+ },+ ],+ "workspace_grain": "run",+ "session_settings": {},+ },+ "sessions": {"modeller": "session-1"},+ "state": {+ "id": AnyString(),+ "inputs": [],+ "steps": [+ {+ "phase": "pending",+ "given": [],+ "submission": None,+ "verifications": [],+ },+ ],+ "created_at": AnyString(),+ "phase": "pending",+ },+ },+ )++ self.assertIsNone(await self.storage.get_sop_run("user-2", run.id))+ self.assertTrue(await self.storage.delete_sop_run("user-1", run.id))+ self.assertFalse(await self.storage.delete_sop_run("user-1", run.id))++ async def test_sop_runs_are_listed_by_procedure_and_phase(self) -> None:+ """``phase`` is a column, so the database does the filtering."""+ waiting = SOPRunRecord(+ user_id="user-1",+ sop_id="sop-1",+ definition=SOPData(name="a", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING)],+ ),+ )+ done = SOPRunRecord(+ user_id="user-1",+ sop_id="sop-1",+ definition=SOPData(name="a", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.COMPLETED)],+ ),+ )+ other = SOPRunRecord(+ user_id="user-1",+ sop_id="sop-2",+ definition=SOPData(name="b", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING)],+ ),+ )+ for record in (waiting, done, other):+ await self.storage.upsert_sop_run("user-1", record)++ self.assertEqual(+ {_.id for _ in await self.storage.list_sop_runs("user-1")},+ {waiting.id, done.id, other.id},+ )+ self.assertEqual(+ {+ _.id+ for _ in await self.storage.list_sop_runs(+ "user-1",+ sop_id="sop-1",+ )+ },+ {waiting.id, done.id},+ )+ self.assertEqual(+ {+ _.id+ for _ in await self.storage.list_sop_runs(+ "user-1",+ phase=SOPPhase.AWAITING,+ )+ },+ {waiting.id, other.id},+ )+ self.assertEqual(await self.storage.list_sop_runs("user-2"), [])++ async def test_update_sop_run_writes_the_run_and_not_the_snapshot(+ self,+ ) -> None:+ """The hot path rewrites state and sessions, and keeps the rest."""+ run = SOPRunRecord(+ user_id="user-1",+ sop_id="sop-1",+ definition=SOPData(name="ship", steps=[_A_STEP]),+ state=SOPRunState(steps=[SOPStepRunState()]),+ )+ await self.storage.upsert_sop_run("user-1", run)++ await self.storage.update_sop_run(+ "user-1",+ run.id,+ SOPRunState(+ id=run.state.id,+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING)],+ ),+ sessions={"modeller": "session-1"},+ )++ updated = await self.storage.get_sop_run("user-1", run.id)++ self.maxDiff = None+ self.assertDictEqual(+ updated.model_dump(mode="json"),+ {+ "id": run.id,+ "created_at": AnyString(),+ "updated_at": AnyString(),+ "user_id": "user-1",+ "sop_id": "sop-1",+ "definition": {+ "name": "ship",+ "description": "",+ "steps": [+ {+ "version": "v1",+ "subject": "model",+ "description": "make the hull",+ "executor": {+ "agent_id": "a-1",+ "session_key": "modeller",+ },+ "verifier": None,+ "max_attempts": 3,+ },+ ],+ "workspace_grain": "run",+ "session_settings": {},+ },+ "sessions": {"modeller": "session-1"},+ "state": {+ "id": AnyString(),+ "inputs": [],+ "steps": [+ {+ "phase": "awaiting",+ "given": [],+ "submission": None,+ "verifications": [],+ },+ ],+ "created_at": AnyString(),+ "phase": "awaiting",+ },+ },+ )+ # The promoted column moved with it, so the filter still finds it.+ self.assertEqual(+ [+ _.id+ for _ in await self.storage.list_sop_runs(+ "user-1",+ phase=SOPPhase.AWAITING,+ )+ ],+ [run.id],+ )++ with self.assertRaises(KeyError):+ await self.storage.update_sop_run(+ "user-1",+ "nope",+ SOPRunState(),+ )+ with self.assertRaises(KeyError):+ await self.storage.update_sop_run(+ "user-2",+ run.id,+ SOPRunState(),+ )++ async def test_deleting_a_sop_takes_its_runs_with_it(self) -> None:+ """A run is only readable through the definition it snapshotted."""+ sop = SOPRecord(+ user_id="user-1",+ data=SOPData(name="ship", steps=[_A_STEP]),+ )+ await self.storage.upsert_sop("user-1", sop)+ run = SOPRunRecord(+ user_id="user-1",+ sop_id=sop.id,+ definition=sop.data,+ )+ await self.storage.upsert_sop_run("user-1", run)++ self.assertTrue(await self.storage.delete_sop("user-1", sop.id))++ self.assertIsNone(await self.storage.get_sop_run("user-1", run.id))+ self.assertEqual(await self.storage.list_sop_runs("user-1"), [])++ async def test_a_step_state_subclass_survives_the_database(self) -> None:+ """What a step kept beyond the base record is stored, not trimmed."""+ run = SOPRunRecord(+ user_id="user-1",+ sop_id="sop-1",+ definition=SOPData(name="ship", steps=[_A_STEP]),+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING, call_id="c1")],+ ),+ )+ await self.storage.upsert_sop_run("user-1", run)++ fetched = await self.storage.get_sop_run("user-1", run.id)++ self.assertDictEqual(+ fetched.state.steps[0].model_dump(mode="json"),+ {+ "phase": "awaiting",+ "given": [],+ "submission": None,+ "verifications": [],+ "call_id": "c1",+ },+ )+# ------------------------------------------------------------------# Teams# ------------------------------------------------------------------@@ -1154,6 +1545,46 @@ class AsyncSQLAlchemyStorageAutoMigrateTest(IsolatedAsyncioTestCase):"chan-1",)+ async def test_migrations_alone_create_the_sop_tables(self) -> None:+ """Same isolation for 0004 — without ``metadata.create_all`` a+ missing migration surfaces here rather than in production."""+ import os+ import tempfile++ with tempfile.TemporaryDirectory() as tmp:+ url = f"sqlite+aiosqlite:///{os.path.join(tmp, 'as.db')}"++ async with AsyncSQLAlchemyStorage(+ url,+ auto_migrate=True,+ create_tables=False,+ ) as storage:+ sop = SOPRecord(+ user_id="user-1",+ data=SOPData(name="ship", steps=[_A_STEP]),+ )+ await storage.upsert_sop("user-1", sop)+ await storage.upsert_sop_run(+ "user-1",+ SOPRunRecord(+ user_id="user-1",+ sop_id=sop.id,+ definition=sop.data,+ state=SOPRunState(+ steps=[SOPStepRunState(phase=SOPPhase.AWAITING)],+ ),+ ),+ )+ self.assertEqual(+ len(+ await storage.list_sop_runs(+ "user-1",+ phase=SOPPhase.AWAITING,+ ),+ ),+ 1,+ )+class ChannelTimestampPrecisionTest(TestCase):"""``channels.updated_at`` is the channel's configuration version.