Skip to content

Build and run agents you can see, understand and trust.

feat(agent-team): add loop middleware for subagent in teams (#2379)

DavdGaoe0e43cad9d1a
diff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.py
index 519f28bed..8165a385c 100644
--- a/src/agentscope/agent/_config.py
+++ b/src/agentscope/agent/_config.py
@@ -299,7 +299,7 @@ class ReActConfig(BaseModel):
max_iters: int = Field(
title="Max Iterations",
- default=20,
+ default=50,
description="The maximum number of reasoning-acting iterations in "
"one reply",
)
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index c2e222ec7..a4b2b8dd4 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -51,7 +51,7 @@ from ..storage import (
)
from ...message import ToolCallState
from ...state import ToolContext
-from ..storage._utils import _ensure_team_members
+from ..storage._utils import _ensure_team_members, _resolve_team_leader
from ...event import CustomEvent
from ..workspace_manager import WorkspaceManagerBase
@@ -79,19 +79,14 @@ async def _build_team_detail(
member paired with its session id when available).
"""
leader_agent: AgentView | None = None
- leader_session = await storage.get_session(user_id, "", team.session_id)
- if leader_session is not None:
- leader_record = await storage.get_agent(
- user_id,
- leader_session.agent_id,
+ leader = await _resolve_team_leader(storage, user_id, team)
+ if leader is not None:
+ leader_agent = AgentView.model_validate(
+ {
+ **leader.agent.model_dump(),
+ "editable": leader.agent.user_id == user_id,
+ },
)
- if leader_record is not None:
- leader_agent = AgentView.model_validate(
- {
- **leader_record.model_dump(),
- "editable": leader_record.user_id == user_id,
- },
- )
members: list[TeamMemberView] = []
for member in await _ensure_team_members(storage, user_id, team):
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index 739b40f03..310fb2322 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
"""
import asyncio
import inspect
-from typing import TYPE_CHECKING
+from dataclasses import dataclass
+from typing import Literal, TYPE_CHECKING
from fastapi import HTTPException
@@ -29,12 +30,14 @@ from ..message_bus import MessageBus, MessageBusKeys
from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
from ..channel import ChatKind
from ..storage import StorageBase, AgentRecord, SessionRecord, SessionSource
+from ..storage._utils import _resolve_team_leader
from .._manager import BackgroundTaskManager, SchedulerManager
from ..workspace_manager import WorkspaceManagerBase
from ..middleware import (
InboxMiddleware,
StateChangeMiddleware,
ToolOffloadMiddleware,
+ TeamMemberLoopMiddleware,
)
from ...middleware import TTSMiddleware, RAGMiddleware
from ...rag import KnowledgeBase
@@ -71,6 +74,24 @@ if TYPE_CHECKING:
from ..channel import ChannelLifecycleDispatcher
+@dataclass(frozen=True)
+class _LeaderContext:
+ """This session leads its team."""
+
+ role: Literal["leader"] = "leader"
+
+
+@dataclass(frozen=True)
+class _WorkerContext:
+ """This session is a worker; its leader is fully resolved."""
+
+ leader_name: str
+ role: Literal["worker"] = "worker"
+
+
+_TeamContext = _LeaderContext | _WorkerContext
+
+
class ChatService:
"""Run an agent against a session, persisting input/reply messages
and updated agent state.
@@ -165,7 +186,7 @@ class ChatService:
channel_dispatcher (`ChannelLifecycleDispatcher | None`, \
optional):
The node's channel dispatcher, forwarded to
- :func:`get_toolkit` so a channel-originated session's
+ the run context so a channel-originated session's
agent gets that channel's platform tools.
"""
self._storage = storage
@@ -586,6 +607,60 @@ optional):
source="session",
)
+ # -------------------------------------------------------------
+ # 1b. Resolve team identity + channel binding ONCE; all
+ # downstream consumers reuse these instead of re-fetching.
+ # -------------------------------------------------------------
+ team_ctx: _TeamContext | None = None
+ if session_record.team_id is not None:
+ team = await self._storage.get_team(
+ user_id,
+ session_record.team_id,
+ )
+ if team is None:
+ # Dissolved concurrently, or a stale team_id:
+ # nothing to be a member of, so run teamless.
+ logger.warning(
+ "Session %r points at team %r which no longer "
+ "exists; running teamless.",
+ session_id,
+ session_record.team_id,
+ )
+ elif team.session_id == session_record.id:
+ team_ctx = _LeaderContext()
+ else:
+ leader = await _resolve_team_leader(
+ self._storage,
+ user_id,
+ team,
+ )
+ if leader is None:
+ # Unreachable while the data is consistent:
+ # deleting a leader dissolves the team.
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"Team {team.id!r} has no resolvable "
+ f"leader; worker session "
+ f"{session_id!r} cannot run."
+ ),
+ )
+ team_ctx = _WorkerContext(leader_name=leader.name)
+
+ channel = (
+ self._channel_dispatcher.get_local_channel(
+ session_record.source_channel_id,
+ )
+ if session_record.source_channel_id
+ and self._channel_dispatcher is not None
+ else None
+ )
+ channel_tools = (
+ await channel.list_tools(workspace)
+ if channel is not None
+ else []
+ )
+
# -------------------------------------------------------------
# 2. Middlewares — framework-supplied first, then caller
# extras. Background-tool completions deliver their results
@@ -606,6 +681,14 @@ optional):
agent_id=agent_id,
),
]
+ # Equip the member middleware for loop control
+ if isinstance(team_ctx, _WorkerContext):
+ middlewares.append(
+ TeamMemberLoopMiddleware(
+ leader_name=team_ctx.leader_name,
+ ),
+ )
+
if self._extra_agent_middlewares is not None:
factory_args: tuple = (user_id, agent_id, session_id)
if self._middlewares_take_workspace:
@@ -701,7 +784,8 @@ optional):
resource_access_service=self._access,
extra_factory=self._extra_agent_tools,
sub_agent_templates=self._sub_agent_templates,
- channel_dispatcher=self._channel_dispatcher,
+ team_role=team_ctx.role if team_ctx else None,
+ channel_tools=channel_tools,
)
# -------------------------------------------------------------
@@ -731,44 +815,35 @@ optional):
attachment = f"You're within a session (id={session_id})."
# Channel-bound sessions: tell the agent which chat it serves.
- if (
- session_record.source_channel_id
- and self._channel_dispatcher is not None
- ):
- channel = self._channel_dispatcher.get_local_channel(
- session_record.source_channel_id,
+ if channel is not None:
+ tools = ", ".join(t.name for t in channel_tools)
+ chat_id = session_record.source_chat_id or ""
+ kind = await channel.chat_kind(chat_id)
+ name = await channel.chat_name(chat_id)
+ where = f' named "{name}"' if name else ""
+ attachment += (
+ f" This session is bound to a chat{where} on the "
+ f"{channel.display_name} platform: the messages, "
+ f"images and files people send there are relayed "
+ f"to you here, and your replies are delivered "
+ f"back to that same chat."
)
- if channel is not None:
- tools = ", ".join(
- t.name for t in await channel.list_tools(workspace)
+ if kind is ChatKind.GROUP:
+ attachment += (
+ " It is a group chat, so messages may come "
+ "from several different people; each incoming "
+ "user turn is labelled with its sender."
)
- chat_id = session_record.source_chat_id or ""
- kind = await channel.chat_kind(chat_id)
- name = await channel.chat_name(chat_id)
- where = f' named "{name}"' if name else ""
+ elif kind is ChatKind.PRIVATE:
attachment += (
- f" This session is bound to a chat{where} on the "
- f"{channel.display_name} platform: the messages, "
- f"images and files people send there are relayed "
- f"to you here, and your replies are delivered "
- f"back to that same chat."
+ " It is a one-to-one private chat with a "
+ "single user."
+ )
+ if tools:
+ attachment += (
+ f" You also have these {channel.display_name} "
+ f"tools available: {tools}."
)
- if kind is ChatKind.GROUP:
- attachment += (
- " It is a group chat, so messages may come "
- "from several different people; each incoming "
- "user turn is labelled with its sender."
- )
- elif kind is ChatKind.PRIVATE:
- attachment += (
- " It is a one-to-one private chat with a "
- "single user."
- )
- if tools:
- attachment += (
- f" You also have these {channel.display_name} "
- f"tools available: {tools}."
- )
attachment = (
f"<system-notification>{attachment}</system-notification>"
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index 7da740f09..5281e1bae 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -6,7 +6,7 @@ workspace builtins, MCPs, skills, planning tools (Task*), background-task
control (ToolStop), schedule control (Schedule*), team participation
tools, and caller-supplied extras — into one :class:`Toolkit`.
"""
-from typing import Any, Literal, TYPE_CHECKING
+from typing import Any, Literal
from .._manager import BackgroundTaskManager, SchedulerManager
from ..message_bus import MessageBus
@@ -26,6 +26,7 @@ from ...tool import (
TaskGet,
TaskList,
TaskUpdate,
+ ToolBase,
Toolkit,
ToolGroup,
)
@@ -33,9 +34,6 @@ from ...workspace import WorkspaceBase
from ..access import ResourceKind
from ._access import ResourceAccessService
-if TYPE_CHECKING:
- from ..channel import ChannelLifecycleDispatcher
-
async def get_toolkit(
*,
@@ -52,7 +50,8 @@ async def get_toolkit(
resource_access_service: ResourceAccessService,
extra_factory: AgentToolFactory | None = None,
sub_agent_templates: dict[str, SubAgentTemplate] | None = None,
- channel_dispatcher: "ChannelLifecycleDispatcher | None" = None,
+ team_role: Literal["leader", "worker"] | None = None,
+ channel_tools: list[ToolBase] | None = None,
) -> Toolkit:
"""Assemble the complete :class:`Toolkit` for one chat turn.
@@ -68,19 +67,11 @@ async def get_toolkit(
:meth:`SchedulerManager.list_tools`). Only attached when the
session has a model configured (Schedule tools need a model to
fire new chats with).
- 5. Team tools — variant based on the *session's* team role, not
- the agent's ``source``. This matters because a borrowed
- ("invited") agent's session must see worker-only tools even
- though its underlying :class:`AgentRecord` still has
- ``source='user'``. A session that is a worker in some team
- gets only ``TeamSay``. A session that is not in any team OR
- that is its team's leader gets the full leader-side toolset
- (``TeamCreate / AgentCreate / TeamSay / TeamDelete``, plus
- ``AgentInvite`` when the user has at least one invitable agent).
+ 5. Team tools — by caller-resolved ``team_role``: a worker gets only
+ ``TeamSay``; anyone else gets the full leader-side toolset.
6. Caller-supplied extras (``extra_factory``)
- 7. Channel platform tools — only for a session that originated from
- a channel; the channel exposes them via
- :meth:`ChannelBase.list_tools` (e.g. send a file to another user).
+ 7. Channel platform tools — the caller resolves them (once, shared
+ with the system-prompt attachment) and passes ``channel_tools``.
Plus the workspace's skills and MCPs, which become the toolkit's
``skills_or_loaders`` and ``mcps`` parameters.
@@ -113,13 +104,10 @@ async def get_toolkit(
Pre-loaded agent record (loaded once by the caller). Still
used for its identity (``id``) and for pipeline consumers
downstream; the ``source`` field is no longer the team-tool
- gate — see :attr:`session_record.team_id` below.
+ gate — see ``team_role`` below.
session_record (`SessionRecord`):
Pre-loaded session record (loaded once by the caller).
- Used for the schedule-tool model configuration and — via
- :attr:`SessionRecord.team_id` and the resolved team's
- leader session id — for deciding which team tools to
- attach.
+ Used for the schedule-tool model configuration.
extra_factory (`AgentToolFactory | None`, optional):
Async factory invoked once per assembly to produce
user/session-specific extra tools.
@@ -129,10 +117,12 @@ optional):
Passed to the ``AgentCreate`` tool so it can route to
the appropriate template when a ``subagent_type`` is
specified by the leader agent.
- channel_dispatcher (`ChannelLifecycleDispatcher | None`, optional):
- The node's channel dispatcher. When the session came from a
- channel, its local channel is resolved through this to attach
- that channel's platform tools. ``None`` disables them.
+ team_role (`Literal["leader", "worker"] | None`, optional):
+ The session's team role, resolved once by the caller.
+ ``None`` means not in any team.
+ channel_tools (`list[ToolBase] | None`, optional):
+ Platform tools of the originating channel, resolved once
+ by the caller. ``None`` / empty when channel-less.
Returns:
`Toolkit`: Fully populated toolkit (tools + skills + MCPs).
@@ -178,14 +168,8 @@ time or interval"
),
)
- # Team tools — variant based on the session's team role rather
- # than the agent's ``source`` field. A borrowed ("invited") agent
- # runs with ``source='user'`` on its underlying AgentRecord but
- # its session must behave as a worker; the session-level check
- # captures both created and invited workers uniformly. Sessions
- # not in a team fall through to the leader-side toolset — each
- # leader tool has a runtime precondition check anyway (am I in a
- # team? am I the leader?), so attaching the full set is safe.
+ # Team tools by caller-resolved role; non-team sessions get the
+ # leader set (each leader tool rechecks its precondition at call time).
team_tool_kwargs: dict[str, Any] = {
"storage": storage,
"message_bus": message_bus,
@@ -194,13 +178,6 @@ time or interval"
"session_id": session_record.id,
"agent_id": agent_record.id,
}
- team_role: Literal["leader", "worker"] | None = None
- if session_record.team_id is not None:
- team = await storage.get_team(user_id, session_record.team_id)
- if team is not None:
- team_role = (
- "leader" if team.session_id == session_record.id else "worker"
- )
if team_role == "worker":
tools.append(TeamSay(**team_tool_kwargs, role="worker"))
else:
@@ -254,16 +231,10 @@ time or interval"
for mw in middlewares:
tools.extend(await mw.list_tools())
- # Channel platform tools — when this session originated from a
- # channel, ask that channel (resolved locally; every node runs every
- # channel) for the tools it lets the agent call, e.g. send a file to
- # another user. Mirrors ``workspace.list_tools`` / ``mw.list_tools``.
- if session_record.source_channel_id and channel_dispatcher is not None:
- channel = channel_dispatcher.get_local_channel(
- session_record.source_channel_id,
- )
- if channel is not None:
- tools += await channel.list_tools(workspace)
+ # Channel platform tools, resolved once by the caller (also feeds
+ # the channel section of the system prompt).
+ if channel_tools:
+ tools += channel_tools
return Toolkit(
tools=tools,
diff --git a/src/agentscope/app/_tool/__init__.py b/src/agentscope/app/_tool/__init__.py
index 1585fd3d9..6f87b1f0a 100644
--- a/src/agentscope/app/_tool/__init__.py
+++ b/src/agentscope/app/_tool/__init__.py
@@ -5,11 +5,11 @@ 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.
+ :class:`StorageBase` + :class:`MessageBus` +
+ :class:`WorkspaceManagerBase` 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`.
2. **Visibility depends on the session's team role, not the agent's
source field** — a session that is not in any team OR that is its
team's leader gets the full leader-side toolset (``TeamCreate /
@@ -27,8 +27,9 @@ Task series, …) in two ways:
refresh point because the toolkit never changed; only the
underlying storage state did, which the next tool reads fresh.
-Selection of the right subset happens inline in :func:`get_toolkit`;
-there is no separate "team tool factory" helper.
+Which subset is attached is decided by the caller-resolved team role
+that :func:`get_toolkit` receives; there is no separate "team tool
+factory" helper.
"""
from ._agent_create import AgentCreate, DEFAULT_SUB_AGENT_TEMPLATE
from ._agent_invite import AgentInvite
diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.py
index d4130154e..98f83edab 100644
--- a/src/agentscope/app/_tool/_agent_create.py
+++ b/src/agentscope/app/_tool/_agent_create.py
@@ -12,7 +12,7 @@ from ._team_tool_base import _TeamToolBase
from .._types import SubAgentTemplate
from .._bus_ops import deliver_to_inbox
from ..storage import AgentData, AgentRecord, SessionConfig, TeamMember
-from ..storage._utils import _ensure_team_members
+from ..storage._utils import _ensure_team_members, _resolve_team_leader
from ...message import HintBlock, TextBlock, ToolResultState
from ...permission import PermissionContext
from ...state import AgentState
@@ -184,12 +184,10 @@ overall communication topology unnecessarily complex.
agent_id: str,
sub_agent_templates: dict[str, SubAgentTemplate] | None = None,
) -> None:
- """Bind request-scoped identifiers plus sub-agent templates.
+ """Bind the base dependencies plus the sub-agent templates.
- Extends :meth:`_TeamToolBase.__init__` with the optional
- template registry. The built-in ``"default"`` template is
- always injected; extra templates unlock a ``subagent_type``
- enum in the tool's input schema.
+ The built-in ``"default"`` template is always injected; extra
+ templates unlock a ``subagent_type`` enum in the input schema.
Args:
storage (`StorageBase`):
@@ -197,8 +195,8 @@ overall communication topology unnecessarily complex.
message_bus (`MessageBus`):
Application message bus.
workspace_manager (`WorkspaceManagerBase`):
- Workspace manager (forwarded to base for uniform
- team-tool wiring; currently unused here).
+ Forwarded to the base for uniform team-tool wiring;
+ unused here — a worker inherits the leader's workspace.
user_id (`str`):
The owner user id.
session_id (`str`):
@@ -291,52 +289,7 @@ optional):
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,
- )
+ team = await self._require_leader_team("add members")
# Look up leader session for chat-model inheritance + name.
leader_session = await self._storage.get_session(
@@ -398,13 +351,15 @@ optional):
state=ToolResultState.ERROR,
)
- leader_agent_record = await self._storage.get_agent(
+ leader = await _resolve_team_leader(
+ self._storage,
self._user_id,
- leader_session.agent_id,
+ team,
)
- existing_names: set[str] = set()
- if leader_agent_record is not None:
- existing_names.add(leader_agent_record.data.name)
+ # Fall back to the id so a missing leader agent record does
+ # not block member creation.
+ leader_name = leader.name if leader else leader_session.agent_id
+ existing_names: set[str] = {leader_name}
members = await _ensure_team_members(
self._storage,
self._user_id,
@@ -433,14 +388,6 @@ optional):
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(
diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.py
index b6420dfb0..187242873 100644
--- a/src/agentscope/app/_tool/_agent_invite.py
+++ b/src/agentscope/app/_tool/_agent_invite.py
@@ -26,7 +26,7 @@ from ._constants import HANDLE_LEN
from ._team_tool_base import _TeamToolBase
from .._bus_ops import deliver_to_inbox
from ..storage import SessionConfig, TeamMember
-from ..storage._utils import _ensure_team_members
+from ..storage._utils import _ensure_team_members, _resolve_team_leader
from ...message import HintBlock, TextBlock, ToolResultState
from ...state import AgentState
from ...tool import ToolChunk, ParamsBase
@@ -169,7 +169,7 @@ class AgentInvite(_TeamToolBase):
agent_id: str,
invitable_pool: list["AgentRecord"],
) -> None:
- """Bind request-scoped identifiers plus the invitable pool snapshot.
+ """Bind the base dependencies plus the invitable pool snapshot.
Args:
storage (`StorageBase`):
@@ -177,8 +177,8 @@ class AgentInvite(_TeamToolBase):
message_bus (`MessageBus`):
Application message bus.
workspace_manager (`WorkspaceManagerBase`):
- Used to mint the workspace id for freshly-invited
- agents (see :meth:`__call__`).
+ Assigns the borrowed session's workspace id when the
+ invited agent has no session of its own yet.
user_id (`str`):
The owner user id.
session_id (`str`):
@@ -264,30 +264,7 @@ class AgentInvite(_TeamToolBase):
return _error(resolve_err)
assert invited is not None # narrows for mypy
- 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 _error(
- "AgentInvite: this session is not in any team — "
- "call TeamCreate first.",
- )
- team = await self._storage.get_team(
- self._user_id,
- session.team_id,
- )
- if team is None:
- return _error(
- f"AgentInvite: team {session.team_id} no longer "
- f"exists.",
- )
- if team.session_id != self._session_id:
- return _error(
- "AgentInvite: only the team leader can invite "
- "members; this session is a worker.",
- )
+ team = await self._require_leader_team("invite members")
# Re-fetch fresh — the snapshot could be stale if the user
# just toggled the invite off.
@@ -335,15 +312,14 @@ class AgentInvite(_TeamToolBase):
f"for team {team.id} is missing — team is in an "
f"inconsistent state.",
)
- leader_agent = await self._storage.get_agent(
+ leader = await _resolve_team_leader(
+ self._storage,
self._user_id,
- leader_session.agent_id,
- )
- leader_name = (
- leader_agent.data.name
- if leader_agent is not None
- else leader_session.agent_id
+ team,
)
+ # Fall back to the id so a missing leader agent record does
+ # not block the invite.
+ leader_name = leader.name if leader else leader_session.agent_id
# Prefer the invited agent's own primary session for
# workspace + chat-model reuse: it already has any MCP /
diff --git a/src/agentscope/app/_tool/_team_create.py b/src/agentscope/app/_tool/_team_create.py
index d2c2c4782..43e20a57f 100644
--- a/src/agentscope/app/_tool/_team_create.py
+++ b/src/agentscope/app/_tool/_team_create.py
@@ -114,6 +114,7 @@ one team at a time.
team = TeamRecord(
user_id=self._user_id,
session_id=self._session_id,
+ leader_agent_id=self._agent_id,
data=TeamData(
name=name,
description=description,
diff --git a/src/agentscope/app/_tool/_team_delete.py b/src/agentscope/app/_tool/_team_delete.py
index 8e957df93..046ec33c9 100644
--- a/src/agentscope/app/_tool/_team_delete.py
+++ b/src/agentscope/app/_tool/_team_delete.py
@@ -56,52 +56,7 @@ This is irreversible.
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,
- )
+ team = await self._require_leader_team("dissolve the team")
# Local import to avoid a circular dependency between
# ``_tools`` and ``_service`` at module load.
diff --git a/src/agentscope/app/_tool/_team_say.py b/src/agentscope/app/_tool/_team_say.py
index 7aeb00752..ad2affbe9 100644
--- a/src/agentscope/app/_tool/_team_say.py
+++ b/src/agentscope/app/_tool/_team_say.py
@@ -8,7 +8,7 @@ from pydantic import Field
from ._constants import HANDLE_LEN
from ._team_tool_base import _TeamToolBase
from .._bus_ops import deliver_to_inbox
-from ..storage._utils import _ensure_team_members
+from ..storage._utils import _ensure_team_members, _resolve_team_leader
from ...message import HintBlock, TextBlock, ToolResultState
from ...tool import ToolChunk, ParamsBase
@@ -147,60 +147,7 @@ class TeamSay(_TeamToolBase):
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,
- )
+ team = await self._require_team()
# Build a (name -> (session_id, agent_id)) directory. The
# leader is always in the directory under its plain agent
@@ -215,17 +162,25 @@ class TeamSay(_TeamToolBase):
# is preserved by the AgentCreate name check (which rejects
# ``@``) and by AgentInvite's one-borrow-per-agent-per-team
# rule.
- leader_agent = await self._storage.get_agent(
+ leader = await _resolve_team_leader(
+ self._storage,
self._user_id,
- leader_session.agent_id,
- )
- leader_name = (
- leader_agent.data.name
- if leader_agent is not None
- else leader_session.agent_id
+ team,
)
+ if leader is None:
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=(
+ f"TeamSay: leader records missing for "
+ f"team {team.id}."
+ ),
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ )
directory: dict[str, tuple[str, str]] = {
- leader_name: (leader_session.id, leader_session.agent_id),
+ leader.name: (leader.session_id, leader.agent.id),
}
members = await _ensure_team_members(
self._storage,
diff --git a/src/agentscope/app/_tool/_team_tool_base.py b/src/agentscope/app/_tool/_team_tool_base.py
index 04100bc04..6d5eedfb9 100644
--- a/src/agentscope/app/_tool/_team_tool_base.py
+++ b/src/agentscope/app/_tool/_team_tool_base.py
@@ -11,10 +11,14 @@ from ...tool import ToolBase
if TYPE_CHECKING:
from ..message_bus import MessageBus
- from ..storage import StorageBase
+ from ..storage import StorageBase, TeamRecord
from ..workspace_manager import WorkspaceManagerBase
+class _TeamToolError(Exception):
+ """A failed precondition, rendered by each tool's error wrapper."""
+
+
class _TeamToolBase(ToolBase):
"""Shared base for the team tools.
@@ -25,10 +29,10 @@ class _TeamToolBase(ToolBase):
its work directly via those 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.
+ Permissions: all team tools allow themselves unconditionally —
+ which tools get attached is already role-gated in
+ :func:`get_toolkit`, and the leader-side ones re-check their
+ precondition at call time via :meth:`_require_leader_team`.
"""
name: str
@@ -58,9 +62,9 @@ class _TeamToolBase(ToolBase):
message_bus (`MessageBus`):
Application message bus for inter-session delivery.
workspace_manager (`WorkspaceManagerBase`):
- Workspace manager, consulted by tools that provision
- brand-new sessions (e.g. ``AgentInvite``) to honour
- the deployment's isolation policy.
+ Workspace manager, used by ``AgentInvite`` to assign a
+ borrowed session's workspace and by ``TeamDelete`` to
+ drop each deleted session's workspace state.
user_id (`str`):
The owner user id of the calling agent.
session_id (`str`):
@@ -75,6 +79,58 @@ class _TeamToolBase(ToolBase):
self._session_id = session_id
self._agent_id = agent_id
+ async def _require_team(self) -> "TeamRecord":
+ """Return this session's team, read fresh at call time.
+
+ Read fresh rather than taken from assembly-time context: the
+ leader may have called ``TeamCreate`` earlier in this same
+ reply, so a cached view would be stale.
+
+ Returns:
+ `TeamRecord`: The team this session participates in.
+
+ Raises:
+ `_TeamToolError`: When the session is teamless or its team
+ record is gone.
+ """
+ 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:
+ raise _TeamToolError(
+ "this session is not in any team — call TeamCreate first.",
+ )
+ team = await self._storage.get_team(self._user_id, session.team_id)
+ if team is None:
+ raise _TeamToolError(f"team {session.team_id} no longer exists.")
+ return team
+
+ async def _require_leader_team(self, leader_only: str) -> "TeamRecord":
+ """Return the team this session **leads**.
+
+ Args:
+ leader_only (`str`):
+ What only the leader may do, e.g. ``"add members"`` —
+ spliced into the rejection so the LLM keeps a concrete
+ next step.
+
+ Returns:
+ `TeamRecord`: The team whose leader is this session.
+
+ Raises:
+ `_TeamToolError`: As :meth:`_require_team`, plus when this
+ session is a worker rather than the leader.
+ """
+ team = await self._require_team()
+ if team.session_id != self._session_id:
+ raise _TeamToolError(
+ f"only the team leader can {leader_only}; this session "
+ f"is a worker.",
+ )
+ return team
+
async def check_permissions(
self,
tool_input: dict[str, Any],
diff --git a/src/agentscope/app/middleware/__init__.py b/src/agentscope/app/middleware/__init__.py
index 640d8a8b7..77e4a05bf 100644
--- a/src/agentscope/app/middleware/__init__.py
+++ b/src/agentscope/app/middleware/__init__.py
@@ -4,6 +4,7 @@
from ._inbox_middleware import InboxMiddleware
from ._protocol import ProtocolMiddlewareBase, AGUIProtocolMiddleware
from ._state_change_middleware import StateChangeMiddleware
+from ._team_member_middleware import TeamMemberLoopMiddleware
from ._tool_offload_middleware import ToolOffloadMiddleware
@@ -13,4 +14,5 @@ __all__ = [
"AGUIProtocolMiddleware",
"StateChangeMiddleware",
"ToolOffloadMiddleware",
+ "TeamMemberLoopMiddleware",
]
diff --git a/src/agentscope/app/middleware/_team_member_middleware.py b/src/agentscope/app/middleware/_team_member_middleware.py
new file mode 100644
index 000000000..42d8ff9c9
--- /dev/null
+++ b/src/agentscope/app/middleware/_team_member_middleware.py
@@ -0,0 +1,220 @@
+# -*- coding: utf-8 -*-
+"""The team member middleware that should be equipped with the member agents
+within a team."""
+
+import json
+from typing import AsyncGenerator, Callable
+
+from ..._utils._common import _json_loads_with_repair
+from ...agent import Agent
+from ...event import HintBlockEvent, ReplyEndEvent
+from ...message import (
+ HintBlock,
+ ToolCallBlock,
+ ToolResultBlock,
+ ToolResultState,
+)
+from ...middleware import MiddlewareBase
+from ...types import ErrorInfo, ErrorType, ReplyFinishedReason
+
+
+class TeamMemberLoopMiddleware(MiddlewareBase):
+ """The team member loop engineering middleware, that requires:
+
+ 1. The member should end its reply by calling `TeamSay` tool to report to
+ the team leader.
+ 2. When exceeds the max iteration numbers, the agent is guided to send
+ team leader a message to ask for permission to continue the operation.
+
+ A member that keeps ending without reporting is nudged at most
+ ``max_nudges`` times; after that the reply is released as an
+ ``ERROR`` so it terminates and the failure travels the normal
+ error path instead of looping under the session lock forever.
+ """
+
+ def __init__(self, leader_name: str, max_nudges: int = 3) -> None:
+ """Initialize the middleware.
+
+ Args:
+ leader_name (`str`):
+ The name of the team leader, i.e. the only valid
+ ``TeamSay(to=...)`` target that counts as a report.
+ max_nudges (`int`, defaults to 3):
+ How many times one reply may be forced to continue
+ before it is failed instead.
+ """
+ super().__init__()
+ self._leader_name: str = leader_name
+ self._max_nudges: int = max_nudges
+
+ def _last_tool_call_reports_to_leader(self, agent: "Agent") -> bool:
+ """Whether this reply's final tool call successfully reports back.
+
+ Args:
+ agent (`Agent`):
+ The replying member agent, read for its context and
+ the id of the reply in flight.
+
+ Returns:
+ `bool`:
+ ``True`` when the reply's last tool call is a
+ ``TeamSay`` addressed to the leader (or broadcast) that
+ returned ``SUCCESS``.
+ """
+ for msg in reversed(agent.state.context):
+ if (
+ msg.id != agent.state.reply_id
+ or msg.role != "assistant"
+ or msg.name != agent.name
+ ):
+ continue
+
+ blocks = msg.get_content_blocks()
+ last_tool_call = next(
+ (
+ block
+ for block in reversed(blocks)
+ if isinstance(block, ToolCallBlock)
+ ),
+ None,
+ )
+ if last_tool_call is None:
+ continue
+
+ # The last tool action must be a successful TeamSay addressed to
+ # the leader or broadcast to the whole team. A later non-TeamSay
+ # tool therefore invalidates an earlier progress report.
+ if last_tool_call.name != "TeamSay":
+ return False
+ try:
+ kwargs = _json_loads_with_repair(last_tool_call.input)
+ except Exception: # pylint: disable=broad-except
+ # Unparsable arguments (e.g. a truncated stream) cannot
+ # have produced a successful report.
+ return False
+ if kwargs.get("to") not in [None, self._leader_name]:
+ return False
+
+ result = next(
+ (
+ block
+ for block in blocks
+ if isinstance(block, ToolResultBlock)
+ and block.id == last_tool_call.id
+ ),
+ None,
+ )
+ return (
+ result is not None and result.state == ToolResultState.SUCCESS
+ )
+
+ return False
+
+ async def on_reply(
+ self,
+ agent: "Agent",
+ input_kwargs: dict,
+ next_handler: Callable[..., AsyncGenerator],
+ ) -> AsyncGenerator:
+ """Discard normal `ReplyEndEvent`s until `TeamSay` reports success.
+
+ Args:
+ agent (`Agent`):
+ The replying member agent. Its context receives the
+ reminder hints, and its ``cur_iter`` is relaxed so a
+ nudged reply can still act.
+ input_kwargs (`dict`):
+ The reply arguments, forwarded to ``next_handler``
+ unchanged.
+ next_handler (`Callable[..., AsyncGenerator]`):
+ The rest of the middleware chain.
+
+ Yields:
+ `AgentEvent | Msg`:
+ Everything the inner reply produces, except a
+ ``ReplyEndEvent`` that arrives without a successful
+ report: that one is replaced by a reminder
+ ``HintBlockEvent`` (forcing another round) or, once the
+ nudge budget is spent, by an ``ERROR`` reply-end event.
+ """
+ nudges = 0
+
+ async for evt in next_handler(**input_kwargs):
+ if not isinstance(evt, ReplyEndEvent):
+ yield evt
+ continue
+
+ # For the ReplyEndEvent
+ if self._last_tool_call_reports_to_leader(agent):
+ # The report has been delivered successfully, so let the
+ # original reply-end event escape the middleware chain.
+ yield evt
+ continue
+
+ if evt.finished_reason not in (
+ ReplyFinishedReason.COMPLETED,
+ ReplyFinishedReason.EXCEED_MAX_ITERS,
+ ):
+ # Interrupted / already-failed endings cannot be continued
+ # by swallowing their ReplyEndEvent. Forward unchanged.
+ # TODO: When the subagent fails, the leader should be aware
+ # of that.
+ yield evt
+ continue
+
+ if nudges >= self._max_nudges:
+ # Out of patience: end the reply as an error so it stops
+ # holding the session, and let the error path report it.
+ yield ReplyEndEvent(
+ session_id=evt.session_id,
+ reply_id=evt.reply_id,
+ finished_reason=ReplyFinishedReason.ERROR,
+ error=ErrorInfo(
+ type=ErrorType.INTERNAL,
+ message=(
+ f"{agent.name} ended {nudges} replies in a row "
+ f"without reporting to {self._leader_name} via "
+ f"TeamSay; giving up on this turn."
+ ),
+ ),
+ )
+ continue
+
+ nudges += 1
+ if evt.finished_reason == ReplyFinishedReason.EXCEED_MAX_ITERS:
+ instruction = (
+ "<system-reminder>You have reached the maximum number "
+ f"of ReAct iterations ({agent.react_config.max_iters}). "
+ "Call `TeamSay` now to report to the leader and ask for "
+ "permission to continue.</system-reminder>"
+ )
+ else:
+ instruction = (
+ "<system-reminder>You MUST call the tool `TeamSay` "
+ "to report to the leader to finish your task."
+ "</system-reminder>"
+ )
+
+ # Free one iteration so the agent can actually make the
+ # TeamSay call. Both endings need this: a COMPLETED reply on
+ # the very last iteration would otherwise come straight back
+ # as EXCEED_MAX_ITERS with no reasoning in between, which the
+ # agent rejects as a swallow-without-progress loop.
+ agent.state.cur_iter = min(
+ agent.state.cur_iter,
+ agent.react_config.max_iters - 1,
+ )
+
+ hint_block = HintBlock(
+ hint=instruction,
+ source=json.dumps(
+ {"label": "System", "sublabel": "Reminder"},
+ ),
+ )
+ agent.state.append_context(agent.name, [hint_block])
+ yield HintBlockEvent(
+ reply_id=agent.state.reply_id,
+ block_id=hint_block.id,
+ source=hint_block.source,
+ hint=instruction,
+ )
diff --git a/src/agentscope/app/storage/_model/_team.py b/src/agentscope/app/storage/_model/_team.py
index 48fd32ba0..235c176b6 100644
--- a/src/agentscope/app/storage/_model/_team.py
+++ b/src/agentscope/app/storage/_model/_team.py
@@ -118,5 +118,11 @@ class TeamRecord(_RecordBase):
session_id: str
"""The leader session id — the session that called ``create_team``."""
+ leader_agent_id: str | None = None
+ """The leader session's agent id, denormalised so resolving the
+ leader's name skips the session read. ``None`` on records written
+ before this field; read it via ``_resolve_team_leader``, which
+ backfills."""
+
data: TeamData
"""The team data."""
diff --git a/src/agentscope/app/storage/_utils.py b/src/agentscope/app/storage/_utils.py
index 40bf22f63..385f738a7 100644
--- a/src/agentscope/app/storage/_utils.py
+++ b/src/agentscope/app/storage/_utils.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""The utils for storage."""
+from dataclasses import dataclass
from typing import TYPE_CHECKING
from pydantic import BaseModel, SecretStr
@@ -8,7 +9,7 @@ from ._model import TeamMember
if TYPE_CHECKING:
from ._base import StorageBase
- from ._model import TeamRecord
+ from ._model import AgentRecord, TeamRecord
def _dump_with_secrets(model: BaseModel) -> dict:
@@ -105,3 +106,63 @@ async def _ensure_team_members(
team.data.member_ids = [m.agent_id for m in migrated]
await storage.upsert_team(user_id, team)
return migrated
+
+
+@dataclass(frozen=True)
+class _TeamLeader:
+ """A team's leader: its session id plus its agent record."""
+
+ session_id: str
+ agent: "AgentRecord"
+
+ @property
+ def name(self) -> str:
+ """The leader's current display name.
+
+ Returns:
+ `str`: The leader agent's name, as read this call.
+ """
+ return self.agent.data.name
+
+
+async def _resolve_team_leader(
+ storage: "StorageBase",
+ user_id: str,
+ team: "TeamRecord",
+) -> "_TeamLeader | None":
+ """Resolve *team*'s leader.
+
+ The single read path for the leader's identity, shared by the team
+ tools, the chat run context and the session router. Teams created
+ with :attr:`TeamRecord.leader_agent_id` go straight to the agent
+ record; older ones pay one extra session read every time, which
+ beats writing to the team record on what are mostly read paths
+ (including a GET endpoint) for one saved lookup. The name is always
+ read fresh — an agent can be renamed at any time and ``TeamSay``
+ routes by name.
+
+ Args:
+ storage (`StorageBase`):
+ Storage backend for the lookups.
+ user_id (`str`):
+ The team owner (also the leader agent's owner).
+ team (`TeamRecord`):
+ The team whose leader to resolve.
+
+ Returns:
+ `_TeamLeader | None`:
+ The leader's session id and agent record, or ``None`` when
+ either is missing — an inconsistent state, since deleting a
+ leader session or agent dissolves the team.
+ """
+ agent_id = team.leader_agent_id
+ if agent_id is None:
+ session = await storage.get_session(user_id, "", team.session_id)
+ if session is None:
+ return None
+ agent_id = session.agent_id
+
+ agent = await storage.get_agent(user_id, agent_id)
+ if agent is None:
+ return None
+ return _TeamLeader(session_id=team.session_id, agent=agent)
diff --git a/tests/service_chat_run_context_test.py b/tests/service_chat_run_context_test.py
new file mode 100644
index 000000000..cc82b02ca
--- /dev/null
+++ b/tests/service_chat_run_context_test.py
@@ -0,0 +1,213 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access, using-constant-test
+"""ChatService resolves team/channel context once and fans it out."""
+
+from types import SimpleNamespace
+from typing import AsyncGenerator
+from unittest import IsolatedAsyncioTestCase
+from unittest.mock import patch
+
+from agentscope.agent import ContextConfig, ReActConfig
+from agentscope.app._service import ChatService
+from agentscope.app.message_bus import InMemoryMessageBus
+from agentscope.app.storage import (
+ AgentData,
+ AgentRecord,
+ ChatModelConfig,
+ SessionConfig,
+ SessionRecord,
+ TeamData,
+ TeamRecord,
+)
+
+
+class _Storage:
+ """Serve one worker session + its team/leader, counting team reads."""
+
+ def __init__(
+ self,
+ sessions: dict[str, SessionRecord],
+ agents: dict[str, AgentRecord],
+ team: TeamRecord,
+ ) -> None:
+ self.sessions = sessions
+ self.agents = agents
+ self.team = team
+ self.get_team_calls = 0
+
+ async def get_session(
+ self,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ ) -> SessionRecord | None:
+ """Return a detached copy; ``agent_id`` may be blank for leaders."""
+ del user_id, agent_id
+ record = self.sessions.get(session_id)
+ return record.model_copy(deep=True) if record else None
+
+ async def get_agent(
+ self,
+ user_id: str,
+ agent_id: str,
+ ) -> AgentRecord | None:
+ """Return a detached agent record."""
+ del user_id
+ record = self.agents.get(agent_id)
+ return record.model_copy(deep=True) if record else None
+
+ async def get_team(self, user_id: str, team_id: str) -> TeamRecord | None:
+ """Count every read — the run must need exactly one."""
+ del user_id
+ self.get_team_calls += 1
+ return self.team if team_id == self.team.id else None
+
+ async def update_session_state(self, *_: object, **__: object) -> None:
+ """Accept the post-run state persistence."""
+
+ async def upsert_message(self, *_: object, **__: object) -> None:
+ """Accept synthesized failure messages (none expected)."""
+
+
+class _WorkspaceManager:
+ """Return a minimal workspace handle."""
+
+ async def get_workspace(self, *_: object, **__: object) -> object:
+ """Return an inert workspace."""
+ return SimpleNamespace(workdir="/tmp/agentscope-run-ctx-test")
+
+
+class TestRunContextResolution(IsolatedAsyncioTestCase):
+ """Team identity is read once and shared by toolkit + middleware."""
+
+ async def test_worker_run_fetches_team_once(self) -> None:
+ """One ``get_team`` read serves both consumers of the role."""
+ user_id = "user-1"
+ worker_agent = AgentRecord(
+ id="agent-w",
+ user_id=user_id,
+ source="team",
+ data=AgentData(
+ name="worker",
+ context_config=ContextConfig(),
+ react_config=ReActConfig(),
+ ),
+ )
+ leader_agent = AgentRecord(
+ id="agent-l",
+ user_id=user_id,
+ data=AgentData(
+ name="Leader",
+ context_config=ContextConfig(),
+ react_config=ReActConfig(),
+ ),
+ )
+ config = SessionConfig(
+ workspace_id="ws-1",
+ chat_model_config=ChatModelConfig(
+ type="test",
+ credential_id="cred-1",
+ model="m",
+ parameters={},
+ ),
+ )
+ worker_session = SessionRecord(
+ id="session-w",
+ user_id=user_id,
+ agent_id=worker_agent.id,
+ team_id="team-1",
+ config=config,
+ )
+ leader_session = SessionRecord(
+ id="session-l",
+ user_id=user_id,
+ agent_id=leader_agent.id,
+ team_id="team-1",
+ config=config,
+ )
+ team = TeamRecord(
+ id="team-1",
+ user_id=user_id,
+ session_id=leader_session.id,
+ data=TeamData(name="team"),
+ )
+ storage = _Storage(
+ sessions={s.id: s for s in (worker_session, leader_session)},
+ agents={a.id: a for a in (worker_agent, leader_agent)},
+ team=team,
+ )
+ equipped: list[list] = []
+
+ class _Agent:
+ """Capture the middlewares; reply without doing anything."""
+
+ def __init__(self, *, middlewares: list, **_: object) -> None:
+ equipped.append(middlewares)
+
+ async def reply_stream(
+ self,
+ inputs: object,
+ ) -> AsyncGenerator[object, None]:
+ """Yield nothing."""
+ del inputs
+ if False:
+ yield object()
+
+ toolkit_kwargs: dict = {}
+
+ async def _get_toolkit(**kwargs: object) -> object:
+ toolkit_kwargs.update(kwargs)
+ return object()
+
+ async def _get_model(*_: object, **__: object) -> object:
+ return object()
+
+ class _Access:
+ """Resolve the one worker agent."""
+
+ async def resolve_agent(self, *_: object) -> AgentRecord:
+ """Return a detached copy."""
+ return worker_agent.model_copy(deep=True)
+
+ service = ChatService(
+ storage=storage,
+ workspace_manager=_WorkspaceManager(),
+ scheduler_manager=object(),
+ background_task_manager=object(),
+ message_bus=InMemoryMessageBus(),
+ resource_access_service=_Access(),
+ custom_agent_cls=_Agent,
+ )
+ with (
+ patch(
+ "agentscope.app._service._chat.get_toolkit",
+ new=_get_toolkit,
+ ),
+ patch("agentscope.app._service._chat.get_model", new=_get_model),
+ ):
+ await service._run_impl(
+ user_id,
+ worker_session.id,
+ worker_agent.id,
+ None,
+ )
+
+ self.assertDictEqual(
+ {
+ "get_team_calls": storage.get_team_calls,
+ "team_role": toolkit_kwargs["team_role"],
+ "channel_tools": toolkit_kwargs["channel_tools"],
+ "leader_names": [
+ mw._leader_name
+ for mws in equipped
+ for mw in mws
+ if hasattr(mw, "_leader_name")
+ ],
+ },
+ {
+ "get_team_calls": 1,
+ "team_role": "worker",
+ "channel_tools": [],
+ "leader_names": ["Leader"],
+ },
+ )
diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.py
index 025f18846..a6a156a87 100644
--- a/tests/service_team_tools_test.py
+++ b/tests/service_team_tools_test.py
@@ -1783,3 +1783,53 @@ class TestEnsureTeamMembersMigration(_TeamToolsTestBase):
# path.
stored = await self.storage.get_team(self.user_id, team.id)
self.assertEqual(len(stored.data.members), 1)
+
+
+class TestResolveTeamLeader(_TeamToolsTestBase):
+ """``_resolve_team_leader`` resolves the leader without writing."""
+
+ async def test_legacy_team_resolves_via_leader_session(self) -> None:
+ """A record without ``leader_agent_id`` still resolves, via the
+ leader session, and is left untouched on disk."""
+ from agentscope.app.storage._model import TeamData, TeamRecord
+ from agentscope.app.storage._utils import _resolve_team_leader
+
+ team = TeamRecord(
+ user_id=self.user_id,
+ session_id=self.leader_session.id,
+ data=TeamData(name="legacy", description="d"),
+ )
+ await self.storage.upsert_team(self.user_id, team)
+
+ leader = await _resolve_team_leader(self.storage, self.user_id, team)
+ persisted = await self.storage.get_team(self.user_id, team.id)
+ self.assertDictEqual(
+ {
+ "session_id": leader.session_id,
+ "agent_id": leader.agent.id,
+ "name": leader.name,
+ "persisted_leader_agent_id": persisted.leader_agent_id,
+ },
+ {
+ "session_id": self.leader_session.id,
+ "agent_id": self.leader_agent.id,
+ "name": self.leader_agent.data.name,
+ "persisted_leader_agent_id": None,
+ },
+ )
+
+ async def test_missing_leader_agent_resolves_to_none(self) -> None:
+ """A team pointing at a deleted leader agent yields ``None``."""
+ from agentscope.app.storage._model import TeamData, TeamRecord
+ from agentscope.app.storage._utils import _resolve_team_leader
+
+ team = TeamRecord(
+ user_id=self.user_id,
+ session_id=self.leader_session.id,
+ leader_agent_id="agent-gone",
+ data=TeamData(name="broken", description="d"),
+ )
+ await self.storage.upsert_team(self.user_id, team)
+ self.assertIsNone(
+ await _resolve_team_leader(self.storage, self.user_id, team),
+ )
diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.py
index 8275260f0..6d0f41e3d 100644
--- a/tests/service_toolkit_test.py
+++ b/tests/service_toolkit_test.py
@@ -33,8 +33,6 @@ from agentscope.app.storage import (
ChatModelConfig,
SessionConfig,
SessionRecord,
- TeamData,
- TeamRecord,
)
from agentscope.tool import ToolBase
@@ -133,31 +131,12 @@ class _NoOpStorage:
list — the toolkit tests care about which team tools are attached,
not about the pool contents; the non-empty case is covered by the
``AgentInvite`` tests in ``service_team_tools_test.py``.
- Additionally, when the session has a ``team_id`` set, ``get_toolkit``
- calls ``get_team`` to decide leader-vs-worker; the ``team_id_map``
- constructor arg lets a test inject a lookup so the worker branch
- can be exercised.
"""
- def __init__(
- self,
- team_id_map: dict[str, TeamRecord] | None = None,
- ) -> None:
- """Initialize the storage placeholder."""
- self._teams = team_id_map or {}
-
async def list_agents(self, _user_id: str) -> list:
"""List agents for a team."""
return []
- async def get_team(
- self,
- _user_id: str,
- team_id: str,
- ) -> TeamRecord | None:
- """Return the team record for ``team_id``."""
- return self._teams.get(team_id)
-
def _make_access(storage: Any) -> ResourceAccessService:
"""Build a :class:`ResourceAccessService` bound to ``storage`` with a
@@ -272,12 +251,8 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):
class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
- """A session whose team role is worker only gets ``TeamSay``.
-
- The worker/leader distinction is now session-level: a session with
- ``team_id`` set and ``team.session_id != session.id`` is a worker
- regardless of the agent record's ``source`` (an ``AgentInvite``
- borrowed session runs on ``source='user'`` but is still a worker)."""
+ """A session passed ``team_role="worker"`` only gets ``TeamSay``;
+ the role is resolved by the caller, not looked up here."""
async def test_worker_only_gets_team_say(self) -> None:
"""A worker session receives only ``TeamSay`` from the team
@@ -289,16 +264,8 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
with_model=True,
team_id="t1",
)
- # Team exists and its leader session is NOT this one → worker.
- team = TeamRecord(
- user_id="u",
- session_id="leader-sid",
- data=TeamData(name="team", description="d"),
- )
toolkit = await get_toolkit(
- storage=_NoOpStorage(
- team_id_map={"t1": team},
- ), # type: ignore[arg-type]
+ storage=_NoOpStorage(), # type: ignore[arg-type]
workspace=_FakeWorkspace(), # type: ignore[arg-type]
workspace_manager=FakeWorkspaceManager(),
scheduler_manager=SchedulerManager(
@@ -315,6 +282,7 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
extra_factory=None,
middlewares=[],
resource_access_service=_make_access(_NoOpStorage()),
+ team_role="worker",
)
names = set(_tool_names(toolkit))
# Only TeamSay from the team toolset.
diff --git a/tests/team_member_middleware_test.py b/tests/team_member_middleware_test.py
new file mode 100644
index 000000000..debf2d04a
--- /dev/null
+++ b/tests/team_member_middleware_test.py
@@ -0,0 +1,315 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Unit tests for :class:`TeamMemberLoopMiddleware`.
+
+The middleware is exercised against a real :class:`Agent` driven by a
+mock model and a stand-in ``TeamSay`` tool, so the reasoning-acting
+loop is genuine while nothing touches the app service layer.
+"""
+import itertools
+import json
+from typing import Any
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import MockModel
+
+from agentscope.agent import Agent, InjectionConfig, ReActConfig
+from agentscope.app.middleware import TeamMemberLoopMiddleware
+from agentscope.event import ReplyEndEvent
+from agentscope.message import TextBlock, ToolCallBlock, ToolResultState
+from agentscope.message import UserMsg
+from agentscope.model import ChatResponse
+from agentscope.permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+)
+from agentscope.tool import ToolBase, ToolChunk, Toolkit
+from agentscope.types import ReplyFinishedReason
+
+
+class _FakeTeamSay(ToolBase):
+ """Stand-in for the real ``TeamSay`` — records calls, never fails."""
+
+ name: str = "TeamSay"
+ description: str = "Report to the team leader."
+ input_schema: dict = {
+ "type": "object",
+ "properties": {
+ "to": {"type": "string"},
+ "content": {"type": "string"},
+ },
+ "required": ["content"],
+ }
+ is_concurrency_safe: bool = True
+ 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, state: ToolResultState = ToolResultState.SUCCESS):
+ super().__init__()
+ self.calls: list[dict] = []
+ self._state = state
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Always allow."""
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ message="allowed",
+ )
+
+ async def __call__(self, content: str, to: str | None = None) -> ToolChunk:
+ """Record the call and answer with the configured state."""
+ self.calls.append({"to": to, "content": content})
+ return ToolChunk(
+ content=[TextBlock(text="delivered")],
+ state=self._state,
+ )
+
+
+class _OtherTool(_FakeTeamSay):
+ """A non-``TeamSay`` tool, used to invalidate an earlier report."""
+
+ name: str = "Note"
+ description: str = "Write a note."
+
+ async def __call__(self, content: str, to: str | None = None) -> ToolChunk:
+ """Answer successfully without reporting anywhere."""
+ self.calls.append({"to": to, "content": content})
+ return ToolChunk(content=[TextBlock(text="noted")])
+
+
+def _text(text: str) -> ChatResponse:
+ """A plain text reply — ends the reasoning-acting loop."""
+ return ChatResponse(content=[TextBlock(text=text)], is_last=True)
+
+
+_CALL_SEQ = itertools.count()
+
+
+def _call(tool: str, **kwargs: Any) -> ChatResponse:
+ """A single tool call reply; ``input`` is the raw JSON string."""
+ return ChatResponse(
+ content=[
+ ToolCallBlock(
+ type="tool_call",
+ id=f"call-{tool}-{next(_CALL_SEQ)}",
+ name=tool,
+ input=json.dumps(kwargs),
+ ),
+ ],
+ is_last=True,
+ )
+
+
+class TeamMemberLoopMiddlewareTest(IsolatedAsyncioTestCase):
+ """The nudge / release / give-up decisions of the middleware."""
+
+ async def asyncSetUp(self) -> None:
+ """Build a worker agent wired to the middleware."""
+ self.model = MockModel()
+ self.team_say = _FakeTeamSay()
+ self.extra_tools: list = []
+
+ async def _run(
+ self,
+ responses: list,
+ *,
+ max_iters: int = 5,
+ max_nudges: int = 3,
+ extra_tools: list | None = None,
+ ) -> list:
+ """Drive one reply and return the streamed items."""
+ toolkit = Toolkit(tools=[self.team_say, *(extra_tools or [])])
+ self.model.set_responses(responses)
+ agent = Agent(
+ name="worker",
+ system_prompt="You are a worker.",
+ model=self.model,
+ toolkit=toolkit,
+ react_config=ReActConfig(max_iters=max_iters),
+ middlewares=[
+ TeamMemberLoopMiddleware(
+ leader_name="Leader",
+ max_nudges=max_nudges,
+ ),
+ ],
+ injection_config=InjectionConfig(inject_runtime_state=False),
+ )
+ items = []
+ async for item in agent.reply_stream(UserMsg("user", "do it")):
+ items.append(item)
+ return items
+
+ @staticmethod
+ def _end_events(items: list) -> list[ReplyEndEvent]:
+ """The reply-end events that escaped the middleware."""
+ return [_ for _ in items if isinstance(_, ReplyEndEvent)]
+
+ async def test_successful_report_passes_through(self) -> None:
+ """A final successful ``TeamSay`` to the leader ends the reply."""
+ items = await self._run(
+ [
+ _call("TeamSay", to="Leader", content="done"),
+ _text("reported"),
+ ],
+ )
+ ends = self._end_events(items)
+ self.assertDictEqual(
+ {
+ "model_calls": self.model.cnt,
+ "reasons": [_.finished_reason for _ in ends],
+ "team_say_calls": self.team_say.calls,
+ },
+ {
+ "model_calls": 2,
+ "reasons": [ReplyFinishedReason.COMPLETED],
+ "team_say_calls": [{"to": "Leader", "content": "done"}],
+ },
+ )
+
+ async def test_broadcast_report_passes_through(self) -> None:
+ """``TeamSay`` without ``to`` broadcasts and still counts."""
+ items = await self._run(
+ [_call("TeamSay", content="done"), _text("reported")],
+ )
+ self.assertListEqual(
+ [_.finished_reason for _ in self._end_events(items)],
+ [ReplyFinishedReason.COMPLETED],
+ )
+
+ async def test_report_to_other_member_is_not_accepted(self) -> None:
+ """A report addressed to another worker does not end the reply."""
+ items = await self._run(
+ [
+ _call("TeamSay", to="OtherWorker", content="fyi"),
+ _text("done"),
+ _call("TeamSay", to="Leader", content="done"),
+ _text("reported"),
+ ],
+ )
+ self.assertListEqual(
+ [_.finished_reason for _ in self._end_events(items)],
+ [ReplyFinishedReason.COMPLETED],
+ )
+ self.assertListEqual(
+ self.team_say.calls,
+ [
+ {"to": "OtherWorker", "content": "fyi"},
+ {"to": "Leader", "content": "done"},
+ ],
+ )
+
+ async def test_failed_report_is_not_accepted(self) -> None:
+ """A ``TeamSay`` that errored does not count as a report."""
+ self.team_say = _FakeTeamSay(state=ToolResultState.ERROR)
+ items = await self._run(
+ [
+ _call("TeamSay", to="Leader", content="done"),
+ _text("done"),
+ _text("still not reporting"),
+ _text("nor now"),
+ _text("nor now either"),
+ ],
+ max_nudges=2,
+ )
+ ends = self._end_events(items)
+ self.assertListEqual(
+ [_.finished_reason for _ in ends],
+ [ReplyFinishedReason.ERROR],
+ )
+
+ async def test_later_tool_invalidates_earlier_report(self) -> None:
+ """A non-``TeamSay`` call after the report re-opens the reply."""
+ note = _OtherTool()
+ items = await self._run(
+ [
+ _call("TeamSay", to="Leader", content="done"),
+ _call("Note", content="afterthought"),
+ _text("finished"),
+ _call("TeamSay", to="Leader", content="really done"),
+ _text("reported"),
+ ],
+ extra_tools=[note],
+ )
+ self.assertListEqual(
+ [_.finished_reason for _ in self._end_events(items)],
+ [ReplyFinishedReason.COMPLETED],
+ )
+ self.assertEqual(len(self.team_say.calls), 2)
+
+ async def test_silent_worker_is_failed_after_max_nudges(self) -> None:
+ """A worker that never reports fails instead of looping."""
+ items = await self._run(
+ [_text(f"turn {i}") for i in range(10)],
+ max_nudges=2,
+ )
+ ends = self._end_events(items)
+ self.assertDictEqual(
+ {
+ "reasons": [_.finished_reason for _ in ends],
+ "error_type": ends[-1].error.type if ends[-1].error else None,
+ "team_say_calls": self.team_say.calls,
+ # 1 initial reply + 2 nudged retries, then give up
+ "model_calls": self.model.cnt,
+ },
+ {
+ "reasons": [ReplyFinishedReason.ERROR],
+ "error_type": "internal",
+ "team_say_calls": [],
+ "model_calls": 3,
+ },
+ )
+
+ async def test_exceed_max_iters_is_nudged_then_failed(self) -> None:
+ """The EXCEED ending is nudged too, and also bounded."""
+ note = _OtherTool()
+ items = await self._run(
+ [_call("Note", content=f"n{i}") for i in range(10)],
+ max_iters=2,
+ max_nudges=1,
+ extra_tools=[note],
+ )
+ self.assertListEqual(
+ [_.finished_reason for _ in self._end_events(items)],
+ [ReplyFinishedReason.ERROR],
+ )
+
+ async def test_completed_on_the_last_iteration_does_not_raise(
+ self,
+ ) -> None:
+ """A COMPLETED ending exactly at ``max_iters`` must not trip the
+ agent's swallow-without-progress guard.
+
+ Without freeing an iteration the next decision would be
+ EXCEED_MAX_ITERS with no reasoning in between, and swallowing
+ that raises inside the agent.
+ """
+ items = await self._run(
+ [
+ _text("done early"),
+ _call("TeamSay", to="Leader", content="done"),
+ _text("reported"),
+ ],
+ max_iters=1,
+ )
+ self.assertDictEqual(
+ {
+ "reasons": [
+ _.finished_reason for _ in self._end_events(items)
+ ],
+ "team_say_calls": self.team_say.calls,
+ },
+ {
+ # The nudged round spends the freed iteration, so the
+ # released ending is the EXCEED one.
+ "reasons": [ReplyFinishedReason.EXCEED_MAX_ITERS],
+ "team_say_calls": [{"to": "Leader", "content": "done"}],
+ },
+ )