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/copilot-bot): outbound channel/thread delivery RPC (#13348)

Bently78cf0ac6106d
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
index 8839a51e86..d5832de46d 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
@@ -44,6 +44,32 @@ class FileAttachment(BaseModel):
content: bytes
+class ChannelInfo(BaseModel):
+ """A channel the bot can post to, scoped to a server it's connected to.
+
+ Returned by ``list_text_channels`` so the proactive-output path (and the
+ copilot tool above it) can resolve a human channel reference like
+ ``#announcements`` to a concrete ``id`` and present a picker.
+ """
+
+ id: str
+ name: str
+ server_id: str
+ server_name: Optional[str] = None
+
+
+class PostedRef(BaseModel):
+ """Pointer to something the bot just created on the platform.
+
+ ``url`` is a best-effort permalink (Discord ``jump_url``) so callers can
+ surface a clickable link in their confirmation; platforms without
+ permalinks leave it ``None``.
+ """
+
+ id: str
+ url: Optional[str] = None
+
+
@dataclass
class MessageContext:
"""Everything the core handler needs to know about an incoming message."""
@@ -179,3 +205,53 @@ class PlatformAdapter(ABC):
the handler enforces that upstream via the workspace fetch path.
"""
...
+
+ # -- Proactive output (backend → platform) ----------------------------
+ # These power scheduled / autopilot-initiated posts, where the bot speaks
+ # without a triggering user message. Authorization (which servers a user
+ # may post to) is enforced one layer up; adapters here only translate an
+ # already-authorized request into platform API calls.
+
+ @abstractmethod
+ async def list_text_channels(
+ self, server_ids: tuple[str, ...]
+ ) -> list[ChannelInfo]:
+ """List the text channels the bot can post to across ``server_ids``.
+
+ Only channels the bot can actually send in should be returned, so the
+ caller's picker never offers a channel the post would fail on.
+ """
+ ...
+
+ @abstractmethod
+ async def get_channel_server_id(self, channel_id: str) -> Optional[str]:
+ """Return the server (guild) ID a channel belongs to, or ``None``.
+
+ Used to authorize a post target given a raw channel ID without
+ enumerating every channel first.
+ """
+ ...
+
+ @abstractmethod
+ async def post_channel_message(
+ self, channel_id: str, text: str
+ ) -> Optional[PostedRef]:
+ """Post a standalone message to ``channel_id``.
+
+ Distinct from ``send_message`` (the streaming-reply path): this
+ returns a ``PostedRef`` so proactive callers can report what was
+ created. Returns ``None`` if the channel can't be posted to.
+ """
+ ...
+
+ @abstractmethod
+ async def create_channel_thread(
+ self, channel_id: str, name: str, text: str
+ ) -> Optional[PostedRef]:
+ """Create a standalone thread in ``channel_id`` and post ``text`` in it.
+
+ "Standalone" = not anchored to a pre-existing message (unlike
+ ``create_thread``). Returns the thread's ``PostedRef``, or ``None`` if
+ the platform/channel doesn't support it.
+ """
+ ...
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
index 80d48e788b..519e3aec50 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -15,14 +15,17 @@ from discord import app_commands
from backend.copilot.bot import threads
from backend.copilot.bot.bot_backend import BotBackend
+from backend.copilot.bot.text import split_at_boundary
from ..base import (
+ ChannelInfo,
ChannelType,
FileAttachment,
MessageCallback,
MessageContext,
MessageHistoryEntry,
PlatformAdapter,
+ PostedRef,
)
from . import commands, config, intro
@@ -200,6 +203,113 @@ class DiscordAdapter(PlatformAdapter):
logger.exception("Failed to rename thread %s", thread_id)
return False
+ # -- Proactive output --
+
+ async def list_text_channels(
+ self, server_ids: tuple[str, ...]
+ ) -> list[ChannelInfo]:
+ wanted = set(server_ids)
+ channels: list[ChannelInfo] = []
+ for guild in self._client.guilds:
+ if str(guild.id) not in wanted:
+ continue
+ me = guild.me
+ for channel in guild.text_channels:
+ # Only surface channels the bot can actually post in, so the
+ # picker upstream never offers a target that would 403 on send.
+ # If the bot member isn't cached (`me is None`) we can't check,
+ # so we surface the channel and let the eventual send fail
+ # loudly rather than hide everything.
+ if me is not None and not channel.permissions_for(me).send_messages:
+ continue
+ channels.append(
+ ChannelInfo(
+ id=str(channel.id),
+ name=channel.name,
+ server_id=str(guild.id),
+ server_name=guild.name,
+ )
+ )
+ return channels
+
+ async def get_channel_server_id(self, channel_id: str) -> Optional[str]:
+ channel = await self._resolve_channel(channel_id)
+ # Guild channels and threads carry `.guild`; DM/group channels don't,
+ # so they resolve to None (never authorized for a server post).
+ if isinstance(channel, (discord.abc.GuildChannel, discord.Thread)):
+ return str(channel.guild.id)
+ return None
+
+ async def post_channel_message(
+ self, channel_id: str, text: str
+ ) -> Optional[PostedRef]:
+ channel = await self._resolve_channel(channel_id)
+ if channel is None or not isinstance(channel, discord.abc.Messageable):
+ logger.warning("Cannot post to non-messageable channel %s", channel_id)
+ return None
+ try:
+ first = await self._send_chunked(channel, text)
+ except discord.HTTPException:
+ logger.exception("Failed to post message to channel %s", channel_id)
+ return None
+ if first is None:
+ return None
+ return PostedRef(id=str(first.id), url=first.jump_url)
+
+ async def create_channel_thread(
+ self, channel_id: str, name: str, text: str
+ ) -> Optional[PostedRef]:
+ channel = await self._resolve_channel(channel_id)
+ if channel is None or not isinstance(channel, discord.TextChannel):
+ logger.warning("Cannot create thread in non-text channel %s", channel_id)
+ return None
+ try:
+ thread = await channel.create_thread(
+ name=name[:100],
+ type=discord.ChannelType.public_thread,
+ )
+ except discord.HTTPException:
+ logger.exception("Failed to create thread in channel %s", channel_id)
+ return None
+ # The thread now exists on Discord. Surface its ref even if posting the
+ # body fails, so the caller reports partial success and doesn't retry
+ # into a duplicate thread.
+ try:
+ await self._send_chunked(thread, text)
+ except discord.HTTPException:
+ logger.exception(
+ "Thread %s created but posting its content failed", thread.id
+ )
+ return PostedRef(id=str(thread.id), url=thread.jump_url)
+
+ async def _send_chunked(
+ self, channel: discord.abc.Messageable, text: str
+ ) -> Optional[discord.Message]:
+ """Send ``text`` to ``channel``, splitting at natural boundaries to stay
+ under Discord's per-message cap. Returns the first message sent (the one
+ callers permalink to), or ``None`` if there was nothing to send.
+
+ Raises only if the *first* chunk fails — once anything is delivered, a
+ later-chunk failure stops the send and keeps the partial result rather
+ than discarding what already posted (a retry would duplicate it).
+ """
+ remaining = text.strip()
+ first: Optional[discord.Message] = None
+ while remaining:
+ chunk, remaining = split_at_boundary(remaining, config.CHUNK_FLUSH_AT)
+ if not chunk:
+ break
+ try:
+ msg = await channel.send(chunk, tts=False)
+ except discord.HTTPException:
+ if first is None:
+ raise
+ logger.exception("Dropping trailing chunk after partial send")
+ break
+ if first is None:
+ first = msg
+ return first
+
# -- Internal --
def _register_events(self) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
index d4982334ed..5a9668972a 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
@@ -788,3 +788,173 @@ class TestLockedThread:
await handlers["on_message"](msg)
callback.assert_awaited_once()
+
+
+# ── Proactive output (backend → platform) ──────────────────────────────
+
+
+def _guild_channel(channel_id: int, name: str, can_send: bool) -> MagicMock:
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.id = channel_id
+ channel.name = name
+ perms = MagicMock()
+ perms.send_messages = can_send
+ channel.permissions_for = MagicMock(return_value=perms)
+ return channel
+
+
+def _guild_with_channels(
+ guild_id: int, name: str, channels: list[MagicMock]
+) -> MagicMock:
+ guild = MagicMock()
+ guild.id = guild_id
+ guild.name = name
+ guild.me = MagicMock()
+ guild.text_channels = channels
+ return guild
+
+
+class TestProactiveOutput:
+ @pytest.mark.asyncio
+ async def test_list_text_channels_filters_servers_and_permissions(self):
+ adapter, client = _bare_adapter()
+ g1 = _guild_with_channels(
+ 111,
+ "Guild One",
+ [
+ _guild_channel(10, "general", True),
+ _guild_channel(11, "locked", False),
+ ],
+ )
+ g2 = _guild_with_channels(222, "Guild Two", [_guild_channel(20, "other", True)])
+ client.guilds = [g1, g2]
+
+ result = await adapter.list_text_channels(("111",))
+
+ assert [(c.id, c.name, c.server_id) for c in result] == [
+ ("10", "general", "111")
+ ]
+
+ @pytest.mark.asyncio
+ async def test_get_channel_server_id_returns_guild(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.guild = MagicMock(id=111)
+ client.get_channel.return_value = channel
+
+ assert await adapter.get_channel_server_id("10") == "111"
+
+ @pytest.mark.asyncio
+ async def test_get_channel_server_id_none_when_missing(self):
+ adapter, client = _bare_adapter()
+ client.get_channel.return_value = None
+ client.fetch_channel = AsyncMock(
+ side_effect=discord.NotFound(MagicMock(status=404), "gone")
+ )
+ assert await adapter.get_channel_server_id("10") is None
+
+ @pytest.mark.asyncio
+ async def test_post_channel_message_returns_ref_with_url(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ sent = MagicMock(id=999, jump_url="https://discord.com/channels/1/2/999")
+ channel.send = AsyncMock(return_value=sent)
+ client.get_channel.return_value = channel
+
+ ref = await adapter.post_channel_message("10", "hello")
+
+ assert ref is not None
+ assert ref.id == "999"
+ assert ref.url == "https://discord.com/channels/1/2/999"
+
+ @pytest.mark.asyncio
+ async def test_create_channel_thread_creates_and_posts(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ thread = MagicMock(spec=discord.Thread)
+ thread.id = 555
+ thread.jump_url = "https://discord.com/channels/1/555"
+ thread.send = AsyncMock()
+ channel.create_thread = AsyncMock(return_value=thread)
+ client.get_channel.return_value = channel
+
+ ref = await adapter.create_channel_thread("10", "Monday update", "body")
+
+ assert ref is not None
+ assert ref.id == "555"
+ channel.create_thread.assert_awaited_once()
+ thread.send.assert_awaited()
+
+ @pytest.mark.asyncio
+ async def test_create_channel_thread_rejects_non_text_channel(self):
+ adapter, client = _bare_adapter()
+ client.get_channel.return_value = MagicMock(spec=discord.Thread)
+
+ assert await adapter.create_channel_thread("10", "x", "body") is None
+
+ @pytest.mark.asyncio
+ async def test_send_chunked_splits_long_text(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.send = AsyncMock(
+ side_effect=lambda *a, **k: MagicMock(id=1, jump_url="u")
+ )
+ client.get_channel.return_value = channel
+
+ long_text = ("word " * 1000).strip()
+ ref = await adapter.post_channel_message("10", long_text)
+
+ assert ref is not None
+ # 5000 chars at ~1900/chunk → more than one send.
+ assert channel.send.await_count >= 2
+
+ @pytest.mark.asyncio
+ async def test_post_message_keeps_first_chunk_on_later_failure(self):
+ # First chunk posts, a later chunk 500s: the already-posted message is
+ # surfaced (partial success) rather than discarded into a retry-duplicate.
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ first = MagicMock(id=111, jump_url="u1")
+ channel.send = AsyncMock(
+ side_effect=[first, discord.HTTPException(MagicMock(status=500), "boom")]
+ )
+ client.get_channel.return_value = channel
+
+ ref = await adapter.post_channel_message("10", ("word " * 1000).strip())
+
+ assert ref is not None
+ assert ref.id == "111"
+ # Prove the later (failing) chunk was actually reached, so chunk-sizing
+ # changes can't quietly turn this into a single-send happy path.
+ assert channel.send.await_count >= 2
+
+ @pytest.mark.asyncio
+ async def test_post_message_returns_none_when_first_chunk_fails(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.send = AsyncMock(
+ side_effect=discord.HTTPException(MagicMock(status=500), "boom")
+ )
+ client.get_channel.return_value = channel
+
+ assert await adapter.post_channel_message("10", "hi") is None
+
+ @pytest.mark.asyncio
+ async def test_create_thread_returns_ref_when_content_post_fails(self):
+ # Thread created but posting body fails → still return the thread ref so
+ # the caller doesn't retry and spawn a duplicate thread.
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ thread = MagicMock(spec=discord.Thread)
+ thread.id = 777
+ thread.jump_url = "https://discord.com/t/777"
+ thread.send = AsyncMock(
+ side_effect=discord.HTTPException(MagicMock(status=500), "boom")
+ )
+ channel.create_thread = AsyncMock(return_value=thread)
+ client.get_channel.return_value = channel
+
+ ref = await adapter.create_channel_thread("10", "Monday", "body")
+
+ assert ref is not None
+ assert ref.id == "777"
diff --git a/autogpt_platform/backend/backend/copilot/bot/app.py b/autogpt_platform/backend/backend/copilot/bot/app.py
index 277eda50f4..34bdfc6a6c 100644
--- a/autogpt_platform/backend/backend/copilot/bot/app.py
+++ b/autogpt_platform/backend/backend/copilot/bot/app.py
@@ -17,11 +17,13 @@ from backend.util.service import (
)
from backend.util.settings import Settings
-from .adapters.base import PlatformAdapter
+from . import outbound
+from .adapters.base import ChannelInfo, PlatformAdapter
from .adapters.discord import config as discord_config
from .adapters.discord.adapter import DiscordAdapter
from .bot_backend import BotBackend
from .handler import MessageHandler
+from .outbound import DeliveryResult
logger = logging.getLogger(__name__)
@@ -40,6 +42,12 @@ class CoPilotChatBridge(AppService):
# for any reason. Consumed by `health_check` so orchestrators can
# restart the pod when the bridge is dead-but-listening.
self._adapters_healthy = False
+ # Populated by `_run_adapters` so the outbound RPC handlers can reach
+ # the live adapter (and its gateway connection) by platform name. The
+ # RPC handlers run on the same shared event loop as the adapters, so
+ # they can await adapter methods directly.
+ self._api: BotBackend | None = None
+ self._adapters_by_platform: dict[str, PlatformAdapter] = {}
@classmethod
def get_port(cls) -> int:
@@ -54,7 +62,9 @@ class CoPilotChatBridge(AppService):
async def _run_adapters(self) -> None:
api = BotBackend()
+ self._api = api
adapters = _build_adapters(api)
+ self._adapters_by_platform = {a.platform_name: a for a in adapters}
if not adapters:
logger.info(
@@ -88,6 +98,11 @@ class CoPilotChatBridge(AppService):
cheerfully reporting OK on a dead bridge.
"""
self._adapters_healthy = False
+ # Drop the adapter/api handles so outbound RPCs raise UnhealthyService
+ # instead of dispatching into an adapter whose gateway connection has
+ # already torn down.
+ self._adapters_by_platform = {}
+ self._api = None
exc = future.exception()
if exc is not None:
logger.error("CoPilotChatBridge adapters crashed: %r", exc, exc_info=exc)
@@ -99,36 +114,68 @@ class CoPilotChatBridge(AppService):
raise UnhealthyServiceError("CoPilotChatBridge adapter task is not running")
return await super().health_check()
+ def _require(self, platform: Platform) -> tuple[PlatformAdapter, BotBackend]:
+ """Resolve the live adapter + backend for ``platform`` or raise.
+
+ Raises ``UnhealthyServiceError`` (a transient-shaped error) when the
+ bridge hasn't finished starting or the platform's adapter isn't
+ configured, so a retrying caller backs off instead of treating it as
+ a permanent failure.
+ """
+ if not self._adapters_healthy:
+ raise UnhealthyServiceError("CoPilotChatBridge adapter task is not running")
+ adapter = self._adapters_by_platform.get(platform.value.lower())
+ if adapter is None or self._api is None:
+ raise UnhealthyServiceError(
+ f"No running adapter for platform {platform.value}"
+ )
+ return adapter, self._api
+
@expose
- async def send_message_to_channel(
+ async def list_channels(
self,
platform: Platform,
- channel_id: str,
- content: str,
- ) -> bool:
- """Deliver a message to a channel on the given platform.
-
- Stub — scaffolding for the inbound-RPC pattern (backend → chat
- platform). Not yet wired to a concrete adapter. Callers must not use
- ``request_retry=True`` on the client until this is implemented, since
- ``ValueError`` crosses the RPC boundary as a client-side 4xx-ish error
- rather than a transient 5xx.
+ user_id: str,
+ ) -> list[ChannelInfo]:
+ """List channels ``user_id`` may post to via the bot on ``platform``.
+
+ Backs channel-name resolution and the picker in the copilot tool.
"""
- raise ValueError(f"send_message_to_channel not yet wired for {platform.value}")
+ adapter, api = self._require(platform)
+ return await outbound.list_channels(adapter, api, platform.value, user_id)
@expose
- async def send_dm(
+ async def send_message_to_channel(
self,
platform: Platform,
- platform_user_id: str,
+ user_id: str,
+ channel: str,
content: str,
- ) -> bool:
- """Deliver a DM to a user on the given platform.
+ ) -> DeliveryResult:
+ """Post ``content`` to ``channel`` (name or ID) as a standalone message.
- Stub — scaffolding for the inbound-RPC pattern. See
- :meth:`send_message_to_channel` for the retry caveat.
+ ``user_id`` is the AutoGPT user the post acts on behalf of; delivery
+ is authorized against the servers that user has linked.
"""
- raise ValueError(f"send_dm not yet wired for {platform.value}")
+ adapter, api = self._require(platform)
+ return await outbound.deliver_message(
+ adapter, api, platform.value, user_id, channel, content
+ )
+
+ @expose
+ async def create_thread_in_channel(
+ self,
+ platform: Platform,
+ user_id: str,
+ channel: str,
+ thread_name: str,
+ content: str,
+ ) -> DeliveryResult:
+ """Create a standalone thread in ``channel`` and post ``content`` in it."""
+ adapter, api = self._require(platform)
+ return await outbound.create_thread(
+ adapter, api, platform.value, user_id, channel, thread_name, content
+ )
class CoPilotChatBridgeClient(AppServiceClient):
@@ -136,10 +183,13 @@ class CoPilotChatBridgeClient(AppServiceClient):
def get_service_type(cls):
return CoPilotChatBridge
+ list_channels = endpoint_to_async(CoPilotChatBridge.list_channels)
send_message_to_channel = endpoint_to_async(
CoPilotChatBridge.send_message_to_channel
)
- send_dm = endpoint_to_async(CoPilotChatBridge.send_dm)
+ create_thread_in_channel = endpoint_to_async(
+ CoPilotChatBridge.create_thread_in_channel
+ )
def _build_adapters(api: BotBackend) -> list[PlatformAdapter]:
diff --git a/autogpt_platform/backend/backend/copilot/bot/app_test.py b/autogpt_platform/backend/backend/copilot/bot/app_test.py
new file mode 100644
index 0000000000..f6525e1e63
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/app_test.py
@@ -0,0 +1,93 @@
+"""Tests for CoPilotChatBridge's outbound RPC dispatch.
+
+Covers the seam that maps a ``Platform`` enum to the live adapter and routes
+into ``outbound`` — including the casing round-trip (``platform.value`` vs
+``platform_name``) and the no-adapter guard.
+"""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.platform_linking.models import Platform
+from backend.util.service import UnhealthyServiceError
+
+from .app import CoPilotChatBridge
+from .outbound import DeliveryResult
+
+
+def _bridge(*, with_adapter: bool = True) -> tuple[CoPilotChatBridge, MagicMock]:
+ """Build a bridge without AppService.__init__, with a stubbed adapter+api."""
+ bridge = CoPilotChatBridge.__new__(CoPilotChatBridge)
+ adapter = MagicMock()
+ adapter.platform_name = "discord"
+ bridge._adapters_healthy = True
+ bridge._api = MagicMock()
+ bridge._adapters_by_platform = {"discord": adapter} if with_adapter else {}
+ return bridge, adapter
+
+
+async def test_require_raises_when_adapter_missing():
+ bridge, _ = _bridge(with_adapter=False)
+ with pytest.raises(UnhealthyServiceError):
+ bridge._require(Platform.DISCORD)
+
+
+async def test_require_raises_when_unhealthy():
+ bridge, _ = _bridge()
+ bridge._adapters_healthy = False
+ with pytest.raises(UnhealthyServiceError):
+ bridge._require(Platform.DISCORD)
+
+
+async def test_send_message_to_channel_routes_platform_value():
+ bridge, _ = _bridge()
+ expected = DeliveryResult(ok=True, kind="message", channel_id="42", ref_id="1")
+ with patch(
+ "backend.copilot.bot.app.outbound.deliver_message",
+ new=AsyncMock(return_value=expected),
+ ) as deliver:
+ result = await bridge.send_message_to_channel(
+ platform=Platform.DISCORD, user_id="u1", channel="#x", content="hi"
+ )
+ assert result is expected
+ # platform passed through as the string value the lower layers expect.
+ call = deliver.await_args
+ assert call is not None
+ _, _, platform_value, user_id, channel, content = call.args
+ assert platform_value == "DISCORD"
+ assert (user_id, channel, content) == ("u1", "#x", "hi")
+
+
+async def test_create_thread_in_channel_routes_to_outbound():
+ bridge, _ = _bridge()
+ expected = DeliveryResult(ok=True, kind="thread", channel_id="42", ref_id="t1")
+ with patch(
+ "backend.copilot.bot.app.outbound.create_thread",
+ new=AsyncMock(return_value=expected),
+ ) as create:
+ result = await bridge.create_thread_in_channel(
+ platform=Platform.DISCORD,
+ user_id="u1",
+ channel="#x",
+ thread_name="Monday",
+ content="body",
+ )
+ assert result is expected
+ create.assert_awaited_once()
+
+
+async def test_list_channels_routes_to_outbound():
+ bridge, _ = _bridge()
+ with patch(
+ "backend.copilot.bot.app.outbound.list_channels",
+ new=AsyncMock(return_value=[]),
+ ) as lister:
+ result = await bridge.list_channels(platform=Platform.DISCORD, user_id="u1")
+ assert result == []
+ lister.assert_awaited_once()
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
index 57bd5f9240..60e38bb148 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -222,6 +222,17 @@ class BotBackend:
)
return ResolveResult(linked=resp.linked)
+ async def list_linked_server_ids(self, platform: str, user_id: str) -> list[str]:
+ """Return the platform server (guild) IDs ``user_id`` has linked.
+
+ Backs the proactive-output authorization check: a scheduled/autopilot
+ post is only allowed into a channel whose server appears in this list.
+ """
+ return await self._client.list_user_server_ids(
+ platform=Platform(platform.upper()),
+ user_id=user_id,
+ )
+
async def refresh_server_name(
self, platform: str, platform_server_id: str, server_name: str
) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
index 04dcffbc17..b67195cef9 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
@@ -62,6 +62,22 @@ class TestResolve:
assert result.linked is False
+class TestListLinkedServerIds:
+ @pytest.mark.asyncio
+ async def test_forwards_uppercased_platform_and_returns_ids(self, api: BotBackend):
+ api._client.list_user_server_ids = AsyncMock(return_value=["g1", "g2"])
+ result = await api.list_linked_server_ids("discord", "user-1")
+ assert result == ["g1", "g2"]
+ api._client.list_user_server_ids.assert_awaited_once_with(
+ platform=Platform.DISCORD, user_id="user-1"
+ )
+
+ @pytest.mark.asyncio
+ async def test_empty_when_no_links(self, api: BotBackend):
+ api._client.list_user_server_ids = AsyncMock(return_value=[])
+ assert await api.list_linked_server_ids("discord", "user-1") == []
+
+
class TestRefreshServerName:
@pytest.mark.asyncio
async def test_forwards_uppercased_platform(self, api: BotBackend):
diff --git a/autogpt_platform/backend/backend/copilot/bot/outbound.py b/autogpt_platform/backend/backend/copilot/bot/outbound.py
new file mode 100644
index 0000000000..81efe44bbf
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/outbound.py
@@ -0,0 +1,161 @@
+"""Proactive (backend → platform) message delivery.
+
+Turns an *already-authenticated* "post this to a channel" request into
+adapter calls. Two concerns live here, both platform-agnostic:
+
+- **Authorization** — a user may only post into channels that belong to a
+ server they've linked (``BotBackend.list_linked_server_ids``). Channel
+ resolution is funneled through that allowlist so an unauthorized target can
+ never be reached, whether referenced by ID or by name.
+- **Resolution** — a human channel reference (``#announcements``, a bare
+ name, or a raw snowflake ID) is mapped to a concrete channel ID.
+
+The adapter owns everything platform-specific (enumerating channels, sending,
+thread creation); this module never imports ``discord``.
+"""
+
+import logging
+import re
+from typing import Literal, Optional
+
+from pydantic import BaseModel
+
+from backend.copilot.bot.adapters.base import ChannelInfo, PlatformAdapter
+from backend.copilot.bot.bot_backend import BotBackend
+
+logger = logging.getLogger(__name__)
+
+# Discord snowflakes are 17-19 digits today; allow a little slack so the ID
+# path stays robust as the epoch advances rather than silently treating a
+# valid ID as a channel name.
+_SNOWFLAKE = re.compile(r"^\d{15,21}$")
+
+
+class DeliveryResult(BaseModel):
+ """Outcome of a proactive post, shaped for a tool/LLM to relay.
+
+ ``error`` is a stable machine code (e.g. ``not_authorized``) so the
+ caller can phrase its own user-facing message; ``ok`` is the only field
+ callers must branch on.
+ """
+
+ ok: bool
+ kind: Literal["message", "thread"]
+ channel_id: Optional[str] = None
+ ref_id: Optional[str] = None
+ url: Optional[str] = None
+ error: Optional[str] = None
+
+
+async def list_channels(
+ adapter: PlatformAdapter,
+ api: BotBackend,
+ platform: str,
+ user_id: str,
+) -> list[ChannelInfo]:
+ """List channels ``user_id`` may post to via the bot on ``platform``."""
+ server_ids = tuple(await api.list_linked_server_ids(platform, user_id))
+ if not server_ids:
+ return []
+ # Re-filter the adapter's output against the linked-server allowlist so the
+ # picker can never surface a channel from an unlinked server, even if an
+ # adapter over-returns. Mirrors the same guard in `_resolve_target`.
+ allowed = set(server_ids)
+ return [
+ channel
+ for channel in await adapter.list_text_channels(server_ids)
+ if channel.server_id in allowed
+ ]
+
+
+async def deliver_message(
+ adapter: PlatformAdapter,
+ api: BotBackend,
+ platform: str,
+ user_id: str,
+ channel: str,
+ content: str,
+) -> DeliveryResult:
+ """Post ``content`` to ``channel`` (name or ID) as a standalone message."""
+ if not content or not content.strip():
+ return DeliveryResult(ok=False, kind="message", error="empty_content")
+ channel_id, error = await _resolve_target(adapter, api, platform, user_id, channel)
+ if channel_id is None:
+ return DeliveryResult(ok=False, kind="message", error=error)
+ ref = await adapter.post_channel_message(channel_id, content)
+ if ref is None:
+ return DeliveryResult(
+ ok=False, kind="message", channel_id=channel_id, error="send_failed"
+ )
+ return DeliveryResult(
+ ok=True, kind="message", channel_id=channel_id, ref_id=ref.id, url=ref.url
+ )
+
+
+async def create_thread(
+ adapter: PlatformAdapter,
+ api: BotBackend,
+ platform: str,
+ user_id: str,
+ channel: str,
+ thread_name: str,
+ content: str,
+) -> DeliveryResult:
+ """Create a standalone thread in ``channel`` and post ``content`` in it."""
+ if not content or not content.strip():
+ return DeliveryResult(ok=False, kind="thread", error="empty_content")
+ channel_id, error = await _resolve_target(adapter, api, platform, user_id, channel)
+ if channel_id is None:
+ return DeliveryResult(ok=False, kind="thread", error=error)
+ ref = await adapter.create_channel_thread(channel_id, thread_name, content)
+ if ref is None:
+ return DeliveryResult(
+ ok=False, kind="thread", channel_id=channel_id, error="thread_failed"
+ )
+ return DeliveryResult(
+ ok=True, kind="thread", channel_id=channel_id, ref_id=ref.id, url=ref.url
+ )
+
+
+async def _resolve_target(
+ adapter: PlatformAdapter,
+ api: BotBackend,
+ platform: str,
+ user_id: str,
+ channel: str,
+) -> tuple[Optional[str], Optional[str]]:
+ """Resolve a channel reference to an authorized channel ID.
+
+ Returns ``(channel_id, None)`` on success or ``(None, error_code)``. Both
+ the ID path and the name path are constrained to the user's linked
+ servers, so resolution and authorization are the same step.
+ """
+ server_ids = tuple(await api.list_linked_server_ids(platform, user_id))
+ if not server_ids:
+ return None, "no_linked_servers"
+
+ ref = channel.strip().lstrip("#").strip()
+ if not ref:
+ return None, "channel_not_found"
+
+ if _SNOWFLAKE.match(ref):
+ guild_id = await adapter.get_channel_server_id(ref)
+ if guild_id is None:
+ return None, "channel_not_found"
+ if guild_id not in server_ids:
+ return None, "not_authorized"
+ return ref, None
+
+ # `c.server_id in server_ids` is redundant with passing `server_ids` to
+ # the adapter, but re-asserting it here keeps authorization correct even
+ # if an adapter ever returns channels outside the requested servers.
+ matches = [
+ c
+ for c in await adapter.list_text_channels(server_ids)
+ if c.name.lower() == ref.lower() and c.server_id in server_ids
+ ]
+ if not matches:
+ return None, "channel_not_found"
+ if len(matches) > 1:
+ return None, "ambiguous_channel"
+ return matches[0].id, None
diff --git a/autogpt_platform/backend/backend/copilot/bot/outbound_test.py b/autogpt_platform/backend/backend/copilot/bot/outbound_test.py
new file mode 100644
index 0000000000..5092d877e3
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/outbound_test.py
@@ -0,0 +1,203 @@
+"""Tests for proactive-output authorization + channel resolution."""
+
+from unittest.mock import AsyncMock
+
+import pytest
+
+from backend.copilot.bot import outbound
+from backend.copilot.bot.adapters.base import ChannelInfo, PostedRef
+
+
+def _api(server_ids: list[str]) -> AsyncMock:
+ api = AsyncMock()
+ api.list_linked_server_ids.return_value = server_ids
+ return api
+
+
+def _adapter(
+ *,
+ channels: list[ChannelInfo] | None = None,
+ channel_server: str | None = None,
+ posted: PostedRef | None = None,
+ thread: PostedRef | None = None,
+) -> AsyncMock:
+ adapter = AsyncMock()
+ adapter.list_text_channels.return_value = channels or []
+ adapter.get_channel_server_id.return_value = channel_server
+ adapter.post_channel_message.return_value = posted
+ adapter.create_channel_thread.return_value = thread
+ return adapter
+
+
+async def test_deliver_message_resolves_name_and_posts():
+ adapter = _adapter(
+ channels=[ChannelInfo(id="42", name="announcements", server_id="g1")],
+ posted=PostedRef(id="100", url="https://discord.com/x"),
+ )
+ result = await outbound.deliver_message(
+ adapter, _api(["g1"]), "discord", "user-1", "#announcements", "hi"
+ )
+ assert result.ok is True
+ assert result.kind == "message"
+ assert result.channel_id == "42"
+ assert result.ref_id == "100"
+ assert result.url == "https://discord.com/x"
+ adapter.post_channel_message.assert_awaited_once_with("42", "hi")
+
+
+async def test_deliver_message_by_authorized_id():
+ adapter = _adapter(channel_server="g1", posted=PostedRef(id="100"))
+ result = await outbound.deliver_message(
+ adapter, _api(["g1", "g2"]), "discord", "user-1", "999888777666555444", "hi"
+ )
+ assert result.ok is True
+ assert result.channel_id == "999888777666555444"
+ # ID path must not enumerate channels.
+ adapter.list_text_channels.assert_not_awaited()
+
+
+async def test_deliver_message_id_in_unlinked_server_is_rejected():
+ adapter = _adapter(channel_server="other-guild", posted=PostedRef(id="100"))
+ result = await outbound.deliver_message(
+ adapter, _api(["g1"]), "discord", "user-1", "999888777666555444", "hi"
+ )
+ assert result.ok is False
+ assert result.error == "not_authorized"
+ adapter.post_channel_message.assert_not_awaited()
+
+
+async def test_deliver_message_unknown_id_is_not_found():
+ adapter = _adapter(channel_server=None)
+ result = await outbound.deliver_message(
+ adapter, _api(["g1"]), "discord", "user-1", "999888777666555444", "hi"
+ )
+ assert result.ok is False
+ assert result.error == "channel_not_found"
+
+
+async def test_deliver_message_name_not_found():
+ adapter = _adapter(channels=[ChannelInfo(id="42", name="general", server_id="g1")])
+ result = await outbound.deliver_message(
+ adapter, _api(["g1"]), "discord", "user-1", "#announcements", "hi"
+ )
+ assert result.ok is False
+ assert result.error == "channel_not_found"
+
+
+async def test_deliver_message_ambiguous_name():
+ adapter = _adapter(
+ channels=[
+ ChannelInfo(id="42", name="general", server_id="g1"),
+ ChannelInfo(id="43", name="general", server_id="g2"),
+ ]
+ )
+ result = await outbound.deliver_message(
+ adapter, _api(["g1", "g2"]), "discord", "user-1", "general", "hi"
+ )
+ assert result.ok is False
+ assert result.error == "ambiguous_channel"
+
+
+async def test_no_linked_servers_short_circuits():
+ adapter = _adapter()
+ result = await outbound.deliver_message(
+ adapter, _api([]), "discord", "user-1", "#announcements", "hi"
+ )
+ assert result.ok is False
+ assert result.error == "no_linked_servers"
+ adapter.list_text_channels.assert_not_awaited()
+
+
+async def test_deliver_message_send_failure():
+ adapter = _adapter(
+ channels=[ChannelInfo(id="42", name="announcements", server_id="g1")],
+ posted=None,
+ )
+ result = await outbound.deliver_message(
+ adapter, _api(["g1"]), "discord", "user-1", "#announcements", "hi"
+ )
+ assert result.ok is False
+ assert result.error == "send_failed"
+ assert result.channel_id == "42"
+
+
+async def test_deliver_message_empty_content_is_distinct_error():
+ adapter = _adapter()
+ result = await outbound.deliver_message(
+ adapter, _api(["g1"]), "discord", "user-1", "#x", " "
+ )
+ assert result.ok is False
+ assert result.error == "empty_content"
+ # Nothing should be resolved or sent for empty content.
+ adapter.list_text_channels.assert_not_awaited()
+ adapter.post_channel_message.assert_not_awaited()
+
+
+async def test_create_thread_empty_content_is_distinct_error():
+ adapter = _adapter()
+ result = await outbound.create_thread(
+ adapter, _api(["g1"]), "discord", "user-1", "#x", "Monday", ""
+ )
+ assert result.ok is False
+ assert result.error == "empty_content"
+ adapter.create_channel_thread.assert_not_awaited()
+
+
+async def test_create_thread_happy_path():
+ adapter = _adapter(
+ channels=[ChannelInfo(id="42", name="announcements", server_id="g1")],
+ thread=PostedRef(id="t1", url="https://discord.com/t"),
+ )
+ result = await outbound.create_thread(
+ adapter, _api(["g1"]), "discord", "user-1", "#announcements", "Monday", "body"
+ )
+ assert result.ok is True
+ assert result.kind == "thread"
+ assert result.ref_id == "t1"
+ adapter.create_channel_thread.assert_awaited_once_with("42", "Monday", "body")
+
+
+async def test_create_thread_failure():
+ adapter = _adapter(
+ channels=[ChannelInfo(id="42", name="announcements", server_id="g1")],
+ thread=None,
+ )
+ result = await outbound.create_thread(
+ adapter, _api(["g1"]), "discord", "user-1", "#announcements", "Monday", "body"
+ )
+ assert result.ok is False
+ assert result.error == "thread_failed"
+
+
+async def test_list_channels_empty_without_links():
+ adapter = _adapter(channels=[ChannelInfo(id="42", name="x", server_id="g1")])
+ result = await outbound.list_channels(adapter, _api([]), "discord", "user-1")
+ assert result == []
+ adapter.list_text_channels.assert_not_awaited()
+
+
+async def test_list_channels_drops_unlinked_server_channels():
+ # Defense-in-depth: even if the adapter over-returns, channels outside the
+ # user's linked servers are filtered out of the picker.
+ adapter = _adapter(
+ channels=[
+ ChannelInfo(id="10", name="ours", server_id="g1"),
+ ChannelInfo(id="20", name="leaked", server_id="other"),
+ ]
+ )
+ result = await outbound.list_channels(adapter, _api(["g1"]), "discord", "user-1")
+ assert [c.id for c in result] == ["10"]
diff --git a/autogpt_platform/backend/backend/platform_linking/manager.py b/autogpt_platform/backend/backend/platform_linking/manager.py
index 650baf3e1a..4824308a80 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager.py
@@ -62,6 +62,19 @@ class PlatformLinkingManager(AppService):
async def get_link_token_status(self, token: str) -> LinkTokenStatusResponse:
return await platform_linking_db().get_link_token_status(token)
+ @expose
+ async def list_user_server_ids(self, platform: Platform, user_id: str) -> list[str]:
+ """Bot-scoped: the platform server IDs ``user_id`` has linked.
+
+ Deliberately returns only the IDs (not full ``PlatformLinkInfo``) so the
+ bot client stays a narrow surface — the user-facing ``list_server_links``
+ stays off the bot client. Backs proactive-output authorization.
+ """
+ links = await platform_linking_db().list_server_links(user_id)
+ return [
+ link.platform_server_id for link in links if link.platform == platform.value
+ ]
+
@expose
async def start_chat_turn(self, request: BotChatRequest) -> ChatTurnHandle:
return await start_chat_turn(request)
@@ -127,6 +140,9 @@ class PlatformLinkingManagerClient(AppServiceClient):
get_link_token_status = endpoint_to_async(
PlatformLinkingManager.get_link_token_status
)
+ list_user_server_ids = endpoint_to_async(
+ PlatformLinkingManager.list_user_server_ids
+ )
start_chat_turn = endpoint_to_async(PlatformLinkingManager.start_chat_turn)
refresh_server_link_name = endpoint_to_async(
PlatformLinkingManager.refresh_server_link_name
diff --git a/autogpt_platform/backend/backend/platform_linking/manager_test.py b/autogpt_platform/backend/backend/platform_linking/manager_test.py
index 1ae306762b..b33b33729b 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager_test.py
@@ -41,6 +41,7 @@ class TestManagerWiring:
"create_user_link_token",
"get_link_token_status",
"start_chat_turn",
+ "list_user_server_ids",
}
for name in expected:
assert hasattr(