Skip to content

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.

feat(backend): experts run only installed workflows with granted credentials (#14415)

Abhimanyu Yadav2ee0819cc530
diff --git a/autogpt_platform/backend/backend/api/features/experts/credentials.py b/autogpt_platform/backend/backend/api/features/experts/credentials.py
index d8f3da2313..b67d5044c8 100644
--- a/autogpt_platform/backend/backend/api/features/experts/credentials.py
+++ b/autogpt_platform/backend/backend/api/features/experts/credentials.py
@@ -14,6 +14,7 @@ or no expert could run a single LLM block.
import logging
from datetime import datetime, timezone
+from typing import TYPE_CHECKING
import prisma.models
@@ -23,6 +24,9 @@ from backend.data.model import Credentials
from backend.integrations.credentials_store import is_system_credential
from backend.util.exceptions import ExpertNotFoundError
+if TYPE_CHECKING:
+ from backend.data.graph import GraphModel
+
logger = logging.getLogger(__name__)
_WORKFLOW_INCLUDE = {"Workflows": {"include": {"LibraryAgent": True}}}
@@ -65,6 +69,7 @@ async def _derive_from_workflows(
derived: dict[str, str] = {}
is_complete = True
+ owned_ids: set[str] | None = None
for workflow in expert.Workflows or []:
library_agent = workflow.LibraryAgent
if library_agent is None:
@@ -81,6 +86,9 @@ async def _derive_from_workflows(
if graph is None:
continue
matched, _ = await match_user_credentials_to_graph(user_id, graph)
+ pickers = _picker_credential_ids(graph)
+ if pickers and owned_ids is None:
+ owned_ids = {c.id for c in await _user_credentials(user_id)}
except Exception:
logger.warning(
f"Could not derive credentials for workflow #{workflow.id} on "
@@ -92,9 +100,36 @@ async def _derive_from_workflows(
for meta in matched.values():
if not is_system_credential(meta.id):
derived[meta.id] = str(meta.provider)
+ for credential_id, provider in pickers.items():
+ if credential_id in (owned_ids or set()) and not is_system_credential(
+ credential_id
+ ):
+ derived.setdefault(credential_id, provider)
return derived, is_complete
+def _picker_credential_ids(graph: "GraphModel") -> dict[str, str]:
+ """Credential id → provider for picker-populated fields (``_credentials_id``).
+
+ These never appear in ``match_user_credentials_to_graph``, which only sees
+ explicit credential fields, yet the executor holds them to the same grants.
+ """
+ found: dict[str, str] = {}
+ for part in [graph, *graph.sub_graphs]:
+ for node in part.nodes:
+ if not node.input_default:
+ continue
+ for info in node.block.input_schema.get_auto_credentials_fields().values():
+ value = node.input_default.get(info["field_name"])
+ if isinstance(value, dict) and isinstance(
+ value.get("_credentials_id"), str
+ ):
+ found[value["_credentials_id"]] = str(
+ info.get("config", {}).get("provider", "unknown")
+ )
+ return found
+
+
async def _seed_if_needed(user_id: str, expert: prisma.models.Expert) -> None:
"""Seed the allow-list from the expert's workflows, once.
@@ -240,6 +275,19 @@ async def revoke_expert_credential(
return _to_refs(await _grants(expert_id), await _user_credentials(user_id))
+async def settle_credential_seed(user_id: str, expert_id: str) -> None:
+ """Freeze the allow-list before the expert changes its own workflows.
+
+ Seeding derives grants from installed workflows, so an install made from
+ the expert's own session must not be able to feed it. Stamped even when a
+ workflow failed to derive: a missing grant is visible and fixable, while a
+ self-granted one is not.
+ """
+ expert = await _owned_expert(user_id, expert_id)
+ await _seed_if_needed(user_id, expert)
+ await _stamp_seeded(expert.id)
+
+
async def expert_allowed_credential_ids(user_id: str, expert_id: str) -> list[str]:
"""The credential ids *expert_id* may use. Enforcement's source of truth.
diff --git a/autogpt_platform/backend/backend/api/features/experts/credentials_test.py b/autogpt_platform/backend/backend/api/features/experts/credentials_test.py
index ef9324c8dd..44bc4d53c0 100644
--- a/autogpt_platform/backend/backend/api/features/experts/credentials_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/credentials_test.py
@@ -11,6 +11,7 @@ from backend.api.features.experts.credentials import (
_derive_from_workflows,
_to_refs,
filter_credentials_for_expert,
+ settle_credential_seed,
)
from backend.data.model import APIKeyCredentials, CredentialsMetaInput
from backend.executor.utils import _enforce_expert_credential_scope
@@ -201,3 +202,25 @@ async def test_a_run_with_no_credentials_skips_the_lookup_entirely(
await _enforce_expert_credential_scope("user-1", "expert-1", None)
accessor.assert_not_called()
+
+
+async def test_settling_the_seed_stamps_even_when_derivation_was_incomplete(
+ mocker: pytest_mock.MockFixture,
+):
+ expert = SimpleNamespace(id="expert-1", Workflows=[], credentialsSeededAt=None)
+ mocker.patch(
+ "backend.api.features.experts.credentials._owned_expert",
+ AsyncMock(return_value=expert),
+ )
+ seed = mocker.patch(
+ "backend.api.features.experts.credentials._seed_if_needed", AsyncMock()
+ )
+ stamp = mocker.patch(
+ "backend.api.features.experts.credentials._stamp_seeded", AsyncMock()
+ )
+
+ await settle_credential_seed("user-1", "expert-1")
+
+ seed.assert_awaited_once_with("user-1", expert)
+ stamp.assert_awaited_once_with("expert-1")
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 3ef1e3d54d..702adb2b26 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -21,6 +21,18 @@ from backend.api.features.experts.credential_counts import expert_credential_pro
from backend.api.features.experts.credentials import (
expert_allowed_credential_ids as expert_allowed_credential_ids,
)
+from backend.api.features.experts.credentials import (
+ grant_expert_credentials as grant_expert_credentials,
+)
+from backend.api.features.experts.credentials import (
+ list_expert_credentials as list_expert_credentials,
+)
+from backend.api.features.experts.credentials import (
+ revoke_expert_credential as revoke_expert_credential,
+)
+from backend.api.features.experts.credentials import (
+ settle_credential_seed as settle_credential_seed,
+)
from backend.api.features.experts.errors import (
ACTIVE_EXPERT_LIMIT,
LIFETIME_RAISED_EXPERT_LIMIT,
@@ -1784,10 +1796,12 @@ async def _install_marketplace_workflow(
return _to_workflow_ref(row)
-async def remove_workflow(user_id: str, expert_id: str, workflow_id: str) -> None:
- """Detach a workflow from a hired expert, dropping its install-time
- schedule. The library agent itself is left alone — it is still the
- user's, and another expert may share it."""
+async def remove_workflow(user_id: str, expert_id: str, workflow_id: str) -> list[str]:
+ """Detach a workflow from a hired expert and stop its triggers.
+
+ Returns the names of the triggers that were paused or deactivated, so the
+ caller can say what it stopped. The library agent itself is left alone — it
+ is still the user's, and another expert may share it."""
expert = await prisma.models.Expert.prisma().find_first(
where={
"id": expert_id,
@@ -1801,14 +1815,24 @@ async def remove_workflow(user_id: str, expert_id: str, workflow_id: str) -> Non
raise ExpertNotFoundError(expert_id)
row = await prisma.models.ExpertWorkflow.prisma().find_first(
- where={"id": workflow_id, "expertId": expert_id}
+ where={"id": workflow_id, "expertId": expert_id},
+ include={"LibraryAgent": True},
)
if row is None:
raise NotFoundError(f"Workflow #{workflow_id} not found on expert")
if row.scheduleId:
await scheduling.delete_workflow_schedule(row.scheduleId, user_id, expert_id)
+ stopped: list[str] = []
+ if row.LibraryAgent is not None:
+ stopped = await scheduling.suspend_workflow_triggers(
+ user_id,
+ expert_id,
+ row.LibraryAgent.agentGraphId,
+ except_schedule_id=row.scheduleId,
+ )
await prisma.models.ExpertWorkflow.prisma().delete(where={"id": row.id})
+ return stopped
async def resolve_expert_for_graph(user_id: str, graph_id: str) -> str | None:
diff --git a/autogpt_platform/backend/backend/api/features/experts/scheduling.py b/autogpt_platform/backend/backend/api/features/experts/scheduling.py
index a8f2a45aa4..e7244e88d1 100644
--- a/autogpt_platform/backend/backend/api/features/experts/scheduling.py
+++ b/autogpt_platform/backend/backend/api/features/experts/scheduling.py
@@ -311,6 +311,73 @@ async def detach_expert_triggers(user_id: str, expert_id: str) -> None:
)
+async def suspend_workflow_triggers(
+ user_id: str,
+ expert_id: str,
+ graph_id: str,
+ *,
+ except_schedule_id: str | None = None,
+) -> list[str]:
+ """Stop the expert's remaining triggers for *graph_id*, and name them.
+
+ ``ExpertWorkflow.scheduleId`` records only the install-time schedule. A cron
+ the expert made through ``run_agent`` and a webhook preset it set up are
+ stored separately, so without this an uninstalled workflow keeps firing
+ under the expert's attribution and spending the owner's money. Paused
+ rather than deleted, because a schedule the user made themselves is theirs
+ to keep.
+ """
+ stopped: list[str] = []
+ presets = await prisma.models.AgentPreset.prisma().find_many(
+ where={
+ "expertId": expert_id,
+ "userId": user_id,
+ "agentGraphId": graph_id,
+ "isDeleted": False,
+ "isActive": True,
+ }
+ )
+ if presets:
+ await prisma.models.AgentPreset.prisma().update_many(
+ where={
+ "expertId": expert_id,
+ "userId": user_id,
+ "agentGraphId": graph_id,
+ "isDeleted": False,
+ "isActive": True,
+ },
+ data={"isActive": False},
+ )
+ stopped.extend(p.name for p in presets)
+
+ try:
+ scheduler = get_scheduler_client()
+ schedules = await _get_expert_schedules(user_id, expert_id)
+ except Exception as e:
+ # Best-effort: an unreachable scheduler must not fail the uninstall
+ # itself. The survivors stay expert-attributed, so the detach preview
+ # and the archive sweep still find them.
+ logger.warning(
+ f"Could not list schedules while removing graph #{graph_id} from "
+ f"expert #{expert_id}: {type(e).__name__}: {e}"
+ )
+ return stopped
+ for schedule in schedules:
+ if schedule.graph_id != graph_id or schedule.id == except_schedule_id:
+ continue
+ try:
+ await scheduler.pause_schedule(schedule.id, user_id=user_id)
+ stopped.append(schedule.name or schedule.cron or schedule.id)
+ except Exception as e:
+ # Unlike detach, no run-time gate catches a survivor: the expert
+ # stays active and execution never checks membership (#14607).
+ logger.warning(
+ f"Failed to pause schedule #{schedule.id} while removing graph "
+ f"#{graph_id} from expert #{expert_id}: {type(e).__name__}: {e}"
+ )
+ return stopped
+
+
async def reattach_expert_triggers(user_id: str, expert_id: str) -> None:
"""Reverse of ``detach_expert_triggers``, for re-hire revival:
reactivate the presets archiving deactivated (never ones the user had
diff --git a/autogpt_platform/backend/backend/api/features/experts/workflow_removal_test.py b/autogpt_platform/backend/backend/api/features/experts/workflow_removal_test.py
index 773370243f..401adae2b8 100644
--- a/autogpt_platform/backend/backend/api/features/experts/workflow_removal_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/workflow_removal_test.py
@@ -25,7 +25,9 @@ async def test_remove_workflow_preserves_row_until_schedule_is_deleted(
expert_client = SimpleNamespace(find_first=AsyncMock(return_value=object()))
workflow_client = SimpleNamespace(
find_first=AsyncMock(
- return_value=SimpleNamespace(id="workflow-1", scheduleId="schedule-1")
+ return_value=SimpleNamespace(
+ id="workflow-1", scheduleId="schedule-1", LibraryAgent=None
+ )
),
delete=AsyncMock(),
)
@@ -47,7 +49,8 @@ async def test_remove_workflow_preserves_row_until_schedule_is_deleted(
expert_client.find_first.await_args.kwargs["where"]["ownerUserId"] == "owner-1"
)
workflow_client.find_first.assert_awaited_once_with(
- where={"id": "workflow-1", "expertId": "expert-1"}
+ where={"id": "workflow-1", "expertId": "expert-1"},
+ include={"LibraryAgent": True},
)
assert scheduler.delete_schedule.await_count == len(outcomes)
scheduler.delete_schedule.assert_awaited_with("schedule-1", user_id="owner-1")
@@ -55,3 +58,118 @@ async def test_remove_workflow_preserves_row_until_schedule_is_deleted(
workflow_client.delete.assert_awaited_once_with(where={"id": "workflow-1"})
else:
workflow_client.delete.assert_not_awaited()
+
+
+async def test_remove_workflow_stops_the_triggers_the_expert_made_itself():
+ """ExpertWorkflow.scheduleId records only the install-time schedule, so a
+ cron the expert made through run_agent used to keep firing — and spending —
+ after the tool reported the workflow removed."""
+ expert_client = SimpleNamespace(find_first=AsyncMock(return_value=object()))
+ workflow_client = SimpleNamespace(
+ find_first=AsyncMock(
+ return_value=SimpleNamespace(
+ id="workflow-1",
+ scheduleId="install-schedule",
+ LibraryAgent=SimpleNamespace(agentGraphId="graph-1"),
+ )
+ ),
+ delete=AsyncMock(),
+ )
+ preset = SimpleNamespace(name="Inbox webhook")
+ preset_client = SimpleNamespace(
+ find_many=AsyncMock(return_value=[preset]), update_many=AsyncMock()
+ )
+ scheduler = SimpleNamespace(
+ delete_schedule=AsyncMock(return_value=None),
+ pause_schedule=AsyncMock(),
+ get_execution_schedules=AsyncMock(
+ return_value=[
+ SimpleNamespace(
+ id="self-made",
+ kind="graph",
+ expert_id="expert-1",
+ graph_id="graph-1",
+ name="Daily wire transfer",
+ cron="0 9 * * *",
+ ),
+ SimpleNamespace(
+ id="install-schedule",
+ kind="graph",
+ expert_id="expert-1",
+ graph_id="graph-1",
+ name="Install cadence",
+ cron="0 8 * * *",
+ ),
+ SimpleNamespace(
+ id="other-graph",
+ kind="graph",
+ expert_id="expert-1",
+ graph_id="graph-2",
+ name="Unrelated",
+ cron="0 7 * * *",
+ ),
+ ]
+ ),
+ )
+ with (
+ patch.object(prisma.models.Expert, "prisma", return_value=expert_client),
+ patch.object(
+ prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client
+ ),
+ patch.object(prisma.models.AgentPreset, "prisma", return_value=preset_client),
+ patch.object(scheduling, "get_scheduler_client", return_value=scheduler),
+ ):
+ stopped = await experts_db.remove_workflow("owner-1", "expert-1", "workflow-1")
+
+ # The install-time schedule is deleted, not paused; the expert's own one is
+ # paused; another graph's is left alone.
+ scheduler.pause_schedule.assert_awaited_once_with("self-made", user_id="owner-1")
+ assert stopped == ["Inbox webhook", "Daily wire transfer"]
+
+
+async def test_a_nameless_schedule_is_reported_by_id_not_as_none():
+ """A one-shot has neither name nor cron, and the caller joins this list
+ into its message — appending None raised TypeError there."""
+ expert_client = SimpleNamespace(find_first=AsyncMock(return_value=object()))
+ workflow_client = SimpleNamespace(
+ find_first=AsyncMock(
+ return_value=SimpleNamespace(
+ id="workflow-1",
+ scheduleId=None,
+ LibraryAgent=SimpleNamespace(agentGraphId="graph-1"),
+ )
+ ),
+ delete=AsyncMock(),
+ )
+ preset_client = SimpleNamespace(
+ find_many=AsyncMock(return_value=[]), update_many=AsyncMock()
+ )
+ scheduler = SimpleNamespace(
+ pause_schedule=AsyncMock(),
+ get_execution_schedules=AsyncMock(
+ return_value=[
+ SimpleNamespace(
+ id="one-shot",
+ kind="graph",
+ expert_id="expert-1",
+ graph_id="graph-1",
+ name=None,
+ cron=None,
+ )
+ ]
+ ),
+ )
+ with (
+ patch.object(prisma.models.Expert, "prisma", return_value=expert_client),
+ patch.object(
+ prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client
+ ),
+ patch.object(prisma.models.AgentPreset, "prisma", return_value=preset_client),
+ patch.object(scheduling, "get_scheduler_client", return_value=scheduler),
+ ):
+ stopped = await experts_db.remove_workflow("owner-1", "expert-1", "workflow-1")
+
+ assert stopped == ["one-shot"]
+ assert ", ".join(stopped) == "one-shot"
diff --git a/autogpt_platform/backend/backend/blocks/mcp/helpers.py b/autogpt_platform/backend/backend/blocks/mcp/helpers.py
index 97e3c97096..72cfd2152d 100644
--- a/autogpt_platform/backend/backend/blocks/mcp/helpers.py
+++ b/autogpt_platform/backend/backend/blocks/mcp/helpers.py
@@ -145,13 +145,16 @@ async def invalidate_mcp_credential(user_id: str, credential_id: str) -> None:
async def auto_lookup_mcp_credential(
- user_id: str, server_url: str
+ user_id: str, server_url: str, allowed_ids: set[str] | None = None
) -> OAuth2Credentials | None:
"""Look up the best stored MCP credential for *server_url*.
The caller should pass a **normalized** URL (via :func:`normalize_mcp_url`)
so the comparison with ``mcp_server_url`` in credential metadata matches.
+ ``allowed_ids`` narrows the candidates before ranking, so an expert whose
+ grant is outranked by an ungranted row still gets the one it may use.
+
Returns the credential with the latest ``access_token_expires_at``, refreshed
if it can expire and needs it, or ``None`` when no match is found.
@@ -180,6 +183,7 @@ async def auto_lookup_mcp_credential(
if (
isinstance(cred, OAuth2Credentials)
and (cred.metadata or {}).get("mcp_server_url") == server_url
+ and (allowed_ids is None or cred.id in allowed_ids)
):
if best is None or rank(cred) >= rank(best):
best = cred
diff --git a/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py b/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py
index 96fa22c75e..547ea706e4 100644
--- a/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py
+++ b/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py
@@ -294,3 +294,57 @@ async def test_auto_lookup_returns_none_when_a_real_refresh_fails():
),
):
assert await auto_lookup_mcp_credential("user-1", _SERVER_URL) is None
+
+
+# ---------------------------------------------------------------------------
+# auto_lookup_mcp_credential — allowed_ids
+# ---------------------------------------------------------------------------
+
+
+def _manual_credential(cred_id: str, expires_at: int) -> OAuth2Credentials:
+ """A pasted MCP credential for _SERVER_URL; no refresh, so no refresh call."""
+ return OAuth2Credentials(
+ id=cred_id,
+ provider="mcp",
+ title=f"MCP: {cred_id}",
+ access_token=SecretStr(f"token-{cred_id}"),
+ refresh_token=None,
+ access_token_expires_at=expires_at,
+ scopes=[],
+ metadata={"mcp_server_url": _SERVER_URL},
+ )
+
+
+async def test_allowed_ids_narrows_before_ranking():
+ """The grant filter has to run before the ranking, not after it.
+
+ Ranking the whole set and checking only the winner refuses an expert that
+ holds a usable grant, whenever an ungranted row outranks it.
+ """
+ granted = _manual_credential("granted", expires_at=1)
+ ungranted = _manual_credential("ungranted", expires_at=999)
+
+ with _real_manager_over([granted, ungranted]):
+ best = await auto_lookup_mcp_credential(
+ "user-1", _SERVER_URL, allowed_ids={"granted"}
+ )
+
+ assert best is not None and best.id == "granted"
+
+
+async def test_no_allowed_ids_keeps_the_global_best():
+ granted = _manual_credential("granted", expires_at=1)
+ ungranted = _manual_credential("ungranted", expires_at=999)
+
+ with _real_manager_over([granted, ungranted]):
+ best = await auto_lookup_mcp_credential("user-1", _SERVER_URL)
+
+ assert best is not None and best.id == "ungranted"
+
+
+async def test_allowed_ids_matching_nothing_yields_none():
+ with _real_manager_over([_manual_credential("ungranted", expires_at=1)]):
+ assert (
+ await auto_lookup_mcp_credential("user-1", _SERVER_URL, allowed_ids=set())
+ is None
+ )
diff --git a/autogpt_platform/backend/backend/copilot/expert_context.py b/autogpt_platform/backend/backend/copilot/expert_context.py
index 14094e0ab7..77efba4cd4 100644
--- a/autogpt_platform/backend/backend/copilot/expert_context.py
+++ b/autogpt_platform/backend/backend/copilot/expert_context.py
@@ -262,9 +262,11 @@ def render_expert_workflows_block(expert: Expert) -> str:
return (
f"<expert_workflows>\n"
- f"Workflows installed on this expert. For requests that match a "
- f"workflow's purpose, prefer running it with `run_agent` using the "
- f"IDs below over building something new:\n"
+ f"Workflows installed on this expert — the only ones you can run, edit, "
+ f"or schedule (`run_agent` with the IDs below). To use another agent, "
+ f"install it first with `install_expert_workflow` from the marketplace "
+ f"or the owner's library — `find_library_agent` lists what the library "
+ f"holds; agents you build here are installed for you:\n"
f"{workflow_lines}\n"
# The skip comes after the kickoff message's ask, so the rule lives in
# session context, which every later turn sees, not in that message.
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index 7c79ce3161..4232779c2c 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -103,11 +103,15 @@ ToolName = Literal[
"get_mcp_guide",
"get_platform_info",
"get_sub_session_result",
+ "grant_expert_credential",
"handoff_to_expert",
"hire_expert",
+ "install_expert_workflow",
"list_agent_triggers",
"list_chat_platform_channels",
"list_expert_chats",
+ "list_expert_credentials",
+ "list_expert_workflows",
"list_folders",
"list_presets",
"list_schedules",
@@ -125,6 +129,9 @@ ToolName = Literal[
"read_expert_chat",
"read_skill",
"read_workspace_file",
+ "remove_expert_workflow",
+ "request_credential_grant",
+ "revoke_expert_credential",
"run_agent",
"run_block",
"run_mcp_tool",
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 416619faa4..ffd1a1ddfb 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -27,6 +27,15 @@ from .edit_agent import EditAgentTool
from .enter_building_mode import EnterAgentBuildingModeTool
from .expert_chats import ListExpertChatsTool, ReadExpertChatTool
from .expert_onboarding import ExpertOnboardingTool
+from .expert_resources import (
+ GrantExpertCredentialTool,
+ InstallExpertWorkflowTool,
+ ListExpertCredentialsTool,
+ ListExpertWorkflowsTool,
+ RemoveExpertWorkflowTool,
+ RequestCredentialGrantTool,
+ RevokeExpertCredentialTool,
+)
from .feature_requests import CreateFeatureRequestTool, SearchFeatureRequestsTool
from .find_agent import FindAgentTool
from .find_block import FindBlockTool
@@ -182,6 +191,15 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
# own data, read with the query the chat API uses.
"list_expert_chats": ListExpertChatsTool(),
"read_expert_chat": ReadExpertChatTool(),
+ # Expert resources: an expert installs onto itself, Otto names the
+ # expert. Credential grants are the owner's call, so Otto only.
+ "install_expert_workflow": InstallExpertWorkflowTool(),
+ "remove_expert_workflow": RemoveExpertWorkflowTool(),
+ "list_expert_workflows": ListExpertWorkflowsTool(),
+ "list_expert_credentials": ListExpertCredentialsTool(),
+ "grant_expert_credential": GrantExpertCredentialTool(),
+ "revoke_expert_credential": RevokeExpertCredentialTool(),
+ "request_credential_grant": RequestCredentialGrantTool(),
}
# Export individual tool instances for backwards compatibility
@@ -195,7 +213,9 @@ run_agent_tool = TOOL_REGISTRY["run_agent"]
# for tools whose backend is off and then hit opaque runtime errors. Add
# a new group by extending ``ToolGroup`` and registering its members in
# ``TOOL_GROUPS`` below.
-ToolGroup = Literal["graphiti", "experts", "expert_admin", "delegation"]
+ToolGroup = Literal[
+ "graphiti", "experts", "expert_admin", "delegation", "expert_resources"
+]
TOOL_GROUPS: dict[str, ToolGroup] = {
"memory_store": "graphiti",
@@ -225,6 +245,16 @@ 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",
+ # Workflow installs work from either side; credential grants are
+ # owner-only, so they ride the staffing gate.
+ "install_expert_workflow": "expert_resources",
+ "remove_expert_workflow": "expert_resources",
+ "list_expert_workflows": "expert_resources",
+ "list_expert_credentials": "expert_resources",
+ "grant_expert_credential": "expert_admin",
+ "revoke_expert_credential": "expert_admin",
+ # Only an expert has someone to ask.
+ "request_credential_grant": "experts",
# Read-only, but it shares the same gate: with the flag off there is no
# team to list.
"list_team": "delegation",
@@ -242,7 +272,7 @@ def expert_tool_disabled_groups(
expert-session tools (``experts``).
"""
if not experts_enabled:
- return ["experts", "expert_admin", "delegation"]
+ return ["experts", "expert_admin", "delegation", "expert_resources"]
return ["expert_admin"] if expert_id else ["experts"]
diff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
index 03ceb33d34..fab3cd927b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
@@ -119,7 +119,6 @@ class ConnectIntegrationTool(BaseTool):
Returns an :class:`ErrorResponse` if *provider* is unknown.
"""
- _ = user_id # setup card is user-agnostic; auth is enforced via requires_auth
session_id = session.session_id if session else None
provider = (provider or "").strip().lower()
reason = (reason or "").strip()[:500] # cap LLM-controlled text
@@ -155,6 +154,12 @@ class ConnectIntegrationTool(BaseTool):
]
if reason:
message_parts.append(reason)
+ if session.expert_id is not None:
+ message_parts.append(
+ "Note: a credential connected here belongs to the account and "
+ "still needs to be granted to this expert before it can use it; "
+ "the next run will name it if so."
+ )
# Route the single-provider entry through the shared serializer
# used by run_block / run_agent so the payload shape (sorted scopes,
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
index f83c445383..fa80a772b4 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
@@ -132,7 +132,7 @@ class ContinueRunBlockTool(BaseTool):
)
matched_creds, missing_creds = await resolve_block_credentials(
- user_id, block, input_data
+ user_id, block, input_data, session.expert_id
)
if missing_creds:
return ErrorResponse(
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py
index 935fad32f5..4ef0a45726 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py
@@ -184,3 +184,36 @@ class TestContinueRunBlock:
mock_db.delete_review_by_node_exec_id.assert_called_once_with(
review_id, _TEST_USER_ID
)
+
+
[email protected](loop_scope="session")
+async def test_continuation_resolves_credentials_under_the_experts_grants():
+ """The approved continuation re-resolves credentials, so it must be held
+ to the expert's grants like the original run_block call."""
+ tool = ContinueRunBlockTool()
+ session = make_session(user_id=_TEST_USER_ID, expert_id="expert-a")
+ review_id = "copilot-node-some-block:abc12345"
+ review = _make_review_model(
+ review_id, graph_exec_id=f"copilot-session-{session.session_id}"
+ )
+ mock_db = MagicMock()
+ mock_db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})
+ block = MagicMock()
+ block.name = "Some Block"
+
+ with (
+ patch(
+ "backend.copilot.tools.continue_run_block.review_db",
+ return_value=mock_db,
+ ),
+ patch("backend.copilot.tools.continue_run_block.get_block", return_value=block),
+ patch(
+ "backend.copilot.tools.continue_run_block.resolve_block_credentials",
+ new_callable=AsyncMock,
+ return_value=({}, {"credentials": {}}),
+ ) as resolve,
+ ):
+ await tool._execute(user_id=_TEST_USER_ID, session=session, review_id=review_id)
+
+ resolve.assert_awaited_once()
+ assert resolve.await_args_list[0].args[3] == "expert-a"
diff --git a/autogpt_platform/backend/backend/copilot/tools/create_agent.py b/autogpt_platform/backend/backend/copilot/tools/create_agent.py
index a874f509b7..bb74f806c8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/create_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/create_agent.py
@@ -14,6 +14,7 @@ from .agent_json_input import (
resolve_agent_json_or_error,
)
from .base import BaseTool
+from .expert_scope import install_saved_agent
from .helpers import require_guide_read, require_library_check
from .models import ErrorResponse, ToolResponseBase
@@ -150,7 +151,7 @@ class CreateAgentTool(BaseTool):
# Fetch library agents for AgentExecutorBlock validation
library_agents = await fetch_library_agents(user_id, library_agent_ids)
- return await fix_validate_and_save(
+ saved = await fix_validate_and_save(
agent_json,
user_id=user_id,
session_id=session_id,
@@ -161,3 +162,6 @@ class CreateAgentTool(BaseTool):
folder_id=folder_id,
is_hidden=is_hidden,
)
+ if user_id:
+ return await install_saved_agent(user_id, session, saved)
+ return saved
diff --git a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
index 770deccfd2..e8851f22df 100644
--- a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
@@ -13,6 +13,7 @@ from .agent_json_input import (
resolve_agent_json_or_error,
)
from .base import BaseTool
+from .expert_scope import install_saved_agent
from .models import ErrorResponse, ToolResponseBase
logger = logging.getLogger(__name__)
@@ -108,7 +109,7 @@ class CustomizeAgentTool(BaseTool):
# Fetch library agents for AgentExecutorBlock validation
library_agents = await fetch_library_agents(user_id, library_agent_ids)
- return await fix_validate_and_save(
+ saved = await fix_validate_and_save(
agent_json,
user_id=user_id,
session_id=session_id,
@@ -118,3 +119,6 @@ class CustomizeAgentTool(BaseTool):
library_agents=library_agents,
folder_id=folder_id,
)
+ if user_id:
+ return await install_saved_agent(user_id, session, saved)
+ return saved
diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
index bc2a66507e..5bdd2eba6d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
@@ -15,6 +15,7 @@ from .agent_json_input import (
resolve_agent_json_or_error,
)
from .base import BaseTool
+from .expert_scope import require_installed_workflow
from .helpers import require_guide_read
from .models import ErrorResponse, ToolResponseBase
@@ -108,6 +109,16 @@ class EditAgentTool(BaseTool):
error="missing_agent_id",
session_id=session_id,
)
+ if user_id:
+ scope_error = await require_installed_workflow(
+ user_id,
+ session,
+ graph_id=agent_id,
+ library_agent_id=agent_id,
+ name=agent_id,
+ )
+ if scope_error is not None:
+ return scope_error
agent_json, resolve_error = await resolve_agent_json_or_error(
agent_json=agent_json,
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_resources.py b/autogpt_platform/backend/backend/copilot/tools/expert_resources.py
new file mode 100644
index 0000000000..e4681481d0
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_resources.py
@@ -0,0 +1,637 @@
+"""Manage an expert's installed workflows and credential grants from chat.
+
+An expert session installs onto itself. Personal AutoPilot names the expert.
+Credential grants are the owner's decision, so grant/revoke live in the
+``expert_admin`` group and only personal AutoPilot sees them.
+"""
+
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from backend.api.features.experts.models import ExpertCredentialRef, ExpertWorkflowRef
+from backend.copilot.model import ChatSession, PendingQuestion
+from backend.data.activity_event import ActivityEventDraft
+from backend.data.db_accessors import chat_db, experts_db
+from backend.util.exceptions import ExpertNotFoundError, NotFoundError
+
+from .base import BaseTool
+from .expert_scope import resolve_target_expert, settle_expert_grants
+from .models import ErrorResponse, ResponseType, ToolResponseBase
+from .utils import fetch_graph_from_store_slug
+
+logger = logging.getLogger(__name__)
+
+_EXPERT_ID_PARAM = {
+ "type": "string",
+ "description": "Target expert (AutoPilot only; experts act on themselves).",
+}
+
+
+class ExpertWorkflowResponse(ToolResponseBase):
+ type: ResponseType = ResponseType.EXPERT_WORKFLOW
+ expert_id: str
+ workflow_id: str | None = None
+ library_agent_id: str | None = None
+ graph_id: str | None = None
+ name: str | None = None
+
+
+class ExpertCredentialsResponse(ToolResponseBase):
+ type: ResponseType = ResponseType.EXPERT_CREDENTIALS
+ expert_id: str
+ granted: list[ExpertCredentialRef]
+
+
+class InstallExpertWorkflowTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "install_expert_workflow"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Install a workflow on an expert so it can run it. Give exactly one "
+ "source: library_agent_id, username_agent_slug, or "
+ "store_listing_version_id."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "library_agent_id": {"type": "string", "description": "Library agent."},
+ "username_agent_slug": {
+ "type": "string",
+ "description": "Marketplace 'creator/slug'.",
+ },
+ "store_listing_version_id": {
+ "type": "string",
+ "description": "Marketplace listing version.",
+ },
+ "expert_id": _EXPERT_ID_PARAM,
+ },
+ "required": [],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ library_agent_id: str = "",
+ username_agent_slug: str = "",
+ store_listing_version_id: str = "",
+ expert_id: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ target = await resolve_target_expert(user_id, session, expert_id)
+ if isinstance(target, ErrorResponse):
+ return target
+ sources = [
+ s
+ for s in (library_agent_id, username_agent_slug, store_listing_version_id)
+ if s.strip()
+ ]
+ if len(sources) != 1:
+ return ErrorResponse(
+ message=(
+ "Provide exactly one of library_agent_id, "
+ "username_agent_slug, or store_listing_version_id."
+ ),
+ session_id=session_id,
+ )
+ try:
+ listing_id = store_listing_version_id.strip() or None
+ if username_agent_slug.strip():
+ listing_id = await _listing_id_from_slug(username_agent_slug)
+ if listing_id is None:
+ return ErrorResponse(
+ message=f"Marketplace agent '{username_agent_slug}' not found",
+ session_id=session_id,
+ )
+ await settle_expert_grants(user_id, session)
+ ref: ExpertWorkflowRef = await experts_db().install_workflow(
+ user_id,
+ target,
+ library_agent_id=library_agent_id.strip() or None,
+ store_listing_version_id=listing_id,
+ )
+ except ExpertNotFoundError:
+ return ErrorResponse(
+ message="This expert is no longer available.",
+ error="expert_not_found",
+ session_id=session_id,
+ )
+ except (NotFoundError, ValueError) as exc:
+ return ErrorResponse(message=str(exc), session_id=session_id)
+ return ExpertWorkflowResponse(
+ expert_id=target,
+ workflow_id=ref.id,
+ library_agent_id=ref.library_agent_id,
+ graph_id=ref.graph_id,
+ name=ref.name,
+ message=(
+ f"Installed '{ref.name or 'workflow'}' on expert {target}. "
+ f"Run it with run_agent using library_agent_id='{ref.library_agent_id}'."
+ ),
+ session_id=session_id,
+ )
+
+
+async def _listing_id_from_slug(slug: str) -> str | None:
+ if "/" not in slug:
+ return None
+ username, agent_name = slug.strip().split("/", 1)
+ _, details = await fetch_graph_from_store_slug(username, agent_name)
+ return details.store_listing_version_id if details is not None else None
+
+
+class RemoveExpertWorkflowTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "remove_expert_workflow"
+
+ @property
+ def description(self) -> str:
+ return "Uninstall a workflow from an expert (agent stays in the library)."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "workflow_id": {"type": "string", "description": "Installed workflow."},
+ "library_agent_id": {"type": "string", "description": "Library agent."},
+ "expert_id": _EXPERT_ID_PARAM,
+ },
+ "required": [],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ workflow_id: str = "",
+ library_agent_id: str = "",
+ expert_id: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ target = await resolve_target_expert(user_id, session, expert_id)
+ if isinstance(target, ErrorResponse):
+ return target
+ expert = await experts_db().get_expert(user_id, target)
+ if expert is None:
+ return ErrorResponse(
+ message="This expert is no longer available.",
+ error="expert_not_found",
+ session_id=session_id,
+ )
+ selectors = [v.strip() for v in (workflow_id, library_agent_id) if v.strip()]
+ if len(selectors) != 1:
+ return ErrorResponse(
+ message="Provide exactly one of workflow_id or library_agent_id.",
+ session_id=session_id,
+ )
+ row = next(
+ (
+ w
+ for w in expert.workflows
+ if w.id == workflow_id.strip()
+ or (
+ library_agent_id.strip()
+ and w.library_agent_id == library_agent_id.strip()
+ )
+ ),
+ None,
+ )
+ if row is None:
+ return ErrorResponse(
+ message="That workflow is not installed on this expert.",
+ error="workflow_not_installed",
+ session_id=session_id,
+ )
+ try:
+ stopped = await experts_db().remove_workflow(user_id, target, row.id)
+ except (ExpertNotFoundError, NotFoundError) as exc:
+ return ErrorResponse(message=str(exc), session_id=session_id)
+ message = f"Removed '{row.name or 'workflow'}' from expert {target}."
+ if stopped:
+ message += " Also stopped: " + ", ".join(stopped) + "."
+ return ExpertWorkflowResponse(
+ expert_id=target,
+ workflow_id=row.id,
+ library_agent_id=row.library_agent_id,
+ graph_id=row.graph_id,
+ name=row.name,
+ message=message,
+ session_id=session_id,
+ )
+
+
+class GrantExpertCredentialTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "grant_expert_credential"
+
+ @property
+ def description(self) -> str:
+ return "Let an expert use one of the owner's credentials (id from a missing-credentials hint)."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "expert_id": {"type": "string", "description": "Expert to grant to."},
+ "credential_id": {"type": "string", "description": "Credential id."},
+ },
+ "required": ["expert_id", "credential_id"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ expert_id: str = "",
+ credential_id: str = "",
+ **kwargs,
+ ) -> ToolResponseBase:
+ return await _change_grant(
+ user_id, session, expert_id, credential_id, grant=True
+ )
+
+
+class RevokeExpertCredentialTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "revoke_expert_credential"
+
+ @property
+ def description(self) -> str:
+ return "Stop an expert from using one of the owner's integration credentials."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "expert_id": {
+ "type": "string",
+ "description": "Expert to revoke from.",
+ },
+ "credential_id": {"type": "string", "description": "Credential id."},
+ },
+ "required": ["expert_id", "credential_id"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ expert_id: str = "",
+ credential_id: str = "",
+ **kwargs,
+ ) -> ToolResponseBase:
+ return await _change_grant(
+ user_id, session, expert_id, credential_id, grant=False
+ )
+
+
+async def _change_grant(
+ user_id: str | None,
+ session: ChatSession,
+ expert_id: str,
+ credential_id: str,
+ *,
+ grant: bool,
+) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(message="Authentication required", session_id=session_id)
+ if session.expert_id is not None:
+ return ErrorResponse(
+ message=(
+ "An expert cannot change credential grants. Use "
+ "request_credential_grant to ask the user for access."
+ ),
+ error="access_denied",
+ session_id=session_id,
+ )
+ target = await resolve_target_expert(user_id, session, expert_id.strip() or None)
+ if isinstance(target, ErrorResponse):
+ return target
+ if not credential_id.strip():
+ return ErrorResponse(message="credential_id is required", session_id=session_id)
+ try:
+ if grant:
+ granted = await experts_db().grant_expert_credentials(
+ user_id, target, [credential_id.strip()]
+ )
+ else:
+ granted = await experts_db().revoke_expert_credential(
+ user_id, target, credential_id.strip()
+ )
+ except ExpertNotFoundError:
+ return ErrorResponse(
+ message="This expert is no longer available.",
+ error="expert_not_found",
+ session_id=session_id,
+ )
+ except ValueError as exc:
+ return ErrorResponse(message=str(exc), session_id=session_id)
+ verb = "Granted" if grant else "Revoked"
+ return ExpertCredentialsResponse(
+ expert_id=target,
+ granted=granted,
+ message=(
+ f"{verb} credential {credential_id} for expert {target}. "
+ f"It now has {len(granted)} granted credential(s)."
+ ),
+ session_id=session_id,
+ )
+
+
+class ExpertWorkflowsResponse(ToolResponseBase):
+ type: ResponseType = ResponseType.EXPERT_WORKFLOWS
+ expert_id: str
+ workflows: list[ExpertWorkflowRef]
+
+
+class ListExpertWorkflowsTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "list_expert_workflows"
+
+ @property
+ def description(self) -> str:
+ return "List an expert's installed workflows (the only ones it can run)."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {"expert_id": _EXPERT_ID_PARAM},
+ "required": [],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ expert_id: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ target = await resolve_target_expert(user_id, session, expert_id)
+ if isinstance(target, ErrorResponse):
+ return target
+ expert = await experts_db().get_expert(user_id, target)
+ if expert is None:
+ return ErrorResponse(
+ message="This expert is no longer available.",
+ error="expert_not_found",
+ session_id=session_id,
+ )
+ lines = "; ".join(
+ f"{w.name or 'Unnamed'} (workflow_id={w.id}, "
+ f"library_agent_id={w.library_agent_id})"
+ for w in expert.workflows
+ )
+ return ExpertWorkflowsResponse(
+ expert_id=target,
+ workflows=expert.workflows,
+ message=(
+ f"{len(expert.workflows)} workflow(s) installed on {expert.name}: "
+ f"{lines or 'none'}. Add more with install_expert_workflow."
+ ),
+ session_id=session_id,
+ )
+
+
+class ListExpertCredentialsTool(BaseTool):
+ @property
+ def name(self) -> str:
+ return "list_expert_credentials"
+
+ @property
+ def description(self) -> str:
+ return "List the credentials an expert has been granted."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {"expert_id": _EXPERT_ID_PARAM},
+ "required": [],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ expert_id: str | None = None,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ target = await resolve_target_expert(user_id, session, expert_id)
+ if isinstance(target, ErrorResponse):
+ return target
+ try:
+ granted = await experts_db().list_expert_credentials(user_id, target)
+ except ExpertNotFoundError:
+ return ErrorResponse(
+ message="This expert is no longer available.",
+ error="expert_not_found",
+ session_id=session_id,
+ )
+ lines = "; ".join(
+ f"{c.title} ({c.provider}, credential_id={c.credential_id})"
+ for c in granted
+ )
+ return ExpertCredentialsResponse(
+ expert_id=target,
+ granted=granted,
+ message=(
+ f"Expert {target} can use {len(granted)} credential(s): "
+ f"{lines or 'none'}. Platform system credentials are always available."
+ ),
+ session_id=session_id,
+ )
+
+
+class CredentialGrantRequestedResponse(ToolResponseBase):
+ type: ResponseType = ResponseType.CREDENTIAL_GRANT_REQUESTED
+ expert_id: str
+ credential_id: str
+ provider: str | None = None
+
+
+class RequestCredentialGrantTool(BaseTool):
+ """An expert asks the owner for one of the account's credentials.
+
+ The request is recorded as this chat's pending question, so it appears
+ on Home under "Needs you", and as an integration activity event. Only the
+ owner can grant it — on the expert's Integrations page or from personal
+ AutoPilot with grant_expert_credential.
+ """
+
+ @property
+ def name(self) -> str:
+ return "request_credential_grant"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Ask the owner to grant this expert an account credential, then "
+ "stop and wait for their answer."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "credential_id": {"type": "string", "description": "Credential id."},
+ "provider": {
+ "type": "string",
+ "description": "Provider slug, for the note.",
+ },
+ "reason": {
+ "type": "string",
+ "description": "What it unblocks, one sentence.",
+ "maxLength": 300,
+ },
+ },
+ "required": ["credential_id"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ def activity_event(
+ self, session: ChatSession, result: ToolResponseBase, **kwargs
+ ) -> ActivityEventDraft | None:
+ if not isinstance(result, CredentialGrantRequestedResponse):
+ return None
+ return ActivityEventDraft(
+ category="INTEGRATION",
+ event_type="credential.grant_requested",
+ title=f"Expert asked for access to a {result.provider or 'credential'}",
+ expert_id=result.expert_id,
+ session_id=session.session_id,
+ provider=result.provider,
+ object_id=result.credential_id,
+ )
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ credential_id: str = "",
+ provider: str = "",
+ reason: str = "",
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required", session_id=session_id
+ )
+ if session.expert_id is None:
+ return ErrorResponse(
+ message=(
+ "Personal AutoPilot already holds every credential; use "
+ "grant_expert_credential to give one to an expert."
+ ),
+ error="not_an_expert_session",
+ session_id=session_id,
+ )
+ credential_id = credential_id.strip()
+ if not credential_id:
+ return ErrorResponse(
+ message="credential_id is required", session_id=session_id
+ )
+ provider_slug = provider.strip().lower() or None
+ reason = reason.strip()[:300]
+ text = (
+ f"Grant me the {provider_slug or 'integration'} credential "
+ f"(credential_id={credential_id})"
+ + (f" so I can {reason}" if reason else "")
+ + ". Approve it on my Integrations page, or tell personal AutoPilot "
+ f"to run grant_expert_credential for expert {session.expert_id}."
+ )
+ asked_at = datetime.now(timezone.utc)
+ try:
+ await chat_db().set_session_pending_question(
+ session_id, session.user_id, text, asked_at
+ )
+ except Exception:
+ logger.exception(
+ "Could not record credential grant request for session %s",
+ session_id,
+ )
+ return ErrorResponse(
+ message=(
+ "Couldn't record the request for the owner right now. "
+ "Try again in a moment."
+ ),
+ error="request_not_recorded",
+ session_id=session_id,
+ )
+ session.metadata.pending_question = PendingQuestion(
+ text=text, asked_at=asked_at
+ )
+ return CredentialGrantRequestedResponse(
+ expert_id=session.expert_id,
+ credential_id=credential_id,
+ provider=provider_slug,
+ message=(
+ f"Asked the owner to grant credential {credential_id}. This shows "
+ "on Home under Needs You; stop here and wait for their answer."
+ ),
+ session_id=session_id,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_resources_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_resources_test.py
new file mode 100644
index 0000000000..ccd523f964
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_resources_test.py
@@ -0,0 +1,319 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.api.features.experts.models import ExpertCredentialRef, ExpertWorkflowRef
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.expert_resources import (
+ CredentialGrantRequestedResponse,
+ ExpertCredentialsResponse,
+ ExpertWorkflowResponse,
+ GrantExpertCredentialTool,
+ InstallExpertWorkflowTool,
+ RemoveExpertWorkflowTool,
+ RevokeExpertCredentialTool,
+)
+from backend.copilot.tools.models import ErrorResponse
+
+_PATH = "backend.copilot.tools.expert_resources"
+_SCOPE = "backend.copilot.tools.expert_scope"
+
+
+def _ref():
+ return ExpertWorkflowRef(
+ id="wf-1",
+ store_listing_version_id=None,
+ library_agent_id="lib-1",
+ graph_id="graph-1",
+ name="Digest",
+ description=None,
+ )
+
+
+def _cred():
+ return ExpertCredentialRef(
+ credential_id="cred-1", provider="github", title="GH", type="api_key"
+ )
+
+
+def experts():
+ db = MagicMock()
+ db.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: (
+ MagicMock(id=expert_id, workflows=[_ref()])
+ if expert_id in {"expert-a", "expert-b"}
+ else None
+ )
+ )
+ db.install_workflow = AsyncMock(return_value=_ref())
+ db.settle_credential_seed = AsyncMock()
+ db.remove_workflow = AsyncMock(return_value=[])
+ db.grant_expert_credentials = AsyncMock(return_value=[_cred()])
+ db.revoke_expert_credential = AsyncMock(return_value=[])
+ with (
+ patch(f"{_PATH}.experts_db", return_value=db),
+ patch(f"{_SCOPE}.experts_db", return_value=db),
+ ):
+ yield db
+
+
+def _session(expert_id: str | None) -> ChatSession:
+ return ChatSession.new("user-1", dry_run=False, expert_id=expert_id)
+
+
+async def test_expert_installs_out_of_the_accounts_library_onto_itself(experts):
+ """The posted ownership rules allow it: "install a workflow from the owner's
+ library or the marketplace". What stops it widening its own access is the
+ grant seed, settled before the install lands, not a refusal here."""
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), library_agent_id="lib-1"
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ assert result.expert_id == "expert-a"
+ experts.install_workflow.assert_awaited_once_with(
+ "user-1", "expert-a", library_agent_id="lib-1", store_listing_version_id=None
+ )
+
+
+async def test_expert_installs_a_marketplace_agent_onto_itself(experts):
+ """A marketplace agent is public, so self-install stays open."""
+ details = MagicMock(store_listing_version_id="slv-9")
+ with patch(
+ f"{_PATH}.fetch_graph_from_store_slug",
+ new=AsyncMock(return_value=(MagicMock(), details)),
+ ):
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), username_agent_slug="creator/digest"
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ assert result.expert_id == "expert-a"
+ experts.install_workflow.assert_awaited_once_with(
+ "user-1", "expert-a", library_agent_id=None, store_listing_version_id="slv-9"
+ )
+
+
+async def test_expert_cannot_install_onto_another_expert(experts):
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), library_agent_id="lib-1", expert_id="expert-b"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "access_denied"
+ experts.install_workflow.assert_not_awaited()
+
+
+async def test_autopilot_installs_marketplace_agent_by_slug(experts):
+ details = MagicMock(store_listing_version_id="slv-9")
+ with patch(
+ f"{_PATH}.fetch_graph_from_store_slug",
+ new=AsyncMock(return_value=(MagicMock(), details)),
+ ):
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1",
+ _session(None),
+ username_agent_slug="creator/digest",
+ expert_id="expert-b",
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ experts.install_workflow.assert_awaited_once_with(
+ "user-1", "expert-b", library_agent_id=None, store_listing_version_id="slv-9"
+ )
+
+
+async def test_autopilot_must_name_the_expert(experts):
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1", _session(None), library_agent_id="lib-1"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "expert_required"
+
+
+async def test_install_needs_exactly_one_source(experts):
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1",
+ _session("expert-a"),
+ library_agent_id="lib-1",
+ username_agent_slug="a/b",
+ )
+ assert isinstance(result, ErrorResponse)
+ experts.install_workflow.assert_not_awaited()
+
+
+async def test_remove_by_library_agent_id(experts):
+ result = await RemoveExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), library_agent_id="lib-1"
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ experts.remove_workflow.assert_awaited_once_with("user-1", "expert-a", "wf-1")
+
+
+async def test_remove_unknown_workflow_is_refused(experts):
+ result = await RemoveExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), workflow_id="nope"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "workflow_not_installed"
+ experts.remove_workflow.assert_not_awaited()
+
+
+async def test_autopilot_grants_and_revokes(experts):
+ granted = await GrantExpertCredentialTool()._execute(
+ "user-1", _session(None), expert_id="expert-a", credential_id="cred-1"
+ )
+ revoked = await RevokeExpertCredentialTool()._execute(
+ "user-1", _session(None), expert_id="expert-a", credential_id="cred-1"
+ )
+ assert isinstance(granted, ExpertCredentialsResponse)
+ assert isinstance(revoked, ExpertCredentialsResponse)
+ experts.grant_expert_credentials.assert_awaited_once_with(
+ "user-1", "expert-a", ["cred-1"]
+ )
+ experts.revoke_expert_credential.assert_awaited_once_with(
+ "user-1", "expert-a", "cred-1"
+ )
+
+
+async def test_expert_cannot_grant_to_another_expert(experts):
+ result = await GrantExpertCredentialTool()._execute(
+ "user-1", _session("expert-a"), expert_id="expert-b", credential_id="cred-1"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "access_denied"
+ experts.grant_expert_credentials.assert_not_awaited()
+
+
+async def test_grant_rejects_foreign_credential(experts):
+ experts.grant_expert_credentials.side_effect = ValueError("Not your credentials")
+ result = await GrantExpertCredentialTool()._execute(
+ "user-1", _session(None), expert_id="expert-a", credential_id="x"
+ )
+ assert isinstance(result, ErrorResponse) and "Not your" in result.message
+
+
+async def test_list_expert_workflows_for_own_expert(experts):
+ from backend.copilot.tools.expert_resources import (
+ ExpertWorkflowsResponse,
+ ListExpertWorkflowsTool,
+ )
+
+ result = await ListExpertWorkflowsTool()._execute("user-1", _session("expert-a"))
+ assert isinstance(result, ExpertWorkflowsResponse)
+ assert [w.id for w in result.workflows] == ["wf-1"]
+ assert "wf-1" in result.message
+
+
+async def test_autopilot_lists_an_experts_credentials(experts):
+ from backend.copilot.tools.expert_resources import ListExpertCredentialsTool
+
+ experts.list_expert_credentials = AsyncMock(return_value=[_cred()])
+ result = await ListExpertCredentialsTool()._execute(
+ "user-1", _session(None), expert_id="expert-b"
+ )
+ assert isinstance(result, ExpertCredentialsResponse)
+ assert "cred-1" in result.message
+ experts.list_expert_credentials.assert_awaited_once_with("user-1", "expert-b")
+
+
+async def test_expert_requests_a_grant_and_leaves_a_pending_question(experts):
+ from backend.copilot.tools.expert_resources import (
+ CredentialGrantRequestedResponse,
+ RequestCredentialGrantTool,
+ )
+
+ chat = MagicMock()
+ chat.set_session_pending_question = AsyncMock()
+ session = _session("expert-a")
+ with patch(f"{_PATH}.chat_db", return_value=chat):
+ result = await RequestCredentialGrantTool()._execute(
+ "user-1", session, credential_id="cred-9", provider="github", reason="push"
+ )
+ assert isinstance(result, CredentialGrantRequestedResponse)
+ assert session.metadata.pending_question is not None
+ assert "cred-9" in session.metadata.pending_question.text
+ chat.set_session_pending_question.assert_awaited_once()
+ event = RequestCredentialGrantTool().activity_event(session, result)
+ assert event is not None and event.category == "INTEGRATION"
+ assert event.expert_id == "expert-a" and event.object_id == "cred-9"
+
+
+async def test_personal_autopilot_cannot_request_a_grant(experts):
+ from backend.copilot.tools.expert_resources import RequestCredentialGrantTool
+
+ result = await RequestCredentialGrantTool()._execute(
+ "user-1", _session(None), credential_id="cred-9"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "not_an_expert_session"
+
+
+async def test_remove_rejects_conflicting_selectors(experts):
+ result = await RemoveExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), workflow_id="wf-1", library_agent_id="lib-1"
+ )
+ assert isinstance(result, ErrorResponse)
+ experts.remove_workflow.assert_not_awaited()
+
+
+async def test_grant_request_fails_when_it_cannot_be_recorded(experts):
+ from backend.copilot.tools.expert_resources import RequestCredentialGrantTool
+
+ chat = MagicMock()
+ chat.set_session_pending_question = AsyncMock(side_effect=RuntimeError("db"))
+ session = _session("expert-a")
+ with patch(f"{_PATH}.chat_db", return_value=chat):
+ result = await RequestCredentialGrantTool()._execute(
+ "user-1", session, credential_id="cred-9"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "request_not_recorded"
+ assert session.metadata.pending_question is None
+
+
+async def test_expert_cannot_grant_itself(experts):
+ result = await GrantExpertCredentialTool()._execute(
+ "user-1", _session("expert-a"), expert_id="expert-a", credential_id="cred-1"
+ )
+ assert isinstance(result, ErrorResponse) and result.error == "access_denied"
+ experts.grant_expert_credentials.assert_not_awaited()
+
+
+async def test_expert_install_settles_its_grants_before_the_workflow_lands(experts):
+ order: list[str] = []
+ experts.settle_credential_seed.side_effect = lambda *_: order.append("settle")
+ experts.install_workflow.side_effect = lambda *_, **__: (
+ order.append("install") or _ref()
+ )
+ # The library path, because that is the one an expert can aim at any
+ # credential the owner holds: the seed must be stamped before it lands.
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), library_agent_id="lib-1"
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ assert order == ["settle", "install"]
+ experts.settle_credential_seed.assert_awaited_once_with("user-1", "expert-a")
+
+
+async def test_autopilot_install_does_not_touch_the_experts_grants(experts):
+ result = await InstallExpertWorkflowTool()._execute(
+ "user-1", _session(None), expert_id="expert-a", library_agent_id="lib-1"
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ experts.settle_credential_seed.assert_not_awaited()
+
+
+async def test_a_grant_request_is_a_different_response_type_from_a_grant_list():
+ """Both carried ResponseType.EXPERT_CREDENTIALS while holding different
+ fields, so a consumer discriminating on `type` could not tell a request
+ for one credential from the list of everything granted."""
+ assert (
+ CredentialGrantRequestedResponse.model_fields["type"].default
+ != ExpertCredentialsResponse.model_fields["type"].default
+ )
+
+
+async def test_remove_says_which_triggers_it_stopped(experts):
+ """A cron that survives the uninstall keeps spending, so the tool has to
+ name what it stopped rather than report a clean removal."""
+ experts.remove_workflow = AsyncMock(return_value=["Daily wire transfer"])
+ result = await RemoveExpertWorkflowTool()._execute(
+ "user-1", _session("expert-a"), library_agent_id="lib-1"
+ )
+ assert isinstance(result, ExpertWorkflowResponse)
+ assert "Also stopped: Daily wire transfer." in result.message
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
new file mode 100644
index 0000000000..022dee1c00
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
@@ -0,0 +1,237 @@
+"""Trusted expert scope for workflows, credentials, and runs.
+
+Every check here derives from ``session.expert_id`` — the persisted expert
+attribution the executor loaded — never from a tool argument. A personal
+AutoPilot session (``expert_id is None``) is the account owner acting and is
+unrestricted; it may also name one of the owner's experts to manage that
+expert's resources.
+"""
+
+import logging
+from enum import Enum
+
+from pydantic import BaseModel, Field
+
+from backend.copilot.model import ChatSession
+from backend.data.db_accessors import experts_db
+from backend.data.model import Credentials
+from backend.integrations.credentials_store import is_system_credential
+
+from .models import AgentSavedResponse, ErrorResponse, ToolResponseBase
+
+logger = logging.getLogger(__name__)
+
+WORKFLOW_NOT_INSTALLED = (
+ "'{name}' is not installed on this expert. Experts can only run, edit, "
+ "and schedule their installed workflows. Install it first with "
+ "install_expert_workflow, from the marketplace or the owner's library."
+)
+EXPERT_OWNER_DENIED = (
+ "Experts can only manage their own workflows and integrations. Open "
+ "personal AutoPilot to manage another expert."
+)
+EXPERT_REQUIRED = (
+ "Name the expert with expert_id. Personal AutoPilot manages experts' "
+ "resources on their behalf; list_team shows their ids."
+)
+
+
+class ExpertWorkflowScope(BaseModel):
+ """The workflows an expert may run, edit, and schedule."""
+
+ expert_id: str
+ library_agent_ids: list[str] = Field(default_factory=list)
+ graph_ids: list[str] = Field(default_factory=list)
+
+ def allows_graph(self, graph_id: str) -> bool:
+ return graph_id in self.graph_ids
+
+ def allows_agent(
+ self, *, library_agent_id: str | None, graph_id: str | None
+ ) -> bool:
+ return (library_agent_id in self.library_agent_ids) or (
+ graph_id is not None and self.allows_graph(graph_id)
+ )
+
+
+async def expert_workflow_scope(user_id: str, expert_id: str) -> ExpertWorkflowScope:
+ """Installed workflows of *expert_id*. Fails closed to an empty scope."""
+ expert = await experts_db().get_expert(user_id, expert_id)
+ if expert is None:
+ return ExpertWorkflowScope(expert_id=expert_id)
+ return ExpertWorkflowScope(
+ expert_id=expert_id,
+ library_agent_ids=[
+ w.library_agent_id for w in expert.workflows if w.library_agent_id
+ ],
+ graph_ids=[w.graph_id for w in expert.workflows if w.graph_id],
+ )
+
+
+async def session_workflow_scope(
+ user_id: str, session: ChatSession
+) -> ExpertWorkflowScope | None:
+ """``None`` for personal AutoPilot: every workflow in the account."""
+ if session.expert_id is None:
+ return None
+ return await expert_workflow_scope(user_id, session.expert_id)
+
+
+async def require_installed_workflow(
+ user_id: str,
+ session: ChatSession,
+ *,
+ graph_id: str | None = None,
+ library_agent_id: str | None = None,
+ name: str,
+) -> ErrorResponse | None:
+ """Refuse a workflow an expert session has not installed.
+
+ Either identifier form satisfies the check, so callers that accept a
+ library agent id or a graph id can pass the value as both.
+ """
+ scope = await session_workflow_scope(user_id, session)
+ if scope is None or scope.allows_agent(
+ library_agent_id=library_agent_id, graph_id=graph_id
+ ):
+ return None
+ return ErrorResponse(
+ message=WORKFLOW_NOT_INSTALLED.format(name=name),
+ error="workflow_not_installed",
+ session_id=session.session_id,
+ )
+
+
+async def resolve_target_expert(
+ user_id: str, session: ChatSession, requested_expert_id: str | None
+) -> str | ErrorResponse:
+ """Which expert a management tool call acts on.
+
+ An expert session always acts on itself and may not name another expert.
+ Personal AutoPilot must name one of the owner's active experts.
+ """
+ session_id = session.session_id
+ if session.expert_id is not None:
+ if requested_expert_id and requested_expert_id != session.expert_id:
+ return ErrorResponse(
+ message=EXPERT_OWNER_DENIED,
+ error="access_denied",
+ session_id=session_id,
+ )
+ return session.expert_id
+ if not requested_expert_id:
+ return ErrorResponse(
+ message=EXPERT_REQUIRED, error="expert_required", session_id=session_id
+ )
+ expert = await experts_db().get_expert(
+ user_id, requested_expert_id, include_workflows=False
+ )
+ if expert is None:
+ return ErrorResponse(
+ message=f"Expert '{requested_expert_id}' was not found on this account.",
+ error="expert_not_found",
+ session_id=session_id,
+ )
+ return expert.id
+
+
+async def settle_expert_grants(user_id: str, session: ChatSession) -> None:
+ """An expert installing a workflow on itself must not widen its own grants.
+
+ The allow-list is seeded from the expert's workflows on first read, so
+ settle it before the install lands; otherwise the new workflow's
+ credentials would be granted by the expert's own action.
+ """
+ if session.expert_id is None:
+ return
+ await experts_db().settle_credential_seed(user_id, session.expert_id)
+
+
+async def install_saved_agent(
+ user_id: str, session: ChatSession, result: ToolResponseBase
+) -> ToolResponseBase:
+ """An agent an expert just built becomes one of its installed workflows.
+
+ Keeps the invariant that an expert only ever runs installed workflows
+ without making it re-request its own creation. Failure is reported in
+ the response message, never raised: the agent is already saved.
+ """
+ if session.expert_id is None or not isinstance(result, AgentSavedResponse):
+ return result
+ try:
+ await settle_expert_grants(user_id, session)
+ await experts_db().install_workflow(
+ user_id, session.expert_id, library_agent_id=result.library_agent_id
+ )
+ except Exception:
+ logger.exception(
+ f"Failed to install created agent {result.library_agent_id} "
+ f"on expert {session.expert_id}"
+ )
+ return result.model_copy(
+ update={
+ "message": (
+ f"{result.message} The agent was saved but could not be "
+ "installed on this expert; run install_expert_workflow "
+ f"with library_agent_id='{result.library_agent_id}'."
+ )
+ }
+ )
+ return result.model_copy(
+ update={"message": f"{result.message} Installed on this expert."}
+ )
+
+
+def provider_slug(value: object) -> str:
+ """The wire value of a provider, whether it arrives as the ``ProviderName``
+ enum (whose ``str()`` is ``ProviderName.X``) or as a plain string."""
+ return str(value.value) if isinstance(value, Enum) else str(value)
+
+
+async def _ungranted_credentials(
+ user_id: str, expert_id: str, providers: set[str]
+) -> list[Credentials]:
+ """Account credentials for *providers* that *expert_id* cannot use yet."""
+ from backend.integrations.creds_manager import IntegrationCredentialsManager
+
+ try:
+ owned = await IntegrationCredentialsManager().store.get_all_creds(user_id)
+ allowed = set(
+ await experts_db().expert_allowed_credential_ids(user_id, expert_id)
+ )
+ except Exception:
+ logger.warning("Could not resolve ungranted credentials", exc_info=True)
+ return []
+ return [
+ c
+ for c in owned
+ if provider_slug(c.provider) in providers
+ and c.id not in allowed
+ and not is_system_credential(c.id)
+ ]
+
+
+async def ungranted_credential_hint(
+ user_id: str, expert_id: str | None, providers: set[str]
+) -> str:
+ """Point at credentials the account already has but the expert lacks.
+
+ Appended to a missing-credentials message in expert chats so the user is
+ asked to grant an existing integration instead of connecting a duplicate
+ the expert still could not use.
+ """
+ if expert_id is None or not providers:
+ return ""
+ candidates = await _ungranted_credentials(user_id, expert_id, providers)
+ if not candidates:
+ return ""
+ lines = "\n".join(
+ f"- {c.title or c.provider} ({c.provider}, credential_id={c.id})"
+ for c in candidates
+ )
+ return (
+ "\n\nThe account already has matching credentials that this expert has "
+ f"not been granted:\n{lines}\nAsk the user to grant one on the expert's "
+ "Integrations page, or from personal AutoPilot with "
+ "grant_expert_credential."
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py
new file mode 100644
index 0000000000..c80f15ddb5
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_scope_test.py
@@ -0,0 +1,190 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.expert_scope import (
+ ExpertWorkflowScope,
+ install_saved_agent,
+ require_installed_workflow,
+ resolve_target_expert,
+ ungranted_credential_hint,
+)
+from backend.copilot.tools.models import AgentSavedResponse, ErrorResponse
+
+_PATH = "backend.copilot.tools.expert_scope"
+
+
+def _expert(expert_id: str, graph_ids: list[str] = ()):
+ return MagicMock(
+ id=expert_id,
+ workflows=[
+ MagicMock(library_agent_id=f"lib-{g}", graph_id=g) for g in graph_ids
+ ],
+ )
+
+
+def experts():
+ db = MagicMock()
+ db.get_expert = AsyncMock(
+ side_effect=lambda user_id, expert_id, **_: (
+ _expert(expert_id, ["installed"]) if expert_id == "expert-a" else None
+ )
+ )
+ db.install_workflow = AsyncMock()
+ db.expert_allowed_credential_ids = AsyncMock(return_value=["granted-cred"])
+ db.settle_credential_seed = AsyncMock()
+ with patch(f"{_PATH}.experts_db", return_value=db):
+ yield db
+
+
+def _expert_session(expert_id: str | None = "expert-a") -> ChatSession:
+ return ChatSession.new("user-1", dry_run=False, expert_id=expert_id)
+
+
+def test_scope_allows_only_installed_workflows():
+ scope = ExpertWorkflowScope(
+ expert_id="e", library_agent_ids=["lib-1"], graph_ids=["graph-1"]
+ )
+ assert scope.allows_graph("graph-1")
+ assert not scope.allows_graph("graph-2")
+ assert scope.allows_agent(library_agent_id="lib-1", graph_id=None)
+ assert scope.allows_agent(library_agent_id="other", graph_id="graph-1")
+ assert not scope.allows_agent(library_agent_id="other", graph_id="graph-2")
+
+
+async def test_expert_is_refused_uninstalled_workflow(experts):
+ error = await require_installed_workflow(
+ "user-1", _expert_session(), graph_id="other", name="Other"
+ )
+ assert isinstance(error, ErrorResponse)
+ assert error.error == "workflow_not_installed"
+ assert "install_expert_workflow" in error.message
+
+
+async def test_expert_may_use_installed_workflow(experts):
+ assert (
+ await require_installed_workflow(
+ "user-1", _expert_session(), graph_id="installed", name="x"
+ )
+ is None
+ )
+ assert (
+ await require_installed_workflow(
+ "user-1",
+ _expert_session(),
+ graph_id="lib-installed",
+ library_agent_id="lib-installed",
+ name="x",
+ )
+ is None
+ )
+
+
+async def test_personal_autopilot_may_use_any_workflow(experts):
+ assert (
+ await require_installed_workflow(
+ "user-1", _expert_session(None), graph_id="anything", name="x"
+ )
+ is None
+ )
+ experts.get_expert.assert_not_awaited()
+
+
+async def test_missing_expert_fails_closed(experts):
+ error = await require_installed_workflow(
+ "user-1", _expert_session("expert-gone"), graph_id="installed", name="x"
+ )
+ assert isinstance(error, ErrorResponse)
+
+
+async def test_expert_session_targets_itself_only(experts):
+ assert await resolve_target_expert("user-1", _expert_session(), None) == "expert-a"
+ assert (
+ await resolve_target_expert("user-1", _expert_session(), "expert-a")
+ == "expert-a"
+ )
+ denied = await resolve_target_expert("user-1", _expert_session(), "expert-b")
+ assert isinstance(denied, ErrorResponse) and denied.error == "access_denied"
+
+
+async def test_personal_autopilot_must_name_a_real_expert(experts):
+ missing = await resolve_target_expert("user-1", _expert_session(None), None)
+ assert isinstance(missing, ErrorResponse) and missing.error == "expert_required"
+ unknown = await resolve_target_expert("user-1", _expert_session(None), "nope")
+ assert isinstance(unknown, ErrorResponse) and unknown.error == "expert_not_found"
+ assert (
+ await resolve_target_expert("user-1", _expert_session(None), "expert-a")
+ == "expert-a"
+ )
+
+
+def _saved() -> AgentSavedResponse:
+ return AgentSavedResponse(
+ message="Saved.",
+ agent_id="graph-new",
+ agent_name="New",
+ library_agent_id="lib-new",
+ library_agent_link="/library/agents/lib-new",
+ agent_page_link="/build?flowID=graph-new",
+ )
+
+
+async def test_agent_built_by_expert_is_installed_on_it(experts):
+ result = await install_saved_agent("user-1", _expert_session(), _saved())
+ experts.install_workflow.assert_awaited_once_with(
+ "user-1", "expert-a", library_agent_id="lib-new"
+ )
+ assert isinstance(result, AgentSavedResponse)
+ assert "Installed on this expert" in result.message
+
+
+async def test_failed_install_is_reported_not_raised(experts):
+ experts.install_workflow.side_effect = RuntimeError("boom")
+ result = await install_saved_agent("user-1", _expert_session(), _saved())
+ assert "install_expert_workflow" in result.message
+
+
+async def test_personal_autopilot_build_is_not_installed_anywhere(experts):
+ result = await install_saved_agent("user-1", _expert_session(None), _saved())
+ experts.install_workflow.assert_not_awaited()
+ assert result.message == "Saved."
+
+
+def test_provider_slug_uses_the_wire_value_of_enums():
+ from backend.copilot.tools.expert_scope import provider_slug
+ from backend.integrations.providers import ProviderName
+
+ assert provider_slug(ProviderName.GITHUB) == "github"
+ assert provider_slug("github") == "github"
+
+
+async def test_hint_lists_owned_but_ungranted_credentials(experts):
+ store = MagicMock()
+ store.get_all_creds = AsyncMock(
+ return_value=[
+ MagicMock(id="granted-cred", provider="github", title="GH granted"),
+ MagicMock(id="spare-cred", provider="github", title="GH spare"),
+ MagicMock(id="other-cred", provider="slack", title="Slack"),
+ ]
+ )
+ with patch(
+ "backend.integrations.creds_manager.IntegrationCredentialsManager",
+ return_value=MagicMock(store=store),
+ ):
+ hint = await ungranted_credential_hint("user-1", "expert-a", {"github"})
+ none = await ungranted_credential_hint("user-1", "expert-a", {"notion"})
+ personal = await ungranted_credential_hint("user-1", None, {"github"})
+ assert "spare-cred" in hint and "GH spare" in hint
+ assert "granted-cred" not in hint and "other-cred" not in hint
+ assert "grant_expert_credential" in hint
+ assert none == "" and personal == ""
+
+
+async def test_agent_built_by_expert_settles_grants_before_install(experts):
+ order: list[str] = []
+ experts.settle_credential_seed.side_effect = lambda *_: order.append("settle")
+ experts.install_workflow.side_effect = lambda *_, **__: order.append("install")
+ await install_saved_agent("user-1", _expert_session(), _saved())
+ assert order == ["settle", "install"]
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_agent.py
index a7747bcc25..cae6a0c634 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_agent.py
@@ -6,7 +6,7 @@ from backend.copilot.model import ChatSession
from .agent_search import search_agents
from .base import BaseTool
-from .models import ToolResponseBase
+from .models import AgentsFoundResponse, ToolResponseBase
class FindAgentTool(BaseTool):
@@ -41,9 +41,21 @@ class FindAgentTool(BaseTool):
**kwargs,
) -> ToolResponseBase:
"""Search marketplace for agents matching the query."""
- return await search_agents(
+ result = await search_agents(
query=query.strip(),
source="marketplace",
session_id=session.session_id,
user_id=user_id,
)
+ if session.expert_id is None or not isinstance(result, AgentsFoundResponse):
+ return result
+ return result.model_copy(
+ update={
+ "message": (
+ f"{result.message} This is an expert chat: a marketplace agent "
+ "must be installed with install_expert_workflow "
+ "(username_agent_slug='creator/slug', the agent id below) "
+ "before run_agent can use it."
+ )
+ }
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py
index 4f69627e1a..50e7eeef92 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py
@@ -12,7 +12,8 @@ from .agent_search import (
search_library_for_creation,
)
from .base import BaseTool
-from .models import AgentsFoundResponse, ErrorResponse, ToolResponseBase
+from .expert_scope import require_installed_workflow, session_workflow_scope
+from .models import AgentInfo, AgentsFoundResponse, ErrorResponse, ToolResponseBase
class FindLibraryAgentTool(BaseTool):
@@ -97,6 +98,82 @@ class FindLibraryAgentTool(BaseTool):
for_creation: bool = False,
goal_summary: str = "",
**kwargs,
+ ) -> ToolResponseBase:
+ if user_id and (direct_id := agent_id.strip()):
+ scope_error = await require_installed_workflow(
+ user_id,
+ session,
+ graph_id=direct_id,
+ library_agent_id=direct_id,
+ name=direct_id,
+ )
+ if scope_error is not None:
+ return scope_error
+ result = await self._search(
+ user_id,
+ session,
+ query=query,
+ agent_id=agent_id,
+ include_graph=include_graph,
+ write_graph_to=write_graph_to,
+ for_creation=for_creation,
+ goal_summary=goal_summary,
+ )
+ if not user_id or not isinstance(result, AgentsFoundResponse):
+ return result
+ scope = await session_workflow_scope(user_id, session)
+ if scope is None:
+ return result
+ if for_creation:
+ # The pre-create similarity check exists to avoid duplicates, so it
+ # must see the whole library; an expert installs a match instead
+ # of building it again.
+ return result.model_copy(
+ update={
+ "message": (
+ f"{result.message} You are an expert: to reuse a match, "
+ "install it with install_expert_workflow rather than "
+ "building a new agent."
+ )
+ }
+ )
+ installed: list[AgentInfo] = []
+ uninstalled: list[AgentInfo] = []
+ for agent in result.agents:
+ allowed = scope.allows_agent(
+ library_agent_id=agent.id, graph_id=agent.graph_id
+ )
+ (installed if allowed else uninstalled).append(agent)
+ message = (
+ f"Found {len(installed)} installed workflows. Only installed "
+ "workflows can be run, edited or scheduled."
+ )
+ if uninstalled:
+ message += (
+ " Also in the owner's library, not installed on you: "
+ f"{_install_candidates(uninstalled)} — install one with "
+ "install_expert_workflow to use it."
+ )
+ return result.model_copy(
+ update={
+ "agents": installed,
+ "count": len(installed),
+ "title": f"Found {len(installed)} installed workflows",
+ "message": message,
+ }
+ )
+
+ async def _search(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ *,
+ query: str,
+ agent_id: str,
+ include_graph: bool,
+ write_graph_to: str,
+ for_creation: bool,
+ goal_summary: str,
) -> ToolResponseBase:
if for_creation:
# No ``or query`` fallback: the gate only accepts non-empty
@@ -138,6 +215,21 @@ class FindLibraryAgentTool(BaseTool):
)
+_INSTALL_CANDIDATE_LIMIT = 10
+
+
+def _install_candidates(agents: list[AgentInfo]) -> str:
+ """Name library agents an expert may install, with the id install takes.
+
+ They stay out of ``agents``, which consumers read as the runnable set.
+ """
+ shown = agents[:_INSTALL_CANDIDATE_LIMIT]
+ listed = ", ".join(f'"{a.name}" ({a.id})' for a in shown)
+ if len(agents) > len(shown):
+ listed += f", and {len(agents) - len(shown)} more"
+ return listed
+
+
async def _write_graph_note(
agent_id: str, write_to: str, user_id: str | None, session_id: str | None
) -> str:
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py
index 694ca42a63..28db250152 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py
@@ -4,8 +4,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.expert_scope import ExpertWorkflowScope
from backend.copilot.tools.find_library_agent import FindLibraryAgentTool
from backend.copilot.tools.models import (
+ AgentInfo,
AgentsFoundResponse,
ErrorResponse,
NoResultsResponse,
@@ -456,3 +459,138 @@ async def test_write_graph_to_write_failure_notes_fallback(tool, session):
assert isinstance(result, AgentsFoundResponse)
assert "could not write" in result.message
assert "include_graph=true" in result.message
+
+
+async def test_expert_cannot_export_an_uninstalled_agent_by_id(tool):
+ from backend.copilot.model import ChatSession
+ from backend.copilot.tools.expert_scope import ExpertWorkflowScope
+
+ session = ChatSession.new("user-1", dry_run=False, expert_id="expert-a")
+ scope = ExpertWorkflowScope(expert_id="expert-a", graph_ids=["graph-in"])
+ with (
+ patch(
+ "backend.copilot.tools.expert_scope.session_workflow_scope",
+ new=AsyncMock(return_value=scope),
+ ),
+ patch.object(FindLibraryAgentTool, "_search", new=AsyncMock()) as search,
+ ):
+ result = await tool._execute(
+ "user-1", session, agent_id="graph-out", write_graph_to="graph.json"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "workflow_not_installed"
+ search.assert_not_awaited()
+
+
+async def test_expert_similarity_check_sees_the_whole_library(tool):
+ from backend.copilot.model import ChatSession
+ from backend.copilot.tools.expert_scope import ExpertWorkflowScope
+ from backend.copilot.tools.models import AgentInfo
+
+ session = ChatSession.new("user-1", dry_run=False, expert_id="expert-a")
+ scope = ExpertWorkflowScope(expert_id="expert-a", graph_ids=["graph-in"])
+ found = AgentsFoundResponse(
+ message="Similar agents",
+ agents=[
+ AgentInfo(
+ id="lib-out",
+ name="x",
+ description="",
+ source="library",
+ graph_id="graph-out",
+ )
+ ],
+ count=1,
+ )
+ with (
+ patch(
+ "backend.copilot.tools.find_library_agent.session_workflow_scope",
+ new=AsyncMock(return_value=scope),
+ ),
+ patch.object(
+ FindLibraryAgentTool, "_search", new=AsyncMock(return_value=found)
+ ),
+ ):
+ result = await tool._execute(
+ "user-1", session, for_creation=True, goal_summary="do x"
+ )
+ assert isinstance(result, AgentsFoundResponse)
+ assert result.count == 1
+ assert "install_expert_workflow" in result.message
+
+
+async def test_expert_search_counts_only_installed_workflows(tool):
+ scope = ExpertWorkflowScope(expert_id="expert-a", graph_ids=["graph-0", "graph-1"])
+ found = AgentsFoundResponse(
+ title="Found 3 agents in your library",
+ message="Found 3 agents in your library",
+ agents=[
+ AgentInfo(
+ id=f"lib-{i}",
+ graph_id=f"graph-{i}",
+ name=f"Agent {i}",
+ description="",
+ source="library",
+ )
+ for i in range(3)
+ ],
+ count=3,
+ )
+ with (
+ patch(
+ "backend.copilot.tools.find_library_agent.session_workflow_scope",
+ AsyncMock(return_value=scope),
+ ),
+ patch.object(FindLibraryAgentTool, "_search", AsyncMock(return_value=found)),
+ ):
+ result = await tool._execute(
+ "owner", ChatSession.new("owner", dry_run=False, expert_id="expert-a")
+ )
+ assert isinstance(result, AgentsFoundResponse)
+ assert len(result.agents) == result.count == 2
+ assert result.title == "Found 2 installed workflows"
+ assert "3 agents" not in result.message
+
+
+async def test_expert_search_names_the_library_agents_it_could_install(tool):
+ """The posted ownership rules let an expert "install a workflow from the
+ owner's library or the marketplace", so the library has to be findable.
+ The uninstalled matches stay out of `agents`, which consumers read as the
+ runnable set, and are named with the id install_expert_workflow takes."""
+ scope = ExpertWorkflowScope(expert_id="expert-a", graph_ids=["graph-0"])
+ found = AgentsFoundResponse(
+ title="Found 12 agents in your library",
+ message="Found 12 agents in your library",
+ agents=[
+ AgentInfo(
+ id=f"lib-{i}",
+ graph_id=f"graph-{i}",
+ name=f"Agent {i}",
+ description="",
+ source="library",
+ )
+ for i in range(12)
+ ],
+ count=12,
+ )
+ with (
+ patch(
+ "backend.copilot.tools.find_library_agent.session_workflow_scope",
+ AsyncMock(return_value=scope),
+ ),
+ patch.object(FindLibraryAgentTool, "_search", AsyncMock(return_value=found)),
+ ):
+ result = await tool._execute(
+ "owner", ChatSession.new("owner", dry_run=False, expert_id="expert-a")
+ )
+ assert isinstance(result, AgentsFoundResponse)
+ assert [a.id for a in result.agents] == ["lib-0"]
+ assert '"Agent 1" (lib-1)' in result.message
+ assert "install_expert_workflow" in result.message
+ # Capped, so a large library cannot crowd out the turn.
+ assert '"Agent 11" (lib-11)' not in result.message
+ assert "and 1 more" in result.message
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.py
index 552a1ba476..9deaf100cf 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
@@ -693,14 +693,15 @@ class TestExpertToolGate:
experts_enabled=False for user_id=None)."""
def test_flag_off_disables_every_team_group(self) -> None:
- assert expert_tool_disabled_groups(experts_enabled=False, expert_id=None) == [
- "experts",
- "expert_admin",
- "delegation",
- ]
- assert expert_tool_disabled_groups(
- experts_enabled=False, expert_id="expert-a"
- ) == ["experts", "expert_admin", "delegation"]
+ expected = ["experts", "expert_admin", "delegation", "expert_resources"]
+ assert (
+ expert_tool_disabled_groups(experts_enabled=False, expert_id=None)
+ == expected
+ )
+ assert (
+ expert_tool_disabled_groups(experts_enabled=False, expert_id="expert-a")
+ == expected
+ )
def test_plain_session_loses_expert_session_tools(self) -> None:
assert expert_tool_disabled_groups(experts_enabled=True, expert_id=None) == [
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index 6a225195a2..fc643e88e3 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -50,6 +50,7 @@ from backend.util.feature_flag import Flag, is_feature_enabled
from backend.util.timezone_utils import get_user_timezone_or_utc
from backend.util.type import coerce_inputs_to_schema
+from .expert_scope import provider_slug, ungranted_credential_hint
from .models import (
BlockOutputResponse,
CredentialRejection,
@@ -415,6 +416,7 @@ async def execute_block(
input_data=input_data,
creds_manager=creds_manager,
user_id=user_id,
+ expert_id=expert_id,
)
except MissingAutoCredentialsError as e:
await _release_credential_leases(credential_leases)
@@ -717,10 +719,12 @@ async def resolve_block_credentials(
user_id: str,
block: AnyBlockSchema,
input_data: dict[str, Any] | None = None,
+ expert_id: str | None = None,
) -> tuple[dict[str, CredentialsMetaInput], list[CredentialsMetaInput]]:
"""Resolve credentials for a block by matching user's available credentials.
Handles discriminated credentials (e.g. provider selection based on model).
+ ``expert_id`` narrows the pool to that expert's granted credentials.
Returns:
(matched_credentials, missing_credentials)
@@ -731,7 +735,7 @@ async def resolve_block_credentials(
if not requirements:
return {}, []
- return await match_credentials_to_requirements(user_id, requirements)
+ return await match_credentials_to_requirements(user_id, requirements, expert_id)
@dataclass
@@ -842,7 +846,7 @@ async def prepare_block_for_execution(
input_data.pop(field_name)
matched_credentials, missing_credentials = await resolve_block_credentials(
- user_id, block, input_data
+ user_id, block, input_data, session.expert_id
)
try:
@@ -903,6 +907,10 @@ async def prepare_block_for_execution(
f"Block '{block.name}' requires credentials that are not "
"configured. Please set up the required credentials before "
"running this block."
+ ) + await ungranted_credential_hint(
+ user_id,
+ session.expert_id,
+ {provider_slug(m.provider) for m in missing_credentials},
)
else:
message = (
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index 7f3c264809..a0005fd4c2 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -1222,7 +1222,7 @@ async def test_prepare_block_null_non_credential_field_not_stripped() -> None:
excl_ids, excl_types = _patch_excluded()
captured: list[dict] = []
- async def _capture_resolve(user_id, block, input_data):
+ async def _capture_resolve(user_id, block, input_data, expert_id=None):
captured.append(dict(input_data))
return {}, []
diff --git a/autogpt_platform/backend/backend/copilot/tools/list_team.py b/autogpt_platform/backend/backend/copilot/tools/list_team.py
index ee2a75e0f1..6a9e1f0bc0 100644
--- a/autogpt_platform/backend/backend/copilot/tools/list_team.py
+++ b/autogpt_platform/backend/backend/copilot/tools/list_team.py
@@ -56,7 +56,7 @@ class ListTeamTool(BaseTool):
message="Authentication required", session_id=session.session_id
)
try:
- experts = await experts_db().list_experts(user_id, with_metrics=False)
+ experts = await experts_db().list_experts(user_id)
except Exception as e:
logger.warning(f"list_team roster lookup failed: {e}")
return ErrorResponse(
@@ -72,16 +72,24 @@ class ListTeamTool(BaseTool):
),
session_id=session.session_id,
)
+ # The grant count is the owner's view of its team: an expert picking
+ # someone to delegate to is served by the workflow count, and must not
+ # learn how much access its teammates hold.
+ show_credentials = session.expert_id is None
lines = "; ".join(
- f"{e.name} — {e.role} (expert_id: {e.id})"
+ f"{e.name} — {e.role} (expert_id: {e.id}, "
+ f"{len(e.workflows)} workflow(s)"
+ + (f", {e.credential_count} credential(s))" if show_credentials else ")")
+ (" [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."
+ f"team: {lines}. Use these expert_ids with delegate_to_expert; an "
+ "expert can only run its installed workflows with its granted "
+ "credentials, so check those before delegating. Never re-raise "
+ "an expert who is already listed here."
),
session_id=session.session_id,
experts=[
@@ -92,6 +100,8 @@ class ListTeamTool(BaseTool):
color=e.color,
avatar_url=e.avatar_url,
is_paused=e.schedules_paused_at is not None,
+ workflow_count=len(e.workflows),
+ credential_count=(e.credential_count if show_credentials else 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.py
index 962f85e34a..643dd22f02 100644
--- a/autogpt_platform/backend/backend/copilot/tools/list_team_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/list_team_test.py
@@ -27,6 +27,8 @@ def _expert(
avatar_url=None,
is_archived=is_archived,
schedules_paused_at=schedules_paused_at,
+ workflows=[],
+ credential_count=0,
)
@@ -94,3 +96,33 @@ async def test_lookup_failure_returns_error(monkeypatch):
async def test_requires_auth():
result = await ListTeamTool()._execute(user_id=None, session=make_session(_USER))
assert isinstance(result, ErrorResponse)
+
+
+async def test_autopilot_sees_each_teammates_grant_count(monkeypatch):
+ _patch_db(monkeypatch, [_expert_with_credentials(3)])
+ result = await ListTeamTool()._execute(user_id=_USER, session=make_session(_USER))
+ assert isinstance(result, TeamRosterResponse)
+ assert "3 credential(s)" in result.message
+ assert result.experts[0].credential_count == 3
+
+
+async def test_an_expert_is_not_told_how_much_access_its_teammates_hold(monkeypatch):
+ """An expert picks who to delegate to from the workflow count; a teammate's
+ grant count is the owner's view of the team, not an expert's."""
+ _patch_db(monkeypatch, [_expert_with_credentials(3)])
+ result = await ListTeamTool()._execute(
+ user_id=_USER, session=make_session(_USER, expert_id="exp-9")
+ )
+ assert isinstance(result, TeamRosterResponse)
+ assert "credential(s)" not in result.message
+ assert result.experts[0].credential_count is None
+ # The rest of the row still reaches the expert.
+ assert "0 workflow(s)" in result.message
+
+
+def _expert_with_credentials(count: int):
+ expert = _expert()
+ expert.credential_count = count
+ return expert
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 4952f106f2..e9d5f02d40 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -49,6 +49,11 @@ class ResponseType(str, Enum):
# Schedules
SCHEDULE_LIST = "schedule_list"
SCHEDULE_DELETED = "schedule_deleted"
+ # Expert resources (installed workflows, credential grants)
+ EXPERT_WORKFLOW = "expert_workflow"
+ EXPERT_WORKFLOWS = "expert_workflows"
+ EXPERT_CREDENTIALS = "expert_credentials"
+ CREDENTIAL_GRANT_REQUESTED = "credential_grant_requested"
SCHEDULE_CREATED = "schedule_created"
# Agent triggers
@@ -613,6 +618,9 @@ class TeamExpertInfo(BaseModel):
color: str = ""
avatar_url: str | None = None
is_paused: bool = False
+ workflow_count: int = 0
+ # None for an expert session: a teammate's grant count is the owner's view.
+ credential_count: int | None = None
class TeamRosterResponse(ToolResponseBase):
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
index fcc48df1e4..e1c40cd354 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
@@ -43,6 +43,11 @@ from .execution_utils import (
summarize_node_failures,
wait_for_execution,
)
+from .expert_scope import (
+ provider_slug,
+ require_installed_workflow,
+ ungranted_credential_hint,
+)
from .helpers import get_inputs_from_schema, get_picker_inputs_from_schema
from .models import (
AgentDetails,
@@ -184,7 +189,7 @@ class RunAgentTool(BaseTool):
},
"library_agent_id": {
"type": "string",
- "description": "Library agent ID.",
+ "description": "Library agent ID or graph ID from your library.",
},
"preset_id": {
"type": "string",
@@ -318,9 +323,19 @@ class RunAgentTool(BaseTool):
# Priority: library_agent_id if provided
if has_library_id:
- library_agent = await library_db().get_library_agent(
- params.library_agent_id, user_id
- )
+ try:
+ library_agent = await library_db().get_library_agent(
+ params.library_agent_id, user_id
+ )
+ except NotFoundError:
+ # get_library_agent raises rather than returning None, so
+ # the graph-id fallback this tool documents is only
+ # reachable from here.
+ library_agent = None
+ if not library_agent:
+ library_agent = await library_db().get_library_agent_by_graph_id(
+ user_id, params.library_agent_id
+ )
if not library_agent:
return ErrorResponse(
message=f"Library agent '{params.library_agent_id}' not found",
@@ -348,6 +363,15 @@ class RunAgentTool(BaseTool):
message=f"Agent '{identifier}' not found",
session_id=session_id,
)
+ scope_error = await require_installed_workflow(
+ user_id,
+ session,
+ graph_id=graph.id,
+ library_agent_id=library_agent.id if library_agent else None,
+ name=graph.name,
+ )
+ if scope_error is not None:
+ return scope_error
# Builder-bound sessions can only run their bound agent. We
# resolve the graph first so the user sees a precise error that
@@ -670,7 +694,16 @@ class RunAgentTool(BaseTool):
graph, graph_credentials
)
return graph_credentials, SetupRequirementsResponse(
- message=self._build_inputs_message(graph, MSG_WHAT_VALUES_TO_USE),
+ message=self._build_inputs_message(graph, MSG_WHAT_VALUES_TO_USE)
+ + await ungranted_credential_hint(
+ user_id,
+ expert_id,
+ {
+ provider_slug(m.get("provider", ""))
+ for m in missing_credentials_dict.values()
+ }
+ - {""},
+ ),
session_id=session_id,
setup_info=SetupInfo(
agent_id=graph.id,
@@ -796,6 +829,11 @@ class RunAgentTool(BaseTool):
),
session_id=session_id,
)
+ scope_error = await require_installed_workflow(
+ user_id, session, graph_id=graph.id, name=graph.name
+ )
+ if scope_error is not None:
+ return scope_error
# Builder-bound sessions can only run their bound agent — enforce the
# same guard as the regular run path so a preset for a different graph
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_graph_reference_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_graph_reference_test.py
new file mode 100644
index 0000000000..d6b9040eaf
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_graph_reference_test.py
@@ -0,0 +1,54 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import ErrorResponse
+from backend.copilot.tools.run_agent import RunAgentTool
+from backend.util.exceptions import NotFoundError
+
+_PATH = "backend.copilot.tools.run_agent"
+
+
[email protected]("installed", [True, False])
+ "miss",
+ [
+ # What the real layer does: get_library_agent is annotated non-optional
+ # and raises. Mocking it as returning None passed the fallback without
+ # ever reaching it.
+ pytest.param(
+ {"side_effect": NotFoundError("no such library agent")}, id="raises"
+ ),
+ pytest.param({"return_value": None}, id="returns-none"),
+ ],
+)
+async def test_graph_reference_resolves_before_installed_gate(installed, miss):
+ session = ChatSession.new("owner", dry_run=False, expert_id="expert-a")
+ library = MagicMock()
+ library.get_library_agent = AsyncMock(**miss)
+ library.get_library_agent_by_graph_id = AsyncMock(
+ return_value=MagicMock(id="lib-1", graph_id="graph-1", graph_version=1)
+ )
+ graph = MagicMock(id="graph-1")
+ gate_result = ErrorResponse(
+ message="scope reached" if installed else "not installed",
+ error="test_stop" if installed else "workflow_not_installed",
+ )
+ gate = AsyncMock(return_value=gate_result)
+ with (
+ patch(f"{_PATH}.library_db", return_value=library),
+ patch(
+ f"{_PATH}.graph_db",
+ return_value=MagicMock(get_graph=AsyncMock(return_value=graph)),
+ ),
+ patch(f"{_PATH}.require_installed_workflow", gate),
+ ):
+ result = await RunAgentTool()._execute(
+ "owner", session, library_agent_id="graph-1"
+ )
+ assert result == gate_result
+ library.get_library_agent_by_graph_id.assert_awaited_once_with("owner", "graph-1")
+ assert gate.await_args.kwargs["library_agent_id"] == "lib-1"
+ assert gate.await_args.kwargs["graph_id"] == "graph-1"
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
index aaf5345031..df55327ad8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
@@ -762,6 +762,7 @@ async def test_run_agent_schedule_credential_race_returns_setup_card(
@pytest.mark.asyncio(loop_scope="session")
async def test_run_agent_schedule_in_expert_session_stamps_expert_id(
setup_test_data,
+ request,
):
"""A schedule created from an expert-scoped chat session must carry the
session's expert_id, otherwise it never shows on the Team card / expert
@@ -788,6 +789,12 @@ async def test_run_agent_schedule_in_expert_session_stamps_expert_id(
expert_id=expert_id,
)
+ installed = patch(
+ "backend.copilot.tools.run_agent.require_installed_workflow",
+ new=AsyncMock(return_value=None),
+ )
+ installed.start()
+ request.addfinalizer(installed.stop)
with patch(
"backend.copilot.tools.run_agent.get_scheduler_client",
return_value=fake_scheduler,
@@ -1073,6 +1080,7 @@ async def test_run_agent_execution_credential_race_returns_setup_card(
@pytest.mark.asyncio(loop_scope="session")
async def test_run_agent_expert_workspace_unavailable_returns_stable_error(
setup_test_data,
+ request,
):
user = setup_test_data["user"]
store_submission = setup_test_data["store_submission"]
@@ -1080,6 +1088,12 @@ async def test_run_agent_expert_workspace_unavailable_returns_stable_error(
agent_marketplace_id = f"{user.email.split('@')[0]}/{store_submission.slug}"
session = make_session(user_id=user.id, expert_id="expert-1")
+ installed = patch(
+ "backend.copilot.tools.run_agent.require_installed_workflow",
+ new=AsyncMock(return_value=None),
+ )
+ installed.start()
+ request.addfinalizer(installed.stop)
with patch(
"backend.copilot.tools.run_agent.execution_utils.add_graph_execution",
new_callable=AsyncMock,
@@ -1739,3 +1753,42 @@ async def test_detailed_fetch_failure_degrades_to_summary(mocker):
assert "completed successfully" in response.message
assert response.execution.nodes_failed is None
+
+
[email protected](loop_scope="session")
+async def test_run_preset_refuses_uninstalled_workflow_for_expert():
+ from backend.copilot.tools.run_agent import RunAgentInput
+
+ tool = RunAgentTool()
+ session = make_session(user_id="preset-user", expert_id="expert-a")
+ preset = MagicMock(
+ expert_id="expert-a", graph_id="graph-out", graph_version=1, inputs={}
+ )
+ lib_db = MagicMock()
+ lib_db.get_preset = AsyncMock(return_value=preset)
+ graph_db_mock = MagicMock()
+ graph_db_mock.get_graph = AsyncMock(
+ return_value=MagicMock(id="graph-out", name="Outside", version=1)
+ )
+ experts = MagicMock()
+ experts.get_expert = AsyncMock(
+ return_value=MagicMock(
+ workflows=[MagicMock(library_agent_id="lib-in", graph_id="graph-in")]
+ )
+ )
+ add_exec = AsyncMock()
+ with (
+ patch("backend.copilot.tools.run_agent.library_db", return_value=lib_db),
+ patch("backend.copilot.tools.run_agent.graph_db", return_value=graph_db_mock),
+ patch("backend.copilot.tools.expert_scope.experts_db", return_value=experts),
+ patch(
+ "backend.copilot.tools.run_agent.execution_utils.add_graph_execution",
+ new=add_exec,
+ ),
+ ):
+ result = await tool._handle_preset_run(
+ "preset-user", session, RunAgentInput(preset_id="p1")
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "workflow_not_installed"
+ add_exec.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
index 1ffbfc6fe4..feb4132c6d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -25,6 +25,7 @@ from backend.copilot.tools.utils import (
build_missing_credentials_from_field_info,
sanitize_provider_message,
)
+from backend.data.db_accessors import experts_db
from backend.data.model import OAuth2Credentials
from backend.integrations.providers import ProviderName
from backend.util.request import (
@@ -223,7 +224,34 @@ class RunMCPToolTool(BaseTool):
# Fast DB lookup — no network call.
# Normalize for matching because stored credentials use normalized URLs.
- creds = await auto_lookup_mcp_credential(user_id, normalize_mcp_url(server_url))
+ normalized_url = normalize_mcp_url(server_url)
+ # Narrow before ranking, not after: an ungranted manual token outranks a
+ # granted OAuth row, so checking the single best match would refuse an
+ # expert that does have usable access to this server.
+ allowed_ids: set[str] | None = None
+ if session.expert_id is not None:
+ allowed_ids = set(
+ await experts_db().expert_allowed_credential_ids(
+ user_id, session.expert_id
+ )
+ )
+ creds = await auto_lookup_mcp_credential(
+ user_id, normalized_url, allowed_ids=allowed_ids
+ )
+ if creds is None and allowed_ids is not None:
+ ungranted = await auto_lookup_mcp_credential(user_id, normalized_url)
+ if ungranted is not None:
+ return ErrorResponse(
+ message=(
+ f"The account's credential for {server_host(server_url)} "
+ f"(credential_id={ungranted.id}) is not granted to this "
+ "expert. Ask the user to grant it on the expert's "
+ "Integrations page or from personal AutoPilot with "
+ "grant_expert_credential."
+ ),
+ error="credential_not_granted",
+ session_id=session_id,
+ )
client = (
MCPClient(server_url, authorization=mcp_authorization_header(creds))
if creds is not None
diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
index 39e04d10cf..ff928d7d96 100644
--- a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
@@ -30,6 +30,7 @@ from backend.util.exceptions import (
)
from .base import BaseTool
+from .expert_scope import require_installed_workflow
from .models import (
ErrorResponse,
ResponseType,
@@ -187,6 +188,15 @@ class SetupAgentWebhookTriggerTool(BaseTool):
if error:
return error
assert graph is not None
+ scope_error = await require_installed_workflow(
+ user_id,
+ session,
+ graph_id=graph.id,
+ library_agent_id=(kwargs.get("library_agent_id") or "").strip() or None,
+ name=graph.name,
+ )
+ if scope_error is not None:
+ return scope_error
if not (trigger_node := graph.webhook_input_node):
return ErrorResponse(
diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
index f51c1e9985..9bef55b26f 100644
--- a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
@@ -199,7 +199,9 @@ async def test_manual_webhook_no_creds_proceeds(tool, session):
@pytest.mark.asyncio
-async def test_expert_session_passes_expert_scope_to_trigger_setup(tool, session):
+async def test_expert_session_passes_expert_scope_to_trigger_setup(
+ tool, session, request
+):
session.expert_id = "expert-1"
graph = _make_graph(manual=True, regular_credentials={})
preset = _make_preset(
@@ -207,6 +209,12 @@ async def test_expert_session_passes_expert_scope_to_trigger_setup(tool, session
url="https://backend.agpt.co/api/integrations/generic_webhook/webhooks/wh-1/ingress",
)
ctxs, setup_mock = _patches(graph, preset=preset)
+ installed = patch(
+ "backend.copilot.tools.setup_agent_webhook_trigger.require_installed_workflow",
+ new=AsyncMock(return_value=None),
+ )
+ installed.start()
+ request.addfinalizer(installed.stop)
with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
result = await tool._execute(
user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
@@ -217,13 +225,19 @@ async def test_expert_session_passes_expert_scope_to_trigger_setup(tool, session
@pytest.mark.asyncio
-async def test_expert_session_attributes_trigger_to_expert(tool):
+async def test_expert_session_attributes_trigger_to_expert(tool, request):
"""A trigger set up inside an expert chat threads that expert's id through
to preset creation, so its webhook fires count as the expert's work."""
session = make_session(_USER, expert_id="expert-1")
graph = _make_graph(manual=True, regular_credentials={})
preset = _make_preset(provider="generic_webhook", url="https://x/ingress")
ctxs, setup_mock = _patches(graph, preset=preset)
+ installed = patch(
+ "backend.copilot.tools.setup_agent_webhook_trigger.require_installed_workflow",
+ new=AsyncMock(return_value=None),
+ )
+ installed.start()
+ request.addfinalizer(installed.stop)
with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
result = await tool._execute(
user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
index 29c48ce870..dab5fa8f0a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
@@ -1196,8 +1196,11 @@ async def test_credential_lookup_normalizes_trailing_slash():
session=session,
server_url=url_with_slash,
)
- # Credential lookup should use the normalized URL (no trailing slash)
- mock_lookup.assert_called_once_with(_USER_ID, "https://mcp.example.com/mcp")
+ # Credential lookup should use the normalized URL (no trailing slash),
+ # and a personal session narrows by nothing.
+ mock_lookup.assert_called_once_with(
+ _USER_ID, "https://mcp.example.com/mcp", allowed_ids=None
+ )
# ---------------------------------------------------------------------------
@@ -1462,3 +1465,63 @@ async def test_rejected_card_differs_from_never_connected_by_the_rejection():
assert {k: v for k, v in rejected.model_dump().items() if k not in ignored} == {
k: v for k, v in never_connected.model_dump().items() if k not in ignored
}
+
+
+# ---------------------------------------------------------------------------
+# Expert credential grants
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_an_ungranted_mcp_credential_is_refused_for_an_expert():
+ response = await _run_with_grants([])
+ assert isinstance(response, ErrorResponse)
+ assert response.error == "credential_not_granted"
+
+
[email protected](loop_scope="session")
+async def test_a_granted_mcp_credential_is_used():
+ response = await _run_with_grants(["mcp-cred"])
+ assert isinstance(response, MCPToolsDiscoveredResponse)
+
+
+async def _run_with_grants(allowed: list[str]):
+ """Discover tools in an expert session whose grant list is *allowed*, with
+ one stored MCP credential for the server."""
+ creds = OAuth2Credentials(
+ id="mcp-cred",
+ provider="mcp",
+ title="MCP: remote.mcpservers.org",
+ access_token=SecretStr("test-token-abc"),
+ scopes=[],
+ metadata={"mcp_server_url": _SERVER_URL},
+ )
+ experts = MagicMock()
+ experts.expert_allowed_credential_ids = AsyncMock(return_value=allowed)
+ client = AsyncMock()
+ client.list_tools = AsyncMock(return_value=_make_tool_list("fetch"))
+
+ # The real lookup narrows by allowed_ids before ranking, so the stub has to
+ # as well — otherwise the tool never sees the filter it now relies on.
+ async def _lookup(_user_id, _url, allowed_ids=None):
+ if allowed_ids is not None and creds.id not in allowed_ids:
+ return None
+ return creds
+
+ with (
+ patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new=_lookup,
+ ),
+ patch("backend.copilot.tools.run_mcp_tool.experts_db", return_value=experts),
+ patch("backend.copilot.tools.run_mcp_tool.MCPClient", return_value=client),
+ ):
+ return await RunMCPToolTool()._execute(
+ user_id=_USER_ID,
+ session=make_session(_USER_ID, expert_id="expert-a"),
+ server_url=_SERVER_URL,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils_test.py b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
index b49bb71234..d824ab1226 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
@@ -3,8 +3,10 @@
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from pydantic import SecretStr
-from backend.data.model import CredentialsFieldInfo
+from backend.blocks.http import SendAuthenticatedWebRequestBlock
+from backend.data.model import CredentialsFieldInfo, HostScopedCredentials
def _make_regular_field() -> CredentialsFieldInfo:
@@ -170,3 +172,56 @@ def test_credential_rejection_status_only_matches_rejections(exc, expected):
from backend.copilot.tools.utils import credential_rejection_status
assert credential_rejection_status(exc) == expected
+
+
+async def test_a_block_run_in_an_expert_session_uses_only_a_granted_credential():
+ matched, missing = await _resolve_for("expert-a", ["granted-cred"])
+ assert matched["credentials"].id == "granted-cred"
+ assert missing == []
+
+
+async def test_an_ungranted_credential_surfaces_as_missing_not_as_a_match():
+ matched, missing = await _resolve_for("expert-a", [])
+ assert matched == {}
+ assert len(missing) == 1
+
+
+async def test_a_plain_session_keeps_every_account_credential():
+ matched, _ = await _resolve_for(None, [])
+ assert matched["credentials"].id == "ungranted-cred"
+
+
+def _host_cred(cred_id: str) -> HostScopedCredentials:
+ return HostScopedCredentials(
+ id=cred_id,
+ provider="http",
+ host="api.example.com",
+ headers={"Authorization": SecretStr("Bearer token")},
+ title=cred_id,
+ )
+
+
+async def _resolve_for(expert_id: str | None, allowed: list[str]):
+ """Resolve an authenticated-request block against two account credentials
+ for the same host, only one of which the expert has been granted."""
+ from backend.copilot.tools.helpers import resolve_block_credentials
+
+ experts = MagicMock()
+ experts.expert_allowed_credential_ids = AsyncMock(return_value=allowed)
+ with (
+ patch(
+ "backend.copilot.tools.utils.IntegrationCredentialsManager"
+ ) as MockCredsMgr,
+ patch("backend.data.db_accessors.experts_db", return_value=experts),
+ ):
+ MockCredsMgr.return_value.store = AsyncMock()
+ MockCredsMgr.return_value.store.get_all_creds.return_value = [
+ _host_cred("ungranted-cred"),
+ _host_cred("granted-cred"),
+ ]
+ return await resolve_block_credentials(
+ "test-user",
+ SendAuthenticatedWebRequestBlock(),
+ {"url": "https://api.example.com/v1/data"},
+ expert_id,
+ )
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index e88cd4917b..c05b40969e 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -539,12 +539,18 @@ class DatabaseManager(AppService):
parked_spend_decision = _(experts_spend_approval.parked_spend_decision)
open_chat_spend_review = _(experts_spend_approval.open_chat_spend_review)
expert_allowed_credential_ids = _(expert_credentials.expert_allowed_credential_ids)
+ settle_credential_seed = _(expert_credentials.settle_credential_seed)
update_soul = _(experts_db.update_soul)
update_soul_if_current = _(experts_db.update_soul_if_current)
update_soul_fields = _(experts_db.update_soul_fields)
update_soul_fields_if_current = _(experts_db.update_soul_fields_if_current)
add_expert_skill_name = _(experts_db.add_expert_skill_name)
remove_expert_skill_name = _(experts_db.remove_expert_skill_name)
+ install_workflow = _(experts_db.install_workflow)
+ remove_workflow = _(experts_db.remove_workflow)
+ grant_expert_credentials = _(expert_credentials.grant_expert_credentials)
+ revoke_expert_credential = _(expert_credentials.revoke_expert_credential)
+ list_expert_credentials = _(expert_credentials.list_expert_credentials)
# Hire / raise from the copilot chat tools, plus the counts their
# preview step uses to refuse a change that could never land.
list_templates = _(experts_db.list_templates)
@@ -930,12 +936,18 @@ class DatabaseManagerAsyncClient(AppServiceClient):
parked_spend_decision = d.parked_spend_decision
open_chat_spend_review = d.open_chat_spend_review
expert_allowed_credential_ids = d.expert_allowed_credential_ids
+ settle_credential_seed = d.settle_credential_seed
update_soul = d.update_soul
update_soul_if_current = d.update_soul_if_current
update_soul_fields = d.update_soul_fields
update_soul_fields_if_current = d.update_soul_fields_if_current
add_expert_skill_name = d.add_expert_skill_name
remove_expert_skill_name = d.remove_expert_skill_name
+ install_workflow = d.install_workflow
+ remove_workflow = d.remove_workflow
+ grant_expert_credentials = d.grant_expert_credentials
+ revoke_expert_credential = d.revoke_expert_credential
+ list_expert_credentials = d.list_expert_credentials
list_templates = d.list_templates
hire_expert = d.hire_expert
create_raised_expert = d.create_raised_expert
diff --git a/autogpt_platform/backend/backend/executor/auto_credentials.py b/autogpt_platform/backend/backend/executor/auto_credentials.py
index f94c671a63..5a6fc1b426 100644
--- a/autogpt_platform/backend/backend/executor/auto_credentials.py
+++ b/autogpt_platform/backend/backend/executor/auto_credentials.py
@@ -11,6 +11,8 @@ from typing import Any
from redis.asyncio.lock import Lock as AsyncRedisLock
from backend.blocks._base import BlockSchema
+from backend.data.db_accessors import experts_db
+from backend.integrations.credentials_store import is_system_credential
from backend.integrations.creds_manager import IntegrationCredentialsManager
logger = logging.getLogger(__name__)
@@ -30,9 +32,13 @@ async def acquire_auto_credentials(
input_data: dict[str, Any],
creds_manager: IntegrationCredentialsManager,
user_id: str,
+ expert_id: str | None = None,
) -> tuple[dict[str, Any], list[AsyncRedisLock]]:
"""Resolve ``auto_credentials`` from ``GoogleDriveFileField``-style inputs.
+ ``expert_id`` holds the picker credentials to that expert's grants, the same
+ allow-list the explicit credential fields go through.
+
Returns:
(extra_exec_kwargs, locks): kwargs to inject into block execution,
and credential locks to release after execution completes.
@@ -45,6 +51,7 @@ async def acquire_auto_credentials(
"""
extra_exec_kwargs: dict[str, Any] = {}
locks: list[AsyncRedisLock] = []
+ allowed: set[str] | None = None
try:
for kwarg_name, info in input_model.get_auto_credentials_fields().items():
@@ -68,6 +75,20 @@ async def acquire_auto_credentials(
f"builder and re-select the file."
)
file_name = field_data.get("name", "selected file")
+ if expert_id is not None and not is_system_credential(cred_id):
+ if allowed is None:
+ allowed = set(
+ await experts_db().expert_allowed_credential_ids(
+ user_id, expert_id
+ )
+ )
+ if cred_id not in allowed:
+ raise ValueError(
+ f"{provider.capitalize()} credentials for "
+ f"'{file_name}' in field '{field_name}' have "
+ f"not been granted to this expert. Grant them "
+ f"on the expert's Integrations page."
+ )
try:
credentials, lock = await creds_manager.acquire(
user_id, cred_id
diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.py
index 4b11d00345..cac0cd1dac 100644
--- a/autogpt_platform/backend/backend/executor/manager.py
+++ b/autogpt_platform/backend/backend/executor/manager.py
@@ -442,6 +442,7 @@ async def execute_node(
input_data=input_data,
creds_manager=creds_manager,
user_id=user_id,
+ expert_id=execution_context.expert_id,
)
extra_exec_kwargs.update(auto_extra_kwargs)
creds_locks.extend(auto_locks)
diff --git a/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py b/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py
index 74ce936b51..060385fe5a 100644
--- a/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py
@@ -469,3 +469,80 @@ async def test_acquire_auto_credentials_rejects_non_dict_value_with_type_message
# can't silently regress to the old generic message.
assert type(bad_value).__name__ in msg
manager.acquire.assert_not_called()
+
+
+async def test_auto_credentials_expert_is_refused_an_ungranted_credential(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """A picker credential is held to the expert's grants like any other."""
+ from backend.executor.auto_credentials import acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ experts = mocker.MagicMock()
+ experts.expert_allowed_credential_ids = mocker.AsyncMock(return_value=["other"])
+ mocker.patch("backend.executor.auto_credentials.experts_db", return_value=experts)
+
+ with pytest.raises(ValueError, match="not been granted to this expert"):
+ await acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data={"spreadsheet": google_drive_file_data["valid"]},
+ creds_manager=manager,
+ user_id="user-1",
+ expert_id="expert-a",
+ )
+
+ experts.expert_allowed_credential_ids.assert_awaited_once_with("user-1", "expert-a")
+ manager.acquire.assert_not_called()
+
+
+async def test_auto_credentials_expert_may_use_a_granted_credential(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ from backend.executor.auto_credentials import acquire_auto_credentials
+
+ manager, mock_creds, _ = mock_creds_manager
+ experts = mocker.MagicMock()
+ experts.expert_allowed_credential_ids = mocker.AsyncMock(
+ return_value=["cred-id-123"]
+ )
+ mocker.patch("backend.executor.auto_credentials.experts_db", return_value=experts)
+
+ extra_kwargs, _ = await acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data={"spreadsheet": google_drive_file_data["valid"]},
+ creds_manager=manager,
+ user_id="user-1",
+ expert_id="expert-a",
+ )
+
+ assert extra_kwargs["credentials"] == mock_creds
+
+
+async def test_auto_credentials_personal_session_skips_the_grant_lookup(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ from backend.executor.auto_credentials import acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ experts_db = mocker.patch("backend.executor.auto_credentials.experts_db")
+
+ await acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data={"spreadsheet": google_drive_file_data["valid"]},
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ experts_db.assert_not_called()
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index bc91fb4aa2..90db4de9d2 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -27469,6 +27469,10 @@
"review_required",
"schedule_list",
"schedule_deleted",
+ "expert_workflow",
+ "expert_workflows",
+ "expert_credentials",
+ "credential_grant_requested",
"schedule_created",
"agent_trigger_list",
"trigger_setup",
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index ccb227f29e..d1312d1bdd 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -96,7 +96,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
| transport | Run on platform credits, or on your connected ChatGPT subscription if supported by your plan. | "platform" \| "codex_app_server" | No |
| session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No |
| max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |
-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "handoff_to_expert" \| "hire_expert" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "revoke_expert_credential" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |
| blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |