Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
refactor(message_bus): refactor and decouple message bus from service logic (#1923)
DavdGao337a2d797e06
diff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.pynew file mode 100644index 000000000..73b4256fb--- /dev/null+++ b/src/agentscope/app/_bus_ops.py@@ -0,0 +1,122 @@+# -*- coding: utf-8 -*-+"""Business-level operations built on top of MessageBus primitives.++These helpers compose generic bus primitives (``log_append``, ``publish``,+``queue_push``) with domain-specific key layouts from ``MessageBusKeys``.+They live here — between the transport layer (``message_bus``) and the+service layer (``_service``) — so that neither layer needs to know about the+other's internals.++.. list-table::+ :widths: 30 70++ * - :func:`publish_session_event`+ - Append an event to the session replay log and fan it out live.+ * - :func:`enqueue_run_trigger`+ - Enqueue a typed run trigger and signal dispatchers.+"""+from __future__ import annotations++from typing import TYPE_CHECKING, Literal++from .message_bus._keys import MessageBusKeys++if TYPE_CHECKING:+ from .message_bus._base import MessageBus++ from agentscope.event import (+ ExternalExecutionResultEvent,+ UserConfirmResultEvent,+ )+++# ── publish_session_event ──────────────────────────────────────────────+++async def publish_session_event(+ bus: "MessageBus",+ session_id: str,+ event: dict,+) -> str:+ """Append event to replay log + fan out live.++ Args:+ bus (`MessageBus`):+ The application message bus.+ session_id (`str`):+ The session this event belongs to.+ event (`dict`):+ JSON-serializable event payload.++ Returns:+ `str`:+ The replay-log entry id assigned by the backend.+ """+ key = MessageBusKeys.session_events(session_id)+ entry_id = await bus.log_append(+ key,+ event,+ max_len=MessageBusKeys.SESSION_REPLAY_MAX_LEN,+ )+ await bus.publish(key, {**event, "_entry_id": entry_id})+ return entry_id+++# ── enqueue_run_trigger ────────────────────────────────────────────────+++async def enqueue_run_trigger(+ bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ *,+ kind: Literal["wake", "resume"] = MessageBusKeys.WAKEUP_KIND_WAKE,+ inputs: UserConfirmResultEvent+ | ExternalExecutionResultEvent+ | None = None,+) -> None:+ """Enqueue a typed run trigger and signal dispatchers.++ ``kind`` selects how the dispatcher handles the entry:++ - ``wake`` — idle-session wake-up. The dispatcher skips the entry+ when the session is already running (the live run drains the inbox+ itself). ``inputs`` must be ``None``.+ - ``resume`` — resume a HITL-parked session with a user confirmation+ or external execution result. The dispatcher waits (with backoff)+ until the parked run releases its lock, then spawns with+ ``input_msg`` set to the deserialised event.++ The payload is serialised to a plain dict before being pushed to the+ wakeup queue; the ``MessageBus`` transport layer never sees event+ types.++ Args:+ bus (`MessageBus`):+ The application message bus.+ user_id (`str`):+ The owning user id.+ session_id (`str`):+ The session to trigger a run for.+ agent_id (`str`):+ The agent id that owns the session.+ kind:+ Trigger kind. Defaults to ``"wake"``.+ inputs:+ The input event for ``resume`` triggers. Ignored (and+ should be ``None``) for ``wake``. The function calls+ ``model_dump(mode="json")`` internally — callers pass the+ event object, not a pre-serialised dict.+ """+ await bus.queue_push(+ MessageBusKeys.wakeup_queue(),+ {+ "user_id": user_id,+ "session_id": session_id,+ "agent_id": agent_id,+ "kind": kind,+ "input": inputs.model_dump(mode="json") if inputs else None,+ },+ )+ await bus.publish(MessageBusKeys.wakeup_signal(), {})diff --git a/src/agentscope/app/_manager/_background_task_manager.py b/src/agentscope/app/_manager/_background_task_manager.pyindex 6394f90af..660770ce2 100644--- a/src/agentscope/app/_manager/_background_task_manager.py+++ b/src/agentscope/app/_manager/_background_task_manager.py@@ -18,6 +18,7 @@ from agentscope.permission import ()from agentscope.tool import ToolBase, ToolChunkfrom agentscope._logging import logger+from ..message_bus import MessageBusKeysif TYPE_CHECKING:from ..message_bus import MessageBus@@ -176,11 +177,14 @@ class ToolStop(ToolBase):# Path 2: task exists in the global registry (another worker, or# a different session on this worker).- if await self._message_bus.bg_task_exists(- self._session_id,+ if await self._message_bus.registry_exists(+ MessageBusKeys.bg_tasks(self._session_id),task_id,):- await self._message_bus.task_publish_cancel(task_id)+ await self._message_bus.publish(+ MessageBusKeys.task_cancel_channel(),+ {"task_id": task_id},+ )logger.info("Background task cancel broadcast via ToolStop (remote): ""task_id=%s, session_id=%s",@@ -290,10 +294,11 @@ class BackgroundTaskManager:"started_at": time.time(),},)- await self._message_bus.bg_task_register(- session_id,+ await self._message_bus.registry_set(+ MessageBusKeys.bg_tasks(session_id),task_id,metadata,+ ttl_secs=MessageBusKeys.BG_TASKS_TTL_SECS,)logger.info(@@ -336,8 +341,8 @@ class BackgroundTaskManager:The task id to unregister from the global registry."""try:- await self._message_bus.bg_task_unregister(- session_id,+ await self._message_bus.registry_del(+ MessageBusKeys.bg_tasks(session_id),task_id,)except Exception as e: # pylint: disable=broad-exceptdiff --git a/src/agentscope/app/_manager/_cancel_dispatcher.py b/src/agentscope/app/_manager/_cancel_dispatcher.pyindex 86cff396f..d5e9edf88 100644--- a/src/agentscope/app/_manager/_cancel_dispatcher.py+++ b/src/agentscope/app/_manager/_cancel_dispatcher.py@@ -17,6 +17,7 @@ import asynciofrom typing import TYPE_CHECKING, Selffrom ..._logging import logger+from ..message_bus import MessageBusKeysif TYPE_CHECKING:from ..message_bus import MessageBus@@ -108,10 +109,13 @@ class CancelDispatcher:Signalled after the underlying SUBSCRIBE completes."""try:- async for session_id in self._bus.session_subscribe_cancel(+ async for payload in self._bus.subscribe(+ MessageBusKeys.session_cancel_channel(),on_ready=ready.set,):- self._cancel_session(session_id)+ sid = payload.get("session_id")+ if isinstance(sid, str):+ self._cancel_session(sid)except Exception: # pylint: disable=broad-exceptlogger.exception("CancelDispatcher session-cancel loop crashed.",@@ -158,9 +162,13 @@ class CancelDispatcher:Signalled after the underlying SUBSCRIBE completes."""try:- async for task_id in self._bus.task_subscribe_cancel(+ async for payload in self._bus.subscribe(+ MessageBusKeys.task_cancel_channel(),on_ready=ready.set,):+ task_id = payload.get("task_id")+ if not isinstance(task_id, str):+ continuecancelled = self._bg_manager.cancel_task(task_id)if cancelled:logger.info(diff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.pyindex b96597ae8..18aa81acf 100644--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py@@ -11,7 +11,8 @@ from ....state import AgentStatefrom ....tool import ToolBasefrom ...._logging import loggerfrom ._tools import ScheduleCreate, ScheduleDelete, ScheduleList, ScheduleView-from ...message_bus import MessageBus+from ...message_bus import MessageBus, MessageBusKeys+from ..._bus_ops import enqueue_run_triggerfrom ...storage import (StorageBase,ScheduleRecord,@@ -232,11 +233,12 @@ class SchedulerManager:ensure_ascii=False,),)- await message_bus.inbox_push(- session.id,+ await message_bus.queue_push(+ MessageBusKeys.inbox(session.id),hint.model_dump(mode="json"),)- await message_bus.enqueue_wakeup(+ await enqueue_run_trigger(+ message_bus,user_id=record.user_id,session_id=session.id,agent_id=record.agent_id,diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.pyindex 7aa684235..6ffc5d3a4 100644--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py@@ -33,6 +33,7 @@ from pydantic import TypeAdapterfrom ..._logging import loggerfrom ...event import UserConfirmResultEvent, ExternalExecutionResultEventfrom ..message_bus import MessageBusKeys+from .._bus_ops import enqueue_run_triggerif TYPE_CHECKING:from ..message_bus import MessageBus@@ -156,7 +157,8 @@ class WakeupDispatcher:trigger immediately after start without racing."""try:- async for _signal in self._bus.subscribe_wakeup_signal(+ async for _signal in self._bus.subscribe(+ MessageBusKeys.wakeup_signal(),on_ready=ready.set,):await self._drain_and_dispatch()@@ -168,7 +170,11 @@ class WakeupDispatcher:async def _drain_and_dispatch(self) -> None:"""Read up to a batch of trigger entries and dispatch each."""try:- entries = await self._bus.dequeue_wakeups(max_count=64)+ raw_entries = await self._bus.queue_drain(+ MessageBusKeys.wakeup_queue(),+ max_count=64,+ )+ entries = [payload for _entry_id, payload in raw_entries]except Exception: # pylint: disable=broad-exceptlogger.exception("WakeupDispatcher: dequeue_wakeups failed.")return@@ -219,7 +225,33 @@ class WakeupDispatcher:"""is_resume = kind == MessageBusKeys.WAKEUP_KIND_RESUME- if await self._bus.session_is_running(session_id):+ # Parse the resume input early so every downstream path+ # (lock-retry, spawn-retry) receives a typed event object+ # rather than a raw dict.+ input_msg: UserConfirmResultEvent | ExternalExecutionResultEvent | None+ input_msg = None+ if is_resume:+ if raw_input is None:+ logger.warning(+ "WakeupDispatcher: dropping resume trigger for session "+ "%s — no input event carried.",+ session_id,+ )+ return+ try:+ input_msg = _RESUME_INPUT_ADAPTER.validate_python(raw_input)+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: dropping resume trigger for session "+ "%s — input event failed to parse: %r",+ session_id,+ raw_input,+ )+ return++ if await self._bus.is_locked(+ MessageBusKeys.session_lock(session_id),+ ):if is_resume:# The session is busy finishing its parked tail. Do NOT# drop the resume — re-queue it after a short backoff so@@ -228,7 +260,7 @@ class WakeupDispatcher:user_id,session_id,agent_id,- raw_input,+ input_msg,)# ``wake`` triggers are safe to drop while running — the# live run drains the inbox itself.@@ -255,27 +287,6 @@ class WakeupDispatcher:)return- input_msg: UserConfirmResultEvent | ExternalExecutionResultEvent | None- input_msg = None- if is_resume:- if raw_input is None:- logger.warning(- "WakeupDispatcher: dropping resume trigger for session "- "%s — no input event carried.",- session_id,- )- return- try:- input_msg = _RESUME_INPUT_ADAPTER.validate_python(raw_input)- except Exception: # pylint: disable=broad-except- logger.exception(- "WakeupDispatcher: dropping resume trigger for session "- "%s — input event failed to parse: %r",- session_id,- raw_input,- )- return-try:self._registry.spawn(self._chat_service.run(@@ -296,7 +307,7 @@ class WakeupDispatcher:user_id,session_id,agent_id,- raw_input,+ input_msg,)else:logger.debug(@@ -310,7 +321,9 @@ class WakeupDispatcher:user_id: str,session_id: str,agent_id: str,- raw_input: dict | None,+ input_msg: UserConfirmResultEvent+ | ExternalExecutionResultEvent+ | None,) -> None:"""Re-enqueue a ``resume`` trigger after a short backoff.@@ -326,19 +339,20 @@ class WakeupDispatcher:The session to resume.agent_id (`str`):The agent that owns the session.- raw_input (`dict | None`):- The serialised input event to redeliver.+ input_msg:+ The parsed input event to redeliver."""async def _retry() -> None:try:await asyncio.sleep(_RESUME_RETRY_BACKOFF_SECS)- await self._bus.enqueue_input(+ await enqueue_run_trigger(+ self._bus,user_id=user_id,session_id=session_id,agent_id=agent_id,kind=MessageBusKeys.WAKEUP_KIND_RESUME,- inputs=raw_input,+ inputs=input_msg,)except asyncio.CancelledError:passdiff --git a/src/agentscope/app/_router/_chat.py b/src/agentscope/app/_router/_chat.pyindex 63898494d..ae76a39bd 100644--- a/src/agentscope/app/_router/_chat.py+++ b/src/agentscope/app/_router/_chat.py@@ -30,8 +30,13 @@ from ..deps import ()from ._schema import ChatRequest, ChatTriggerResponsefrom .._manager import ChatRunRegistry-from .._service import ChatService, SessionProjection, SubagentHitlProjector+from .._service import (+ ChatService,+ SessionProjection,+ SubagentHitlProjector,+)from ..message_bus import MessageBus, MessageBusKeys+from .._bus_ops import enqueue_run_triggerfrom ...event import UserConfirmResultEvent, ExternalExecutionResultEventchat_router = APIRouter(@@ -120,12 +125,13 @@ async def chat(run_session_id = target["worker_session_id"]run_agent_id = target["worker_agent_id"]- await message_bus.enqueue_input(+ await enqueue_run_trigger(+ message_bus,user_id=user_id,session_id=run_session_id,agent_id=run_agent_id,kind=MessageBusKeys.WAKEUP_KIND_RESUME,- inputs=request.input.model_dump(mode="json"),+ inputs=request.input,)return ChatTriggerResponse(status="started", session_id=run_session_id)diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex e7b648311..f8d31e160 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -24,7 +24,7 @@ from ._schema import (TeamMemberView,UpdateSessionRequest,)-from ..message_bus import MessageBus+from ..message_bus import MessageBus, MessageBusKeysfrom .._service import SessionService, SessionProjection, SubagentHitlProjectorfrom ..storage import (AgentRecord,@@ -184,7 +184,9 @@ async def list_sessions(views.append(SessionView(session=session,- is_running=await message_bus.session_is_running(session.id),+ is_running=await message_bus.is_locked(+ MessageBusKeys.session_lock(session.id),+ ),team=team_detail,),)@@ -412,7 +414,9 @@ async def list_messages()return ListMessagesResponse(messages=messages,- is_running=await message_bus.session_is_running(session_id),+ is_running=await message_bus.is_locked(+ MessageBusKeys.session_lock(session_id),+ ),)@@ -529,8 +533,9 @@ async def stream_session_events(async def _sse_generator() -> AsyncGenerator[str, None]:# 1. Replay buffered events from the current run (if any).- for _entry_id, event in await message_bus.session_read_events(- session_id,+ for _entry_id, event in await message_bus.log_read(+ MessageBusKeys.session_events(session_id),+ max_count=MessageBusKeys.SESSION_REPLAY_MAX_LEN,):yield f"data: {json.dumps(event)}\n\n"@@ -587,10 +592,12 @@ async def stream_session_events((which in practice only happens if the bus shuts down)."""try:- async for evt in message_bus.session_subscribe_events(- session_id,+ async for evt in message_bus.subscribe(+ MessageBusKeys.session_events(session_id),):- await queue.put(evt)+ await queue.put(+ {k: v for k, v in evt.items() if k != "_entry_id"},+ )except asyncio.CancelledError:passfinally:diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 0bc1230b5..67647e241 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -13,7 +13,8 @@ that wants them subscribes through the"""from fastapi import HTTPException-from ..message_bus import MessageBus+from ..message_bus import MessageBus, MessageBusKeys+from .._bus_ops import publish_session_eventfrom ..storage import StorageBase, AgentRecord, SessionRecordfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..workspace_manager import WorkspaceManagerBase@@ -379,102 +380,110 @@ class ChatService:return# ----------------------------------------------------------------- # 7. Run the agent inside the bus's distributed session lock+ # 7. Run the agent inside the distributed session lock# ----------------------------------------------------------------- async with self._message_bus.session_run(session_id):- reply_msg: Msg | None = None-- if input_msg is None or isinstance(input_msg, (Msg, list)):- # Case A: new reply (user message(s), or retrigger with- # empty input)- if isinstance(input_msg, (Msg, list)):- input_msgs = (- [input_msg]- if isinstance(input_msg, Msg)- else input_msg- )- for msg in input_msgs:- await self._storage.upsert_message(- user_id,+ lock_key = MessageBusKeys.session_lock(session_id)+ events_key = MessageBusKeys.session_events(session_id)+ async with self._message_bus.acquire_lock(+ lock_key,+ ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,+ ):+ try:+ reply_msg: Msg | None = None++ if input_msg is None or isinstance(input_msg, (Msg, list)):+ # Case A: new reply (user message(s), or retrigger with+ # empty input)+ if isinstance(input_msg, (Msg, list)):+ input_msgs = (+ [input_msg]+ if isinstance(input_msg, Msg)+ else input_msg+ )+ for msg in input_msgs:+ await self._storage.upsert_message(+ user_id,+ session_id,+ msg,+ )++ async for event in agent.reply_stream(inputs=input_msg):+ await publish_session_event(+ self._message_bus,session_id,- msg,+ event.model_dump(mode="json"),)-- async for event in agent.reply_stream(inputs=input_msg):- await self._message_bus.session_publish_event(- session_id,- event.model_dump(mode="json"),- )- await self._project_event(+ await self._project_event(+ user_id,+ session_record,+ agent_record,+ event,+ )+ if isinstance(event, ReplyStartEvent):+ reply_msg = AssistantMsg(+ id=event.reply_id,+ name=event.name,+ content=[],+ )+ elif reply_msg is not None:+ reply_msg.append_event(event)++ else:+ # Case B: continuation (UserConfirmResult+ # / ExternalExecResult)+ reply_msg = await self._storage.get_message(user_id,- session_record,- agent_record,- event,+ session_id,+ agent.state.reply_id,)- if isinstance(event, ReplyStartEvent):- reply_msg = AssistantMsg(- id=event.reply_id,- name=event.name,- content=[],- )- elif reply_msg is not None:- reply_msg.append_event(event)- else:- # Case B: continuation (UserConfirmResult / ExternalExecResult)- reply_msg = await self._storage.get_message(- user_id,- session_id,- agent.state.reply_id,- )+ if reply_msg is None:+ logger.warning(+ "Reply message %r not found in storage for "+ "session %r; tool-call state changes from the "+ "incoming event will not be persisted.",+ agent.state.reply_id,+ session_id,+ )+ elif input_msg:+ reply_msg.append_event(input_msg)- if reply_msg is None:- logger.warning(- "Reply message %r not found in storage for session "- "%r; tool-call state changes from the incoming event "- "will not be persisted.",- agent.state.reply_id,- session_id,- )- elif input_msg:- reply_msg.append_event(input_msg)+ async for event in agent.reply_stream(inputs=input_msg):+ await publish_session_event(+ self._message_bus,+ session_id,+ event.model_dump(mode="json"),+ )+ await self._project_event(+ user_id,+ session_record,+ agent_record,+ event,+ )+ if reply_msg is not None:+ reply_msg.append_event(event)- async for event in agent.reply_stream(inputs=input_msg):- await self._message_bus.session_publish_event(- session_id,- event.model_dump(mode="json"),- )- await self._project_event(+ # Persist the reply Msg (upsert: overwrite if same id,+ # append if new).+ if reply_msg is not None:+ await self._storage.upsert_message(user_id,- session_record,- agent_record,- event,+ session_id,+ reply_msg,)- if reply_msg is not None:- reply_msg.append_event(event)- # Persist the reply Msg (upsert: overwrite if same id, append- # if new).- if reply_msg is not None:- await self._storage.upsert_message(- user_id,- session_id,- reply_msg,+ # Persist the updated agent state. MUST happen inside+ # the session lock: if we released the lock first,+ # another process could acquire it and load a stale+ # state from storage before this write lands.+ await self._storage.update_session_state(+ user_id=user_id,+ agent_id=agent_id,+ session_id=session_id,+ state=agent.state,)-- # Persist the updated agent state. MUST happen inside the- # session lock: if we released the lock first, another- # process could acquire it and load a stale state from- # storage before this write lands.- await self._storage.update_session_state(- user_id=user_id,- agent_id=agent_id,- session_id=session_id,- state=agent.state,- )-- # ``session_run.__aexit__`` trims the replay log before- # releasing the lock — see :meth:`MessageBus.session_run`.+ finally:+ await self._message_bus.log_trim(events_key)async def _project_event(self,diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pyindex e6a975aa9..1044c3b2a 100644--- a/src/agentscope/app/_service/_session.py+++ b/src/agentscope/app/_service/_session.py@@ -47,7 +47,7 @@ imports the bus; bus code never imports storage."""import asyncio-from ..message_bus import MessageBus+from ..message_bus import MessageBus, MessageBusKeysfrom ..storage import StorageBasefrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjector@@ -139,11 +139,16 @@ class SessionService:``False`` if the lock was still held when the timeoutexpired."""- await self._bus.session_publish_cancel(session_id)+ await self._bus.publish(+ MessageBusKeys.session_cancel_channel(),+ {"session_id": session_id},+ )deadline = asyncio.get_event_loop().time() + timeoutwhile True:- if not await self._bus.session_is_running(session_id):+ if not await self._bus.is_locked(+ MessageBusKeys.session_lock(session_id),+ ):return Trueif asyncio.get_event_loop().time() >= deadline:logger.warning(@@ -386,7 +391,19 @@ class SessionService:if not session_ids:returnawait asyncio.gather(- *(self._bus.session_purge(sid) for sid in session_ids),+ *(self._purge_session_bus(sid) for sid in session_ids),+ )++ async def _purge_session_bus(self, session_id: str) -> None:+ """Drop all per-session bus state for one session."""+ await self._bus.log_trim(+ MessageBusKeys.session_events(session_id),+ )+ await self._bus.queue_delete(+ MessageBusKeys.inbox(session_id),+ )+ await self._bus.registry_drop(+ MessageBusKeys.bg_tasks(session_id),)async def _purge_subagent_hitl(diff --git a/src/agentscope/app/_service/_session_projection.py b/src/agentscope/app/_service/_session_projection.pyindex 8e7181595..eaa50b0ca 100644--- a/src/agentscope/app/_service/_session_projection.py+++ b/src/agentscope/app/_service/_session_projection.py@@ -35,6 +35,7 @@ import jsonfrom typing import TYPE_CHECKINGfrom ..message_bus import MessageBusKeys+from .._bus_ops import publish_session_eventfrom ...event import CustomEventif TYPE_CHECKING:@@ -178,7 +179,8 @@ class SessionProjection:The event payload."""custom = CustomEvent(name=event_name, value=value)- await self._bus.session_publish_event(+ await publish_session_event(+ self._bus,target_sid,custom.model_dump(mode="json"),)diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pyindex fc34cb2f6..a9bdfdfd4 100644--- a/src/agentscope/app/_service/_toolkit.py+++ b/src/agentscope/app/_service/_toolkit.py@@ -10,7 +10,7 @@ from typing import Anyfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..message_bus import MessageBus-from .._tools import AgentCreate, TeamCreate, TeamDelete, TeamSay+from .._tool import AgentCreate, TeamCreate, TeamDelete, TeamSayfrom .._types import AgentToolFactory, SubAgentTemplatefrom ..storage import AgentRecord, SessionRecord, StorageBasefrom ...tool import (diff --git a/src/agentscope/app/_tool/__init__.py b/src/agentscope/app/_tool/__init__.pynew file mode 100644index 000000000..a90dc0156--- /dev/null+++ b/src/agentscope/app/_tool/__init__.py@@ -0,0 +1,39 @@+# -*- coding: utf-8 -*-+"""Framework-builtin tools wired into team-participating agents.++These tools differ from the workspace-provided builtins (Bash, Read,+Task series, …) in two ways:++1. **Construction depends on app-level resources** — they bind a+ :class:`StorageBase` + :class:`MessageBus` reference plus the+ request-scoped ``user_id`` / ``session_id`` / ``agent_id`` at agent+ assembly time, and call storage / bus directly in their+ ``__call__`` — except ``TeamDelete``, which delegates to+ :class:`SessionService` for cascade deletion.+2. **Visibility depends only on the agent's source field** —+ ``source='user'`` agents always see the full leader-side toolset+ (``TeamCreate / AgentCreate / TeamSay / TeamDelete``) regardless of+ whether they currently lead a team. Each tool checks the storage+ state at ``__call__`` time and fails clearly if its precondition+ is not met. ``source='team'`` workers only see ``TeamSay``.++ The benefit is that a single chat run can ``TeamCreate`` and then+ ``AgentCreate`` immediately afterward — there is no toolkit+ refresh point because the toolkit never changed; only the+ underlying storage state did, which the next tool reads fresh.++Selection of the right subset by ``agent.source`` happens inline in+:func:`get_toolkit`; there is no separate "team tool factory" helper.+"""+from ._agent_create import AgentCreate, DEFAULT_SUB_AGENT_TEMPLATE+from ._team_create import TeamCreate+from ._team_delete import TeamDelete+from ._team_say import TeamSay++__all__ = [+ "AgentCreate",+ "DEFAULT_SUB_AGENT_TEMPLATE",+ "TeamCreate",+ "TeamDelete",+ "TeamSay",+]diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.pynew file mode 100644index 000000000..93caf7eec--- /dev/null+++ b/src/agentscope/app/_tool/_agent_create.py@@ -0,0 +1,530 @@+# -*- coding: utf-8 -*-+"""The AgentCreate tool — spawns a worker into the current team."""+from __future__ import annotations++import copy+import json+from typing import TYPE_CHECKING++from pydantic import Field++from ._team_tool_base import _TeamToolBase+from .._types import SubAgentTemplate+from ..message_bus import MessageBusKeys+from .._bus_ops import enqueue_run_trigger+from ..storage import AgentData, AgentRecord, SessionConfig+from ...message import HintBlock, TextBlock, ToolResultState+from ...permission import PermissionContext+from ...state import AgentState+from ...tool import ToolChunk, ParamsBase++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import StorageBase+++_DEFAULT_SYSTEM_PROMPT_TEMPLATE = (+ "You are {member_name}, a member of team '{team_name}' led by "+ "{leader_name}.\n\n"+ "Team purpose: {team_description}\n\n"+ "Your role: {member_description}\n\n"+ "You communicate with the team leader and other members "+ "through the TeamSay tool. "+ "Speak on the team only when you have something "+ "external to share — your private reasoning stays private."+)++DEFAULT_SUB_AGENT_TEMPLATE = SubAgentTemplate(+ type="default",+ description="Default worker agent with standard configuration.",+ system_prompt_template=_DEFAULT_SYSTEM_PROMPT_TEMPLATE,+ override_leader_mode=False,+ extend_leader_permission_rules=True,+ extend_leader_working_directories=True,+)+# The built-in default sub-agent template.+#+# Used when no custom templates are registered, or when the leader+# agent creates a member without specifying a ``subagent_type`` (or+# explicitly specifies ``subagent_type="default"``). Developers can+# override this by registering their own template with+# ``type="default"`` via :func:`~agentscope.app.create_app`.+#+# The default template fully follows the leader: the worker inherits+# the leader's permission mode, working directories, and rules —+# matching the intuition that a generic worker should behave like the+# leader unless the developer registers a more opinionated template.+++def _merge_leader_permissions(+ template: SubAgentTemplate,+ leader_context: PermissionContext,+) -> PermissionContext:+ """Build the worker's permission context from the template, layered+ with the leader's runtime state according to the template's three+ inherit-from-leader flags.++ - ``override_leader_mode``: if True, the template's+ :attr:`PermissionContext.mode` wins; otherwise the worker+ inherits the leader's mode.+ - ``extend_leader_permission_rules``: if True, the leader's+ allow/deny/ask rules are appended after the template's rules for+ each tool, so the worker doesn't re-prompt for permissions the+ user has already granted in the leader session. The template's+ rules appear first in each list, so the engine — which returns+ on the first matching rule per stage — evaluates the template's+ intent before the leader's.+ - ``extend_leader_working_directories``: if True, the leader's+ working directories are merged in; on key (path) collisions the+ template's entry wins.++ The template fields are deep-copied so the returned context is+ independent of both the template and the leader state.+ """+ merged = template.permission_context.model_copy(deep=True)++ if not template.override_leader_mode:+ merged.mode = leader_context.mode++ if template.extend_leader_working_directories:+ for path, wd in leader_context.working_directories.items():+ merged.working_directories.setdefault(+ path,+ wd.model_copy(deep=True),+ )++ if template.extend_leader_permission_rules:+ for attr in ("allow_rules", "deny_rules", "ask_rules"):+ merged_rules: dict = getattr(merged, attr)+ for tool_name, rules in getattr(leader_context, attr).items():+ merged_rules.setdefault(tool_name, []).extend(+ r.model_copy(deep=True) for r in rules+ )++ return merged+++class _AgentCreateParams(ParamsBase):+ """Parameters for :class:`AgentCreate`."""++ name: str = Field(+ description=(+ 'Short identifier for the new member, e.g. ``"researcher"`` '+ 'or ``"coder-1"``. Other members address it via '+ "``TeamSay(to=<this name>)``, so it MUST be unique within "+ "the team."+ ),+ )+ description: str = Field(+ description=(+ "One-sentence summary of the member's role — e.g. "+ '``"Researches background information on the target topic"``. '+ "Becomes part of the member's system prompt so it understands "+ "its place in the team."+ ),+ )+ prompt: str = Field(+ description=(+ "The first task delivered to the member as a user message. "+ "The member begins executing immediately upon creation, so "+ "make this concrete and self-contained — do not just say "+ '``"wait for instructions"`` (use TeamSay later instead). '+ "Include any context, constraints, deliverables, and "+ "deadlines the member needs."+ ),+ )+++class AgentCreate(_TeamToolBase):+ """Spawn a new worker member into the team you lead."""++ name: str = "AgentCreate"+ is_state_injected: bool = True++ description: str = """Add a new member to the team you lead.++## When to Use This Tool+After ``TeamCreate``, call this for each member you want on the team. \+Each call:+- Creates a worker agent dedicated to this team.+- Delivers ``prompt`` as the worker's first user message — **the worker \+starts executing it immediately**. (So DONT use ``TeamSay`` right after \+creating one agent).++## When NOT to Use This Tool+- You're not currently leading a team. Call ``TeamCreate`` first.+- The new member would duplicate an existing member's role; reuse the \+existing member via ``TeamSay`` instead.++## Effects+- Use the ``name`` you chose as ``to=<name>`` in ``TeamSay`` to direct \+messages to this member specifically. Names must be unique within the \+team (including against the leader's name); duplicates are rejected.+- Members spawned this way live only as long as the team — they are \+deleted when ``TeamDelete`` is called.++## Important+- You are responsible for organising the team, assigning tasks, collecting \+every member's report, and producing the final answer — all members report \+directly to you. Therefore, **DO NOT** encourage members to communicate with \+each other, and **AVOID** creating "integrator"-style members; both make the \+overall communication topology unnecessarily complex.+"""++ input_schema: dict = _AgentCreateParams.model_json_schema()++ def __init__(+ self,+ storage: "StorageBase",+ message_bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ sub_agent_templates: dict[str, SubAgentTemplate] | None = None,+ ) -> None:+ """Bind request-scoped identifiers plus sub-agent templates.++ Extends :meth:`_TeamToolBase.__init__` with an optional+ template registry. The built-in ``"default"`` template is+ always present as a fallback; developers can override it by+ registering their own template with ``type="default"``.++ When more than one template type is available (i.e. custom+ templates were registered), the tool's ``input_schema`` is+ dynamically extended with a ``subagent_type`` enum field so+ the leader agent can choose which type to create.++ Args:+ storage (`StorageBase`):+ Application storage backend.+ message_bus (`MessageBus`):+ Application message bus for inter-session delivery.+ user_id (`str`):+ The owner user id of the calling agent.+ session_id (`str`):+ The current session id of the calling agent.+ agent_id (`str`):+ The id of the agent invoking the tool.+ sub_agent_templates (`dict[str, SubAgentTemplate] | None`, \+optional):+ Template registry keyed by template type. The+ built-in ``"default"`` template is injected+ automatically if not already present.+ """+ super().__init__(storage, message_bus, user_id, session_id, agent_id)++ self._sub_agent_templates: dict[str, SubAgentTemplate] = dict(+ sub_agent_templates or {},+ )+ if "default" not in self._sub_agent_templates:+ self._sub_agent_templates["default"] = DEFAULT_SUB_AGENT_TEMPLATE++ # Only expose subagent_type when the developer registered+ # custom templates — a single "default" type is redundant in+ # the schema and would confuse the LLM.+ has_custom_templates = set(self._sub_agent_templates) != {"default"}+ if has_custom_templates:+ schema = copy.deepcopy(+ _AgentCreateParams.model_json_schema(),+ )+ type_descriptions = "\n".join(+ f"- ``{t.type!r}`` — {t.description}"+ for t in self._sub_agent_templates.values()+ )+ schema["properties"]["subagent_type"] = {+ "type": "string",+ "enum": list(self._sub_agent_templates),+ "description": (+ "The type of sub-agent template to use. "+ "Available types:\n\n"+ f"{type_descriptions}\n\n"+ "Each type has pre-configured system prompt, "+ "permissions, and task context."+ ),+ }+ self.input_schema = schema++ async def __call__(+ self,+ name: str,+ description: str,+ prompt: str,+ subagent_type: str = "default",+ _agent_state: AgentState | None = None,+ ) -> ToolChunk:+ """Spawn the worker agent + session directly via storage.++ Reads the current session + team records from storage to+ enforce two preconditions: the calling session must be in a+ team, and it must be that team's leader.++ The worker's configuration (system prompt, context/react+ config, permission context, task context) is determined by+ the :class:`SubAgentTemplate` matching ``subagent_type``. The+ leader's user-confirmed permission rules and working+ directories are merged into the template's permission context+ so the worker does not re-prompt for permissions the user has+ already granted.++ Args:+ name (`str`):+ Short identifier for the worker, unique within the+ team. Used as the ``to`` target in ``TeamSay``.+ description (`str`):+ One-sentence summary of the worker's role.+ prompt (`str`):+ First task delivered as a user message to the worker.+ subagent_type (`str`, defaults to ``"default"``):+ Template type to use. Must match a registered+ :class:`SubAgentTemplate.type`.+ _agent_state (`AgentState | None`, optional):+ Live leader state injected by the toolkit.++ Returns:+ `ToolChunk`:+ A success message containing the new member id, or an+ error chunk on failure.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "AgentCreate: this session is not in "+ "any team — call TeamCreate first."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "AgentCreate: team "+ f"{session.team_id} no longer exists."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ if team.session_id != self._session_id:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "AgentCreate: only the team leader "+ "can add members; this session is a "+ "worker."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Look up leader session for chat-model inheritance + name.+ leader_session = await self._storage.get_session(+ self._user_id,+ "", # agent_id unused at storage level+ team.session_id,+ )+ if leader_session is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: leader session "+ f"{team.session_id} for team {team.id} is "+ f"missing — team is in an inconsistent "+ f"state."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Resolve the template.+ template = self._sub_agent_templates.get(subagent_type)+ if template is None:+ available = list(self._sub_agent_templates)+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: unknown subagent_type "+ f"{subagent_type!r}; expected one of "+ f"{available}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Enforce team-scoped name uniqueness. TeamSay routes by+ # ``name`` (not agent_id), so duplicates would be ambiguous+ # and unaddressable. The leader's name participates too —+ # workers must not collide with it.+ leader_agent_record = await self._storage.get_agent(+ self._user_id,+ leader_session.agent_id,+ )+ existing_names: set[str] = set()+ if leader_agent_record is not None:+ existing_names.add(leader_agent_record.data.name)+ for member_id in team.data.member_ids:+ member_record = await self._storage.get_agent(+ self._user_id,+ member_id,+ )+ if member_record is not None:+ existing_names.add(member_record.data.name)+ if name in existing_names:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: a team member named "+ f"{name!r} already exists. Member names "+ f"must be unique within the team "+ f"(including the leader's name); pick "+ f"another."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Resolve leader name early — needed both for the system+ # prompt template and for the initial team-message hint.+ leader_name = (+ leader_agent_record.data.name+ if leader_agent_record is not None+ else leader_session.agent_id+ )++ # 1. Build worker AgentRecord (source="team" so it's hidden+ # from the global agent list).+ system_prompt = template.system_prompt_template.format(+ team_name=team.data.name,+ team_description=team.data.description,+ member_name=name,+ member_description=description,+ leader_name=leader_name,+ )+ worker_agent = AgentRecord(+ user_id=self._user_id,+ source="team",+ data=AgentData(+ name=name,+ system_prompt=system_prompt,+ context_config=template.context_config.model_copy(+ deep=True,+ ),+ react_config=template.react_config.model_copy(+ deep=True,+ ),+ ),+ )+ await self._storage.upsert_agent(self._user_id, worker_agent)++ # 2. Build worker SessionRecord, inheriting leader's model+ # config. The template's permission context is the base;+ # on top of it we merge the leader's mode and/or rules+ # and/or working directories according to the template's+ # inherit-from-leader flags. See+ # :func:`_merge_leader_permissions` for the policy.+ leader_permission_context = (+ _agent_state.permission_context+ if _agent_state is not None+ else leader_session.state.permission_context+ )+ worker_permission_context = _merge_leader_permissions(+ template,+ leader_permission_context,+ )+ worker_state = AgentState(+ permission_context=worker_permission_context,+ tasks_context=template.tasks_context.model_copy(+ deep=True,+ ),+ )+ worker_session = await self._storage.upsert_session(+ user_id=self._user_id,+ agent_id=worker_agent.id,+ config=SessionConfig(+ workspace_id=leader_session.config.workspace_id,+ name=f"team:{team.id}/{name}",+ chat_model_config=(+ leader_session.config.chat_model_config+ ),+ fallback_chat_model_config=(+ leader_session.config.fallback_chat_model_config+ ),+ ),+ state=worker_state,+ )+ await self._storage.set_session_team_id(+ self._user_id,+ worker_session.id,+ team.id,+ )++ # 3. Append worker to team.member_ids.+ team.data.member_ids = [+ *team.data.member_ids,+ worker_agent.id,+ ]+ await self._storage.upsert_team(self._user_id, team)++ # 4. Deliver the initial task to the worker's inbox + wakeup.+ hint = HintBlock(+ hint=(+ f'<team-message from="{leader_name}">\n'+ f"{prompt}\n"+ f"</team-message>"+ ),+ source=json.dumps(+ {+ "label": "team_message",+ "sublabel": leader_name,+ },+ ensure_ascii=False,+ ),+ )+ await self._message_bus.queue_push(+ MessageBusKeys.inbox(worker_session.id),+ hint.model_dump(mode="json"),+ )+ await enqueue_run_trigger(+ self._message_bus,+ user_id=self._user_id,+ session_id=worker_session.id,+ agent_id=worker_agent.id,+ )++ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Member {name!r} added to team "+ f"{team.data.name!r}."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"AgentCreate failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tool/_team_create.py b/src/agentscope/app/_tool/_team_create.pynew file mode 100644index 000000000..d2c2c4782--- /dev/null+++ b/src/agentscope/app/_tool/_team_create.py@@ -0,0 +1,145 @@+# -*- coding: utf-8 -*-+"""The TeamCreate tool — establishes a new team led by the current session."""+from pydantic import Field++from ._team_tool_base import _TeamToolBase+from ..storage import TeamData, TeamRecord+from ...message import TextBlock, ToolResultState+from ...tool import ToolChunk, ParamsBase+++class _TeamCreateParams(ParamsBase):+ """Parameters for :class:`TeamCreate`."""++ name: str = Field(+ description=(+ "Display name of the team. Used by the user to identify the "+ "team and shown in the team UI."+ ),+ )+ description: str = Field(+ description=(+ "What the team is for — its overall goal or shared context. "+ "This becomes the team's charter and is wired into every "+ "member's system prompt so all members share the same "+ "high-level understanding of why the team exists."+ ),+ )+++class TeamCreate(_TeamToolBase):+ """Create a new team and become its leader."""++ name: str = "TeamCreate"++ description: str = """Create a new team led by your current session and \+return its team id.++## When to Use This Tool+Use this tool when the task you've been given is best decomposed into \+parallel sub-tasks executed by multiple specialised agents (members) \+under your coordination. After creating the team, use ``AgentCreate`` to \+spawn each member with its own role, prompt, and permission mode. NOTE: \+the ``prompt`` you pass to ``AgentCreate`` is delivered to that member \+automatically, so do **NOT** call ``TeamSay`` right after ``AgentCreate`` — \+just wait for the members to report back.++## When NOT to Use This Tool+- The task is small enough to handle yourself.+- You already lead a team in this session — a session can only lead \+one team at a time.+"""++ input_schema: dict = _TeamCreateParams.model_json_schema()++ async def __call__(+ self,+ name: str,+ description: str,+ ) -> ToolChunk:+ """Create the team directly via storage.++ Reads the current session record from storage to enforce the+ precondition: a session can only lead one team at a time.+ This makes the tool safe to attach unconditionally to+ ``source='user'`` agents — calling it when the session+ already leads a team returns a clear error rather than+ silently corrupting state.++ Args:+ name (`str`):+ Display name of the team.+ description (`str`):+ Description / charter of the team.++ Returns:+ `ToolChunk`:+ A success message containing the team id, or an error+ chunk if a precondition fails or creation failed.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamCreate: session "+ f"{self._session_id} not found."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ if session.team_id is not None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamCreate: this session is already "+ f"part of team {session.team_id}. A "+ "session can only lead one team at a "+ "time — dissolve the current one with "+ "TeamDelete first."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ team = TeamRecord(+ user_id=self._user_id,+ session_id=self._session_id,+ data=TeamData(+ name=name,+ description=description,+ member_ids=[],+ ),+ )+ await self._storage.upsert_team(self._user_id, team)+ await self._storage.set_session_team_id(+ self._user_id,+ self._session_id,+ team.id,+ )++ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Team {team.id} ({team.data.name}) created. "+ f"You are the leader. Use AgentCreate to add "+ f"members, then TeamSay to coordinate them."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"TeamCreate failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tool/_team_delete.py b/src/agentscope/app/_tool/_team_delete.pynew file mode 100644index 000000000..ea34bfe3c--- /dev/null+++ b/src/agentscope/app/_tool/_team_delete.py@@ -0,0 +1,130 @@+# -*- coding: utf-8 -*-+"""The TeamDelete tool — dissolves the team led by the current session."""+from ._team_tool_base import _TeamToolBase+from ...message import TextBlock, ToolResultState+from ...tool import ToolChunk, ParamsBase+++class _TeamDeleteParams(ParamsBase):+ """Parameters for :class:`TeamDelete` — none."""+++class TeamDelete(_TeamToolBase):+ """Dissolve the team you currently lead and clean up all members."""++ name: str = "TeamDelete"++ description: str = """Dissolve the team you currently lead.++## When to Use This Tool+- The team has finished its work and you want to clean up.+- The team is unrecoverably stuck and you want to start over.+- You have collected the deliverables you need from each member.++## When NOT to Use This Tool+- Members are still producing useful output and you may want their \+follow-up; dissolving deletes them and they cannot be revived.+- You want to remove only one specific member — there is no "remove \+single member" tool in v1, only whole-team dissolution.++## Effects+- Every member agent + its session is deleted.+- The team record is deleted.+- Your own session continues to exist but is no longer associated with \+any team — the team-related tools become unavailable on subsequent \+reasoning steps.++This is irreversible.+"""++ input_schema: dict = _TeamDeleteParams.model_json_schema()++ async def __call__(self) -> ToolChunk:+ """Dissolve the bound session's team via :class:`SessionService`.++ Reads the current session + team records from storage to+ enforce: caller must be in a team AND must be its leader.+ Then delegates the actual cancel + delete + bus-purge cascade+ to :meth:`SessionService.delete_team`, which routes every+ member through the shared session-level primitive — so worker+ chat runs are cancelled cross-process and their bus state is+ cleaned up the same way ``DELETE /agents`` would.++ Returns:+ `ToolChunk`:+ A confirmation message, or an error chunk if a+ precondition fails.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamDelete: this session is not in "+ "any team."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamDelete: team "+ f"{session.team_id} no longer exists."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ if team.session_id != self._session_id:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamDelete: only the team leader "+ "can dissolve the team; this session "+ "is a worker."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Local import to avoid a circular dependency between+ # ``_tools`` and ``_service`` at module load.+ from .._service import SessionService # noqa: PLC0415++ session_service = SessionService(+ storage=self._storage,+ message_bus=self._message_bus,+ )+ await session_service.delete_team(self._user_id, team.id)+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Team {team.id} dissolved. All members "+ f"deleted; your session is no longer "+ f"leading any team."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"TeamDelete failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tool/_team_say.py b/src/agentscope/app/_tool/_team_say.pynew file mode 100644index 000000000..d020ae742--- /dev/null+++ b/src/agentscope/app/_tool/_team_say.py@@ -0,0 +1,339 @@+# -*- coding: utf-8 -*-+"""The TeamSay tool — sends a message to one or all team members."""+from typing import Any++from pydantic import Field++from ._team_tool_base import _TeamToolBase+from ..message_bus import MessageBusKeys+from .._bus_ops import enqueue_run_trigger+from ...message import HintBlock, TextBlock, ToolResultState+from ...tool import ToolChunk, ParamsBase+++class _TeamSayParams(ParamsBase):+ """Parameters for :class:`TeamSay`."""++ content: str = Field(+ description=(+ "The message text. Plain natural-language; the recipient "+ "sees it as a user message in its context."+ ),+ )+ to: str | None = Field(+ default=None,+ description=(+ "Recipient member name. Pass ``null`` (the default) to "+ "broadcast to every other member of the team. To address "+ "a specific peer use that member's name."+ ),+ )+++_LEADER_DESCRIPTION = """Send a message to a specific team member or \+broadcast to all members.++## When to Use This Tool+- Pass **new** requirements or context from the user to a specific member.+- Broadcast an update or coordination message to all members.+- Ask a member a follow-up question when you need clarification.++## When NOT to Use This Tool+- DO NOT repeatedly call this to check on a member's progress — members \+will automatically notify you via ``TeamSay`` when they finish their task. \+Wait for their message instead of polling.+- DO NOT call this right after creating a member by ``AgentCreate``, the \+member will receive its initial task from the ``prompt`` of the \+``AgentCreate`` call and report back when done — just wait for their message. \+- The session is not in a team yet (call ``TeamCreate`` first).+- You want to talk to yourself — use your own reasoning.++## Important+- Each member starts working immediately when created via AgentCreate. \+When a member finishes its task, it will call ``TeamSay`` to report results \+back to you. You do NOT need to prompt them — just wait for their reply.+- **DO NOT** reply to a member's report message unless you have further \+questions or requirements. ``TeamSay`` is for coordination, not chit-chat — \+your top priority is to complete the overall task.+"""++_WORKER_DESCRIPTION = """Send a message to the team leader or broadcast to \+all team members.++## When to Use This Tool+- **IMPORTANT**: When you finish your assigned task, you MUST call this \+tool to report your results back to the leader. The leader is waiting \+for your report — do not end your turn without sending it.+- Share intermediate findings or ask the leader for clarification.+- Broadcast information that other members might need.++## When NOT to Use This Tool+- You want to talk to yourself — use your own reasoning.+- The message is a transient internal thought with no value to others.+"""+++class TeamSay(_TeamToolBase):+ """Send a message to a teammate (or broadcast to all teammates).++ Resolves the team membership at ``__call__`` time from storage,+ so a member added moments earlier in the same chat run is+ addressable immediately.++ The ``description`` shown to the agent differs by role: leaders+ are reminded not to poll members, workers are reminded to report+ results when done. The role is passed at construction time via+ the ``role`` parameter.+ """++ name: str = "TeamSay"+ description: str++ is_concurrency_safe: bool = True+ is_read_only: bool = True++ input_schema: dict = _TeamSayParams.model_json_schema()++ def __init__(+ self,+ *args: Any,+ role: str = "leader",+ **kwargs: Any,+ ) -> None:+ """Initialise with role-specific description.++ Args:+ role (`str`, defaults to ``"leader"``):+ Either ``"leader"`` or ``"worker"``. Determines which+ description the agent sees for this tool.+ *args:+ Forwarded to :class:`_TeamToolBase.__init__`.+ **kwargs:+ Forwarded to :class:`_TeamToolBase.__init__`.+ """+ super().__init__(*args, **kwargs)+ self.description = (+ _LEADER_DESCRIPTION if role == "leader" else _WORKER_DESCRIPTION+ )++ async def __call__(+ self,+ content: str,+ to: str | None = None,+ ) -> ToolChunk:+ """Deliver the message directly via storage + message bus.++ Reads the current session record from storage to resolve the+ team_id (the agent's team membership may have changed since+ agent assembly), builds the team's (agent_id, session_id)+ directory, and pushes a HintBlock + wakeup to each recipient.++ Args:+ content (`str`):+ Message body.+ to (`str | None`, defaults to ``None``):+ Display name of a specific team member to target, or+ ``None`` for broadcast. Routing is by name (not+ agent id) so workers can address the leader by the+ name they see in ``<team-message from="...">``.+ Name uniqueness within a team is enforced at+ ``AgentCreate`` time.++ Returns:+ `ToolChunk`:+ A confirmation containing the recipient count, or an+ error chunk on failure.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamSay: this session is not in any "+ "team — call TeamCreate first if you "+ "want to start one."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: team {session.team_id} no longer "+ f"exists."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ leader_session = await self._storage.get_session(+ self._user_id,+ "",+ team.session_id,+ )+ if leader_session is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: leader session "+ f"{team.session_id} missing for team "+ f"{team.id}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Build a (name -> (session_id, agent_id)) directory in one+ # pass over the team. Routing is by **name** rather than+ # agent_id so workers can address the leader (they receive+ # the leader's name in the <team-message from="..."> hint+ # but never see the leader's agent_id). Uniqueness of names+ # within the team is enforced at AgentCreate time.+ leader_agent = await self._storage.get_agent(+ self._user_id,+ leader_session.agent_id,+ )+ leader_name = (+ leader_agent.data.name+ if leader_agent is not None+ else leader_session.agent_id+ )+ directory: dict[str, tuple[str, str]] = {+ leader_name: (leader_session.id, leader_session.agent_id),+ }+ for worker_agent_id in team.data.member_ids:+ worker_agent = await self._storage.get_agent(+ self._user_id,+ worker_agent_id,+ )+ if worker_agent is None:+ continue+ sessions = await self._storage.list_sessions(+ self._user_id,+ worker_agent_id,+ )+ if sessions:+ directory[worker_agent.data.name] = (+ sessions[0].id,+ worker_agent_id,+ )++ own_session_ids = {sid for sid, _aid in directory.values()}+ if self._session_id not in own_session_ids:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: this session "+ f"({self._session_id}) is not part of "+ f"team {team.id}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ if to is None:+ recipients: list[tuple[str, str]] = [+ (sid, aid)+ for sid, aid in directory.values()+ if sid != self._session_id+ ]+ else:+ resolved = directory.get(to)+ if resolved is None:+ known = sorted(directory.keys())+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: no team member is named "+ f"{to!r}. Known members: {known}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ target_session_id, target_agent_id = resolved+ if target_session_id == self._session_id:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamSay: cannot send a message to "+ "yourself; talk to yourself in your "+ "own reasoning instead."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ recipients = [(target_session_id, target_agent_id)]++ # Resolve sender display name once.+ sender_agent = await self._storage.get_agent(+ self._user_id,+ self._agent_id,+ )+ sender_name = (+ sender_agent.data.name+ if sender_agent is not None+ else self._agent_id+ )++ hint = HintBlock(+ hint=(+ f'<team-message from="{sender_name}">\n'+ f"{content}\n"+ f"</team-message>"+ ),+ source=sender_name,+ )+ payload = hint.model_dump(mode="json")++ for sid, aid in recipients:+ await self._message_bus.queue_push(+ MessageBusKeys.inbox(sid),+ payload,+ )+ await enqueue_run_trigger(+ self._message_bus,+ user_id=self._user_id,+ session_id=sid,+ agent_id=aid,+ )++ count = len(recipients)+ target = "broadcast" if to is None else f"member {to!r}"+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Delivered to {count} recipient(s) "+ f"({target})."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"TeamSay failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tool/_team_tool_base.py b/src/agentscope/app/_tool/_team_tool_base.pynew file mode 100644index 000000000..734e74e5f--- /dev/null+++ b/src/agentscope/app/_tool/_team_tool_base.py@@ -0,0 +1,99 @@+# -*- coding: utf-8 -*-+"""Base class shared by the team tools."""+from typing import Any, TYPE_CHECKING++from ...permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from ...tool import ToolBase++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import StorageBase+++class _TeamToolBase(ToolBase):+ """Shared base for the team tools.++ All team tools are constructed at agent assembly time (in+ :func:`get_toolkit`) with the request-scoped ``user_id``,+ ``session_id``, and ``agent_id`` plus ``storage`` + ``message_bus``+ references. Each tool's ``__call__`` does its work directly via+ those two dependencies — there is no intermediate service layer.++ Permissions: all team tools allow themselves unconditionally — the+ agent's authority to call them is already gated by the+ role/source-aware logic inside :func:`get_toolkit` that decides+ which team tools to attach in the first place.+ """++ name: str+ description: str+ input_schema: dict[str, Any]+ is_concurrency_safe: bool = False+ is_read_only: bool = True+ is_state_injected: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ def __init__(+ self,+ storage: "StorageBase",+ message_bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> None:+ """Bind request-scoped identifiers and shared dependencies.++ Args:+ storage (`StorageBase`):+ Application storage. Each tool reads the current+ session / team records at ``__call__`` time to do+ runtime precondition checks (am I in a team? am I the+ leader?) — this is what lets all four team tools be+ attached unconditionally to ``source='user'`` agents+ without depending on a stale snapshot of ``team_id``+ taken at agent assembly time.+ message_bus (`MessageBus`):+ Application message bus. Tools that deliver+ inter-session messages (``AgentCreate``, ``TeamSay``)+ push HintBlocks + wakeups through it.+ user_id (`str`):+ The owner user id of the calling agent.+ session_id (`str`):+ The current session id of the calling agent.+ agent_id (`str`):+ The id of the agent invoking the tool.+ """+ self._storage = storage+ self._message_bus = message_bus+ self._user_id = user_id+ self._session_id = session_id+ self._agent_id = agent_id++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Always allow — gating is done by tool-attachment logic.++ Args:+ tool_input (`dict[str, Any]`):+ The arguments the agent passed; ignored here.+ context (`PermissionContext`):+ The active permission context; ignored here.++ Returns:+ `PermissionDecision`:+ An ``ALLOW`` decision with a brief explanation.+ """+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"{self.name} is always allowed when attached to the "+ f"agent.",+ )diff --git a/src/agentscope/app/message_bus/_base.py b/src/agentscope/app/message_bus/_base.pyindex 6bd6491f6..eb80823a2 100644--- a/src/agentscope/app/message_bus/_base.py+++ b/src/agentscope/app/message_bus/_base.py@@ -45,6 +45,8 @@ from collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanagerfrom typing import Any, Callable, Self+from typing_extensions import deprecated+from ._keys import MessageBusKeys@@ -454,52 +456,39 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods"""# ==================================================================- # Domain helpers — concrete on the base class so all backends- # share the same key conventions and serialisation rules.+ # Deprecated domain helpers+ #+ # These thin shells delegate to the generic primitives above. They+ # exist so that code written against the old API keeps working for+ # one release cycle; new code should use the primitives + MessageBusKeys+ # (or the standalone functions in agentscope.app._service) directly.+ #+ # The _XXX_KEY class-level constants are kept as well — some tests+ # reference them — but new code should use MessageBusKeys instead.# ==================================================================- # Session run coordination -----------------------------------------+ # Key constants (kept for backward compat) -------------------------_SESSION_LOCK_KEY = "agentscope:session:lock:{sid}"- """Per-session distributed-lock key template."""-_SESSION_EVENTS_KEY = "agentscope:session:events:{sid}"- """Per-session replay log + live pub/sub channel key template."""-_SESSION_CANCEL_KEY = "agentscope:session:cancel"- """Global cancel-broadcast channel. Used by- :meth:`session_publish_cancel` to ask whichever process is currently- running a given session to abort its run; the payload carries the- target ``session_id`` and only the worker actually holding that- session's task reacts."""-_SESSION_RUN_TTL_SECS = 600- """Default lock lease for a chat run (10 minutes)."""-_SESSION_REPLAY_MAX_LEN = 1000- """Replay log length cap; older events are trimmed on append."""+ _INBOX_KEY = "agentscope:inbox:{sid}"+ _WAKEUP_QUEUE_KEY = "agentscope:wakeups"+ _WAKEUP_SIGNAL_KEY = "agentscope:wakeup_signal"+ _BG_TASKS_KEY = "agentscope:bg_tasks:{sid}"+ _BG_TASKS_TTL_SECS = 86400+ _TASK_CANCEL_KEY = "agentscope:task:cancel"+ # Session run coordination -----------------------------------------++ @deprecated(+ "Use acquire_lock(MessageBusKeys.session_lock(sid), ...) directly.",+ )@asynccontextmanagerasync def session_run(self, session_id: str) -> AsyncGenerator[None, None]:- """Block until exclusive control of ``session_id`` is held.-- Two processes calling this for the same session_id queue up;- the second only enters after the first releases (or its- lease expires after a crash).-- On exit, the session's replay log is trimmed *before* the- lock is released. This guarantees that any process which- acquires the lock next sees a clean log (and any SSE- subscriber that connects between this run and the next sees- a clean slate, not stale events from this run).-- Args:- session_id (`str`):- The session to lock.-- Yields:- `None`: while the session lock is held.- """+ """Acquire the session lock, yield, then trim the replay log."""async with self.acquire_lock(self._SESSION_LOCK_KEY.format(sid=session_id),ttl_secs=self._SESSION_RUN_TTL_SECS,@@ -507,55 +496,29 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodstry:yieldfinally:- # Replay log was the in-flight buffer for this run;- # the chat run is responsible for persisting the- # complete Msg to storage before releasing the lock,- # so the log is no longer needed by any subscriber.await self.log_trim(self._SESSION_EVENTS_KEY.format(sid=session_id),)+ @deprecated(+ "Use is_locked(MessageBusKeys.session_lock(sid)) directly.",+ )async def session_is_running(self, session_id: str) -> bool:- """Return whether some process is currently running this session.-- Args:- session_id (`str`):- The session to check.-- Returns:- `bool`:- ``True`` if a chat run holds the session lock right now.- """+ """Check whether some process holds the session lock."""return await self.is_locked(self._SESSION_LOCK_KEY.format(sid=session_id),)+ @deprecated(+ "Use publish_session_event(bus, sid, event) from "+ "agentscope.app._bus_ops directly.",+ )async def session_publish_event(self,session_id: str,event: dict,) -> str:- """Append a session event to the replay log + fan it out live.-- The single event is persisted to a Redis Stream (so late-joining- subscribers can replay it) and simultaneously- published on a Pub/Sub channel of the same key (so already-connected- subscribers see it immediately). The persisted- log entry id is included in the live payload as- ``_entry_id`` so subscribers can deduplicate replay vs live- delivery.-- Args:- session_id (`str`):- The session this event belongs to.- event (`dict`):- JSON-serializable event payload (typically- ``AgentEvent.model_dump(mode='json')``).-- Returns:- `str`:- The replay-log entry id assigned by the backend.- """+ """Append + fan-out a session event."""key = self._SESSION_EVENTS_KEY.format(sid=session_id)entry_id = await self.log_append(key,@@ -565,103 +528,60 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsawait self.publish(key, {**event, "_entry_id": entry_id})return entry_id+ @deprecated(+ "Use log_read(MessageBusKeys.session_events(sid), ...) directly.",+ )async def session_read_events(self,session_id: str,since: str | None = None,max_count: int = 1000,) -> list[tuple[str, dict]]:- """Read events from the session's replay log.-- Args:- session_id (`str`):- The session whose events to read.- since (`str | None`, optional):- Cursor — return entries strictly newer than this- replay-log id. ``None`` reads from the beginning.- max_count (`int`, defaults to ``1000``):- Maximum events to return.-- Returns:- `list[tuple[str, dict]]`:- ``(entry_id, event_payload)`` pairs in append order.- """+ """Read events from the session's replay log."""return await self.log_read(self._SESSION_EVENTS_KEY.format(sid=session_id),since=since,max_count=max_count,)+ @deprecated(+ "Use subscribe(MessageBusKeys.session_events(sid), ...) directly, "+ "stripping _entry_id from each payload.",+ )async def session_subscribe_events(self,session_id: str,*,on_ready: Callable[[], None] | None = None,) -> AsyncGenerator[dict, None]:- """Live-subscribe to a session's published events.-- Yields only payloads delivered after the subscription is- established. To replay history first, call- :meth:`session_read_events` separately.-- Args:- session_id (`str`):- The session to subscribe to.- on_ready (`Callable[[], None] | None`, optional):- Forwarded to the underlying :meth:`subscribe`.-- Yields:- `dict`:- Event payloads, with the internal ``_entry_id``- field stripped (callers don't need to see it).- """+ """Live-subscribe to session events, stripping _entry_id."""key = self._SESSION_EVENTS_KEY.format(sid=session_id)async for payload in self.subscribe(key, on_ready=on_ready):yield {k: v for k, v in payload.items() if k != "_entry_id"}# Cross-process cancel ---------------------------------------------+ @deprecated(+ "Use publish(MessageBusKeys.session_cancel_channel(), "+ "{'session_id': sid}) directly.",+ )async def session_publish_cancel(self, session_id: str) -> None:- """Broadcast a cancel request for ``session_id``.-- Sent on a transient pub/sub channel: only processes that have- an active :meth:`session_subscribe_cancel` subscription at- publish time will see it. The process actually running the- session is expected to be such a subscriber (its- :class:`~agentscope.app._manager.CancelDispatcher` subscribes- for the lifetime of the app). Other processes ignore the- message because they hold no asyncio task for that session.-- Args:- session_id (`str`):- The session whose run should be cancelled.- """+ """Broadcast a session cancel request."""await self.publish(self._SESSION_CANCEL_KEY,{"session_id": session_id},)+ @deprecated(+ "Use subscribe(MessageBusKeys.session_cancel_channel(), ...) "+ "directly, extracting session_id from the payload.",+ )async def session_subscribe_cancel(self,*,on_ready: Callable[[], None] | None = None,) -> AsyncGenerator[str, None]:- """Subscribe to the cancel-broadcast channel.-- Yields session ids as cancel requests arrive. A single- subscriber per process is enough — the- :class:`~agentscope.app._manager.CancelDispatcher` filters- locally by checking whether the incoming ``session_id`` is in- its own :class:`ChatRunRegistry`.-- Args:- on_ready (`Callable[[], None] | None`, optional):- Forwarded to the underlying :meth:`subscribe`.-- Yields:- `str`:- The session id from each incoming cancel payload.- """+ """Subscribe to session cancel broadcasts, yielding session ids."""async for payload in self.subscribe(self._SESSION_CANCEL_KEY,on_ready=on_ready,@@ -672,32 +592,21 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods# Purge -------------------------------------------------------------+ @deprecated(+ "Call log_trim / queue_delete / registry_drop with "+ "MessageBusKeys directly.",+ )async def session_purge(self, session_id: str) -> None:- """Delete all per-session bus state.-- Drops the events log, the inbox queue, and the BG task- registry. The distributed run-lock is intentionally not- touched: callers must ensure no run is in flight (e.g. by- publishing cancel via :meth:`session_publish_cancel` and- polling :meth:`is_locked` until it clears) before calling- this. Any residual lock key expires on its own after at most- :attr:`_SESSION_RUN_TTL_SECS`.-- Idempotent: a no-op when the keys are already absent.-- Args:- session_id (`str`):- The session whose bus state should be removed.- """+ """Delete all per-session bus state."""await self.log_trim(self._SESSION_EVENTS_KEY.format(sid=session_id))await self.queue_delete(self._INBOX_KEY.format(sid=session_id))- await self.bg_task_purge(session_id)+ await self.registry_drop(self._BG_TASKS_KEY.format(sid=session_id))# Inbox ------------------------------------------------------------ _INBOX_KEY = "agentscope:inbox:{sid}"- """Per-session inbox queue key template."""-+ @deprecated(+ "Use queue_push(MessageBusKeys.inbox(sid), ...) directly.",+ )async def inbox_push(self,session_id: str,@@ -705,45 +614,22 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods*,ttl_secs: int | None = None,) -> str:- """Append an inbound message to a session's inbox.-- Args:- session_id (`str`):- The recipient session id.- msg (`dict`):- JSON-serializable :class:`Msg` payload (use- ``Msg.model_dump(mode='json')``).- ttl_secs (`int | None`, optional):- Inbox key lifetime; ``None`` means no expiry.-- Returns:- `str`:- The transport-level entry id from- :meth:`queue_push`.- """+ """Push a message to a session's inbox."""return await self.queue_push(self._INBOX_KEY.format(sid=session_id),msg,ttl_secs=ttl_secs,)+ @deprecated(+ "Use queue_drain(MessageBusKeys.inbox(sid), ...) directly.",+ )async def inbox_drain(self,session_id: str,max_count: int = 100,) -> list[tuple[str, dict]]:- """Drain pending inbox messages for a session.-- Args:- session_id (`str`):- The session whose inbox to drain.- max_count (`int`, defaults to ``100``):- Maximum entries to drain in one call.-- Returns:- `list[tuple[str, dict]]`:- ``(entry_id, msg_payload)`` pairs in arrival order.- """+ """Drain pending inbox messages for a session."""return await self.queue_drain(self._INBOX_KEY.format(sid=session_id),max_count=max_count,@@ -751,54 +637,33 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods# Wakeup ----------------------------------------------------------- _WAKEUP_QUEUE_KEY = "agentscope:wakeups"- """Shared run-trigger queue (durable Redis Stream).-- Despite the historical name, this carries *all* dispatcher-driven- run triggers, not just idle wake-ups — each entry's ``kind`` tells- the dispatcher how to spawn the run (see :meth:`enqueue_wakeup` /- :meth:`enqueue_input`)."""-- _WAKEUP_SIGNAL_KEY = "agentscope:wakeup_signal"- """Shared Pub/Sub channel that nudges dispatchers to drain the- run-trigger queue."""-+ @deprecated(+ "Use enqueue_run_trigger(bus, ...) from "+ "agentscope.app._bus_ops directly.",+ )async def enqueue_wakeup(self,user_id: str,session_id: str,agent_id: str,) -> None:- """Enqueue an idle-session wake-up and signal dispatchers.-- Producers (e.g. ``TeamSay``, ``AgentCreate``, the scheduler- trigger, or the BG-tool completion watcher) call this after- depositing a message in the recipient's inbox. The shared- :class:`WakeupDispatcher` (one per process) drains the queue- on each signal and starts a chat run for any session that- is not currently active.-- Equivalent to :meth:`enqueue_input` with- ``kind=MessageBusKeys.WAKEUP_KIND_WAKE`` and no input; kept as the- explicit, narrowly-typed entry point for the common idle-wake- case.-- Args:- user_id (`str`):- The owning user id.- session_id (`str`):- The session to wake.- agent_id (`str`):- The agent id that owns the session.- """- await self.enqueue_input(- user_id=user_id,- session_id=session_id,- agent_id=agent_id,- kind=MessageBusKeys.WAKEUP_KIND_WAKE,- inputs=None,+ """Enqueue an idle-session wake-up."""+ await self.queue_push(+ self._WAKEUP_QUEUE_KEY,+ {+ "user_id": user_id,+ "session_id": session_id,+ "agent_id": agent_id,+ "kind": MessageBusKeys.WAKEUP_KIND_WAKE,+ "input": None,+ },)+ await self.publish(self._WAKEUP_SIGNAL_KEY, {})+ @deprecated(+ "Use enqueue_run_trigger(bus, ...) from "+ "agentscope.app._bus_ops directly.",+ )async def enqueue_input(self,user_id: str,@@ -808,34 +673,7 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodskind: str,inputs: dict | None = None,) -> None:- """Enqueue a typed run trigger and signal dispatchers.-- The generalised producer behind every dispatcher-driven run.- It makes the durable queue a per-session input mailbox: ``wake``- triggers drain inbox content (no input), ``resume`` triggers- carry a serialised human-in-the-loop result so the parked run- can continue. Routing all triggers through this single queue- keeps the :class:`WakeupDispatcher` the sole spawn site, which- is what makes concurrent-spawn races (two writers contending for- one session's run slot) structurally impossible.-- Args:- user_id (`str`):- The owning user id.- session_id (`str`):- The session to trigger a run for.- agent_id (`str`):- The agent id that owns the session.- kind (`str`):- The trigger kind — :attr:`MessageBusKeys.WAKEUP_KIND_WAKE`- or :attr:`MessageBusKeys.WAKEUP_KIND_RESUME`. Governs how- the dispatcher handles a busy session and what it passes- as ``input_msg``.- inputs (`dict | None`, optional):- The JSON-serialised input event to feed the run (e.g. a- ``UserConfirmResultEvent`` dump) for ``resume`` triggers.- ``None`` for ``wake`` triggers.- """+ """Enqueue a typed run trigger."""await self.queue_push(self._WAKEUP_QUEUE_KEY,{@@ -848,48 +686,29 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods)await self.publish(self._WAKEUP_SIGNAL_KEY, {})+ @deprecated(+ "Use queue_drain(MessageBusKeys.wakeup_queue(), ...) directly.",+ )async def dequeue_wakeups(self,max_count: int = 64,) -> list[dict]:- """Drain pending run-trigger entries.-- Args:- max_count (`int`, defaults to ``64``):- Maximum entries to drain per call.-- Returns:- `list[dict]`:- Entries shaped ``{"user_id", "session_id", "agent_id",- "kind", "input"}`` in enqueue order. Entries produced by- older code paths may omit ``kind``/``input``; consumers- should treat a missing ``kind`` as- :attr:`MessageBusKeys.WAKEUP_KIND_WAKE`.- """+ """Drain pending run-trigger entries."""entries = await self.queue_drain(self._WAKEUP_QUEUE_KEY,max_count=max_count,)return [payload for _entry_id, payload in entries]+ @deprecated(+ "Use subscribe(MessageBusKeys.wakeup_signal(), ...) directly.",+ )async def subscribe_wakeup_signal(self,*,on_ready: Callable[[], None] | None = None,) -> AsyncGenerator[dict, None]:- """Subscribe to the shared wake-up signal channel.-- Each yielded item indicates "drain the queue now"; the- payload itself carries no business data.-- Args:- on_ready (`Callable[[], None] | None`, optional):- Forwarded to the underlying :meth:`subscribe`.-- Yields:- `dict`:- The empty / opaque signal payload.- """+ """Subscribe to the shared wake-up signal channel."""async for payload in self.subscribe(self._WAKEUP_SIGNAL_KEY,on_ready=on_ready,@@ -898,41 +717,16 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods# Background task registry -------------------------------------------- _BG_TASKS_KEY = "agentscope:bg_tasks:{sid}"- """Per-session registry of in-flight background tasks."""-- _BG_TASKS_TTL_SECS = 86400- """Fallback TTL for the per-session BG task registry (24 h).-- This TTL is *not* the primary cleanup path — finished tasks remove- themselves via :meth:`bg_task_unregister` and session deletion- triggers :meth:`bg_task_purge`. It is only a safety net for- abandoned entries left behind by a crashed worker whose session is- also never explicitly purged. Sized so that virtually every- realistic long-running tool finishes (and unregisters) before the- fallback kicks in, while still bounding orphan growth in Redis.- """-- _TASK_CANCEL_KEY = "agentscope:task:cancel"- """Pub/Sub channel for single-task cancel broadcasts."""-+ @deprecated(+ "Use registry_set(MessageBusKeys.bg_tasks(sid), ...) directly.",+ )async def bg_task_register(self,session_id: str,task_id: str,metadata: str,) -> None:- """Register a background task in the global registry.-- Args:- session_id (`str`):- The session that owns this task.- task_id (`str`):- Unique task identifier.- metadata (`str`):- JSON-serialized task metadata (e.g. ``tool_name``,- ``agent_id``, ``started_at``).- """+ """Register a background task."""await self.registry_set(self._BG_TASKS_KEY.format(sid=session_id),task_id,@@ -940,108 +734,73 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsttl_secs=self._BG_TASKS_TTL_SECS,)+ @deprecated(+ "Use registry_del(MessageBusKeys.bg_tasks(sid), tid) directly.",+ )async def bg_task_unregister(self,session_id: str,task_id: str,) -> None:- """Remove a background task from the global registry.-- Args:- session_id (`str`):- The session that owns this task.- task_id (`str`):- Task identifier to remove.- """+ """Unregister a background task."""await self.registry_del(self._BG_TASKS_KEY.format(sid=session_id),task_id,)+ @deprecated(+ "Use registry_exists(MessageBusKeys.bg_tasks(sid), tid) directly.",+ )async def bg_task_exists(self,session_id: str,task_id: str,) -> bool:- """Check whether a background task is registered.-- Args:- session_id (`str`):- The session that owns this task.- task_id (`str`):- Task identifier to check.-- Returns:- `bool`:- ``True`` if the task is in the registry.- """+ """Check whether a background task is registered."""return await self.registry_exists(self._BG_TASKS_KEY.format(sid=session_id),task_id,)+ @deprecated(+ "Use registry_getall(MessageBusKeys.bg_tasks(sid)) directly.",+ )async def bg_task_list(self,session_id: str,) -> dict[str, str]:- """List all background tasks for a session.-- Args:- session_id (`str`):- The session whose tasks to list.-- Returns:- `dict[str, str]`:- ``{task_id: metadata_json}`` for all registered tasks.- """+ """List all background tasks for a session."""return await self.registry_getall(self._BG_TASKS_KEY.format(sid=session_id),)+ @deprecated(+ "Use registry_drop(MessageBusKeys.bg_tasks(sid)) directly.",+ )async def bg_task_purge(self, session_id: str) -> None:- """Delete all background task entries for a session.-- Used during session deletion to clean up the registry in one- shot. Actual task cancellation is handled separately by- :class:`CancelDispatcher`.-- Args:- session_id (`str`):- The session whose registry to delete.- """+ """Delete all background task entries for a session."""await self.registry_drop(self._BG_TASKS_KEY.format(sid=session_id),)+ @deprecated(+ "Use publish(MessageBusKeys.task_cancel_channel(), "+ "{'task_id': tid}) directly.",+ )async def task_publish_cancel(self, task_id: str) -> None:- """Broadcast a cancel request for a single background task.-- Sent on a transient Pub/Sub channel; only processes that hold- the target task react. Others ignore the message.-- Args:- task_id (`str`):- The task to cancel.- """+ """Broadcast a cancel request for a single background task."""await self.publish(self._TASK_CANCEL_KEY, {"task_id": task_id})+ @deprecated(+ "Use subscribe(MessageBusKeys.task_cancel_channel(), ...) "+ "directly, extracting task_id from the payload.",+ )async def task_subscribe_cancel(self,*,on_ready: Callable[[], None] | None = None,) -> AsyncGenerator[str, None]:- """Subscribe to the task-level cancel channel.-- Yields task ids as cancel requests arrive.-- Args:- on_ready (`Callable[[], None] | None`, optional):- Forwarded to the underlying :meth:`subscribe`.-- Yields:- `str`:- The task id from each incoming cancel payload.- """+ """Subscribe to task cancel broadcasts, yielding task ids."""async for payload in self.subscribe(self._TASK_CANCEL_KEY,on_ready=on_ready,diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.pyindex eec57b4c6..9057769ef 100644--- a/src/agentscope/app/message_bus/_keys.py+++ b/src/agentscope/app/message_bus/_keys.py@@ -13,6 +13,8 @@ Add new business keys here as needed. As legacy keys are migrated off``MessageBus``, they should move into this class as well."""+from typing import Final+class MessageBusKeys:"""Application-layer key conventions for the message bus."""@@ -24,12 +26,12 @@ class MessageBusKeys:# free of business vocabulary.# ------------------------------------------------------------------- WAKEUP_KIND_WAKE = "wake"+ WAKEUP_KIND_WAKE: Final = "wake""""Trigger kind: wake an *idle* session to drain pending inboxcontent. The dispatcher spawns the run with ``input_msg=None`` andskips the session entirely while it is already running."""- WAKEUP_KIND_RESUME = "resume"+ WAKEUP_KIND_RESUME: Final = "resume""""Trigger kind: resume a session parked on an awaiting tool call byfeeding it a human-in-the-loop result. The dispatcher spawns the runwith the carried ``input`` event and — unlike ``wake`` — must *not*@@ -102,3 +104,90 @@ class MessageBusKeys:The field-key prefix, ``"{kind}:"``."""return f"{kind}:"++ # ------------------------------------------------------------------+ # Session event stream (replay log + live pub/sub)+ # ------------------------------------------------------------------++ _SESSION_EVENTS = "agentscope:session:events:{sid}"++ SESSION_REPLAY_MAX_LEN = 1000+ """Replay log length cap; older events are trimmed on append."""++ @classmethod+ def session_events(cls, session_id: str) -> str:+ """Replay log + live pub/sub channel key for a session."""+ return cls._SESSION_EVENTS.format(sid=session_id)++ # ------------------------------------------------------------------+ # Session run lock+ # ------------------------------------------------------------------++ _SESSION_LOCK = "agentscope:session:lock:{sid}"++ SESSION_RUN_TTL_SECS = 600+ """Default lock lease for a chat run (10 minutes)."""++ @classmethod+ def session_lock(cls, session_id: str) -> str:+ """Per-session distributed-lock key."""+ return cls._SESSION_LOCK.format(sid=session_id)++ # ------------------------------------------------------------------+ # Session inbox+ # ------------------------------------------------------------------++ _INBOX = "agentscope:inbox:{sid}"++ @classmethod+ def inbox(cls, session_id: str) -> str:+ """Per-session inbox drain-queue key."""+ return cls._INBOX.format(sid=session_id)++ # ------------------------------------------------------------------+ # Run trigger queue (wakeup / resume)+ # ------------------------------------------------------------------++ _WAKEUP_QUEUE = "agentscope:wakeups"+ _WAKEUP_SIGNAL = "agentscope:wakeup_signal"++ @classmethod+ def wakeup_queue(cls) -> str:+ """Shared run-trigger queue key."""+ return cls._WAKEUP_QUEUE++ @classmethod+ def wakeup_signal(cls) -> str:+ """Shared signal channel that nudges dispatchers to drain."""+ return cls._WAKEUP_SIGNAL++ # ------------------------------------------------------------------+ # Cross-process cancel+ # ------------------------------------------------------------------++ _SESSION_CANCEL = "agentscope:session:cancel"+ _TASK_CANCEL = "agentscope:task:cancel"++ @classmethod+ def session_cancel_channel(cls) -> str:+ """Global session-cancel broadcast channel."""+ return cls._SESSION_CANCEL++ @classmethod+ def task_cancel_channel(cls) -> str:+ """Single-task cancel broadcast channel."""+ return cls._TASK_CANCEL++ # ------------------------------------------------------------------+ # Background task registry+ # ------------------------------------------------------------------++ _BG_TASKS = "agentscope:bg_tasks:{sid}"++ BG_TASKS_TTL_SECS = 86400+ """Fallback TTL for the per-session BG task registry (24 h)."""++ @classmethod+ def bg_tasks(cls, session_id: str) -> str:+ """Per-session background task registry key."""+ return cls._BG_TASKS.format(sid=session_id)diff --git a/src/agentscope/app/middleware/_inbox_middleware.py b/src/agentscope/app/middleware/_inbox_middleware.pyindex bbf76840d..a494cb09e 100644--- a/src/agentscope/app/middleware/_inbox_middleware.py+++ b/src/agentscope/app/middleware/_inbox_middleware.py@@ -13,7 +13,7 @@ so the front-end SSE stream can render it in real time."""from typing import Any, AsyncGenerator, Callable-from ..message_bus import MessageBus+from ..message_bus import MessageBus, MessageBusKeysfrom ..._logging import loggerfrom ...agent import Agentfrom ...event import HintBlockEvent@@ -78,8 +78,8 @@ class InboxMiddleware(MiddlewareBase): # pylint: disable=abstract-methodOne ``HintBlockEvent`` per drained inbox entry,followed by events from downstream."""- entries = await self._bus.inbox_drain(- agent.state.session_id,+ entries = await self._bus.queue_drain(+ MessageBusKeys.inbox(agent.state.session_id),max_count=self._max_count,)diff --git a/src/agentscope/app/middleware/_state_change_middleware.py b/src/agentscope/app/middleware/_state_change_middleware.pyindex 7ed174bbf..c588c7105 100644--- a/src/agentscope/app/middleware/_state_change_middleware.py+++ b/src/agentscope/app/middleware/_state_change_middleware.py@@ -24,6 +24,7 @@ import hashlibfrom typing import Any, AsyncGenerator, Callablefrom ..message_bus import MessageBus+from .._bus_ops import publish_session_eventfrom ...event import CustomEventfrom ...middleware import MiddlewareBase@@ -124,7 +125,8 @@ class StateChangeMiddleware(MiddlewareBase): # pylint: disable=abstract-method),},)- await self._bus.session_publish_event(+ await publish_session_event(+ self._bus,self._session_id,event.model_dump(mode="json"),)@@ -135,7 +137,8 @@ class StateChangeMiddleware(MiddlewareBase): # pylint: disable=abstract-methodname="team_updated",value={},)- await self._bus.session_publish_event(+ await publish_session_event(+ self._bus,self._session_id,event.model_dump(mode="json"),)diff --git a/src/agentscope/app/middleware/_tool_offload_middleware.py b/src/agentscope/app/middleware/_tool_offload_middleware.pyindex 10f966f31..3c5845934 100644--- a/src/agentscope/app/middleware/_tool_offload_middleware.py+++ b/src/agentscope/app/middleware/_tool_offload_middleware.py@@ -34,7 +34,8 @@ from ...message import (ToolResultState,)from ...agent import Agent-from ..message_bus import MessageBus+from ..message_bus import MessageBus, MessageBusKeys+from .._bus_ops import enqueue_run_triggerfrom ..._logging import logger@@ -344,11 +345,12 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methodtool_name,session_id,)- await self._message_bus.inbox_push(- session_id,+ await self._message_bus.queue_push(+ MessageBusKeys.inbox(session_id),hint.model_dump(mode="json"),)- await self._message_bus.enqueue_wakeup(+ await enqueue_run_trigger(+ self._message_bus,user_id=self._user_id,session_id=session_id,agent_id=self._agent_id,diff --git a/tests/service_subagent_hitl_projector_test.py b/tests/service_subagent_hitl_projector_test.pynew file mode 100644index 000000000..e7b751102--- /dev/null+++ b/tests/service_subagent_hitl_projector_test.py@@ -0,0 +1,350 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for :class:`SubagentHitlProjector` — the strategy that mirrors a+team *member* (worker) session's HITL request onto its *leader* session.++Covers the projection policy:++- A worker ``Require*`` event upserts a pending card on the leader and+ publishes the live ``EVT_REQUIRE`` notification.+- A worker ``*Result`` / ``ReplyEnd`` event deletes the card and+ publishes the ``EVT_RESULT`` clear notification.+- No-op for non-team agents, for sessions with no ``team_id``, and for+ the leader session itself (its own HITL reaches its client directly).+- ``resolve`` finds the worker entry behind a leader+reply_id, and+ returns ``None`` when none matches.+"""+from typing import Any+from unittest import IsolatedAsyncioTestCase++from agentscope.app._service import SubagentHitlProjector+from agentscope.app.storage._model._agent import AgentRecord, AgentData+from agentscope.app.storage._model._session import SessionRecord+from agentscope.app.storage._model._team import TeamRecord+from agentscope.event import (+ RequireUserConfirmEvent,+ RequireExternalExecutionEvent,+ UserConfirmResultEvent,+ ExternalExecutionResultEvent,+ ReplyEndEvent,+)+++class _FakeProjection:+ """Records every mutation the projector makes, no Redis required.++ Mimics :class:`SessionProjection`'s surface (``upsert`` / ``delete``+ / ``publish`` / ``list``) over an in-memory ``{(sid, kind): {eid:+ payload}}`` store so tests can assert exactly what was projected.+ """++ def __init__(self) -> None:+ self.store: dict[tuple[str, str], dict[str, dict]] = {}+ self.published: list[tuple[str, str, dict]] = []++ async def upsert(+ self,+ target_sid: str,+ kind: str,+ entry_id: str,+ payload: dict,+ ) -> None:+ """Record an upsert in the in-memory store."""+ self.store.setdefault((target_sid, kind), {})[entry_id] = payload++ async def delete(+ self,+ target_sid: str,+ kind: str,+ entry_id: str,+ ) -> None:+ """Remove an entry from the in-memory store."""+ self.store.get((target_sid, kind), {}).pop(entry_id, None)++ async def list(self, target_sid: str, kind: str) -> list[dict]:+ """Return all entries for the given session and kind."""+ return list(self.store.get((target_sid, kind), {}).values())++ async def publish(+ self,+ target_sid: str,+ event_name: str,+ value: dict,+ ) -> None:+ """Record a published event for later assertion."""+ self.published.append((target_sid, event_name, value))+++class _FakeStorage:+ """Returns a fixed team for ``get_team``; ``None`` to simulate a+ missing / non-team lookup."""++ def __init__(self, team: TeamRecord | None) -> None:+ self._team = team++ async def get_team(+ self,+ _user_id: str,+ _team_id: str,+ ) -> TeamRecord | None:+ """Return the pre-configured team record."""+ return self._team+++_LEADER_SID = "leader-sid"+_WORKER_SID = "worker-sid"+_TEAM_ID = "team-1"+++def _team() -> TeamRecord:+ """A team whose leader is ``_LEADER_SID``."""+ return TeamRecord.model_construct(+ id=_TEAM_ID,+ user_id="u",+ session_id=_LEADER_SID,+ )+++def _session(sid: str, team_id: str | None = _TEAM_ID) -> SessionRecord:+ """A session record with just the fields the projector reads."""+ return SessionRecord.model_construct(+ id=sid,+ user_id="u",+ agent_id="wa1",+ team_id=team_id,+ )+++def _agent(source: str = "team") -> AgentRecord:+ """An agent record with just the fields the projector reads."""+ return AgentRecord.model_construct(+ id="wa1",+ user_id="u",+ source=source,+ data=AgentData.model_construct(name="researcher"),+ )+++def _projector(team: TeamRecord | None = None) -> SubagentHitlProjector:+ return SubagentHitlProjector(_FakeStorage(team if team else _team()))+++def _entry_id() -> str:+ return SubagentHitlProjector.entry_id(_WORKER_SID, "r1")+++class TestSubagentHitlProjectorRequire(IsolatedAsyncioTestCase):+ """The require → upsert + publish path."""++ async def _run_require(self, event: Any) -> _FakeProjection:+ projection = _FakeProjection()+ await _projector().maybe_project(+ "u",+ _session(_WORKER_SID),+ _agent(),+ event,+ projection,+ )+ return projection++ async def test_require_user_confirm_upserts_and_publishes(self) -> None:+ """A worker ``RequireUserConfirmEvent`` writes a leader card and+ fires the live require notification."""+ event = RequireUserConfirmEvent.model_construct(+ reply_id="r1",+ tool_calls=[],+ )+ projection = await self._run_require(event)++ card = projection.store[(_LEADER_SID, SubagentHitlProjector.KIND)]+ self.assertIn(_entry_id(), card)+ payload = card[_entry_id()]+ self.assertEqual(payload["worker_session_id"], _WORKER_SID)+ self.assertEqual(payload["reply_id"], "r1")+ self.assertEqual(payload["event_type"], "require_user_confirm")++ self.assertEqual(len(projection.published), 1)+ sid, name, _ = projection.published[0]+ self.assertEqual(sid, _LEADER_SID)+ self.assertEqual(name, SubagentHitlProjector.EVT_REQUIRE)++ async def test_require_external_execution_marks_event_type(self) -> None:+ """A ``RequireExternalExecutionEvent`` carries the matching+ ``event_type`` discriminator."""+ event = RequireExternalExecutionEvent.model_construct(+ reply_id="r1",+ tool_calls=[],+ )+ projection = await self._run_require(event)++ card = projection.store[(_LEADER_SID, SubagentHitlProjector.KIND)]+ self.assertEqual(+ card[_entry_id()]["event_type"],+ "require_external_execution",+ )+++class TestSubagentHitlProjectorClear(IsolatedAsyncioTestCase):+ """The result / reply-end → delete + publish path."""++ async def _seed_then(self, clear_event: Any) -> _FakeProjection:+ projection = _FakeProjection()+ projector = _projector()+ # Seed a pending card first.+ await projector.maybe_project(+ "u",+ _session(_WORKER_SID),+ _agent(),+ RequireUserConfirmEvent.model_construct(+ reply_id="r1",+ tool_calls=[],+ ),+ projection,+ )+ projection.published.clear()+ # Now clear it.+ await projector.maybe_project(+ "u",+ _session(_WORKER_SID),+ _agent(),+ clear_event,+ projection,+ )+ return projection++ async def test_user_confirm_result_clears_card(self) -> None:+ """A worker ``UserConfirmResultEvent`` deletes the leader card and+ publishes the clear notification."""+ projection = await self._seed_then(+ UserConfirmResultEvent.model_construct(+ reply_id="r1",+ confirm_results=[],+ ),+ )+ card = projection.store[(_LEADER_SID, SubagentHitlProjector.KIND)]+ self.assertNotIn(_entry_id(), card)++ self.assertEqual(len(projection.published), 1)+ sid, name, value = projection.published[0]+ self.assertEqual(sid, _LEADER_SID)+ self.assertEqual(name, SubagentHitlProjector.EVT_RESULT)+ self.assertEqual(value["worker_session_id"], _WORKER_SID)+ self.assertEqual(value["reply_id"], "r1")++ async def test_external_execution_result_clears_card(self) -> None:+ """An ``ExternalExecutionResultEvent`` also clears the card."""+ projection = await self._seed_then(+ ExternalExecutionResultEvent.model_construct(+ reply_id="r1",+ execution_results=[],+ ),+ )+ card = projection.store[(_LEADER_SID, SubagentHitlProjector.KIND)]+ self.assertNotIn(_entry_id(), card)+ self.assertEqual(+ projection.published[0][1],+ SubagentHitlProjector.EVT_RESULT,+ )++ async def test_reply_end_clears_card(self) -> None:+ """``ReplyEndEvent`` is the primary clear signal (the resume's+ continuation events are not republished through the stream)."""+ projection = await self._seed_then(+ ReplyEndEvent.model_construct(reply_id="r1"),+ )+ card = projection.store[(_LEADER_SID, SubagentHitlProjector.KIND)]+ self.assertNotIn(_entry_id(), card)+ self.assertEqual(+ projection.published[0][1],+ SubagentHitlProjector.EVT_RESULT,+ )+++class TestSubagentHitlProjectorNoOp(IsolatedAsyncioTestCase):+ """Cases where nothing should be projected."""++ async def _assert_noop(+ self,+ *,+ agent_source: str = "team",+ team_id: str | None = _TEAM_ID,+ team: TeamRecord | None = None,+ session_id: str = _WORKER_SID,+ ) -> None:+ projection = _FakeProjection()+ projector = SubagentHitlProjector(+ _FakeStorage(team if team is not None else _team()),+ )+ await projector.maybe_project(+ "u",+ _session(session_id, team_id=team_id),+ _agent(source=agent_source),+ RequireUserConfirmEvent.model_construct(+ reply_id="r1",+ tool_calls=[],+ ),+ projection,+ )+ self.assertEqual(projection.store, {})+ self.assertEqual(projection.published, [])++ async def test_non_team_agent_is_noop(self) -> None:+ """A ``source="user"`` agent never projects."""+ await self._assert_noop(agent_source="user")++ async def test_session_without_team_id_is_noop(self) -> None:+ """A session with no ``team_id`` never projects."""+ await self._assert_noop(team_id=None)++ async def test_leader_session_is_noop(self) -> None:+ """The leader's own HITL reaches its client directly — no+ self-projection."""+ await self._assert_noop(session_id=_LEADER_SID)++ async def test_unrelated_event_is_noop(self) -> None:+ """Events outside the HITL set are ignored."""+ projection = _FakeProjection()+ await _projector().maybe_project(+ "u",+ _session(_WORKER_SID),+ _agent(),+ ReplyEndEvent.model_construct(reply_id="r1"),+ projection,+ )+ # ReplyEnd with no seeded card: delete is a no-op, but it DOES+ # publish a (harmless, idempotent) clear. Assert no card written.+ self.assertEqual(projection.store, {})+++class TestSubagentHitlProjectorResolve(IsolatedAsyncioTestCase):+ """The router-side ``resolve`` helper."""++ async def test_resolve_finds_and_misses(self) -> None:+ """``resolve`` returns the worker entry for a known reply_id and+ ``None`` for an unknown one."""+ projection = _FakeProjection()+ await _projector().maybe_project(+ "u",+ _session(_WORKER_SID),+ _agent(),+ RequireUserConfirmEvent.model_construct(+ reply_id="r1",+ tool_calls=[],+ ),+ projection,+ )++ hit = await SubagentHitlProjector.resolve(+ projection,+ _LEADER_SID,+ "r1",+ )+ self.assertIsNotNone(hit)+ self.assertEqual(hit["worker_session_id"], _WORKER_SID)++ miss = await SubagentHitlProjector.resolve(+ projection,+ _LEADER_SID,+ "nope",+ )+ self.assertIsNone(miss)diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pyindex 093e0582f..86b460684 100644--- a/tests/service_team_tools_test.py+++ b/tests/service_team_tools_test.py@@ -22,7 +22,7 @@ import fakeredis.aioredisfrom utils import AnyStringfrom agentscope.agent import ContextConfig, ReActConfig-from agentscope.app._tools import (+from agentscope.app._tool import (AgentCreate,DEFAULT_SUB_AGENT_TEMPLATE,TeamCreate,diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.pyindex 05c8eb993..66291af72 100644--- a/tests/service_wakeup_dispatcher_test.py+++ b/tests/service_wakeup_dispatcher_test.py@@ -221,10 +221,10 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):chat_run_registry=ChatRunRegistry(),):await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u", "session_id": "s1", "agent_id": "a1"},)- await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await bus.publish(MessageBusKeys.wakeup_signal(), {})await asyncio.wait_for(chat.notify.wait(), timeout=2.0)@@ -246,7 +246,7 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):bus = _FakeBus()chat = _FakeChatService()await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u", "session_id": "pre", "agent_id": "a"},)@@ -284,10 +284,10 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):chat_run_registry=ChatRunRegistry(),):await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u", "session_id": "busy", "agent_id": "a"},)- await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await bus.publish(MessageBusKeys.wakeup_signal(), {})await asyncio.sleep(0.05)self.assertEqual(chat.calls, [])@@ -305,14 +305,14 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):chat_run_registry=ChatRunRegistry(),):await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"oops": True},)await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u", "session_id": "s2", "agent_id": "a"},)- await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await bus.publish(MessageBusKeys.wakeup_signal(), {})await asyncio.wait_for(chat.notify.wait(), timeout=2.0)# Only the valid entry made it through.@@ -344,14 +344,14 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):chat_run_registry=ChatRunRegistry(),):await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u", "session_id": "ghost", "agent_id": "a"},)await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u", "session_id": "live", "agent_id": "a"},)- await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await bus.publish(MessageBusKeys.wakeup_signal(), {})await asyncio.wait_for(chat.notify.wait(), timeout=2.0)self.assertEqual(@@ -385,7 +385,7 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):chat_run_registry=ChatRunRegistry(),):await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u","session_id": "w1",@@ -394,7 +394,7 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):"input": event.model_dump(mode="json"),},)- await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await bus.publish(MessageBusKeys.wakeup_signal(), {})await asyncio.wait_for(chat.notify.wait(), timeout=2.0)self.assertEqual(len(chat.calls), 1)@@ -426,7 +426,7 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):chat_run_registry=ChatRunRegistry(),):await bus.queue_push(- MessageBus._WAKEUP_QUEUE_KEY,+ MessageBusKeys.wakeup_queue(),{"user_id": "u","session_id": "w1",@@ -435,7 +435,7 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):"input": event.model_dump(mode="json"),},)- await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await bus.publish(MessageBusKeys.wakeup_signal(), {})# While locked, the resume must keep deferring — no run yet.await asyncio.sleep(0.25)diff --git a/tests/tool_offload_middleware_test.py b/tests/tool_offload_middleware_test.pyindex f03d75354..6b82bb572 100644--- a/tests/tool_offload_middleware_test.py+++ b/tests/tool_offload_middleware_test.py@@ -13,7 +13,7 @@ from pydantic import BaseModelfrom utils import AnyString, MockModelfrom agentscope.agent import Agent-from agentscope.app.message_bus import MessageBus+from agentscope.app.message_bus import MessageBus, MessageBusKeysfrom agentscope.app.middleware import ToolOffloadMiddlewarefrom agentscope.app._manager import BackgroundTaskManagerfrom agentscope.message import TextBlock, ToolCallBlock@@ -291,8 +291,16 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):# The completed result should now have been pushed to the message bus# inbox as a model-dumped HintBlock.mock_bus = middleware._message_bus- mock_bus.inbox_push.assert_called_once()- session_id_called, hint_dict = mock_bus.inbox_push.call_args.args+ # The middleware uses queue_push(inbox_key, payload) rather+ # than the deprecated inbox_push(session_id, payload).+ inbox_calls = [+ c+ for c in mock_bus.queue_push.call_args_list+ if c.args[0] == MessageBusKeys.inbox(agent.state.session_id)+ ]+ self.assertEqual(len(inbox_calls), 1)+ _, hint_dict = inbox_calls[0].args+ session_id_called = agent.state.session_idself.assertEqual(session_id_called, agent.state.session_id)self.maxDiff = Noneself.assertDictEqual(@@ -341,11 +349,18 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):# enqueue_wakeup must be called exactly once with the correct ids so# WakeupDispatcher can re-invoke ChatService.run for this session.mock_bus = middleware._message_bus- mock_bus.enqueue_wakeup.assert_called_once_with(- user_id="u",- session_id=agent.state.session_id,- agent_id="a",- )+ # enqueue_run_trigger is a standalone function that calls+ # bus.queue_push + bus.publish under the hood.+ wakeup_calls = [+ c+ for c in mock_bus.queue_push.call_args_list+ if c.args[0] == MessageBusKeys.wakeup_queue()+ ]+ self.assertEqual(len(wakeup_calls), 1)+ payload = wakeup_calls[0].args[1]+ self.assertEqual(payload["user_id"], "u")+ self.assertEqual(payload["session_id"], agent.state.session_id)+ self.assertEqual(payload["agent_id"], "a")async def test_tool_stop_cancels_background_task(self) -> None:"""ToolStop tool cancels the running background asyncio task."""