Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent-team): support custom subagent templates in agent service (#1833)
DavdGao08b7a2797168
diff --git a/examples/agent_service/main.py b/examples/agent_service/main.pyindex c1325f016..36e4a2572 100644--- a/examples/agent_service/main.py+++ b/examples/agent_service/main.py@@ -6,12 +6,12 @@ import uvicornfrom fastapi.middleware import Middlewarefrom fastapi.middleware.cors import CORSMiddleware-from agentscope.app import create_app+from agentscope.app import create_app, SubAgentTemplatefrom agentscope.app.message_bus import RedisMessageBusfrom agentscope.app.storage import RedisStoragefrom agentscope.app.workspace_manager import LocalWorkspaceManagerfrom agentscope.mcp import MCPClient, StdioMCPConfig, HttpMCPConfig-+from agentscope.permission import PermissionContext, PermissionModedefault_mcps = [MCPClient(@@ -37,11 +37,11 @@ if os.getenv("AMAP_API_KEY"):)app = create_app(- RedisStorage(+ storage=RedisStorage(host="localhost",port=6379,),- RedisMessageBus(+ message_bus=RedisMessageBus(host="localhost",port=6379,),@@ -53,6 +53,44 @@ app = create_app(# The default MCP servers that will be added into the workspacedefault_mcps=default_mcps,),+ # Customize your own subagent templates+ sub_agent_templates=[+ SubAgentTemplate(+ type="explorer",+ description=(+ "Read-only agents specialized in exploration tasks. It can "+ "read files but cannot modify, create, or delete them. Use "+ "this agent type when you need to investigate the codebase, "+ "understand its structure, or gather information from files "+ "to support planning—without making any changes."+ ),+ system_prompt_template="""You are {member_name}, an explorer \+agent in team '{team_name}' led by {leader_name}.++Team purpose: {team_description}++Your role: {member_description}++## Responsibilities+- Complete the exploration tasks assigned by the team leader.+- You are read-only: you may inspect files and the codebase, but you must \+never modify, create, or delete anything.++## Reporting+- Always report the task result back to {leader_name} using the TeamSay \+tool, whether the task succeeds or fails.+- Keep your private reasoning private; only share conclusions and findings \+that the leader needs.++Note: `TeamSay` is your ONLY channel to communicate with {leader_name} and \+the other team members. Any other output you produce is invisible to them, \+so anything you want them to see MUST be sent through `TeamSay`.""",+ permission_context=PermissionContext(+ # Read-only+ mode=PermissionMode.EXPLORE,+ ),+ ),+ ],extra_middlewares=[Middleware(CORSMiddleware,diff --git a/src/agentscope/app/__init__.py b/src/agentscope/app/__init__.pyindex 127537e33..c6091044c 100644--- a/src/agentscope/app/__init__.py+++ b/src/agentscope/app/__init__.py@@ -4,7 +4,9 @@ components and a configurable FastAPI app factory."""from ._app import create_app+from ._types import SubAgentTemplate__all__ = ["create_app",+ "SubAgentTemplate",]diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex e1bde2917..638efc292 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -13,7 +13,7 @@ from ._router import (session_router,workspace_router,)-from ._types import AgentMiddlewareFactory, AgentToolFactory+from ._types import AgentMiddlewareFactory, AgentToolFactory, SubAgentTemplatefrom .message_bus import MessageBusfrom .storage import StorageBasefrom ..credential import CredentialFactory, CredentialBase@@ -37,6 +37,7 @@ def create_app(extra_middlewares: list[FastAPIMiddleware] | None = None,extra_agent_middlewares: AgentMiddlewareFactory | None = None,extra_agent_tools: AgentToolFactory | None = None,+ sub_agent_templates: list[SubAgentTemplate] | None = None,title: str = "AgentScope",version: str = __version__,) -> FastAPI:@@ -105,6 +106,15 @@ def create_app(availability depends on the caller (per-tenant integrations,user-specific credentials). The returned tools are added tothe workspace-derived tools in the toolkit's ``"basic"`` group.+ sub_agent_templates (`list[SubAgentTemplate] | None`, optional):+ Reusable blueprints for sub-agent creation within teams.+ Each template defines a sub-agent *type* (e.g. ``"researcher"``,+ ``"coder"``) with pre-configured system prompt, context config,+ ReAct config, permission context, and task context. When+ registered, the ``AgentCreate`` tool exposes a+ ``subagent_type`` parameter so the leader agent can route to+ the appropriate template. See+ :class:`~agentscope.app._types.SubAgentTemplate` for details.title (`str`, defaults to ``"AgentScope"``):OpenAPI title shown in the docs UI.version (`str`, defaults to the package version):@@ -127,6 +137,18 @@ def create_app(app.state.workspace_manager = workspace_managerapp.state.extra_agent_middlewares = extra_agent_middlewaresapp.state.extra_agent_tools = extra_agent_tools+ templates = sub_agent_templates or []+ seen_types: set[str] = set()+ duplicates: set[str] = set()+ for t in templates:+ if t.type in seen_types:+ duplicates.add(t.type)+ seen_types.add(t.type)+ if duplicates:+ raise ValueError(+ f"Duplicate sub_agent_template type(s): {duplicates}",+ )+ app.state.sub_agent_templates = {t.type: t for t in templates}# Built-in routersfor router in (diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.pyindex f9f69889f..031436528 100644--- a/src/agentscope/app/_lifespan.py+++ b/src/agentscope/app/_lifespan.py@@ -69,6 +69,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:message_bus=message_bus,extra_agent_middlewares=app.state.extra_agent_middlewares,extra_agent_tools=app.state.extra_agent_tools,+ sub_agent_templates=app.state.sub_agent_templates,)app.state.chat_service = chat_servicediff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 7bbb41e0d..a1a1d2ee9 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -22,7 +22,11 @@ from ..middleware import (StateChangeMiddleware,ToolOffloadMiddleware,)-from .._types import AgentMiddlewareFactory, AgentToolFactory+from .._types import (+ AgentMiddlewareFactory,+ AgentToolFactory,+ SubAgentTemplate,+)from ._model import get_modelfrom ._toolkit import get_toolkit@@ -60,6 +64,7 @@ class ChatService:message_bus: MessageBus,extra_agent_middlewares: AgentMiddlewareFactory | None = None,extra_agent_tools: AgentToolFactory | None = None,+ sub_agent_templates: dict[str, SubAgentTemplate] | None = None,) -> None:"""Initialize chat service.@@ -83,12 +88,18 @@ class ChatService:replay + live fan-out (via :meth:`session_publish_event`),and inbox delivery (via :class:`InboxMiddleware`).extra_agent_middlewares (`AgentMiddlewareFactory | None`, \-optional):+ optional):Async factory invoked at every chat turn to produceuser/session-specific middlewares to attach to the agent.extra_agent_tools (`AgentToolFactory | None`, optional):Async factory invoked at every chat turn to produceuser/session-specific tools to register in the toolkit.+ sub_agent_templates (`dict[str, SubAgentTemplate] | None`, \+ optional):+ Sub-agent template registry, keyed by template type.+ Passed through to :func:`get_toolkit` so that+ ``AgentCreate`` can route to the appropriate template+ when a ``subagent_type`` is specified."""self._storage = storageself._workspace_manager = workspace_manager@@ -97,6 +108,7 @@ optional):self._message_bus = message_busself._extra_agent_middlewares = extra_agent_middlewaresself._extra_agent_tools = extra_agent_tools+ self._sub_agent_templates = sub_agent_templatesasync def run(self,@@ -215,6 +227,7 @@ optional):agent_record=agent_record,session_record=session_record,extra_factory=self._extra_agent_tools,+ sub_agent_templates=self._sub_agent_templates,)# ----------------------------------------------------------------diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pyindex 57166859a..dcc45a1ef 100644--- a/src/agentscope/app/_service/_toolkit.py+++ b/src/agentscope/app/_service/_toolkit.py@@ -11,7 +11,7 @@ from typing import Anyfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..message_bus import MessageBusfrom .._tools import AgentCreate, TeamCreate, TeamDelete, TeamSay-from .._types import AgentToolFactory+from .._types import AgentToolFactory, SubAgentTemplatefrom ..storage import AgentRecord, SessionRecord, StorageBasefrom ...tool import (TaskCreate,@@ -35,6 +35,7 @@ async def get_toolkit(agent_record: AgentRecord,session_record: SessionRecord,extra_factory: AgentToolFactory | None = None,+ sub_agent_templates: dict[str, SubAgentTemplate] | None = None,) -> Toolkit:"""Assemble the complete :class:`Toolkit` for one chat turn.@@ -89,6 +90,12 @@ async def get_toolkit(extra_factory (`AgentToolFactory | None`, optional):Async factory invoked once per assembly to produceuser/session-specific extra tools.+ sub_agent_templates (`dict[str, SubAgentTemplate] | None`, \+optional):+ Sub-agent template registry, keyed by template type.+ Passed to the ``AgentCreate`` tool so it can route to+ the appropriate template when a ``subagent_type`` is+ specified by the leader agent.Returns:`Toolkit`: Fully populated toolkit (tools + skills + MCPs).@@ -150,7 +157,10 @@ time or interval"else:tools += [TeamCreate(**team_tool_kwargs),- AgentCreate(**team_tool_kwargs),+ AgentCreate(+ **team_tool_kwargs,+ sub_agent_templates=sub_agent_templates or {},+ ),TeamSay(**team_tool_kwargs, role="leader"),TeamDelete(**team_tool_kwargs),]diff --git a/src/agentscope/app/_tools/__init__.py b/src/agentscope/app/_tools/__init__.pyindex 6c65309f5..6ad921716 100644--- a/src/agentscope/app/_tools/__init__.py+++ b/src/agentscope/app/_tools/__init__.py@@ -24,13 +24,14 @@ Task series, …) in two ways:Selection of the right subset by ``agent.source`` happens inline in:func:`get_toolkit`; there is no separate "team tool factory" helper."""-from ._agent_create import AgentCreate+from ._agent_create import AgentCreate, DEFAULT_SUB_AGENT_TEMPLATEfrom ._team_create import TeamCreatefrom ._team_delete import TeamDeletefrom ._team_say import TeamSay__all__ = ["AgentCreate",+ "DEFAULT_SUB_AGENT_TEMPLATE","TeamCreate","TeamDelete","TeamSay",diff --git a/src/agentscope/app/_tools/_agent_create.py b/src/agentscope/app/_tools/_agent_create.pyindex b75d3edcd..0acd495da 100644--- a/src/agentscope/app/_tools/_agent_create.py+++ b/src/agentscope/app/_tools/_agent_create.py@@ -1,43 +1,48 @@# -*- coding: utf-8 -*-"""The AgentCreate tool — spawns a worker into the current team."""+from __future__ import annotations++import copyimport json-from typing import Literal+from typing import TYPE_CHECKINGfrom pydantic import Fieldfrom ._team_tool_base import _TeamToolBase+from .._types import SubAgentTemplatefrom ..storage import AgentData, AgentRecord, SessionConfig-from ...agent import ContextConfig, ReActConfigfrom ...message import HintBlock, TextBlock, ToolResultState-from ...permission import PermissionContext, PermissionModefrom ...state import AgentStatefrom ...tool import ToolChunk, ParamsBase+if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import StorageBase-_PERMISSION_MODE_BY_VALUE: dict[str, PermissionMode] = {- mode.value: mode for mode in PermissionMode-}---def _build_worker_system_prompt(- team_name: str,- team_description: str,- member_name: str,- member_description: str,-) -> str:- """Compose the system prompt for a freshly spawned worker."""- sections = [f"You are {member_name}, a member of team {team_name!r}."]- if team_description:- sections.append(f"Team purpose: {team_description}")- if member_description:- sections.append(f"Your role: {member_description}")- sections.append(- "You communicate with the team leader and other members "- "through the TeamSay tool. Other tool calls execute in your "- "own session. Speak on the team only when you have something "- "external to share — your private reasoning stays private.",- )- return "\n\n".join(sections)++_DEFAULT_SYSTEM_PROMPT_TEMPLATE = (+ "You are {member_name}, a member of team '{team_name}' led by "+ "{leader_name}.\n\n"+ "Team purpose: {team_description}\n\n"+ "Your role: {member_description}\n\n"+ "You communicate with the team leader and other members "+ "through the TeamSay tool. "+ "Speak on the team only when you have something "+ "external to share — your private reasoning stays private."+)++DEFAULT_SUB_AGENT_TEMPLATE = SubAgentTemplate(+ type="default",+ description="Default worker agent with standard configuration.",+ system_prompt_template=_DEFAULT_SYSTEM_PROMPT_TEMPLATE,+)+# The built-in default sub-agent template.+#+# Used when no custom templates are registered, or when the leader+# agent creates a member without specifying a ``subagent_type`` (or+# explicitly specifies ``subagent_type="default"``). Developers can+# override this by registering their own template with+# ``type="default"`` via :func:`~agentscope.app.create_app`.class _AgentCreateParams(ParamsBase):@@ -69,40 +74,6 @@ class _AgentCreateParams(ParamsBase):"deadlines the member needs."),)- permission_mode: Literal[- "default",- "accept_edits",- "explore",- "bypass",- "dont_ask",- ] = Field(- default="default",- description=(- "Permission mode controlling how the member handles tool "- "calls that would otherwise require user confirmation.\n\n"- "Choose based on the member's responsibilities:\n\n"- '- ``"default"`` — Each tool call that touches the system '- "(file writes, shell commands, etc.) requires confirmation. "- "Pick this when the member's work has real-world side effects "- "you want the user to review.\n"- '- ``"accept_edits"`` — Auto-approve file edits and '- "filesystem-shaping commands inside the working directory; "- "still confirm other risky calls. Pick this for a member "- "doing rapid iteration on code under your supervision.\n"- '- ``"explore"`` — Read-only mode: allow Read/Grep/Glob, '- "deny anything that mutates state. Pick this for research / "- "audit / planning members that should never modify anything.\n"- '- ``"bypass"`` — Skip every permission check. Pick this '- "ONLY for fully sandboxed members where any operation is "- "guaranteed safe (e.g. a containerised worker on disposable "- "data).\n"- '- ``"dont_ask"`` — Convert every ASK decision to DENY. '- "Pick this for unattended/background members where the user "- 'isn\'t around to answer prompts; safer than ``"bypass"`` '- "because risky calls fail-closed instead of executing.\n\n"- 'When unsure, start with ``"default"``.'- ),- )class AgentCreate(_TeamToolBase):@@ -142,12 +113,83 @@ overall communication topology unnecessarily complex.input_schema: dict = _AgentCreateParams.model_json_schema()+ def __init__(+ self,+ storage: "StorageBase",+ message_bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ sub_agent_templates: dict[str, SubAgentTemplate] | None = None,+ ) -> None:+ """Bind request-scoped identifiers plus sub-agent templates.++ Extends :meth:`_TeamToolBase.__init__` with an optional+ template registry. The built-in ``"default"`` template is+ always present as a fallback; developers can override it by+ registering their own template with ``type="default"``.++ When more than one template type is available (i.e. custom+ templates were registered), the tool's ``input_schema`` is+ dynamically extended with a ``subagent_type`` enum field so+ the leader agent can choose which type to create.++ Args:+ storage (`StorageBase`):+ Application storage backend.+ message_bus (`MessageBus`):+ Application message bus for inter-session delivery.+ user_id (`str`):+ The owner user id of the calling agent.+ session_id (`str`):+ The current session id of the calling agent.+ agent_id (`str`):+ The id of the agent invoking the tool.+ sub_agent_templates (`dict[str, SubAgentTemplate] | None`, \+optional):+ Template registry keyed by template type. The+ built-in ``"default"`` template is injected+ automatically if not already present.+ """+ super().__init__(storage, message_bus, user_id, session_id, agent_id)++ self._sub_agent_templates: dict[str, SubAgentTemplate] = dict(+ sub_agent_templates or {},+ )+ if "default" not in self._sub_agent_templates:+ self._sub_agent_templates["default"] = DEFAULT_SUB_AGENT_TEMPLATE++ # Only expose subagent_type when the developer registered+ # custom templates — a single "default" type is redundant in+ # the schema and would confuse the LLM.+ has_custom_templates = set(self._sub_agent_templates) != {"default"}+ if has_custom_templates:+ schema = copy.deepcopy(+ _AgentCreateParams.model_json_schema(),+ )+ type_descriptions = "\n".join(+ f"- ``{t.type!r}`` — {t.description}"+ for t in self._sub_agent_templates.values()+ )+ schema["properties"]["subagent_type"] = {+ "type": "string",+ "enum": list(self._sub_agent_templates),+ "description": (+ "The type of sub-agent template to use. "+ "Available types:\n\n"+ f"{type_descriptions}\n\n"+ "Each type has pre-configured system prompt, "+ "permissions, and task context."+ ),+ }+ self.input_schema = schema+async def __call__(self,name: str,description: str,prompt: str,- permission_mode: str = "default",+ subagent_type: str = "default",) -> ToolChunk:"""Spawn the worker agent + session directly via storage.@@ -155,15 +197,21 @@ overall communication topology unnecessarily complex.enforce two preconditions: the calling session must be in ateam, and it must be that team's leader.+ The worker's configuration (system prompt, context/react+ config, permission context, task context) is determined by+ the :class:`SubAgentTemplate` matching ``subagent_type``.+Args:name (`str`):- Short identifier for the worker.+ Short identifier for the worker, unique within the+ team. Used as the ``to`` target in ``TeamSay``.description (`str`):One-sentence summary of the worker's role.prompt (`str`):First task delivered as a user message to the worker.- permission_mode (`str`, defaults to ``"default"``):- Permission mode the worker operates under.+ subagent_type (`str`, defaults to ``"default"``):+ Template type to use. Must match a registered+ :class:`SubAgentTemplate.type`.Returns:`ToolChunk`:@@ -239,20 +287,22 @@ overall communication topology unnecessarily complex.state=ToolResultState.ERROR,)- if permission_mode not in _PERMISSION_MODE_BY_VALUE:+ # Resolve the template.+ template = self._sub_agent_templates.get(subagent_type)+ if template is None:+ available = list(self._sub_agent_templates)return ToolChunk(content=[TextBlock(text=(- f"AgentCreate: unknown permission_mode "- f"{permission_mode!r}; expected one of "- f"{list(_PERMISSION_MODE_BY_VALUE)}."+ f"AgentCreate: unknown subagent_type "+ f"{subagent_type!r}; expected one of "+ f"{available}."),),],state=ToolResultState.ERROR,)- mode_enum = _PERMISSION_MODE_BY_VALUE[permission_mode]# Enforce team-scoped name uniqueness. TeamSay routes by# ``name`` (not agent_id), so duplicates would be ambiguous@@ -288,13 +338,22 @@ overall communication topology unnecessarily complex.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 = _build_worker_system_prompt(+ system_prompt = template.system_prompt_template.format(team_name=team.data.name,team_description=team.data.description,member_name=name,member_description=description,+ leader_name=leader_name,)worker_agent = AgentRecord(user_id=self._user_id,@@ -302,8 +361,12 @@ overall communication topology unnecessarily complex.data=AgentData(name=name,system_prompt=system_prompt,- context_config=ContextConfig(),- react_config=ReActConfig(),+ context_config=template.context_config.model_copy(+ deep=True,+ ),+ react_config=template.react_config.model_copy(+ deep=True,+ ),),)await self._storage.upsert_agent(self._user_id, worker_agent)@@ -311,7 +374,12 @@ overall communication topology unnecessarily complex.# 2. Build worker SessionRecord, inheriting leader's model# config.worker_state = AgentState(- permission_context=PermissionContext(mode=mode_enum),+ permission_context=template.permission_context.model_copy(+ deep=True,+ ),+ tasks_context=template.tasks_context.model_copy(+ deep=True,+ ),)worker_session = await self._storage.upsert_session(user_id=self._user_id,@@ -342,11 +410,6 @@ overall communication topology unnecessarily complex.await self._storage.upsert_team(self._user_id, team)# 4. Deliver the initial task to the worker's inbox + wakeup.- leader_name = (- leader_agent_record.data.name- if leader_agent_record is not None- else leader_session.agent_id- )hint = HintBlock(hint=(f'<team-message from="{leader_name}">\n'diff --git a/src/agentscope/app/_types.py b/src/agentscope/app/_types.pyindex 54fb7fcc5..df7513b80 100644--- a/src/agentscope/app/_types.py+++ b/src/agentscope/app/_types.py@@ -2,7 +2,12 @@"""Shared type aliases for the agentscope app layer."""from collections.abc import Awaitable, Callable+from pydantic import BaseModel, Field++from ..agent import ContextConfig, ReActConfigfrom ..middleware import MiddlewareBase+from ..permission import PermissionContext+from ..state import TaskContextfrom ..tool import ToolBase@@ -19,3 +24,74 @@ AgentToolFactory = Callable[]# Async factory signature: ``(user_id, agent_id, session_id)`` →# awaitable of :class:`~agentscope.tool.ToolBase` instances.+++class SubAgentTemplate(BaseModel):+ """A reusable blueprint for sub-agent creation within a team.++ Developers register one or more templates at the ``create_app`` entry+ point. When the leader agent calls ``AgentCreate`` with a matching+ ``subagent_type``, the template's configuration is used instead of the+ built-in defaults.++ The :attr:`type` field serves as the routing key — it becomes an enum+ value of the ``subagent_type`` parameter exposed to the LLM. This is+ distinct from the ``name`` parameter in ``AgentCreate``, which is the+ per-instance identifier the leader assigns to each worker (used for+ ``TeamSay(to=name)``).++ All fields are pure data (no callables), so the template is fully+ serializable for future config-driven startup.+ """++ type: str = Field(+ description=(+ "Template type identifier, e.g. ``'researcher'`` or "+ "``'coder'``. Used as the enum value for the "+ "``subagent_type`` parameter in ``AgentCreate``."+ ),+ )++ description: str = Field(+ description=(+ "Agent-readable description of this sub-agent type. "+ "Exposed to the LLM in the ``AgentCreate`` tool schema "+ "so it can choose the appropriate type."+ ),+ )++ system_prompt_template: str = Field(+ description=(+ "A Python format string for the worker's system prompt. "+ "Available placeholders: ``{team_name}``, "+ "``{team_description}``, ``{member_name}``, "+ "``{member_description}``, ``{leader_name}``."+ ),+ )++ context_config: ContextConfig = Field(+ default_factory=ContextConfig,+ description="Context configuration for the sub-agent.",+ )++ react_config: ReActConfig = Field(+ default_factory=ReActConfig,+ description="ReAct loop configuration for the sub-agent.",+ )++ permission_context: PermissionContext = Field(+ default_factory=PermissionContext,+ description=(+ "Permission context applied to the sub-agent at "+ "creation time. Controls what the worker is allowed "+ "to do (e.g. read-only vs. full access)."+ ),+ )++ tasks_context: TaskContext = Field(+ default_factory=TaskContext,+ description=(+ "Pre-defined task context for the sub-agent, allowing "+ "the template to seed an initial workflow."+ ),+ )diff --git a/src/agentscope/state/__init__.py b/src/agentscope/state/__init__.pyindex a640f6ff4..d9db1c58b 100644--- a/src/agentscope/state/__init__.py+++ b/src/agentscope/state/__init__.py@@ -1,10 +1,11 @@# -*- coding: utf-8 -*-"""The agent state module in agentscope."""-from ._state import AgentState+from ._state import AgentState, TaskContextfrom ._task import Task__all__ = ["Task",+ "TaskContext","AgentState",]diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pyindex 025ea897c..ca18e5321 100644--- a/tests/service_team_tools_test.py+++ b/tests/service_team_tools_test.py@@ -24,10 +24,12 @@ from utils import AnyStringfrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.app._tools import (AgentCreate,+ DEFAULT_SUB_AGENT_TEMPLATE,TeamCreate,TeamDelete,TeamSay,)+from agentscope.app._types import SubAgentTemplatefrom agentscope.app.message_bus import RedisMessageBusfrom agentscope.app.storage import (AgentData,@@ -226,7 +228,6 @@ class TestAgentCreate(_TeamToolsTestBase):name="worker",description="does research",prompt="please look up X",- permission_mode="default",)self.assertDictEqual(chunk.model_dump(),@@ -321,7 +322,6 @@ class TestAgentCreate(_TeamToolsTestBase):name="worker",description="d",prompt="p",- permission_mode="default",)self.assertDictEqual(chunk.model_dump(),@@ -336,8 +336,8 @@ class TestAgentCreate(_TeamToolsTestBase):},)- async def test_rejects_unknown_permission_mode(self) -> None:- """An unrecognised ``permission_mode`` returns an error chunk."""+ async def test_rejects_unknown_subagent_type(self) -> None:+ """An unrecognised ``subagent_type`` returns an error chunk."""tool = AgentCreate(storage=self.storage,message_bus=self.bus,@@ -349,7 +349,7 @@ class TestAgentCreate(_TeamToolsTestBase):name="w",description="d",prompt="p",- permission_mode="not-a-mode", # type: ignore[arg-type]+ subagent_type="not-a-type",)self.assertDictEqual(chunk.model_dump(),@@ -378,7 +378,6 @@ class TestAgentCreate(_TeamToolsTestBase):name="worker",description="d",prompt="p",- permission_mode="default",)self.assertEqual(first.state.value, "running")@@ -386,7 +385,6 @@ class TestAgentCreate(_TeamToolsTestBase):name="worker",description="d",prompt="p",- permission_mode="default",)self.assertEqual(second.state.value, "error")@@ -414,7 +412,6 @@ class TestAgentCreate(_TeamToolsTestBase):name=self.leader_agent.data.name, # "leader"description="d",prompt="p",- permission_mode="default",)self.assertEqual(chunk.state.value, "error")@@ -428,6 +425,167 @@ class TestAgentCreate(_TeamToolsTestBase):self.assertEqual(team.data.member_ids, [])+class TestAgentCreateTemplates(_TeamToolsTestBase):+ """Template-aware ``AgentCreate`` behaviour: schema dynamics,+ template routing, and config isolation."""++ _explorer_template = SubAgentTemplate(+ type="explorer",+ description="Read-only exploration agent.",+ system_prompt_template=(+ "You are {member_name}, an explorer in team "+ "'{team_name}' led by {leader_name}.\n\n"+ "Team purpose: {team_description}\n\n"+ "Your role: {member_description}"+ ),+ )++ async def asyncSetUp(self) -> None:+ await super().asyncSetUp()+ await TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )(name="team", description="team desc")++ async def test_schema_omits_subagent_type_when_no_custom_templates(+ self,+ ) -> None:+ """When only the built-in ``"default"`` template exists, the+ ``input_schema`` must NOT contain a ``subagent_type`` field."""+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ self.assertNotIn("subagent_type", tool.input_schema["properties"])++ async def test_schema_includes_subagent_type_with_custom_templates(+ self,+ ) -> None:+ """When custom templates are registered, ``subagent_type`` appears+ in the schema with the correct enum values."""+ templates = {"explorer": self._explorer_template}+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ sub_agent_templates=templates,+ )+ self.assertIn("subagent_type", tool.input_schema["properties"])+ enum_values = tool.input_schema["properties"]["subagent_type"]["enum"]+ self.assertIn("default", enum_values)+ self.assertIn("explorer", enum_values)++ async def test_default_template_injected_when_missing(self) -> None:+ """The built-in default template is always available even when+ only custom templates are provided."""+ templates = {"explorer": self._explorer_template}+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ sub_agent_templates=templates,+ )+ self.assertIn("default", tool._sub_agent_templates)+ self.assertIs(+ tool._sub_agent_templates["default"],+ DEFAULT_SUB_AGENT_TEMPLATE,+ )++ async def test_custom_template_applies_system_prompt(self) -> None:+ """A worker created with a custom template gets the template's+ system prompt (not the default one)."""+ templates = {"explorer": self._explorer_template}+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ sub_agent_templates=templates,+ )+ chunk = await tool(+ name="scout",+ description="explores code",+ prompt="look around",+ subagent_type="explorer",+ )+ self.assertEqual(chunk.state.value, "running")++ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ worker_agent = await self.storage.get_agent(+ self.user_id,+ team.data.member_ids[0],+ )+ self.assertIn("an explorer in team", worker_agent.data.system_prompt)+ self.assertNotIn(+ "You communicate with the team leader",+ worker_agent.data.system_prompt,+ )++ async def test_configs_are_deep_copied(self) -> None:+ """Each spawned worker receives its own copy of the template's+ config objects — mutations must not leak across agents."""+ templates = {"explorer": self._explorer_template}+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ sub_agent_templates=templates,+ )+ await tool(+ name="w1",+ description="d",+ prompt="p",+ subagent_type="explorer",+ )+ await tool(+ name="w2",+ description="d",+ prompt="p",+ subagent_type="explorer",+ )++ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ a1 = await self.storage.get_agent(+ self.user_id,+ team.data.member_ids[0],+ )+ a2 = await self.storage.get_agent(+ self.user_id,+ team.data.member_ids[1],+ )+ self.assertIsNot(+ a1.data.context_config,+ a2.data.context_config,+ )+ self.assertIsNot(+ a1.data.react_config,+ a2.data.react_config,+ )++class TestTeamSay(_TeamToolsTestBase):"""``TeamSay`` delivers a HintBlock + wakeup to each addressedteammate."""@@ -453,13 +611,11 @@ class TestTeamSay(_TeamToolsTestBase):name="w1",description="d",prompt="p1",- permission_mode="default",)await agent_create(name="w2",description="d",prompt="p2",- permission_mode="default",)# Drain the pre-existing wakeups so subsequent assertions only# see what TeamSay enqueues.