Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(agent-team): inherit permission context from the team leader (#1815)
Yufeng Hefd0470105ae9
diff --git a/src/agentscope/app/_tools/_agent_create.py b/src/agentscope/app/_tools/_agent_create.pyindex 0acd495da..381d393b8 100644--- a/src/agentscope/app/_tools/_agent_create.py+++ b/src/agentscope/app/_tools/_agent_create.py@@ -12,6 +12,7 @@ from ._team_tool_base import _TeamToolBasefrom .._types import SubAgentTemplatefrom ..storage import AgentData, AgentRecord, SessionConfigfrom ...message import HintBlock, TextBlock, ToolResultState+from ...permission import PermissionContextfrom ...state import AgentStatefrom ...tool import ToolChunk, ParamsBase@@ -35,6 +36,9 @@ DEFAULT_SUB_AGENT_TEMPLATE = SubAgentTemplate(type="default",description="Default worker agent with standard configuration.",system_prompt_template=_DEFAULT_SYSTEM_PROMPT_TEMPLATE,+ override_leader_mode=False,+ extend_leader_permission_rules=True,+ extend_leader_working_directories=True,)# The built-in default sub-agent template.#@@ -43,6 +47,59 @@ DEFAULT_SUB_AGENT_TEMPLATE = SubAgentTemplate(# explicitly specifies ``subagent_type="default"``). Developers can# override this by registering their own template with# ``type="default"`` via :func:`~agentscope.app.create_app`.+#+# The default template fully follows the leader: the worker inherits+# the leader's permission mode, working directories, and rules —+# matching the intuition that a generic worker should behave like the+# leader unless the developer registers a more opinionated template.+++def _merge_leader_permissions(+ template: SubAgentTemplate,+ leader_context: PermissionContext,+) -> PermissionContext:+ """Build the worker's permission context from the template, layered+ with the leader's runtime state according to the template's three+ inherit-from-leader flags.++ - ``override_leader_mode``: if True, the template's+ :attr:`PermissionContext.mode` wins; otherwise the worker+ inherits the leader's mode.+ - ``extend_leader_permission_rules``: if True, the leader's+ allow/deny/ask rules are appended after the template's rules for+ each tool, so the worker doesn't re-prompt for permissions the+ user has already granted in the leader session. The template's+ rules appear first in each list, so the engine — which returns+ on the first matching rule per stage — evaluates the template's+ intent before the leader's.+ - ``extend_leader_working_directories``: if True, the leader's+ working directories are merged in; on key (path) collisions the+ template's entry wins.++ The template fields are deep-copied so the returned context is+ independent of both the template and the leader state.+ """+ merged = template.permission_context.model_copy(deep=True)++ if not template.override_leader_mode:+ merged.mode = leader_context.mode++ if template.extend_leader_working_directories:+ for path, wd in leader_context.working_directories.items():+ merged.working_directories.setdefault(+ path,+ wd.model_copy(deep=True),+ )++ if template.extend_leader_permission_rules:+ for attr in ("allow_rules", "deny_rules", "ask_rules"):+ merged_rules: dict = getattr(merged, attr)+ for tool_name, rules in getattr(leader_context, attr).items():+ merged_rules.setdefault(tool_name, []).extend(+ r.model_copy(deep=True) for r in rules+ )++ return mergedclass _AgentCreateParams(ParamsBase):@@ -80,6 +137,7 @@ class AgentCreate(_TeamToolBase):"""Spawn a new worker member into the team you lead."""name: str = "AgentCreate"+ is_state_injected: bool = Truedescription: str = """Add a new member to the team you lead.@@ -190,6 +248,7 @@ optional):description: str,prompt: str,subagent_type: str = "default",+ _agent_state: AgentState | None = None,) -> ToolChunk:"""Spawn the worker agent + session directly via storage.@@ -199,7 +258,11 @@ optional):The worker's configuration (system prompt, context/reactconfig, permission context, task context) is determined by- the :class:`SubAgentTemplate` matching ``subagent_type``.+ the :class:`SubAgentTemplate` matching ``subagent_type``. The+ leader's user-confirmed permission rules and working+ directories are merged into the template's permission context+ so the worker does not re-prompt for permissions the user has+ already granted.Args:name (`str`):@@ -212,6 +275,8 @@ optional):subagent_type (`str`, defaults to ``"default"``):Template type to use. Must match a registered:class:`SubAgentTemplate.type`.+ _agent_state (`AgentState | None`, optional):+ Live leader state injected by the toolkit.Returns:`ToolChunk`:@@ -372,11 +437,22 @@ optional):await self._storage.upsert_agent(self._user_id, worker_agent)# 2. Build worker SessionRecord, inheriting leader's model- # config.+ # config. The template's permission context is the base;+ # on top of it we merge the leader's mode and/or rules+ # and/or working directories according to the template's+ # inherit-from-leader flags. See+ # :func:`_merge_leader_permissions` for the policy.+ leader_permission_context = (+ _agent_state.permission_context+ if _agent_state is not None+ else leader_session.state.permission_context+ )+ worker_permission_context = _merge_leader_permissions(+ template,+ leader_permission_context,+ )worker_state = AgentState(- permission_context=template.permission_context.model_copy(- deep=True,- ),+ permission_context=worker_permission_context,tasks_context=template.tasks_context.model_copy(deep=True,),diff --git a/src/agentscope/app/_types.py b/src/agentscope/app/_types.pyindex df7513b80..fa01c4b45 100644--- a/src/agentscope/app/_types.py+++ b/src/agentscope/app/_types.py@@ -88,6 +88,44 @@ class SubAgentTemplate(BaseModel):),)+ override_leader_mode: bool = Field(+ default=False,+ description=(+ "Whether the template's :attr:`permission_context.mode` "+ "should override the leader session's mode for the worker. "+ "``True`` — the worker runs in the template's mode "+ "(typical for templates that pin a specific posture, e.g. "+ "a read-only research worker). ``False`` (default) — the "+ "worker inherits the leader's current mode."+ ),+ )++ extend_leader_permission_rules: bool = Field(+ default=True,+ description=(+ "Whether the leader session's allow/deny/ask permission "+ "rules should be merged on top of the template's. "+ "``True`` (default) — leader rules are appended after "+ "the template's rules for each tool, so the worker "+ "doesn't re-prompt for permissions the user has already "+ "confirmed; the template's rules take precedence on "+ "evaluation order. ``False`` — the template's rules are "+ "the worker's complete rule set."+ ),+ )++ extend_leader_working_directories: bool = Field(+ default=True,+ description=(+ "Whether the leader session's working directories should "+ "be merged into the template's. ``True`` (default) — "+ "leader directories are added for keys not already in the "+ "template (template wins on key collisions). ``False`` — "+ "the template's working directories are the worker's "+ "complete set."+ ),+ )+tasks_context: TaskContext = Field(default_factory=TaskContext,description=(diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pyindex ca18e5321..94bac2aff 100644--- a/tests/service_team_tools_test.py+++ b/tests/service_team_tools_test.py@@ -37,6 +37,14 @@ from agentscope.app.storage import (RedisStorage,SessionConfig,)+from agentscope.permission import (+ AdditionalWorkingDirectory,+ PermissionBehavior,+ PermissionContext,+ PermissionMode,+ PermissionRule,+)+from agentscope.state import AgentStatedef _make_storage(@@ -302,6 +310,236 @@ class TestAgentCreate(_TeamToolsTestBase):},)+ async def _spawn_worker_with_template(+ self,+ leader_state: AgentState,+ template: SubAgentTemplate,+ worker_name: str = "worker",+ ) -> PermissionContext:+ """Run ``AgentCreate`` with the given template + leader state+ and return the worker session's :class:`PermissionContext`."""+ 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={template.type: template},+ )+ chunk = await tool(+ name=worker_name,+ description="does work",+ prompt="work in the repo",+ subagent_type=template.type,+ _agent_state=leader_state,+ )+ 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)+ # The worker is whichever member was added last.+ worker_agent_id = team.data.member_ids[-1]+ worker_sessions = await self.storage.list_sessions(+ self.user_id,+ worker_agent_id,+ )+ return worker_sessions[0].state.permission_context++ def _make_leader_state(self) -> AgentState:+ """Build a leader :class:`AgentState` with one of every kind of+ permission entry, so tests can assert which pieces leak through+ each flag."""+ return AgentState(+ permission_context=PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ "/tmp/as-workspace": AdditionalWorkingDirectory(+ path="/tmp/as-workspace",+ source="session",+ ),+ },+ allow_rules={+ "Bash": [+ PermissionRule(+ tool_name="Bash",+ rule_content="git status",+ behavior=PermissionBehavior.ALLOW,+ source="session",+ ),+ ],+ },+ ),+ )++ async def test_default_template_follows_leader_completely(self) -> None:+ """The built-in default template inherits the leader's mode,+ working directories, and rules — its own+ :attr:`permission_context` is empty, so the worker effectively+ mirrors the leader."""+ leader_state = self._make_leader_state()+ worker_context = await self._spawn_worker_with_template(+ leader_state,+ DEFAULT_SUB_AGENT_TEMPLATE,+ )+ self.assertEqual(worker_context.mode, PermissionMode.ACCEPT_EDITS)+ self.assertIn("/tmp/as-workspace", worker_context.working_directories)+ self.assertEqual(+ worker_context.allow_rules["Bash"][0].rule_content,+ "git status",+ )++ async def test_override_leader_mode_pins_template_mode(self) -> None:+ """When ``override_leader_mode=True`` the template's mode wins."""+ leader_state = self._make_leader_state()+ explorer = SubAgentTemplate(+ type="explorer",+ description="Read-only worker.",+ system_prompt_template=(+ DEFAULT_SUB_AGENT_TEMPLATE.system_prompt_template+ ),+ permission_context=PermissionContext(+ mode=PermissionMode.EXPLORE,+ ),+ override_leader_mode=True,+ )+ worker_context = await self._spawn_worker_with_template(+ leader_state,+ explorer,+ )+ self.assertEqual(worker_context.mode, PermissionMode.EXPLORE)+ # Rules and dirs still inherited (defaults).+ self.assertIn("/tmp/as-workspace", worker_context.working_directories)+ self.assertIn("Bash", worker_context.allow_rules)++ async def test_extend_flags_off_isolate_template(self) -> None:+ """``extend_*=False`` keeps the leader's rules and dirs out of+ the worker; the template's own entries are the worker's+ complete set."""+ leader_state = self._make_leader_state()+ sandbox = SubAgentTemplate(+ type="sandbox",+ description="Fully isolated worker.",+ system_prompt_template=(+ DEFAULT_SUB_AGENT_TEMPLATE.system_prompt_template+ ),+ permission_context=PermissionContext(+ mode=PermissionMode.BYPASS,+ deny_rules={+ "Write": [+ PermissionRule(+ tool_name="Write",+ rule_content=None,+ behavior=PermissionBehavior.DENY,+ source="template",+ ),+ ],+ },+ ),+ override_leader_mode=True,+ extend_leader_permission_rules=False,+ extend_leader_working_directories=False,+ )+ worker_context = await self._spawn_worker_with_template(+ leader_state,+ sandbox,+ )+ self.assertEqual(worker_context.mode, PermissionMode.BYPASS)+ self.assertEqual(worker_context.working_directories, {})+ self.assertNotIn("Bash", worker_context.allow_rules)+ # Template's own deny rule is preserved.+ self.assertEqual(+ worker_context.deny_rules["Write"][0].source,+ "template",+ )++ async def test_extend_rules_keeps_template_rules_first(self) -> None:+ """When merging rules for the same tool, the template's rules+ appear first in the list so the engine evaluates them before+ the leader's."""+ leader_state = AgentState(+ permission_context=PermissionContext(+ mode=PermissionMode.DEFAULT,+ allow_rules={+ "Bash": [+ PermissionRule(+ tool_name="Bash",+ rule_content="git status",+ behavior=PermissionBehavior.ALLOW,+ source="session",+ ),+ ],+ },+ ),+ )+ template = SubAgentTemplate(+ type="custom",+ description="Custom worker.",+ system_prompt_template=(+ DEFAULT_SUB_AGENT_TEMPLATE.system_prompt_template+ ),+ permission_context=PermissionContext(+ allow_rules={+ "Bash": [+ PermissionRule(+ tool_name="Bash",+ rule_content="ls",+ behavior=PermissionBehavior.ALLOW,+ source="template",+ ),+ ],+ },+ ),+ )+ worker_context = await self._spawn_worker_with_template(+ leader_state,+ template,+ )+ bash_rules = worker_context.allow_rules["Bash"]+ self.assertEqual(+ [r.source for r in bash_rules],+ ["template", "session"],+ )++ async def test_extend_dirs_template_wins_on_collision(self) -> None:+ """When the template and leader both declare the same working+ directory path, the template's entry is kept."""+ leader_state = AgentState(+ permission_context=PermissionContext(+ working_directories={+ "/tmp/shared": AdditionalWorkingDirectory(+ path="/tmp/shared",+ source="session",+ ),+ },+ ),+ )+ template = SubAgentTemplate(+ type="custom",+ description="Custom worker.",+ system_prompt_template=(+ DEFAULT_SUB_AGENT_TEMPLATE.system_prompt_template+ ),+ permission_context=PermissionContext(+ working_directories={+ "/tmp/shared": AdditionalWorkingDirectory(+ path="/tmp/shared",+ source="template",+ ),+ },+ ),+ )+ worker_context = await self._spawn_worker_with_template(+ leader_state,+ template,+ )+ self.assertEqual(+ worker_context.working_directories["/tmp/shared"].source,+ "template",+ )+async def test_rejects_when_not_in_team(self) -> None:"""Calling ``AgentCreate`` from a session that hasn't run``TeamCreate`` yet returns an error chunk."""