AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend/copilot): make expert delegation and team state stale-proof (#14155)
Abhimanyu Yadavd7f2986baa37
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pyindex 66a09b9c2f..eb20b19160 100644--- a/autogpt_platform/backend/backend/copilot/permissions.py+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -110,6 +110,7 @@ ToolName = Literal["list_presets","list_schedules","list_skills",+ "list_team","list_workspace_files","memory_forget_confirm","memory_forget_search",diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.pyindex 86b8f405ca..e56266dd05 100644--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py@@ -40,6 +40,7 @@ from .graphiti_store import MemoryStoreToolfrom .handoff_to_expert import HandoffToExpertToolfrom .hire_expert import HireExpertToolfrom .list_agent_triggers import ListAgentTriggersTool+from .list_team import ListTeamToolfrom .manage_folders import (CreateFolderTool,DeleteFolderTool,@@ -123,6 +124,7 @@ TOOL_REGISTRY: dict[str, BaseTool] = {"run_sub_session": RunSubSessionTool(),"get_sub_session_result": GetSubSessionResultTool(),"delegate_to_expert": DelegateToExpertTool(),+ "list_team": ListTeamTool(),"TodoWrite": TodoWriteTool(),"run_mcp_tool": RunMCPToolTool(),"get_mcp_guide": GetMCPGuideTool(),@@ -211,6 +213,9 @@ TOOL_GROUPS: dict[str, ToolGroup] = {# and expert sessions alike), so it has its own group: the engines# disable it only when the user's hire-experts flag is off."delegate_to_expert": "delegation",+ # Read-only, but it shares the same gate: with the flag off there is no+ # team to list.+ "list_team": "delegation",}diff --git a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.pyindex c6005c1616..131992ea12 100644--- a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py+++ b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py@@ -44,7 +44,12 @@ from backend.copilot.sdk.session_waiter import run_copilot_turn_via_queuefrom backend.data.db_accessors import experts_dbfrom .base import BaseTool-from .expert_delegation import chain_refusal, safe_caller_name+from .expert_delegation import (+ chain_refusal,+ resolve_target_expert,+ safe_caller_name,+ unknown_target_message,+)from .models import DelegatedExpertInfo, ErrorResponse, ToolResponseBasefrom .run_sub_session import (MAX_SUB_SESSION_WAIT_SECONDS,@@ -88,8 +93,9 @@ class DelegateToExpertTool(BaseTool):"expert_id": {"type": "string","description": (- "Teammate to delegate to, from <team_context>. Must "- "not be you."+ "Teammate to delegate to: their expert id from "+ "<team_context>, or their exact name if you don't "+ "have the id. Must not be you."),},"prompt": {@@ -153,6 +159,14 @@ class DelegateToExpertTool(BaseTool):target = await self._load_delegate_target(user_id, target_id, session)if isinstance(target, ErrorResponse):return target+ if target.id == session.expert_id:+ # A name reference can resolve back to the caller even though the+ # raw-id self check above passed.+ return self._error(+ "You are that expert — do the work yourself, or use "+ "run_sub_session to isolate it in a fresh context.",+ session,+ )refusal = await chain_refusal(user_id, session, target)if refusal is not None:@@ -213,9 +227,7 @@ class DelegateToExpertTool(BaseTool):) -> Expert | ErrorResponse:"""Resolve the teammate, refusing anyone who can't safely take work."""try:- target = await experts_db().get_expert(- user_id, target_id, include_workflows=False- )+ target = await resolve_target_expert(user_id, target_id)except Exception as e:logger.warning(f"Delegate target lookup failed for {target_id}: {e}")return self._error(@@ -223,8 +235,7 @@ class DelegateToExpertTool(BaseTool):)if target is None or target.is_archived:return self._error(- f"No active expert with id {target_id} on this team. Pick one "- "of the teammates listed in your team context.",+ await unknown_target_message(user_id, target_id, session.expert_id),session,)if target.schedules_paused_at is not None:diff --git a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.py b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.pyindex efcd58b48e..015c5d324e 100644--- a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.py@@ -69,9 +69,17 @@ def roster(monkeypatch):async def fake_get_expert(user_id, expert_id, *, include_workflows=True, **_):return experts.get(expert_id)+ async def fake_list_experts(user_id, *, with_metrics=True, **_):+ return list(experts.values())+db = MagicMock()db.get_expert = fake_get_expert- for module in ("delegate_to_expert", "get_sub_session_result"):+ db.list_experts = fake_list_experts+ for module in (+ "delegate_to_expert",+ "get_sub_session_result",+ "expert_delegation",+ ):monkeypatch.setattr(f"backend.copilot.tools.{module}.experts_db", lambda: db, raising=True)@@ -224,6 +232,115 @@ class TestValidation:assert isinstance(r, ErrorResponse)mock_turn.assert_not_awaited()+ @pytest.mark.asyncio+ async def test_unknown_expert_error_carries_the_roster(+ self, roster, mock_turn, mock_sessions+ ):+ """The roster ids live only in the first message's <team_context>, so+ a session older than the team needs the error itself to teach them."""+ r = await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="expert-zzz",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ assert "Bea (expert_id: expert-b)" in r.message+ assert "Ari" not in r.message # the caller is not a valid target++ @pytest.mark.asyncio+ async def test_roster_hint_omits_paused_teammates(+ self, roster, mock_turn, mock_sessions+ ):+ """Both tools refuse a paused expert, so naming one in the hint just+ buys another failed call."""+ roster["expert-b"].schedules_paused_at = "2026-01-01T00:00:00Z"+ roster["expert-c"] = _expert("expert-c", "Cy")+ r = await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="expert-zzz",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ assert "Cy (expert_id: expert-c)" in r.message+ assert "expert-b" not in r.message++ @pytest.mark.asyncio+ async def test_db_failure_is_not_reported_as_a_missing_expert(+ self, roster, mock_turn, mock_sessions, monkeypatch+ ):+ """A transient lookup failure must not claim the teammate is gone —+ that reads as "re-raise them", which is how the loop starts."""++ async def boom(*_args, **_kwargs):+ raise RuntimeError("connection reset")++ async def fake_list_experts(user_id, *, with_metrics=True, **_):+ return list(roster.values())++ # Only the id lookup flakes: the roster read still works, so a broad+ # catch here would fall through to the name pass and mislabel a live+ # teammate as missing.+ db = MagicMock()+ db.get_expert = boom+ db.list_experts = fake_list_experts+ monkeypatch.setattr(+ "backend.copilot.tools.expert_delegation.experts_db",+ lambda: db,+ raising=True,+ )+ r = await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="expert-b",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ assert "Could not reach that expert right now" in r.message+ assert "No active expert" not in r.message+ mock_turn.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_name_reference_resolves_unique_teammate(+ self, roster, mock_turn, mock_sessions+ ):+ r = await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="bea",+ prompt="hi",+ wait_for_result=0,+ )+ assert not isinstance(r, ErrorResponse)+ assert mock_sessions[0].expert_id == "expert-b"++ @pytest.mark.asyncio+ async def test_ambiguous_name_rejected(self, roster, mock_turn, mock_sessions):+ roster["expert-c"] = _expert("expert-c", "Bea")+ r = await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="Bea",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ mock_turn.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_name_resolving_to_caller_rejected(+ self, roster, mock_turn, mock_sessions+ ):+ r = await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="Ari",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ assert "yourself" in r.message+ mock_turn.assert_not_awaited()+@pytest.mark.asyncioasync def test_archived_expert_rejected(self, roster, mock_turn, mock_sessions):roster["expert-b"].is_archived = Truediff --git a/autogpt_platform/backend/backend/copilot/tools/expert_change_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_change_test.pyindex 8da133b1cf..b9a1421125 100644--- a/autogpt_platform/backend/backend/copilot/tools/expert_change_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/expert_change_test.py@@ -135,9 +135,11 @@ def _env()db.get_expert = AsyncMock(return_value=_hired_otto())db.update_soul_if_current = AsyncMock(return_value=_created("Otto", "exp-2"))+ db.list_experts = AsyncMock(return_value=[])shared_redis = AsyncMock(return_value=redis or _FakeRedis())with (patch(f"{_HIRE_MODULE}.experts_db", MagicMock(return_value=db)),+ patch(f"{_RAISE_MODULE}.experts_db", MagicMock(return_value=db)),patch(f"{_UPDATE_MODULE}.experts_db", MagicMock(return_value=db)),patch(f"{_PROPOSAL_MODULE}.experts_db", MagicMock(return_value=db)),patch(f"{_HIRE_MODULE}.get_redis_async", shared_redis),@@ -268,6 +270,57 @@ class TestPreviewNeverWrites:assert len(redis.store) == 0db.create_raised_expert.assert_not_called()+ @pytest.mark.asyncio(loop_scope="session")+ async def test_raise_refuses_a_duplicate_active_name(self):+ """Re-raising an existing teammate is the observed stale-context+ loop — the model must be pointed at the live expert, not allowed to+ propose a twin."""+ with _env() as db:+ db.list_experts.return_value = [+ SimpleNamespace(+ id="exp-7", name="otto", role="Inbox triage", is_archived=False+ )+ ]+ resp = await _raise(make_session(_USER), **_CHARTER)+ assert isinstance(resp, ErrorResponse)+ assert "already exists" in resp.message+ assert "exp-7" in resp.message+ db.create_raised_expert.assert_not_called()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_raise_refuses_when_the_roster_cannot_be_read(self):+ """Nothing downstream enforces name uniqueness, so a roster read that+ failed must not pass for "no duplicate"."""+ with _env() as db:+ db.list_experts.side_effect = RuntimeError("connection reset")+ resp = await _raise(make_session(_USER), **_CHARTER)+ assert isinstance(resp, ErrorResponse)+ assert "Try again" in resp.message+ db.create_raised_expert.assert_not_called()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_a_matching_bug_is_not_dressed_up_as_a_roster_outage(self):+ """Only the read is recoverable — a bug in the name matching would+ otherwise be retried forever behind a "try again" message."""+ with _env() as db:+ db.list_experts.return_value = [+ SimpleNamespace(id="exp-7", name=None, role="Ops", is_archived=False)+ ]+ with pytest.raises(AttributeError):+ await _raise(make_session(_USER), **_CHARTER)+ db.create_raised_expert.assert_not_called()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_raise_allows_reusing_an_archived_name(self):+ with _env() as db:+ db.list_experts.return_value = [+ SimpleNamespace(+ id="exp-7", name="Otto", role="Inbox triage", is_archived=True+ )+ ]+ resp = await _raise(make_session(_USER), **_CHARTER)+ assert isinstance(resp, ExpertChangeProposedResponse)+class TestPreviewTimeLimits:@pytest.mark.asyncio(loop_scope="session")diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_delegation.py b/autogpt_platform/backend/backend/copilot/tools/expert_delegation.pyindex 6528d716fc..8e53513e89 100644--- a/autogpt_platform/backend/backend/copilot/tools/expert_delegation.py+++ b/autogpt_platform/backend/backend/copilot/tools/expert_delegation.py@@ -12,8 +12,13 @@ turn, so a bound that lives in only one of them is no bound at all — the modeljust passes the task on with the other tool."""+import logging+from backend.api.features.experts.models import Expertfrom backend.copilot.model import ChatSession, get_chat_session+from backend.data.db_accessors import experts_db++logger = logging.getLogger(__name__)# Long enough for a real name, short enough that a crafted one cannot bury the# preamble's own instructions under padding.@@ -40,6 +45,71 @@ def safe_caller_name(caller: str) -> str:return one_line[:CALLER_NAME_LIMIT].strip() or "a teammate"+async def resolve_target_expert(user_id: str, reference: str) -> Expert | None:+ """Resolve a teammate by id, falling back to a unique name match.++ The roster block that carries expert ids is injected only into the first+ user message, so a session opened before the team was hired knows its+ teammates by name alone. An id miss therefore retries as a+ case-insensitive name lookup; an ambiguous name stays unresolved so the+ model is told the roster instead of the tool guessing between twins.++ ``Expert.id`` is a plain string column, so a bare name simply misses here+ rather than raising — which leaves any exception meaning a real database+ failure. Those propagate to the caller, whose handler says "try again"+ instead of the flat lie that the teammate does not exist.+ """+ expert = await experts_db().get_expert(user_id, reference, include_workflows=False)+ if expert is not None:+ return expert+ wanted = reference.strip().casefold()+ if not wanted:+ return None+ matches = [+ e+ for e in await experts_db().list_experts(user_id, with_metrics=False)+ if not e.is_archived and e.name.strip().casefold() == wanted+ ]+ return matches[0] if len(matches) == 1 else None+++async def unknown_target_message(+ user_id: str, reference: str, exclude_expert_id: str | None+) -> str:+ """A lookup-failure message that carries the roster the model is missing.++ Sessions older than the team never saw a ``<team_context>`` block, so a+ bare "no such expert" leaves the model with nothing to retry with.++ Only teammates who can actually take work are offered: a paused expert is+ refused by both delegation tools, so naming one here would just buy+ another failed call.+ """+ fallback = (+ f"No active expert matching {reference!r} on this team. Pick a "+ "teammate from your team context."+ )+ try:+ experts = await experts_db().list_experts(user_id, with_metrics=False)+ except Exception as e:+ logger.warning(f"Roster lookup for delegation error failed: {e}")+ return fallback+ teammates = [+ e+ for e in experts+ if not e.is_archived+ and e.id != exclude_expert_id+ and e.schedules_paused_at is None+ ]+ if not teammates:+ return fallback+ roster = "; ".join(f"{e.name} (expert_id: {e.id})" for e in teammates)+ return (+ f"No active expert matching {reference!r} on this team. "+ f"Use one of these expert_ids: {roster}."+ )++async def chain_refusal(user_id: str, session: ChatSession, target: Expert) -> str | None:diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_proposal.py b/autogpt_platform/backend/backend/copilot/tools/expert_proposal.pyindex 516417febe..bca9968b2d 100644--- a/autogpt_platform/backend/backend/copilot/tools/expert_proposal.py+++ b/autogpt_platform/backend/backend/copilot/tools/expert_proposal.py@@ -101,8 +101,11 @@ def _stale_preview_error(session_id: str) -> ErrorResponse:return ErrorResponse(message=("This confirmation_id is unknown or has expired — previews last "- f"{PROPOSAL_TTL_MINUTES} minutes. Call {_PREVIEW_TOOLS} again for "- "a fresh preview."+ f"{PROPOSAL_TTL_MINUTES} minutes. If you already confirmed it "+ "earlier in this conversation, that change is APPLIED and the "+ "expert exists — call list_team to check before doing anything "+ f"else. Only call {_PREVIEW_TOOLS} again for a genuinely new "+ "change."),session_id=session_id,)diff --git a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.pyindex c1f65d228c..783bbe7d31 100644--- a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py+++ b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py@@ -40,7 +40,12 @@ from backend.copilot.sdk.session_waiter import (from backend.data.db_accessors import experts_dbfrom .base import BaseTool-from .expert_delegation import chain_refusal, safe_caller_name+from .expert_delegation import (+ chain_refusal,+ resolve_target_expert,+ safe_caller_name,+ unknown_target_message,+)from .models import (DelegatedExpertInfo,ErrorResponse,@@ -135,9 +140,17 @@ class HandoffToExpertTool(BaseTool):if refusal is not None:return self._error(refusal, session)try:- target = await self._resolve_target(user_id, target_id)+ target = await self._resolve_target(user_id, target_id, session.expert_id)except _HandoffRefused as refused:return self._error(refused.message, session)+ if target.id == session.expert_id:+ # A name reference can resolve back to the caller even though the+ # raw-id self check in _request_refusal passed.+ return self._error(+ "You are that expert — the task is already yours. Do it, or "+ "use run_sub_session to isolate it in a fresh context.",+ session,+ )chain = await chain_refusal(user_id, session, target)if chain is not None:return self._error(chain, session)@@ -222,12 +235,12 @@ class HandoffToExpertTool(BaseTool):def _error(self, message: str, session: ChatSession) -> ErrorResponse:return ErrorResponse(message=message, session_id=session.session_id)- async def _resolve_target(self, user_id: str, target_id: str) -> Expert:+ async def _resolve_target(+ self, user_id: str, target_id: str, caller_expert_id: str | None+ ) -> Expert:"""Resolve the teammate, refusing anyone who can't safely own work."""try:- target = await experts_db().get_expert(- user_id, target_id, include_workflows=False- )+ target = await resolve_target_expert(user_id, target_id)except Exception as e:logger.warning(f"Handoff target lookup failed for {target_id}: {e}")raise _HandoffRefused(@@ -235,8 +248,7 @@ class HandoffToExpertTool(BaseTool):) from eif target is None or target.is_archived:raise _HandoffRefused(- f"No active expert with id {target_id} on this team. Pick an "- "active teammate from your team."+ await unknown_target_message(user_id, target_id, caller_expert_id))if target.schedules_paused_at is not None:raise _HandoffRefused(diff --git a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.pyindex 3ee6bab732..8572352a84 100644--- a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py@@ -75,13 +75,18 @@ def roster(monkeypatch):async def fake_get_expert(user_id, expert_id, *, include_workflows=True, **_):return experts.get(expert_id)+ async def fake_list_experts(user_id, *, with_metrics=True, **_):+ return list(experts.values())+db = MagicMock()db.get_expert = fake_get_expert- monkeypatch.setattr(- "backend.copilot.tools.handoff_to_expert.experts_db",- lambda: db,- raising=True,- )+ db.list_experts = fake_list_experts+ for module in ("handoff_to_expert", "expert_delegation"):+ monkeypatch.setattr(+ f"backend.copilot.tools.{module}.experts_db",+ lambda: db,+ raising=True,+ )return experts@@ -191,6 +196,81 @@ class TestGuards:assert isinstance(r, ErrorResponse)mock_turn.assert_not_awaited()+ @pytest.mark.asyncio+ async def test_db_failure_is_not_reported_as_a_missing_expert(+ self, roster, mock_turn, mock_sessions, monkeypatch+ ):+ """A transient lookup failure must not claim the teammate is gone —+ that reads as "re-raise them", which is how the loop starts."""++ async def boom(*_args, **_kwargs):+ raise RuntimeError("connection reset")++ async def fake_list_experts(user_id, *, with_metrics=True, **_):+ return list(roster.values())++ # Only the id lookup flakes: the roster read still works, so a broad+ # catch here would fall through to the name pass and mislabel a live+ # teammate as missing.+ db = MagicMock()+ db.get_expert = boom+ db.list_experts = fake_list_experts+ monkeypatch.setattr(+ "backend.copilot.tools.expert_delegation.experts_db",+ lambda: db,+ raising=True,+ )+ r = await HandoffToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="expert-b",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ assert "Could not reach that expert right now" in r.message+ assert "No active expert" not in r.message+ mock_turn.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_name_reference_resolves_unique_teammate(+ self, roster, mock_turn, mock_sessions+ ):+ r = await HandoffToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="bea",+ prompt="hi",+ )+ assert not isinstance(r, ErrorResponse)+ assert mock_sessions[0].expert_id == "expert-b"++ @pytest.mark.asyncio+ async def test_name_resolving_to_caller_rejected(+ self, roster, mock_turn, mock_sessions+ ):+ r = await HandoffToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="Ari",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ mock_turn.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_unknown_target_error_carries_the_roster(+ self, roster, mock_turn, mock_sessions+ ):+ r = await HandoffToExpertTool()._execute(+ user_id="alice",+ session=_session(expert_id="expert-a"),+ expert_id="expert-zzz",+ prompt="hi",+ )+ assert isinstance(r, ErrorResponse)+ assert "Bea (expert_id: expert-b)" in r.message+ assert "Ari" not in r.message+@pytest.mark.asyncioasync def test_archived_target_rejected(self, roster, mock_turn, mock_sessions):roster["expert-b"].is_archived = Truediff --git a/autogpt_platform/backend/backend/copilot/tools/list_team.py b/autogpt_platform/backend/backend/copilot/tools/list_team.pynew file mode 100644index 0000000000..ee2a75e0f1--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/list_team.py@@ -0,0 +1,98 @@+"""Read the user's current expert roster (never writes).++The ``<team_context>`` roster block is injected only into a session's first+user message, so any team change after that — a hire confirmed three turns+ago, an expert archived from the Team page — is invisible to the model. The+observed failure mode is an expensive guess: the model re-proposes an expert+who already exists, or "checks" existence by delegating a ping. This tool+gives it a cheap, authoritative read instead.+"""++import logging+from typing import Any++from backend.copilot.model import ChatSession+from backend.data.db_accessors import experts_db++from .base import BaseTool+from .models import ErrorResponse, TeamExpertInfo, TeamRosterResponse, ToolResponseBase++logger = logging.getLogger(__name__)+++class ListTeamTool(BaseTool):+ """List the experts currently on the user's team."""++ @property+ def name(self) -> str:+ return "list_team"++ @property+ def requires_auth(self) -> bool:+ return True++ @property+ def description(self) -> str:+ return (+ "List the experts currently on the user's team (name, expert_id, "+ "role, paused state). The roster in <team_context> is a snapshot "+ "from the start of this chat — call this before hiring, raising, "+ "or delegating whenever the team may have changed since, or when "+ "an expert lookup failed."+ )++ @property+ def parameters(self) -> dict[str, Any]:+ return {"type": "object", "properties": {}}++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ if user_id is None:+ return ErrorResponse(+ message="Authentication required", session_id=session.session_id+ )+ try:+ experts = await experts_db().list_experts(user_id, with_metrics=False)+ except Exception as e:+ logger.warning(f"list_team roster lookup failed: {e}")+ return ErrorResponse(+ message="Could not load the team right now. Try again.",+ session_id=session.session_id,+ )+ active = [e for e in experts if not e.is_archived]+ if not active:+ return TeamRosterResponse(+ message=(+ "The team is empty — no experts exist yet. hire_expert or "+ "raise_expert (with user approval) is how one joins."+ ),+ session_id=session.session_id,+ )+ lines = "; ".join(+ f"{e.name} — {e.role} (expert_id: {e.id})"+ + (" [paused]" if e.schedules_paused_at is not None else "")+ for e in active+ )+ return TeamRosterResponse(+ message=(+ f"{len(active)} expert{'s' if len(active) != 1 else ''} on the "+ f"team: {lines}. Use these expert_ids with delegate_to_expert; "+ "never re-raise an expert who is already listed here."+ ),+ session_id=session.session_id,+ experts=[+ TeamExpertInfo(+ id=e.id,+ name=e.name,+ role=e.role,+ color=e.color,+ avatar_url=e.avatar_url,+ is_paused=e.schedules_paused_at is not None,+ )+ for e in active+ ],+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/list_team_test.py b/autogpt_platform/backend/backend/copilot/tools/list_team_test.pynew file mode 100644index 0000000000..962f85e34a--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/list_team_test.py@@ -0,0 +1,96 @@+"""Tests for ListTeamTool — the model's live view of the roster."""++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from ._test_data import make_session+from .list_team import ListTeamTool+from .models import ErrorResponse, TeamRosterResponse++_USER = "user-list-team"+++def _expert(+ expert_id: str = "exp-1",+ name: str = "Vera",+ *,+ is_archived: bool = False,+ schedules_paused_at=None,+):+ return SimpleNamespace(+ id=expert_id,+ name=name,+ role="Market research",+ color="violet-300",+ avatar_url=None,+ is_archived=is_archived,+ schedules_paused_at=schedules_paused_at,+ )+++def _patch_db(monkeypatch, experts):+ db = MagicMock()+ db.list_experts = AsyncMock(return_value=experts)+ monkeypatch.setattr(+ "backend.copilot.tools.list_team.experts_db", lambda: db, raising=True+ )+ return db+++async def test_lists_active_experts_with_ids(monkeypatch):+ _patch_db(monkeypatch, [_expert(), _expert("exp-2", "Max")])+ result = await ListTeamTool()._execute(user_id=_USER, session=make_session(_USER))+ assert isinstance(result, TeamRosterResponse)+ assert [e.id for e in result.experts] == ["exp-1", "exp-2"]+ assert "Vera" in result.message+ assert "exp-2" in result.message+++async def test_archived_experts_are_excluded(monkeypatch):+ _patch_db(monkeypatch, [_expert(), _expert("exp-9", "Old", is_archived=True)])+ result = await ListTeamTool()._execute(user_id=_USER, session=make_session(_USER))+ assert isinstance(result, TeamRosterResponse)+ assert [e.id for e in result.experts] == ["exp-1"]+ assert "Old" not in result.message+++async def test_paused_experts_are_flagged(monkeypatch):+ _patch_db(+ monkeypatch,+ [_expert(schedules_paused_at="2026-01-01T00:00:00Z")],+ )+ result = await ListTeamTool()._execute(user_id=_USER, session=make_session(_USER))+ assert isinstance(result, TeamRosterResponse)+ assert result.experts[0].is_paused is True+ assert "[paused]" in result.message+++async def test_empty_team_says_so(monkeypatch):+ _patch_db(monkeypatch, [])+ result = await ListTeamTool()._execute(user_id=_USER, session=make_session(_USER))+ assert isinstance(result, TeamRosterResponse)+ assert result.experts == []+ assert "empty" in result.message+++async def test_lookup_failure_returns_error(monkeypatch):+ db = MagicMock()+ db.list_experts = AsyncMock(side_effect=RuntimeError("db down"))+ monkeypatch.setattr(+ "backend.copilot.tools.list_team.experts_db", lambda: db, raising=True+ )+ result = await ListTeamTool()._execute(user_id=_USER, session=make_session(_USER))+ assert isinstance(result, ErrorResponse)+++async def test_requires_auth():+ result = await ListTeamTool()._execute(user_id=None, session=make_session(_USER))+ assert isinstance(result, ErrorResponse)diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex b728797fde..a5505861ad 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -127,6 +127,7 @@ class ResponseType(str, Enum):EXPERT_SOUL_UPDATED = "expert_soul_updated"EXPERT_CHANGE_PROPOSED = "expert_change_proposed"EXPERT_CHANGE_APPLIED = "expert_change_applied"+ TEAM_ROSTER = "team_roster"# Base response model@@ -576,6 +577,24 @@ class ExpertSummary(BaseModel):color: str = ""+class TeamExpertInfo(BaseModel):+ """One roster row returned by ``list_team``."""++ id: str+ name: str+ role: str+ color: str = ""+ avatar_url: str | None = None+ is_paused: bool = False+++class TeamRosterResponse(ToolResponseBase):+ """The user's current expert roster, straight from the DB."""++ type: ResponseType = ResponseType.TEAM_ROSTER+ experts: list[TeamExpertInfo] = Field(default_factory=list)++class ExpertChangeProposedResponse(ToolResponseBase):"""Preview returned by ``hire_expert`` / ``raise_expert`` — never a write.diff --git a/autogpt_platform/backend/backend/copilot/tools/raise_expert.py b/autogpt_platform/backend/backend/copilot/tools/raise_expert.pyindex 8ba272bef7..60fd1ec799 100644--- a/autogpt_platform/backend/backend/copilot/tools/raise_expert.py+++ b/autogpt_platform/backend/backend/copilot/tools/raise_expert.py@@ -7,6 +7,7 @@ charter — what the expert owns, what good looks like, and where they stop —before the user is ever asked to approve."""+import loggingimport uuidfrom typing import Any@@ -16,9 +17,11 @@ from backend.api.features.experts.models import (EXPERT_COLOR_MAX_LENGTH,EXPERT_NAME_MAX_LENGTH,WEEKLY_BUDGET_MAX_CREDITS,+ Expert,ExpertSoulFieldsPatch,)from backend.copilot.model import ChatSession+from backend.data.db_accessors import experts_dbfrom backend.data.redis_client import get_redis_asyncfrom .base import BaseTool@@ -58,6 +61,9 @@ COLOR_TOKENS = []+logger = logging.getLogger(__name__)++class _RaiseParams(BaseModel):"""Non-Soul raise fields, validated with the same bounds as the API."""@@ -200,6 +206,28 @@ class RaiseExpertTool(BaseTool):),session_id=session_id,)+ try:+ duplicate = await _active_expert_named(user_id, params.name)+ except _RosterUnavailable as e:+ # Nothing downstream enforces name uniqueness, so a roster read we+ # could not perform must not pass for "no duplicate".+ logger.warning(f"raise_expert duplicate-name check failed: {e}")+ return ErrorResponse(+ message="Could not check the team roster right now. Try again.",+ session_id=session_id,+ )+ if duplicate:+ return ErrorResponse(+ message=(+ f"An active expert named {duplicate.name} already exists "+ f"(expert_id: {duplicate.id}, role: {duplicate.role}) — "+ "do not raise them again. Delegate work to them with "+ "delegate_to_expert, or change their charter with "+ "update_expert. Only propose a differently-named expert "+ "if the user truly wants a second, separate one."+ ),+ session_id=session_id,+ )if error := await capacity_error(user_id, session_id, "raise"):return error@@ -238,6 +266,31 @@ class RaiseExpertTool(BaseTool):)+class _RosterUnavailable(Exception):+ """The roster could not be read — distinct from "nobody has this name"."""+++async def _active_expert_named(user_id: str, name: str) -> Expert | None:+ """The active expert already carrying *name*, or None.++ Only the read is treated as recoverable: a bug in the matching below is+ not a roster outage and propagates instead of being retried forever.+ """+ try:+ experts = await experts_db().list_experts(user_id, with_metrics=False)+ except Exception as e:+ raise _RosterUnavailable(str(e)) from e+ wanted = name.strip().casefold()+ return next(+ (+ expert+ for expert in experts+ if not expert.is_archived and expert.name.strip().casefold() == wanted+ ),+ None,+ )++def _validation_detail(error: ValidationError) -> str:return "; ".join(f"{'.'.join(str(loc) for loc in err['loc'])}: {err['msg']}"diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 943ec5e452..049e529259 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -24430,7 +24430,8 @@"skill_list","expert_soul_updated","expert_change_proposed",- "expert_change_applied"+ "expert_change_applied",+ "team_roster"],"title": "ResponseType","description": "Types of tool responses."