Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(pipeline): support leader-member delegation in a `TeamPipeline` class (#2764)
DavdGao2258f3f4f74c
diff --git a/src/agentscope/pipeline/__init__.py b/src/agentscope/pipeline/__init__.pyindex 0a8195ef2..818cbcda4 100644--- a/src/agentscope/pipeline/__init__.py+++ b/src/agentscope/pipeline/__init__.py@@ -3,8 +3,11 @@from ._base import PipelineProtocolfrom ._goal_pipeline import GoalPipeline+from ._team_pipeline import TeamMember, TeamPipeline__all__ = ["PipelineProtocol","GoalPipeline",+ "TeamMember",+ "TeamPipeline",]diff --git a/src/agentscope/pipeline/_team_pipeline.py b/src/agentscope/pipeline/_team_pipeline.pynew file mode 100644index 000000000..3f293a8f8--- /dev/null+++ b/src/agentscope/pipeline/_team_pipeline.py@@ -0,0 +1,403 @@+# -*- coding: utf-8 -*-+"""The team pipeline class."""+import asyncio+from asyncio import Queue+from typing import Any, AsyncGenerator++from pydantic import BaseModel, ConfigDict++from .._utils._common import _json_loads_with_repair+from ..agent import Agent+from ..event import (+ AgentEvent,+ ExternalExecutionResultEvent,+ ReplyEndEvent,+ RequireExternalExecutionEvent,+ UserConfirmResultEvent,+ UserInterruptEvent,+)+from ..message import (+ DataBlock,+ Msg,+ TextBlock,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+ UserMsg,+)+from ..permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from ..tool import ToolBase+from ..types import ReplyFinishedReason+++class TeamMember(BaseModel):+ """A member of the team: an existing agent plus the description the+ leader reads to decide when to assign a task to it."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ agent: Agent+ """The member agent. Its name is how the leader refers to it, so it+ must be unique within the team."""+ description: str+ """What the member is good at, when to assign to it and what it+ returns. Presented to the leader in the tool description."""+++class _TeamAssign(ToolBase):+ """The external tool the leader calls to assign a task to a member.+ The pipeline executes it by running the member, so it never runs by+ itself."""++ name: str = "TeamAssign"+ is_external_tool: bool = True+ is_concurrency_safe: bool = True+ is_read_only: bool = False++ def __init__(self, members: list[TeamMember]) -> None:+ """Build the tool from the members, listing them in the description+ and offering their names as the choices of ``member``."""+ super().__init__()+ self.description = (+ "Assign a task to a team member and get its reply back as the "+ "result. The members are:\n"+ + "\n".join(f"- {_.agent.name}: {_.description}" for _ in members)+ )+ self.input_schema = {+ "type": "object",+ "properties": {+ "member": {+ "type": "string",+ "enum": [_.agent.name for _ in members],+ "description": "The name of the member to assign to.",+ },+ "prompt": {+ "type": "string",+ "description": (+ "The complete task for the member. It cannot see "+ "your context, so include everything it needs."+ ),+ },+ },+ "required": ["member", "prompt"],+ }++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Assigning itself is always allowed; the member's own tools go+ through their own permission checks."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="Assigning a task to a team member is always allowed.",+ )+++_RESULT_STATES = {+ ReplyFinishedReason.COMPLETED: ToolResultState.SUCCESS,+ ReplyFinishedReason.EXCEED_MAX_ITERS: ToolResultState.SUCCESS,+ ReplyFinishedReason.INTERRUPTED: ToolResultState.INTERRUPTED,+ ReplyFinishedReason.ERROR: ToolResultState.ERROR,+}+++class TeamPipeline:+ """A leader agent that assigns tasks to team members through tool calls.++ The leader gets one external tool, ``TeamAssign``, that names a member+ and a task. When the leader calls it, the pipeline runs that member in+ its own context and feeds its final reply back as the tool result, so+ the leader only ever sees the summary, never the member's intermediate+ steps. Members assigned in the same round run concurrently, except that+ assignments to the same member run one after another in call order, a+ later one waiting until the earlier one finishes, even across a HITL+ pause. Members do not talk to each other; a member's result always+ returns to the leader.++ HITL works per participant: a member that needs user confirmation parks+ like any agent, its request is streamed out unchanged, and the result+ sent back to the pipeline is routed to it by ``reply_id``. Meanwhile+ the leader stays parked on the assignment and resumes once the member+ finishes.+ """++ def __init__(+ self,+ leader: Agent,+ members: list[TeamMember],+ reset_members: bool = True,+ ) -> None:+ """Initialize the team pipeline.++ Args:+ leader (`Agent`):+ The leader agent that assigns tasks.+ members (`list[TeamMember]`):+ The members the leader can assign tasks to.+ reset_members (`bool`, optional):+ Whether to clear every member's context after the leader's+ reply ends. Within one reply the leader can follow up with+ a member; across replies each member starts afresh.+ Defaults to `True`.+ """+ names = [_.agent.name for _ in members]+ if len(set(names)) != len(names) or leader.name in names:+ raise ValueError(+ "Member names must be unique and differ from the leader's, "+ f"got {names!r} with leader {leader.name!r}.",+ )+ self.leader = leader+ self.members = {_.agent.name: _ for _ in members}+ self.reset_members = reset_members+ self._assign_tool = _TeamAssign(members)+ self._tool_registered = False++ async def reply_stream(+ self,+ inputs: Msg+ | list[Msg]+ | UserConfirmResultEvent+ | UserInterruptEvent+ | ExternalExecutionResultEvent+ | None = None,+ ) -> AsyncGenerator[AgentEvent, None]:+ """Reply to the given inputs and stream the events of every+ participant.++ Args:+ inputs (`Msg | list[Msg] | UserConfirmResultEvent | \+ UserInterruptEvent | ExternalExecutionResultEvent | None`, \+ optional):+ Messages go to the leader. A confirmation or external+ result is routed by ``reply_id`` to whichever participant is+ parked on it. An interrupt aborts every parked participant.++ Yields:+ `AgentEvent`:+ The events of the leader and the members it assigns to. The+ stream ends when every participant has either finished or+ parked on a HITL request.+ """+ if not self._tool_registered:+ await self.leader.toolkit.add_tool(self._assign_tool)+ self._tool_registered = True++ try:+ async for evt in self._reply(inputs):+ yield evt+ except asyncio.CancelledError:+ # A leader parked on assignments misses the cancellation, so+ # interrupt it and the parked members as a user interrupt does+ if self.leader.state.has_awaiting_tool_calls(self.leader.name):+ async for evt in self.reply_stream(+ UserInterruptEvent(reply_id=self.leader.state.reply_id),+ ):+ yield evt+ if self.leader.react_config.interruption_raise_cancelled_error:+ raise++ async def _reply(+ self,+ inputs: Msg+ | list[Msg]+ | UserConfirmResultEvent+ | UserInterruptEvent+ | ExternalExecutionResultEvent+ | None,+ ) -> AsyncGenerator[AgentEvent, None]:+ """Route the inputs and drive the leader and the members, see+ :meth:`reply_stream`."""+ if isinstance(inputs, UserInterruptEvent):+ for member in self._parked_members():+ async for evt in member.agent.reply_stream(+ UserInterruptEvent(reply_id=member.agent.state.reply_id),+ ):+ yield evt+ inputs = UserInterruptEvent(reply_id=self.leader.state.reply_id)++ elif (+ isinstance(+ inputs,+ (UserConfirmResultEvent, ExternalExecutionResultEvent),+ )+ and inputs.reply_id != self.leader.state.reply_id+ ):+ # A parked member's turn; the leader only continues once the+ # member finishes, so its reply becomes the tool result. The+ # first awaiting call is the parked one, the rest are queued+ results: list[ToolResultBlock] = []+ member = self._parked_member(inputs.reply_id)+ async for evt in self._run_assignments(+ self._assigning_calls(member),+ results,+ inputs,+ ):+ yield evt+ if not results:+ return+ inputs = ExternalExecutionResultEvent(+ reply_id=self.leader.state.reply_id,+ execution_results=results,+ )++ while True:+ assignments: list[ToolCallBlock] = []+ async for evt in self.leader.reply_stream(inputs):+ # Assignments are executed by the pipeline itself, so their+ # require events are not the caller's business+ if isinstance(evt, RequireExternalExecutionEvent) and all(+ _.name == _TeamAssign.name for _ in evt.tool_calls+ ):+ assignments.extend(evt.tool_calls)+ continue+ yield evt+ if isinstance(evt, ReplyEndEvent) and self.reset_members:+ for member in self.members.values():+ member.agent.state.context.clear()+ member.agent.state.summary = ""++ if not assignments:+ return++ results = []+ async for evt in self._run_assignments(assignments, results):+ yield evt++ # Feed what has finished; with a member parked on HITL the+ # leader stays parked too and the stream ends here+ inputs = ExternalExecutionResultEvent(+ reply_id=self.leader.state.reply_id,+ execution_results=results,+ )+ if len(results) < len(assignments):+ if results:+ async for evt in self.leader.reply_stream(inputs):+ yield evt+ return++ async def _run_assignments(+ self,+ tool_calls: list[ToolCallBlock],+ results: list[ToolResultBlock],+ resumed: UserConfirmResultEvent+ | ExternalExecutionResultEvent+ | None = None,+ ) -> AsyncGenerator[AgentEvent, None]:+ """Run one round of assignments, concurrently across members and+ sequentially within one, appending the tool results of those that+ finish in call order. With ``resumed``, the first call is the parked+ one and continues with it."""+ groups: dict[str, list[ToolCallBlock]] = {}+ for tool_call in tool_calls:+ member = self._parse(tool_call)["member"]+ groups.setdefault(member, []).append(tool_call)++ sentinel = object()+ queue: Queue = Queue()+ round_results: list[ToolResultBlock] = []++ async def run_group(name: str, calls: list[ToolCallBlock]) -> None:+ """Run the assignments to one member one after another, turning+ each final reply into the tool result; once the member parks,+ the rest stay queued until it resumes."""+ member = self.members[name]+ for tool_call in calls:+ async for evt in member.agent.reply_stream(+ resumed+ if tool_call is tool_calls[0] and resumed+ else UserMsg(+ name="user",+ content=self._parse(tool_call)["prompt"],+ ),+ yield_final_msg=True,+ ):+ if not isinstance(evt, Msg):+ await queue.put(evt)+ elif evt.finished_reason is not None:+ round_results.append(+ ToolResultBlock(+ id=tool_call.id,+ name=_TeamAssign.name,+ output=[+ _+ for _ in evt.content+ if isinstance(_, (TextBlock, DataBlock))+ ]+ or "The member finished without a reply.",+ state=_RESULT_STATES[evt.finished_reason],+ ),+ )+ if self._is_parked(member):+ break++ async def run_all() -> None:+ """Run every group and mark the end of the stream."""+ try:+ await asyncio.gather(*[run_group(*_) for _ in groups.items()])+ finally:+ await queue.put(sentinel)++ gather_task = asyncio.create_task(run_all())+ try:+ while (evt := await queue.get()) is not sentinel:+ yield evt+ await gather_task+ except asyncio.CancelledError:+ # The members close themselves as interrupted in their own tasks,+ # stream what they produced before passing the cancellation on+ gather_task.cancel()+ await asyncio.gather(gather_task, return_exceptions=True)+ while not queue.empty():+ if (evt := queue.get_nowait()) is not sentinel:+ yield evt+ raise+ finally:+ gather_task.cancel()+ await asyncio.gather(gather_task, return_exceptions=True)+ # Results land in the leader's context in the order it called+ order = {_.id: i for i, _ in enumerate(tool_calls)}+ results.extend(sorted(round_results, key=lambda _: order[_.id]))++ @staticmethod+ def _is_parked(member: TeamMember) -> bool:+ """Whether the member is waiting on a HITL request."""+ return member.agent.state.has_awaiting_tool_calls(member.agent.name)++ def _parked_members(self) -> list[TeamMember]:+ """The members waiting on a HITL request."""+ return [_ for _ in self.members.values() if self._is_parked(_)]++ def _parked_member(self, reply_id: str) -> TeamMember:+ """The member parked on the reply the given result belongs to."""+ for member in self._parked_members():+ if member.agent.state.reply_id == reply_id:+ return member+ raise ValueError(+ f"No participant is waiting on the reply {reply_id!r}.",+ )++ def _parse(self, tool_call: ToolCallBlock) -> dict:+ """Parse an assignment's input the same way the leader validated+ it, so a repaired input parses here too."""+ return _json_loads_with_repair(+ tool_call.input,+ self._assign_tool.input_schema,+ )++ def _assigning_calls(self, member: TeamMember) -> list[ToolCallBlock]:+ """The leader's awaiting assignments to the member in call order,+ the first of which is the one the member is running."""+ return [+ _+ for _ in self.leader.state.get_awaiting_tool_calls(+ self.leader.name,+ )+ if _.name == _TeamAssign.name+ and self._parse(_)["member"] == member.agent.name+ ]diff --git a/tests/pipeline_team_test.py b/tests/pipeline_team_test.pynew file mode 100644index 000000000..06130ceaf--- /dev/null+++ b/tests/pipeline_team_test.py@@ -0,0 +1,1097 @@+# -*- coding: utf-8 -*-+# pylint: disable=redefined-builtin+"""Test the team pipeline."""+import asyncio+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase++from utils import AnyString, MockModel++from agentscope.agent import Agent, InjectionConfig+from agentscope.event import (+ ConfirmResult,+ UserConfirmResultEvent,+ UserInterruptEvent,+)+from agentscope.message import TextBlock, ToolCallBlock, UserMsg+from agentscope.model import ChatResponse+from agentscope.permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from agentscope.pipeline import TeamMember, TeamPipeline+from agentscope.tool import ToolBase, ToolChunk, Toolkit+++class AskTool(ToolBase):+ """A tool that asks the user before running."""++ name: str = "ask_tool"+ description: str = "A tool that needs confirmation"+ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {"input": {"type": "string"}},+ "required": ["input"],+ }+ is_concurrency_safe: bool = True+ is_read_only: bool = False++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Always ask."""+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message="Needs confirmation",+ )++ async def call(self, input: str) -> ToolChunk:+ """Echo the input."""+ return ToolChunk(content=[TextBlock(text=f"ask result: {input}")])+++class SlowTool(ToolBase):+ """A tool that runs until cancelled, flagging when it starts."""++ name: str = "slow_tool"+ description: str = "A tool that never finishes"+ input_schema: dict[str, Any] = {"type": "object", "properties": {}}+ is_concurrency_safe: bool = True+ is_read_only: bool = True++ def __init__(self) -> None:+ """Create the start flag per tool."""+ super().__init__()+ self.started = asyncio.Event()++ 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) -> ToolChunk:+ """Flag the start and wait forever."""+ self.started.set()+ await asyncio.Event().wait()+ return ToolChunk(content=[TextBlock(text="never")])+++def _tool_call(+ id: str,+ input: str,+ name: str = "TeamAssign",+) -> list[ChatResponse]:+ """A streamed model reply that calls one tool."""+ block = ToolCallBlock(id=id, name=name, input=input)+ return [+ ChatResponse(content=[block], is_last=False, usage=None),+ ChatResponse(content=[block], is_last=True, usage=None),+ ]+++def _text(text: str) -> list[ChatResponse]:+ """A streamed model reply with plain text."""+ return [+ ChatResponse(+ content=[TextBlock(text=text)],+ is_last=False,+ usage=None,+ ),+ ChatResponse(content=[TextBlock(text=text)], is_last=True, usage=None),+ ]+++def _agent(name: str, tools: list[ToolBase] | None = None) -> Agent:+ """An agent driven by its own mock model."""+ return Agent(+ name=name,+ system_prompt=f"You are {name}.",+ model=MockModel(),+ toolkit=Toolkit(tools=tools),+ injection_config=InjectionConfig(inject_runtime_state=False),+ )+++class TeamPipelineTest(IsolatedAsyncioTestCase):+ """The team pipeline test case."""++ async def asyncSetUp(self) -> None:+ """Build a leader with a researcher it can delegate to."""+ self.leader = _agent("leader")+ self.researcher = _agent("researcher", [AskTool()])+ self.pipeline = TeamPipeline(+ leader=self.leader,+ members=[+ TeamMember(agent=self.researcher, description="Researches"),+ ],+ )+ self.query = UserMsg(name="user", content="What is A?")++ async def _run(self, inputs: Any) -> list[tuple[str, str]]:+ """Drain one run into (event type, owner) pairs."""+ events = [_ async for _ in self.pipeline.reply_stream(inputs)]+ agents = [+ self.leader,+ *[_.agent for _ in self.pipeline.members.values()],+ ]+ owners = {_.state.reply_id: _.name for _ in agents}+ return [(_.type.value, owners[_.reply_id]) for _ in events]++ async def test_delegation_round_trip(self) -> None:+ """The researcher's final reply becomes the leader's tool result,+ its intermediate events are streamed, and its context is reset once+ the leader's reply ends."""+ self.leader.model.set_responses(+ [+ _tool_call(+ "call-1",+ '{"member": "researcher", "prompt": "Find A"}',+ ),+ _text("A is 42."),+ ],+ )+ self.researcher.model.set_responses([_text("Found: A = 42")])++ events = await self._run(self.query)++ self.assertListEqual(+ events,+ [+ ("REPLY_START", "leader"),+ ("MODEL_CALL_START", "leader"),+ ("TOOL_CALL_START", "leader"),+ ("TOOL_CALL_DELTA", "leader"),+ ("TOOL_CALL_END", "leader"),+ ("MODEL_CALL_END", "leader"),+ ("TOOL_RESULT_START", "leader"),+ ("REPLY_START", "researcher"),+ ("MODEL_CALL_START", "researcher"),+ ("TEXT_BLOCK_START", "researcher"),+ ("TEXT_BLOCK_DELTA", "researcher"),+ ("TEXT_BLOCK_END", "researcher"),+ ("MODEL_CALL_END", "researcher"),+ ("REPLY_END", "researcher"),+ ("TOOL_RESULT_TEXT_DELTA", "leader"),+ ("TOOL_RESULT_END", "leader"),+ ("MODEL_CALL_START", "leader"),+ ("TEXT_BLOCK_START", "leader"),+ ("TEXT_BLOCK_DELTA", "leader"),+ ("TEXT_BLOCK_END", "leader"),+ ("MODEL_CALL_END", "leader"),+ ("REPLY_END", "leader"),+ ],+ )+ self.assertListEqual(+ [_.model_dump() for _ in self.leader.state.context],+ [+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": AnyString(),+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "user",+ "role": "user",+ "usage": None,+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "What is A?",+ },+ ],+ },+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "leader",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "input": '{"member": "researcher", '+ '"prompt": "Find A"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Found: A = 42",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "A is 42.",+ },+ ],+ },+ ],+ )+ self.assertListEqual(self.researcher.state.context, [])++ async def test_member_hitl_round_trip(self) -> None:+ """A researcher parked on confirmation ends the stream with the+ leader parked on the delegation; the confirmation is routed back+ and the leader continues with the researcher's reply."""+ self.pipeline.reset_members = False+ self.leader.model.set_responses(+ [+ _tool_call(+ "call-1",+ '{"member": "researcher", "prompt": "Find A"}',+ ),+ _text("A is 42."),+ ],+ )+ self.researcher.model.set_responses(+ [+ _tool_call("call-r1", '{"input": "A"}', name="ask_tool"),+ _text("Found: A = 42"),+ ],+ )++ events = await self._run(self.query)++ self.assertListEqual(+ events[6:],+ [+ ("TOOL_RESULT_START", "leader"),+ ("REPLY_START", "researcher"),+ ("MODEL_CALL_START", "researcher"),+ ("TOOL_CALL_START", "researcher"),+ ("TOOL_CALL_DELTA", "researcher"),+ ("TOOL_CALL_END", "researcher"),+ ("MODEL_CALL_END", "researcher"),+ ("REQUIRE_USER_CONFIRM", "researcher"),+ ],+ )+ self.assertListEqual(+ [+ (_.name, _.state)+ for _ in self.leader.state.get_awaiting_tool_calls("leader")+ ],+ [("TeamAssign", "submitted")],+ )+ self.assertListEqual(+ [+ (_.name, _.state)+ for _ in self.researcher.state.get_awaiting_tool_calls(+ "researcher",+ )+ ],+ [("ask_tool", "asking")],+ )++ events = await self._run(+ UserConfirmResultEvent(+ reply_id=self.researcher.state.reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=True,+ tool_call=self.researcher.state.context[-1].content[0],+ ),+ ],+ ),+ )++ self.assertListEqual(+ events,+ [+ ("TOOL_RESULT_START", "researcher"),+ ("TOOL_RESULT_TEXT_DELTA", "researcher"),+ ("TOOL_RESULT_END", "researcher"),+ ("MODEL_CALL_START", "researcher"),+ ("TEXT_BLOCK_START", "researcher"),+ ("TEXT_BLOCK_DELTA", "researcher"),+ ("TEXT_BLOCK_END", "researcher"),+ ("MODEL_CALL_END", "researcher"),+ ("REPLY_END", "researcher"),+ ("TOOL_RESULT_TEXT_DELTA", "leader"),+ ("TOOL_RESULT_END", "leader"),+ ("MODEL_CALL_START", "leader"),+ ("TEXT_BLOCK_START", "leader"),+ ("TEXT_BLOCK_DELTA", "leader"),+ ("TEXT_BLOCK_END", "leader"),+ ("MODEL_CALL_END", "leader"),+ ("REPLY_END", "leader"),+ ],+ )+ self.assertListEqual(+ [_.model_dump() for _ in self.researcher.state.context],+ [+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": AnyString(),+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "user",+ "role": "user",+ "usage": None,+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Find A",+ },+ ],+ },+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "researcher",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-r1",+ "name": "ask_tool",+ "input": '{"input": "A"}',+ "state": "finished",+ "suggested_rules": [+ {+ "tool_name": "ask_tool",+ "rule_content": None,+ "behavior": PermissionBehavior.ALLOW,+ "source": "suggested",+ },+ ],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-r1",+ "name": "ask_tool",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "ask result: A",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Found: A = 42",+ },+ ],+ },+ ],+ )+ self.assertEqual(+ self.leader.state.context[-1].get_text_content(),+ "A is 42.",+ )++ async def test_concurrent_delegations(self) -> None:+ """Delegations to different members in one round run together and+ land in the leader's context in call order."""+ coder = _agent("coder")+ self.pipeline = TeamPipeline(+ leader=self.leader,+ members=[+ TeamMember(agent=self.researcher, description="Researches"),+ TeamMember(agent=coder, description="Codes"),+ ],+ )+ self.leader.model.set_responses(+ [+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="call-1",+ name="TeamAssign",+ input='{"member": "researcher", '+ '"prompt": "Find A"}',+ ),+ ToolCallBlock(+ id="call-2",+ name="TeamAssign",+ input='{"member": "coder", '+ '"prompt": "Write A"}',+ ),+ ],+ is_last=True,+ usage=None,+ ),+ ],+ _text("Both done."),+ ],+ )+ self.researcher.model.set_responses([_text("Found: A = 42")])+ coder.model.set_responses([_text("Wrote a.py")])++ events = await self._run(self.query)++ self.assertListEqual(+ sorted(owner for kind, owner in events if kind == "REPLY_START"),+ ["coder", "leader", "researcher"],+ )+ self.assertListEqual(+ [+ (_.id, _.name, _.output[0].text, _.state)+ for _ in self.leader.state.context[-1].get_content_blocks(+ "tool_result",+ )+ ],+ [+ ("call-1", "TeamAssign", "Found: A = 42", "success"),+ ("call-2", "TeamAssign", "Wrote a.py", "success"),+ ],+ )+ self.assertEqual(+ self.leader.state.context[-1].get_text_content(),+ "Both done.",+ )++ async def test_interrupt_parked_member(self) -> None:+ """An interrupt closes the parked researcher and the leader's+ delegation alike, and resets the researcher afterwards."""+ self.leader.model.set_responses(+ [+ _tool_call(+ "call-1",+ '{"member": "researcher", "prompt": "Find A"}',+ ),+ ],+ )+ self.researcher.model.set_responses(+ [_tool_call("call-r1", '{"input": "A"}', name="ask_tool")],+ )+ await self._run(self.query)++ events = await self._run(+ UserInterruptEvent(reply_id=self.researcher.state.reply_id),+ )++ self.assertListEqual(+ events,+ [+ ("TOOL_RESULT_START", "researcher"),+ ("TOOL_RESULT_TEXT_DELTA", "researcher"),+ ("TOOL_RESULT_END", "researcher"),+ ("REPLY_END", "researcher"),+ ("TOOL_RESULT_TEXT_DELTA", "leader"),+ ("TOOL_RESULT_END", "leader"),+ ("REPLY_END", "leader"),+ ],+ )+ self.assertListEqual(+ [+ (_.id, _.state)+ for _ in self.leader.state.context[-1].get_content_blocks(+ "tool_result",+ )+ ],+ [("call-1", "interrupted")],+ )+ self.assertListEqual(self.researcher.state.context, [])++ async def test_repaired_assignment_input(self) -> None:+ """An assignment input that only parses after repair still reaches+ the member instead of leaving the leader parked."""+ self.leader.model.set_responses(+ [+ _tool_call(+ "call-1",+ "{'member': 'researcher', 'prompt': 'Find A'}",+ ),+ _text("A is 42."),+ ],+ )+ self.researcher.model.set_responses([_text("Found: A = 42")])++ await self._run(self.query)++ self.assertDictEqual(+ self.leader.state.context[-1].model_dump(),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "leader",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "input": "{'member': 'researcher', "+ "'prompt': 'Find A'}",+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Found: A = 42",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "A is 42.",+ },+ ],+ },+ )++ async def test_one_member_parks_in_a_round(self) -> None:+ """With the researcher parked, the coder's result is fed right away+ and the leader stays parked until the researcher resumes."""+ coder = _agent("coder")+ self.pipeline = TeamPipeline(+ leader=self.leader,+ members=[+ TeamMember(agent=self.researcher, description="Researches"),+ TeamMember(agent=coder, description="Codes"),+ ],+ )+ self.leader.model.set_responses(+ [+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="call-1",+ name="TeamAssign",+ input='{"member": "researcher", '+ '"prompt": "Find A"}',+ ),+ ToolCallBlock(+ id="call-2",+ name="TeamAssign",+ input='{"member": "coder", '+ '"prompt": "Write A"}',+ ),+ ],+ is_last=True,+ usage=None,+ ),+ ],+ _text("Both done."),+ ],+ )+ self.researcher.model.set_responses(+ [+ _tool_call("call-r1", '{"input": "A"}', name="ask_tool"),+ _text("Found: A = 42"),+ ],+ )+ coder.model.set_responses([_text("Wrote a.py")])++ await self._run(self.query)++ self.assertListEqual(+ [+ (_.id, _.state)+ for _ in self.leader.state.get_awaiting_tool_calls("leader")+ ],+ [("call-1", "submitted")],+ )++ await self._run(+ UserConfirmResultEvent(+ reply_id=self.researcher.state.reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=True,+ tool_call=self.researcher.state.context[-1].content[0],+ ),+ ],+ ),+ )++ self.assertDictEqual(+ self.leader.state.context[-1].model_dump(),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "leader",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "input": '{"member": "researcher", '+ '"prompt": "Find A"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-2",+ "name": "TeamAssign",+ "input": '{"member": "coder", "prompt": "Write A"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-2",+ "name": "TeamAssign",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Wrote a.py",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Found: A = 42",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Both done.",+ },+ ],+ },+ )++ async def test_same_member_assignments_queue(self) -> None:+ """A second assignment to a parked researcher waits for the first+ one to finish, then runs, and both results land in call order."""+ self.leader.model.set_responses(+ [+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="call-1",+ name="TeamAssign",+ input='{"member": "researcher", '+ '"prompt": "Find A"}',+ ),+ ToolCallBlock(+ id="call-2",+ name="TeamAssign",+ input='{"member": "researcher", '+ '"prompt": "Find B"}',+ ),+ ],+ is_last=True,+ usage=None,+ ),+ ],+ _text("Both found."),+ ],+ )+ self.researcher.model.set_responses(+ [+ _tool_call("call-r1", '{"input": "A"}', name="ask_tool"),+ _text("Found A"),+ _text("Found B"),+ ],+ )++ events = await self._run(self.query)++ self.assertEqual(events.count(("REPLY_START", "researcher")), 1)+ self.assertListEqual(+ [+ (_.id, _.state)+ for _ in self.leader.state.get_awaiting_tool_calls("leader")+ ],+ [("call-1", "submitted"), ("call-2", "submitted")],+ )++ # The researcher starts a new reply for the queued call, so the+ # events are drained without mapping owners+ _ = [+ _+ async for _ in self.pipeline.reply_stream(+ UserConfirmResultEvent(+ reply_id=self.researcher.state.reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=True,+ tool_call=self.researcher.state.context[+ -1+ ].content[0],+ ),+ ],+ ),+ )+ ]++ self.assertDictEqual(+ self.leader.state.context[-1].model_dump(),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "leader",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "input": '{"member": "researcher", '+ '"prompt": "Find A"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-2",+ "name": "TeamAssign",+ "input": '{"member": "researcher", '+ '"prompt": "Find B"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Found A",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-2",+ "name": "TeamAssign",+ "output": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Found B",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Both found.",+ },+ ],+ },+ )++ async def _cancel(self, inputs: Any, tool: SlowTool) -> list[str]:+ """Cancel the run once the slow tool starts, returning the types of+ the events streamed before and after the cancellation."""+ events = []++ async def consume() -> None:+ async for evt in self.pipeline.reply_stream(inputs):+ events.append(evt.type.value)++ task = asyncio.create_task(consume())+ await tool.started.wait()+ task.cancel()+ await task+ return events++ async def test_cancel_running_member(self) -> None:+ """Cancelling while the researcher runs interrupts it and the leader+ parked on the assignment, so the team takes the next query."""+ slow = SlowTool()+ self.researcher = _agent("researcher", [slow])+ self.pipeline = TeamPipeline(+ leader=self.leader,+ members=[+ TeamMember(agent=self.researcher, description="Researches"),+ ],+ )+ self.leader.model.set_responses(+ [+ _tool_call(+ "call-1",+ '{"member": "researcher", "prompt": "Find A"}',+ ),+ _text("Hi again."),+ ],+ )+ self.researcher.model.set_responses(+ [_tool_call("call-r1", "{}", name="slow_tool")],+ )++ events = await self._cancel(self.query, slow)++ self.assertListEqual(+ events[-7:],+ [+ "TOOL_RESULT_START",+ "TOOL_RESULT_TEXT_DELTA",+ "TOOL_RESULT_END",+ "REPLY_END",+ "TOOL_RESULT_TEXT_DELTA",+ "TOOL_RESULT_END",+ "REPLY_END",+ ],+ )+ self.assertDictEqual(+ self.leader.state.context[-1].model_dump(),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "leader",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "input": '{"member": "researcher", '+ '"prompt": "Find A"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "output": "<system-reminder>The tool call has been "+ "interrupted by the user.</system-reminder>",+ "state": "interrupted",+ "metadata": {},+ },+ ],+ },+ )+ self.assertListEqual(self.researcher.state.context, [])++ await self._run(UserMsg(name="user", content="Hi"))++ self.assertEqual(+ self.leader.state.context[-1].get_text_content(),+ "Hi again.",+ )++ async def test_cancel_resumed_member(self) -> None:+ """Cancelling a researcher resumed from HITL ends the leader as+ interrupted instead of letting it reason on."""+ slow = SlowTool()+ self.researcher = _agent("researcher", [AskTool(), slow])+ self.pipeline = TeamPipeline(+ leader=self.leader,+ members=[+ TeamMember(agent=self.researcher, description="Researches"),+ ],+ )+ self.leader.model.set_responses(+ [+ _tool_call(+ "call-1",+ '{"member": "researcher", "prompt": "Find A"}',+ ),+ ],+ )+ self.researcher.model.set_responses(+ [+ _tool_call("call-r1", '{"input": "A"}', name="ask_tool"),+ _tool_call("call-r2", "{}", name="slow_tool"),+ ],+ )+ await self._run(self.query)++ await self._cancel(+ UserConfirmResultEvent(+ reply_id=self.researcher.state.reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=True,+ tool_call=self.researcher.state.context[-1].content[0],+ ),+ ],+ ),+ slow,+ )++ self.assertDictEqual(+ self.leader.state.context[-1].model_dump(),+ {+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "leader",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "tool_call",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "input": '{"member": "researcher", '+ '"prompt": "Find A"}',+ "state": "finished",+ "suggested_rules": [],+ },+ {+ "type": "tool_result",+ "created_at": AnyString(),+ "finished_at": None,+ "id": "call-1",+ "name": "TeamAssign",+ "output": "<system-reminder>The tool call has been "+ "interrupted by the user.</system-reminder>",+ "state": "interrupted",+ "metadata": {},+ },+ ],+ },+ )+ self.assertListEqual(self.researcher.state.context, [])