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/copilot): post_to_discord tool for proactive output (#13349)
Bentlyf7fcde901a99
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pyindex c2dea20c5f..c2a9b0590f 100644--- a/autogpt_platform/backend/backend/copilot/permissions.py+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -97,6 +97,7 @@ ToolName = Literal["get_platform_info","get_sub_session_result","list_agent_triggers",+ "list_chat_platform_channels","list_folders","list_schedules","list_skills",@@ -107,6 +108,7 @@ ToolName = Literal["memory_store","move_agents_to_folder","move_folder",+ "post_to_chat_platform","read_skill","read_workspace_file","run_agent",diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.pyindex 0a7a29aeb6..bd8a0b17b2 100644--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py@@ -13,6 +13,7 @@ from .agent_browser import BrowserActTool, BrowserNavigateTool, BrowserScreenshofrom .agent_output import AgentOutputToolfrom .base import BaseToolfrom .bash_exec import BashExecTool+from .chat_platform import ListChatPlatformChannelsTool, PostToChatPlatformToolfrom .connect_integration import ConnectIntegrationToolfrom .continue_run_block import ContinueRunBlockToolfrom .create_agent import CreateAgentTool@@ -93,6 +94,9 @@ TOOL_REGISTRY: dict[str, BaseTool] = {"list_schedules": ListSchedulesTool(),"delete_schedule": DeleteScheduleTool(),"schedule_followup": ScheduleFollowupTool(),+ # Proactive chat-platform output (post message / open thread on user's behalf)+ "post_to_chat_platform": PostToChatPlatformTool(),+ "list_chat_platform_channels": ListChatPlatformChannelsTool(),# Trigger discovery (parent agent → its triggers)"list_agent_triggers": ListAgentTriggersTool(),"run_block": RunBlockTool(),diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform.pynew file mode 100644index 0000000000..3eb55a39f8--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform.py@@ -0,0 +1,348 @@+"""Tools for the copilot to post to a linked chat platform on the user's behalf.++``post_to_chat_platform`` lets AutoPilot send a standalone message or open a new+thread in a channel of a chat platform (Discord today; Slack/Telegram as their+adapters land) the user has linked. The headline use case is *scheduled*+output: "every Monday post an update in #standup" — AutoPilot schedules a+follow-up turn (via ``schedule_followup``) whose message instructs it to post,+and at fire time it calls this tool.++A single ``platform`` enum keeps the tool surface flat as platforms are added,+instead of one ``post_to_<platform>`` tool per platform. Delivery and+authorization live in the bot bridge (``CoPilotChatBridge``): the tool only+forwards over RPC, and a post is only allowed into channels of a server the+calling user has linked — enforced bridge-side.++``list_chat_platform_channels`` backs channel-name disambiguation and the+"pick a channel" flow.+"""++import logging+from functools import lru_cache+from typing import Any++from backend.copilot.model import ChatSession+from backend.platform_linking.models import Platform+from backend.util.clients import get_copilot_chat_bridge_client+from backend.util.settings import Settings++from .base import BaseTool+from .models import (+ ChatPlatformChannelListResponse,+ ChatPlatformChannelSummary,+ ChatPlatformPostedResponse,+ ErrorResponse,+ ToolResponseBase,+)++logger = logging.getLogger(__name__)++# Chat platforms with a wired bridge adapter. Add a value here (and its bot+# token check in ``_any_chat_platform_configured``) when a new adapter ships —+# the tool surface stays the same.+SUPPORTED_PLATFORMS: tuple[str, ...] = ("discord",)++# Maps the bridge's stable DeliveryResult error codes to user-facing text the+# model can relay or act on. Anything unmapped falls back to the raw code.+_ERROR_MESSAGES: dict[str, str] = {+ "no_linked_servers": (+ "No server is linked to this AutoGPT account on that platform yet. "+ "Link one via the bot's setup command before posting."+ ),+ "channel_not_found": (+ "No channel matching that reference was found in your linked server(s). "+ "Call list_chat_platform_channels to see valid options."+ ),+ "not_authorized": (+ "That channel belongs to a server that isn't linked to your account, "+ "so the bot won't post there."+ ),+ "ambiguous_channel": (+ "More than one channel matches that name across your linked servers. "+ "Use the numeric channel ID, or call list_chat_platform_channels."+ ),+ "send_failed": (+ "The platform rejected the message — the bot likely lacks permission "+ "to post in that channel."+ ),+ "thread_failed": (+ "Couldn't create the thread — the bot likely lacks permission to "+ "create public threads in that channel."+ ),+}+++@lru_cache(maxsize=1)+def _any_chat_platform_configured() -> bool:+ """Whether any chat-platform bot is configured, gating tool availability.++ Cached because ``get_available_tools`` reads ``is_available`` for every tool+ on every request, and constructing ``Settings()`` re-parses the env each+ time. The bot token is fixed at deploy time, so a one-time read is safe.++ Assumes the copilot/executor process shares the bot token env with the+ bridge pod (true for ``poetry run app`` and the standard deployment).+ """+ return bool(Settings().secrets.autopilot_bot_discord_token)+++def _error_message(code: str | None) -> str:+ if not code:+ return "The post could not be completed."+ return _ERROR_MESSAGES.get(code, f"The post failed ({code}).")+++def _platform_param() -> dict[str, Any]:+ return {+ "type": "string",+ "enum": list(SUPPORTED_PLATFORMS),+ "description": "Chat platform to post to; defaults to 'discord'.",+ }+++def _resolve_platform(value: str | None) -> tuple[Platform | None, str]:+ """Map a platform string to the Platform enum; default to the sole one."""+ name = (value or SUPPORTED_PLATFORMS[0]).lower()+ if name not in SUPPORTED_PLATFORMS:+ return None, name+ return Platform(name.upper()), name+++class PostToChatPlatformTool(BaseTool):+ """Post a message or open a thread in a linked chat-platform channel."""++ @property+ def name(self) -> str:+ return "post_to_chat_platform"++ @property+ def description(self) -> str:+ return (+ "Post to a linked chat platform (e.g. Discord) for the user. "+ "mode='message' sends a message; mode='thread' opens a new thread "+ "(needs thread_name). 'channel' is a name (#standup) or numeric ID. "+ "Pair with schedule_followup for recurring posts. If the channel "+ "can't be resolved, call list_chat_platform_channels first."+ )++ @property+ def requires_auth(self) -> bool:+ return True++ @property+ def is_available(self) -> bool:+ return _any_chat_platform_configured()++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {+ "platform": _platform_param(),+ "channel": {+ "type": "string",+ "description": "Channel name (#standup) or numeric ID.",+ },+ "content": {+ "type": "string",+ "description": "Message body to post.",+ },+ "mode": {+ "type": "string",+ "enum": ["message", "thread"],+ "description": "'message' or 'thread'. Defaults to 'message'.",+ },+ "thread_name": {+ "type": "string",+ "description": "Thread title; required when mode='thread'.",+ },+ },+ "required": ["channel", "content"],+ }++ @staticmethod+ def _validate_params(session_id: str | None, **kwargs) -> ErrorResponse | None:+ """Return an ``ErrorResponse`` for the first invalid param, else None."""+ _platform, platform_name = _resolve_platform(kwargs.get("platform"))+ if _platform is None:+ return ErrorResponse(+ message=f"Unsupported platform '{platform_name}'.",+ error="unsupported_platform",+ session_id=session_id,+ )+ channel: str | None = kwargs.get("channel")+ content: str | None = kwargs.get("content")+ mode: str = kwargs.get("mode") or "message"+ if not channel or not channel.strip():+ return ErrorResponse(+ message="`channel` is required.",+ error="missing_channel",+ session_id=session_id,+ )+ if not content or not content.strip():+ return ErrorResponse(+ message="`content` is required.",+ error="missing_content",+ session_id=session_id,+ )+ if mode not in ("message", "thread"):+ return ErrorResponse(+ message="`mode` must be 'message' or 'thread'.",+ error="invalid_mode",+ session_id=session_id,+ )+ if mode == "thread":+ thread_name: str | None = kwargs.get("thread_name")+ if not thread_name or not thread_name.strip():+ return ErrorResponse(+ message="`thread_name` is required when mode='thread'.",+ error="missing_thread_name",+ session_id=session_id,+ )+ return None++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ session_id = session.session_id if session else None+ if not user_id:+ return ErrorResponse(+ message="Authentication required.",+ error="auth_required",+ session_id=session_id,+ )+ invalid = self._validate_params(session_id, **kwargs)+ if invalid is not None:+ return invalid++ platform, platform_name = _resolve_platform(kwargs.get("platform"))+ if platform is None: # already validated; narrows the type+ return ErrorResponse(+ message=f"Unsupported platform '{platform_name}'.",+ error="unsupported_platform",+ session_id=session_id,+ )+ channel: str = kwargs["channel"]+ content: str = kwargs["content"]+ mode: str = kwargs.get("mode") or "message"++ client = get_copilot_chat_bridge_client()+ if mode == "thread":+ result = await client.create_thread_in_channel(+ platform=platform,+ user_id=user_id,+ channel=channel,+ thread_name=kwargs["thread_name"],+ content=content,+ )+ else:+ result = await client.send_message_to_channel(+ platform=platform,+ user_id=user_id,+ channel=channel,+ content=content,+ )++ if not result.ok:+ return ErrorResponse(+ message=_error_message(result.error),+ error=result.error or "chat_platform_post_failed",+ session_id=session_id,+ )++ where = "thread" if result.kind == "thread" else "message"+ link_note = f" ({result.url})" if result.url else ""+ return ChatPlatformPostedResponse(+ message=f"Posted {where} to {platform_name}{link_note}.",+ platform=platform_name,+ kind=result.kind,+ channel_id=result.channel_id or channel,+ ref_id=result.ref_id,+ url=result.url,+ session_id=session_id,+ )+++class ListChatPlatformChannelsTool(BaseTool):+ """List channels the bot can post to across the user's linked servers."""++ @property+ def name(self) -> str:+ return "list_chat_platform_channels"++ @property+ def description(self) -> str:+ return (+ "List channels the bot can post to on a linked chat platform "+ "(e.g. Discord). Use to resolve a channel name to an ID or pick "+ "one before post_to_chat_platform."+ )++ @property+ def requires_auth(self) -> bool:+ return True++ @property+ def is_available(self) -> bool:+ return _any_chat_platform_configured()++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {"platform": _platform_param()},+ }++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ session_id = session.session_id if session else None+ if not user_id:+ return ErrorResponse(+ message="Authentication required.",+ error="auth_required",+ session_id=session_id,+ )+ platform, platform_name = _resolve_platform(kwargs.get("platform"))+ if platform is None:+ return ErrorResponse(+ message=f"Unsupported platform '{platform_name}'.",+ error="unsupported_platform",+ session_id=session_id,+ )++ channels = await get_copilot_chat_bridge_client().list_channels(+ platform=platform,+ user_id=user_id,+ )+ summaries = [+ ChatPlatformChannelSummary(+ id=c.id,+ name=c.name,+ server_id=c.server_id,+ server_name=c.server_name,+ )+ for c in channels+ ]+ if summaries:+ message = (+ f"Found {len(summaries)} channel(s) you can post to on {platform_name}."+ )+ else:+ message = (+ f"No postable {platform_name} channels found. Link a server via "+ "the bot's setup command, or check the bot's channel permissions."+ )+ return ChatPlatformChannelListResponse(+ message=message,+ platform=platform_name,+ channels=summaries,+ count=len(summaries),+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.pynew file mode 100644index 0000000000..73d4cbddd4--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py@@ -0,0 +1,229 @@+"""Tests for PostToChatPlatformTool and ListChatPlatformChannelsTool."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.bot.adapters.base import ChannelInfo+from backend.copilot.bot.outbound import DeliveryResult+from backend.copilot.tools.chat_platform import (+ ListChatPlatformChannelsTool,+ PostToChatPlatformTool,+)+from backend.copilot.tools.models import (+ ChatPlatformChannelListResponse,+ ChatPlatformPostedResponse,+ ErrorResponse,+)++from ._test_data import make_session++_USER = "test-user-chat"+_PATH = "backend.copilot.tools.chat_platform"+++def session():+ return make_session(_USER)+++def _bridge() -> MagicMock:+ bridge = MagicMock()+ bridge.send_message_to_channel = AsyncMock()+ bridge.create_thread_in_channel = AsyncMock()+ bridge.list_channels = AsyncMock()+ return bridge+++# ── PostToChatPlatformTool ─────────────────────────────────────────+++async def test_post_requires_auth(session):+ result = await PostToChatPlatformTool()._execute(+ user_id=None, session=session, channel="#x", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "auth_required"+++async def test_post_missing_channel(session):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel=" ", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_channel"+++async def test_post_thread_requires_thread_name(session):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="#x", content="hi", mode="thread"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_thread_name"+++async def test_post_unsupported_platform(session):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, platform="myspace", channel="#x", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "unsupported_platform"+++async def test_post_message_happy_path_defaults_to_discord(session):+ bridge = _bridge()+ bridge.send_message_to_channel.return_value = DeliveryResult(+ ok=True,+ kind="message",+ channel_id="42",+ ref_id="100",+ url="https://discord.com/x",+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="#standup", content="hi"+ )+ assert isinstance(result, ChatPlatformPostedResponse)+ assert result.platform == "discord"+ assert result.kind == "message"+ assert result.channel_id == "42"+ assert result.url == "https://discord.com/x"+ # platform forwarded to the bridge as the enum value.+ assert (+ bridge.send_message_to_channel.await_args.kwargs["platform"].value == "DISCORD"+ )+ bridge.create_thread_in_channel.assert_not_awaited()+++async def test_post_thread_happy_path(session):+ bridge = _bridge()+ bridge.create_thread_in_channel.return_value = DeliveryResult(+ ok=True,+ kind="thread",+ channel_id="42",+ ref_id="t1",+ url="https://discord.com/t",+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER,+ session=session,+ platform="discord",+ channel="42",+ content="body",+ mode="thread",+ thread_name="Monday",+ )+ assert isinstance(result, ChatPlatformPostedResponse)+ assert result.kind == "thread"+ assert result.ref_id == "t1"+ bridge.create_thread_in_channel.assert_awaited_once()+++async def test_post_maps_authz_error(session):+ bridge = _bridge()+ bridge.send_message_to_channel.return_value = DeliveryResult(+ ok=False, kind="message", error="not_authorized"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="999", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "not_authorized"+ assert "isn't linked" in result.message+++async def test_post_missing_content(session):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="#x", content=" "+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_content"+++async def test_post_invalid_mode(session):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="#x", content="hi", mode="shout"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "invalid_mode"+++async def test_post_message_send_failed_maps_error(session):+ bridge = _bridge()+ bridge.send_message_to_channel.return_value = DeliveryResult(+ ok=False, kind="message", channel_id="42", error="send_failed"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER, session=session, channel="#x", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "send_failed"+ assert "permission" in result.message+++async def test_post_thread_failed_maps_error(session):+ bridge = _bridge()+ bridge.create_thread_in_channel.return_value = DeliveryResult(+ ok=False, kind="thread", channel_id="42", error="thread_failed"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await PostToChatPlatformTool()._execute(+ user_id=_USER,+ session=session,+ channel="#x",+ content="body",+ mode="thread",+ thread_name="Monday",+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "thread_failed"+++async def test_post_unavailable_without_token():+ with patch(f"{_PATH}._any_chat_platform_configured", return_value=False):+ assert PostToChatPlatformTool().is_available is False+ with patch(f"{_PATH}._any_chat_platform_configured", return_value=True):+ assert PostToChatPlatformTool().is_available is True+++# ── ListChatPlatformChannelsTool ───────────────────────────────────+++async def test_list_channels_happy_path(session):+ bridge = _bridge()+ bridge.list_channels.return_value = [+ ChannelInfo(id="10", name="general", server_id="g1", server_name="Guild"),+ ]+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await ListChatPlatformChannelsTool()._execute(+ user_id=_USER, session=session+ )+ assert isinstance(result, ChatPlatformChannelListResponse)+ assert result.platform == "discord"+ assert result.count == 1+ assert result.channels[0].name == "general"+++async def test_list_channels_requires_auth(session):+ result = await ListChatPlatformChannelsTool()._execute(+ user_id=None, session=session+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "auth_required"diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex 77dbf5dc91..d28bb468f6 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -105,6 +105,10 @@ class ResponseType(str, Enum):# Platform infoPLATFORM_INFO = "platform_info"+ # Chat-platform proactive output (post message / create thread)+ CHAT_PLATFORM_CHANNEL_LIST = "chat_platform_channel_list"+ CHAT_PLATFORM_POSTED = "chat_platform_posted"+# Skills (self-distilled procedure registry)SKILL_STORED = "skill_stored"SKILL_LOADED = "skill_loaded"@@ -957,3 +961,35 @@ class PlatformInfoResponse(ToolResponseBase):topic: strtier: str | None = Nonebilling_url: str | None = "/settings/billing"+++# --- Chat-platform proactive output (Discord today; Slack/Telegram later) ---+++class ChatPlatformChannelSummary(BaseModel):+ """A channel the bot can post to on the user's behalf."""++ id: str+ name: str+ server_id: str+ server_name: str | None = None+++class ChatPlatformChannelListResponse(ToolResponseBase):+ """Response for the ``list_chat_platform_channels`` tool."""++ type: ResponseType = ResponseType.CHAT_PLATFORM_CHANNEL_LIST+ platform: str+ channels: list[ChatPlatformChannelSummary] = Field(default_factory=list)+ count: int = 0+++class ChatPlatformPostedResponse(ToolResponseBase):+ """Response after the bot posts a message or creates a thread."""++ type: ResponseType = ResponseType.CHAT_PLATFORM_POSTED+ platform: str+ kind: Literal["message", "thread"]+ channel_id: str+ ref_id: str | None = None+ url: str | None = Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.pyindex 56f45463b2..4c89094f4a 100644--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py@@ -74,7 +74,12 @@ from backend.copilot.tools import TOOL_REGISTRY# a new ``agent_id`` parameter (library_agent_id / graph_id) that resolves the# exact agent with no fuzzy name-search fallback, so the library "Chat" flow is# reliable without a separate tool. Net smaller than a dedicated tool would add.-_CHAR_BUDGET = 41_000+# Bumped 41000 -> 43000 for the proactive chat-platform tools+# (post_to_chat_platform + list_chat_platform_channels): one platform-enum pair+# instead of per-platform tools. Descriptions are already trimmed to the minimum+# viable copy (~1400 chars for both schemas); the base had reached ~40.5k of the+# 41k cap, leaving no headroom, so the bump also restores margin for drift.+_CHAR_BUDGET = 43_000@pytest.fixture(scope="module")diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 95dc757c69..d25f5a29d3 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -18504,6 +18504,8 @@"memory_forget_confirm","todo_write","platform_info",+ "chat_platform_channel_list",+ "chat_platform_posted","skill_stored","skill_loaded","skill_deleted",