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(platform): copilot-bot (Python / discord.py) (#12618)

Bentlyc3c2737c4227
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index 67444c2e36..b17d187b99 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -182,6 +182,10 @@ GOOGLE_MAPS_API_KEY=
# Platform Bot Linking
PLATFORM_LINK_BASE_URL=http://localhost:3000/link
+# CoPilot chat-platform bridge (Discord/Telegram/Slack)
+# Uses FRONTEND_BASE_URL (above) for link confirmation pages.
+AUTOPILOT_BOT_DISCORD_TOKEN=
+
# Communication Services
DISCORD_BOT_TOKEN=
MEDIUM_API_KEY=
diff --git a/autogpt_platform/backend/backend/app.py b/autogpt_platform/backend/backend/app.py
index 534f385009..e349809de3 100644
--- a/autogpt_platform/backend/backend/app.py
+++ b/autogpt_platform/backend/backend/app.py
@@ -38,6 +38,7 @@ def main(**kwargs):
from backend.api.rest_api import AgentServer
from backend.api.ws_api import WebsocketServer
+ from backend.copilot.bot.app import CoPilotChatBridge
from backend.copilot.executor.manager import CoPilotExecutor
from backend.data.db_manager import DatabaseManager
from backend.executor import ExecutionManager, Scheduler
@@ -53,6 +54,7 @@ def main(**kwargs):
AgentServer(),
ExecutionManager(),
CoPilotExecutor(),
+ CoPilotChatBridge(),
**kwargs,
)
diff --git a/autogpt_platform/backend/backend/copilot/bot/AGENTS.md b/autogpt_platform/backend/backend/copilot/bot/AGENTS.md
new file mode 100644
index 0000000000..99ee350f47
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/AGENTS.md
@@ -0,0 +1 @@
diff --git a/autogpt_platform/backend/backend/copilot/bot/CLAUDE.md b/autogpt_platform/backend/backend/copilot/bot/CLAUDE.md
new file mode 100644
index 0000000000..99ee350f47
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.md
new file mode 100644
index 0000000000..8a27d01d73
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/README.md
@@ -0,0 +1,79 @@
+# CoPilot Bot
+
+Multi-platform chat bot that bridges AutoPilot to Discord (and later Telegram, Slack, etc).
+
+## Running
+
+```bash
+# As a standalone service
+poetry run copilot-bot
+
+# Or auto-start alongside the rest of the platform
+poetry run app # starts the bot too if AUTOPILOT_BOT_DISCORD_TOKEN is set
+```
+
+## Required environment variables
+
+See `backend/.env.default` for the full list with documentation. Minimum setup:
+
+| Variable | Purpose |
+|----------|---------|
+| `AUTOPILOT_BOT_DISCORD_TOKEN` | Discord bot token — enables the Discord adapter |
+| `FRONTEND_BASE_URL` | Frontend base URL for link confirmation pages (shared with the rest of the backend) |
+| `REDIS_HOST` / `REDIS_PORT` | Session + thread subscription state + copilot stream subscription (inherited from the shared backend config) |
+| `PLATFORMLINKINGMANAGER_HOST` | DNS name of the `PlatformLinkingManager` service pod (cluster-internal RPC) |
+
+## Architecture
+
+```
+bot/
+├── app.py # CoPilotChatBridge(AppService), adapter factory, outbound @expose RPC
+├── config.py # Shared (platform-agnostic) config
+├── handler.py # Core logic: routing, linking, batched streaming
+├── bot_backend.py # Thin facade over PlatformLinkingManagerClient + stream_registry
+├── text.py # Text splitting + batch formatting
+├── threads.py # Redis-backed thread subscription tracking
+└── adapters/
+ ├── base.py # PlatformAdapter interface + MessageContext
+ └── discord/
+ ├── adapter.py # Gateway connection, events, sends, thread creation
+ ├── commands.py # Slash commands (/setup, /help, /unlink)
+ └── config.py # Discord token + platform limits
+```
+
+**Locality rule:** anything platform-specific lives under `adapters/<platform>/`.
+The only file that names specific platforms is `app.py`, which is the factory
+that decides which adapters to instantiate based on which tokens are set.
+
+## How messaging works
+
+1. User mentions the bot in a channel
+2. Adapter's `on_message` handler fires, constructs a `MessageContext`, passes
+ it to the shared `MessageHandler`
+3. Handler:
+ - Checks if the user/server is linked (via `bot_backend`)
+ - If not linked → sends a "Link Account" button prompt
+ - If linked → creates a thread (for channels) or uses the existing thread/DM
+ - Marks the thread as subscribed in Redis (7-day TTL)
+ - Streams the AutoPilot response back, chunked at the adapter's
+ `chunk_flush_at` boundary
+4. Messages that arrive while a stream is running get batched and sent as a
+ single follow-up turn once the current stream ends
+
+## Adding a new platform
+
+1. Create `adapters/<platform>/` with `adapter.py`, `commands.py` (if the
+ platform has commands), and `config.py`
+2. `adapter.py` subclasses `PlatformAdapter` and implements all its abstract
+ methods — `max_message_length`, `chunk_flush_at`, `send_message`,
+ `send_link`, `create_thread`, etc.
+3. `config.py` declares the platform's env vars and any platform-specific
+ numbers (message limits, token name, etc.)
+4. Add two lines to `app.py::_build_adapters`:
+ ```python
+ if <platform>_config.BOT_TOKEN:
+ adapters.append(<Platform>Adapter(api))
+ ```
+
+The core handler, text utilities, thread tracking, and platform API all stay
+untouched.
diff --git a/autogpt_platform/backend/backend/copilot/bot/__init__.py b/autogpt_platform/backend/backend/copilot/bot/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/copilot/bot/__main__.py b/autogpt_platform/backend/backend/copilot/bot/__main__.py
new file mode 100644
index 0000000000..282a846813
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/__main__.py
@@ -0,0 +1,19 @@
+"""Entry point for running the CoPilot Chat Bridge service.
+
+Usage:
+ poetry run copilot-bot
+ python -m backend.copilot.bot
+"""
+
+from backend.app import run_processes
+
+from .app import CoPilotChatBridge
+
+
+def main():
+ """Run the CoPilot Chat Bridge service."""
+ run_processes(CoPilotChatBridge())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/__init__.py b/autogpt_platform/backend/backend/copilot/bot/adapters/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
new file mode 100644
index 0000000000..658c883130
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
@@ -0,0 +1,110 @@
+"""Abstract base for platform adapters.
+
+Each chat platform (Discord, Telegram, Slack, etc.) implements this interface.
+The core bot logic in handler.py is platform-agnostic — it only speaks through
+these methods.
+"""
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Awaitable, Callable, Literal, Optional
+
+# Callback signature: (ctx, adapter) -> awaitable None
+MessageCallback = Callable[["MessageContext", "PlatformAdapter"], Awaitable[None]]
+
+# Where the message came from:
+# - "dm" — 1:1 conversation, reply in-place
+# - "channel" — public channel, bot was @mentioned, create a thread to respond
+# - "thread" — ongoing thread conversation, reply in-place
+ChannelType = Literal["dm", "channel", "thread"]
+
+
+@dataclass
+class MessageContext:
+ """Everything the core handler needs to know about an incoming message."""
+
+ platform: str
+ channel_type: ChannelType
+ server_id: Optional[str]
+ channel_id: str # DM channel ID / parent channel ID / thread ID
+ message_id: str # the incoming message itself — used to create threads from it
+ user_id: str
+ username: str
+ text: str # with bot mentions stripped
+
+ @property
+ def is_dm(self) -> bool:
+ return self.channel_type == "dm"
+
+
+class PlatformAdapter(ABC):
+ """Interface that each chat platform must implement."""
+
+ @property
+ @abstractmethod
+ def platform_name(self) -> str: ...
+
+ @abstractmethod
+ def on_message(self, callback: MessageCallback) -> None: ...
+
+ @abstractmethod
+ async def start(self) -> None: ...
+
+ @abstractmethod
+ async def stop(self) -> None: ...
+
+ @abstractmethod
+ async def send_message(self, channel_id: str, text: str) -> None: ...
+
+ @abstractmethod
+ async def send_link(
+ self, channel_id: str, text: str, link_label: str, link_url: str
+ ) -> None:
+ """Send a message with a clickable link presented as a button/CTA.
+
+ Platforms without native button support should fall back to rendering
+ the URL inline in the text.
+ """
+ ...
+
+ @abstractmethod
+ async def send_reply(
+ self, channel_id: str, text: str, reply_to_message_id: str
+ ) -> None: ...
+
+ @abstractmethod
+ async def send_ephemeral(
+ self, channel_id: str, user_id: str, text: str
+ ) -> None: ...
+
+ @abstractmethod
+ async def start_typing(self, channel_id: str) -> None: ...
+
+ @abstractmethod
+ async def stop_typing(self, channel_id: str) -> None: ...
+
+ @abstractmethod
+ async def create_thread(
+ self, channel_id: str, message_id: str, name: str
+ ) -> Optional[str]:
+ """Create a thread from a message. Returns the thread ID, or None if
+ the platform doesn't support threads or creation failed.
+ """
+ ...
+
+ @property
+ @abstractmethod
+ def max_message_length(self) -> int:
+ """Hard platform cap on a single message's content length."""
+ ...
+
+ @property
+ @abstractmethod
+ def chunk_flush_at(self) -> int:
+ """Flush the streaming buffer once it reaches this length.
+
+ Should be slightly under max_message_length to leave headroom for
+ any trailing content that the splitter might pull into the current
+ chunk.
+ """
+ ...
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/__init__.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
new file mode 100644
index 0000000000..739fa9f524
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -0,0 +1,209 @@
+"""Discord adapter — connects to the Discord Gateway and forwards messages.
+
+Platform-specific machinery only: Gateway connection, message event handling,
+thread creation, typing, button rendering. All platform-agnostic logic lives
+in the core handler. Slash commands live in commands.py.
+"""
+
+import logging
+from typing import Optional
+
+import discord
+from discord import app_commands
+
+from backend.copilot.bot.bot_backend import BotBackend
+
+from ..base import ChannelType, MessageCallback, MessageContext, PlatformAdapter
+from . import commands, config
+
+logger = logging.getLogger(__name__)
+
+
+class DiscordAdapter(PlatformAdapter):
+ def __init__(self, api: BotBackend):
+ intents = discord.Intents.default()
+ intents.message_content = True
+ # AutoPilot output is untrusted w.r.t. mentions — suppress @everyone,
+ # role, and user pings the LLM might produce. Client-level default
+ # applies to every send() + reply() below.
+ self._client = discord.Client(
+ intents=intents,
+ allowed_mentions=discord.AllowedMentions.none(),
+ )
+ self._tree = app_commands.CommandTree(self._client)
+ self._api = api
+ self._on_message_callback: Optional[MessageCallback] = None
+ self._commands_synced = False
+
+ self._register_events()
+ commands.register(self._tree, self._api)
+
+ @property
+ def platform_name(self) -> str:
+ return "discord"
+
+ @property
+ def max_message_length(self) -> int:
+ return config.MAX_MESSAGE_LENGTH
+
+ @property
+ def chunk_flush_at(self) -> int:
+ return config.CHUNK_FLUSH_AT
+
+ def on_message(self, callback: MessageCallback) -> None:
+ self._on_message_callback = callback
+
+ async def start(self) -> None:
+ await self._client.start(config.get_bot_token())
+
+ async def stop(self) -> None:
+ if not self._client.is_closed():
+ await self._client.close()
+
+ async def _resolve_channel(self, channel_id: str):
+ """Return the channel for ``channel_id``, falling back to a REST fetch.
+
+ ``Client.get_channel`` only reads the in-memory cache, so it misses
+ threads the bot hasn't seen since its last restart. Fall back to
+ ``fetch_channel`` (REST) so long-lived threads keep working.
+ """
+ channel = self._client.get_channel(int(channel_id))
+ if channel is not None:
+ return channel
+ try:
+ return await self._client.fetch_channel(int(channel_id))
+ except (discord.NotFound, discord.Forbidden, discord.HTTPException):
+ logger.warning("Channel %s not found or inaccessible", channel_id)
+ return None
+
+ async def send_message(self, channel_id: str, text: str) -> None:
+ channel = await self._resolve_channel(channel_id)
+ if channel and isinstance(channel, discord.abc.Messageable):
+ # tts=False is the default but we pin it explicitly — AutoPilot
+ # output is untrusted and should never blast through voice.
+ await channel.send(text, tts=False)
+
+ async def send_link(
+ self, channel_id: str, text: str, link_label: str, link_url: str
+ ) -> None:
+ channel = await self._resolve_channel(channel_id)
+ if channel is None or not isinstance(channel, discord.abc.Messageable):
+ return
+ view = discord.ui.View()
+ view.add_item(
+ discord.ui.Button(
+ style=discord.ButtonStyle.link,
+ label=link_label[:80], # Discord button label max
+ url=link_url,
+ )
+ )
+ await channel.send(text, view=view, tts=False)
+
+ async def send_reply(
+ self, channel_id: str, text: str, reply_to_message_id: str
+ ) -> None:
+ channel = await self._resolve_channel(channel_id)
+ if not channel or not isinstance(channel, discord.abc.Messageable):
+ return
+ try:
+ msg = await channel.fetch_message(int(reply_to_message_id))
+ await msg.reply(text, tts=False)
+ except discord.NotFound:
+ await channel.send(text, tts=False)
+
+ async def send_ephemeral(self, channel_id: str, user_id: str, text: str) -> None:
+ # Ephemeral messages are only possible via interaction responses.
+ # Fall back to a normal message for non-interaction contexts.
+ await self.send_message(channel_id, text)
+
+ async def start_typing(self, channel_id: str) -> None:
+ channel = await self._resolve_channel(channel_id)
+ if channel and isinstance(channel, discord.abc.Messageable):
+ await channel.typing()
+
+ async def stop_typing(self, channel_id: str) -> None:
+ pass # Discord typing auto-expires after ~10s
+
+ async def create_thread(
+ self, channel_id: str, message_id: str, name: str
+ ) -> Optional[str]:
+ 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:
+ msg = await channel.fetch_message(int(message_id))
+ thread = await msg.create_thread(name=name[:100])
+ return str(thread.id)
+ except discord.HTTPException:
+ logger.exception("Failed to create thread in channel %s", channel_id)
+ return None
+
+ # -- Internal --
+
+ def _register_events(self) -> None:
+ @self._client.event
+ async def on_ready() -> None:
+ logger.info(f"Discord bot connected as {self._client.user}")
+ # Sync slash commands once per process — on_ready fires on every
+ # gateway reconnect, but the command tree only needs uploading once.
+ if self._commands_synced:
+ return
+ try:
+ synced = await self._tree.sync()
+ self._commands_synced = True
+ logger.info(f"Synced {len(synced)} slash commands")
+ except Exception:
+ logger.exception("Failed to sync slash commands")
+
+ @self._client.event
+ async def on_message(message: discord.Message) -> None:
+ if message.author.bot:
+ return
+ if self._on_message_callback is None:
+ return
+
+ channel_type = self._channel_type(message)
+
+ # Channels require an explicit @mention; DMs and threads always forward
+ # (handler checks thread subscription).
+ if channel_type == "channel" and not self._is_mentioned(message):
+ return
+
+ ctx = MessageContext(
+ platform="discord",
+ channel_type=channel_type,
+ server_id=str(message.guild.id) if message.guild else None,
+ channel_id=str(message.channel.id),
+ message_id=str(message.id),
+ user_id=str(message.author.id),
+ username=message.author.display_name,
+ text=self._strip_mentions(message),
+ )
+ await self._on_message_callback(ctx, self)
+
+ def _is_mentioned(self, message: discord.Message) -> bool:
+ if message.guild is None:
+ return True # DMs always count
+ return bool(self._client.user and self._client.user.mentioned_in(message))
+
+ @staticmethod
+ def _channel_type(message: discord.Message) -> ChannelType:
+ if message.guild is None:
+ return "dm"
+ if isinstance(message.channel, discord.Thread):
+ return "thread"
+ return "channel"
+
+ def _strip_mentions(self, message: discord.Message) -> str:
+ """Strip the bot's own mention; replace other users' raw mention
+ tokens with `@displayname` so the LLM keeps the context.
+ """
+ text = message.content
+ bot_id = self._client.user.id if self._client.user else None
+ for user in message.mentions:
+ raw_tokens = (f"<@{user.id}>", f"<@!{user.id}>")
+ replacement = "" if user.id == bot_id else f"@{user.display_name}"
+ for token in raw_tokens:
+ text = text.replace(token, replacement)
+ return text.strip()
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
new file mode 100644
index 0000000000..9f58e178d3
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
@@ -0,0 +1,259 @@
+"""Tests for DiscordAdapter helpers that don't need a live gateway."""
+
+from typing import cast
+from unittest.mock import AsyncMock, MagicMock
+
+import discord
+import pytest
+
+from backend.copilot.bot.adapters.discord.adapter import DiscordAdapter
+
+
+def _bare_adapter(bot_id: int | None = 1000) -> tuple[DiscordAdapter, MagicMock]:
+ """Build a DiscordAdapter without going through __init__ (which spins up
+ discord.py internals). Returns the adapter alongside the MagicMock that
+ stands in for ``_client`` — tests reach into the mock directly for
+ per-method stubbing.
+ """
+ adapter = DiscordAdapter.__new__(DiscordAdapter)
+ client = MagicMock()
+ client.user = MagicMock(id=bot_id) if bot_id is not None else None
+ adapter._client = cast(discord.Client, client)
+ adapter._on_message_callback = None
+ adapter._commands_synced = False
+ return adapter, client
+
+
+def _mention(user_id: int, display_name: str) -> MagicMock:
+ user = MagicMock()
+ user.id = user_id
+ user.display_name = display_name
+ return user
+
+
+def _message(content: str, mentions: list[MagicMock]) -> MagicMock:
+ msg = MagicMock()
+ msg.content = content
+ msg.mentions = mentions
+ return msg
+
+
+# ── _strip_mentions ────────────────────────────────────────────────────
+
+
+class TestStripMentions:
+ def test_strips_only_bot_mention(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ bot = _mention(1000, "AutoPilot")
+ alice = _mention(2000, "Alice")
+ msg = _message(
+ "<@1000> please summarise what <@2000> said",
+ mentions=[bot, alice],
+ )
+
+ assert adapter._strip_mentions(msg) == "please summarise what @Alice said"
+
+ def test_handles_nickname_style_tokens(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ bot = _mention(1000, "AutoPilot")
+ alice = _mention(2000, "Alice")
+ msg = _message("<@!1000> ping <@!2000>", mentions=[bot, alice])
+
+ assert adapter._strip_mentions(msg) == "ping @Alice"
+
+ def test_no_bot_user_leaves_all_mentions_as_names(self):
+ adapter, _ = _bare_adapter(bot_id=None)
+ alice = _mention(2000, "Alice")
+ msg = _message("hi <@2000>", mentions=[alice])
+
+ assert adapter._strip_mentions(msg) == "hi @Alice"
+
+ def test_message_without_mentions_is_trimmed(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ msg = _message(" hello world ", mentions=[])
+
+ assert adapter._strip_mentions(msg) == "hello world"
+
+ @pytest.mark.parametrize(
+ "content,expected",
+ [
+ ("<@1000>", ""),
+ ("<@!1000>", ""),
+ ("<@1000> hi", "hi"),
+ ("hi <@1000>", "hi"),
+ ],
+ )
+ def test_bot_only_variants(self, content: str, expected: str):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ bot = _mention(1000, "AutoPilot")
+ msg = _message(content, mentions=[bot])
+
+ assert adapter._strip_mentions(msg) == expected
+
+
+# ── _channel_type ──────────────────────────────────────────────────────
+
+
+class TestChannelType:
+ def test_dm_has_no_guild(self):
+ msg = MagicMock()
+ msg.guild = None
+ assert DiscordAdapter._channel_type(msg) == "dm"
+
+ def test_thread_inside_guild(self):
+ msg = MagicMock()
+ msg.guild = MagicMock()
+ msg.channel = MagicMock(spec=discord.Thread)
+ assert DiscordAdapter._channel_type(msg) == "thread"
+
+ def test_regular_channel_inside_guild(self):
+ msg = MagicMock()
+ msg.guild = MagicMock()
+ msg.channel = MagicMock()
+ assert DiscordAdapter._channel_type(msg) == "channel"
+
+
+# ── _is_mentioned ──────────────────────────────────────────────────────
+
+
+class TestIsMentioned:
+ def test_dm_always_counts_as_mentioned(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ msg = MagicMock()
+ msg.guild = None
+ assert adapter._is_mentioned(msg) is True
+
+ def test_guild_requires_explicit_mention(self):
+ adapter, client = _bare_adapter(bot_id=1000)
+ msg = MagicMock()
+ msg.guild = MagicMock()
+ client.user.mentioned_in.return_value = False
+ assert adapter._is_mentioned(msg) is False
+
+ def test_guild_with_mention_passes(self):
+ adapter, client = _bare_adapter(bot_id=1000)
+ msg = MagicMock()
+ msg.guild = MagicMock()
+ client.user.mentioned_in.return_value = True
+ assert adapter._is_mentioned(msg) is True
+
+ def test_no_bot_user_treats_guild_mention_as_false(self):
+ adapter, _ = _bare_adapter(bot_id=None)
+ msg = MagicMock()
+ msg.guild = MagicMock()
+ assert adapter._is_mentioned(msg) is False
+
+
+# ── _resolve_channel ───────────────────────────────────────────────────
+
+
+class TestResolveChannel:
+ @pytest.mark.asyncio
+ async def test_cache_hit_skips_rest_fetch(self):
+ adapter, client = _bare_adapter()
+ cached = MagicMock()
+ client.get_channel.return_value = cached
+ client.fetch_channel = AsyncMock()
+
+ result = await adapter._resolve_channel("123")
+
+ assert result is cached
+ client.fetch_channel.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_cache_miss_falls_back_to_rest(self):
+ adapter, client = _bare_adapter()
+ fetched = MagicMock()
+ client.get_channel.return_value = None
+ client.fetch_channel = AsyncMock(return_value=fetched)
+
+ result = await adapter._resolve_channel("123")
+
+ assert result is fetched
+ client.fetch_channel.assert_awaited_once_with(123)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "exc",
+ [
+ discord.NotFound(MagicMock(status=404), "gone"),
+ discord.Forbidden(MagicMock(status=403), "nope"),
+ discord.HTTPException(MagicMock(status=500), "boom"),
+ ],
+ )
+ async def test_rest_failure_returns_none(self, exc: Exception):
+ adapter, client = _bare_adapter()
+ client.get_channel.return_value = None
+ client.fetch_channel = AsyncMock(side_effect=exc)
+
+ assert await adapter._resolve_channel("123") is None
+
+
+# ── send_message / send_reply / send_link ──────────────────────────────
+
+
+class TestSendMethods:
+ @pytest.mark.asyncio
+ async def test_send_message_pins_tts_false(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.send = AsyncMock()
+ client.get_channel.return_value = channel
+
+ await adapter.send_message("123", "hi")
+
+ channel.send.assert_awaited_once_with("hi", tts=False)
+
+ @pytest.mark.asyncio
+ async def test_send_message_silently_drops_when_channel_missing(self):
+ adapter, client = _bare_adapter()
+ client.get_channel.return_value = None
+ client.fetch_channel = AsyncMock(
+ side_effect=discord.NotFound(MagicMock(status=404), "gone")
+ )
+ # Should not raise even though there's nothing to send to.
+ await adapter.send_message("123", "hi")
+
+ @pytest.mark.asyncio
+ async def test_send_link_attaches_button_and_pins_tts(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.send = AsyncMock()
+ client.get_channel.return_value = channel
+
+ await adapter.send_link("123", "click me", "Open", "https://example.com")
+
+ assert channel.send.await_count == 1
+ kwargs = channel.send.await_args.kwargs
+ assert kwargs["tts"] is False
+ view = kwargs["view"]
+ assert any(
+ getattr(c, "url", None) == "https://example.com" for c in view.children
+ )
+
+ @pytest.mark.asyncio
+ async def test_send_reply_falls_back_to_send_when_message_missing(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.send = AsyncMock()
+ channel.fetch_message = AsyncMock(
+ side_effect=discord.NotFound(MagicMock(status=404), "gone")
+ )
+ client.get_channel.return_value = channel
+
+ await adapter.send_reply("123", "hello", "999")
+
+ channel.send.assert_awaited_once_with("hello", tts=False)
+
+
+# ── properties ─────────────────────────────────────────────────────────
+
+
+class TestProperties:
+ def test_platform_name_is_discord(self):
+ adapter, _ = _bare_adapter()
+ assert adapter.platform_name == "discord"
+
+ def test_chunk_flush_at_is_under_message_limit(self):
+ adapter, _ = _bare_adapter()
+ assert adapter.chunk_flush_at < adapter.max_message_length
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
new file mode 100644
index 0000000000..5fcbb62fb6
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
@@ -0,0 +1,134 @@
+"""Discord slash command handlers.
+
+Registered on the bot's CommandTree at startup. All responses are ephemeral
+(visible only to the invoking user) to keep channels clean and to keep link
+URLs private.
+"""
+
+import logging
+
+import discord
+from discord import app_commands
+
+from backend.copilot.bot.bot_backend import BotBackend
+from backend.util.exceptions import LinkAlreadyExistsError
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+
+
+def register(tree: app_commands.CommandTree, api: BotBackend) -> None:
+ """Register all slash commands on the given CommandTree."""
+
+ @tree.command(
+ name="setup",
+ description="Link this server to an AutoGPT account for AutoPilot",
+ )
+ async def setup_command(interaction: discord.Interaction) -> None:
+ await _handle_setup(interaction, api)
+
+ @tree.command(name="help", description="Show AutoPilot bot usage info")
+ async def help_command(interaction: discord.Interaction) -> None:
+ await _handle_help(interaction)
+
+ @tree.command(
+ name="unlink",
+ description="Manage linked servers from your AutoGPT settings",
+ )
+ async def unlink_command(interaction: discord.Interaction) -> None:
+ await _handle_unlink(interaction)
+
+
+async def _handle_setup(interaction: discord.Interaction, api: BotBackend) -> None:
+ if interaction.guild is None:
+ await interaction.response.send_message(
+ "This command can only be used in a server. "
+ "To link your DMs, just send me a direct message.",
+ ephemeral=True,
+ )
+ return
+
+ await interaction.response.defer(ephemeral=True)
+ try:
+ result = await api.create_link_token(
+ platform="discord",
+ platform_server_id=str(interaction.guild.id),
+ platform_user_id=str(interaction.user.id),
+ platform_username=interaction.user.display_name,
+ server_name=interaction.guild.name,
+ channel_id=str(interaction.channel_id or ""),
+ )
+ except LinkAlreadyExistsError:
+ await interaction.followup.send(
+ "This server is already linked — just mention me!",
+ ephemeral=True,
+ )
+ return
+ except Exception:
+ logger.exception("Failed to create link token")
+ await interaction.followup.send(
+ "Something went wrong. Try again later.",
+ ephemeral=True,
+ )
+ return
+
+ view = discord.ui.View()
+ view.add_item(
+ discord.ui.Button(
+ style=discord.ButtonStyle.link,
+ label="Link Server",
+ url=result.link_url,
+ )
+ )
+ await interaction.followup.send(
+ f"**Set up AutoPilot for {interaction.guild.name}**\n\n"
+ "Click the button below to connect this server to your AutoGPT "
+ "account. Once confirmed, everyone here can mention me to use "
+ "AutoPilot.\n\n"
+ "All usage will be billed to your account.\n"
+ "This link expires in 30 minutes.",
+ ephemeral=True,
+ view=view,
+ )
+
+
+async def _handle_help(interaction: discord.Interaction) -> None:
+ await interaction.response.send_message(
+ "**AutoPilot Bot**\n\n"
+ "Mention me in a server or DM me directly to chat.\n\n"
+ "**Commands:**\n"
+ "- `/setup` — Link this server to your AutoGPT account\n"
+ "- `/help` — Show this message\n"
+ "- `/unlink` — Manage linked accounts\n\n"
+ "**How it works:**\n"
+ "- In a server: the person who runs `/setup` pays for usage\n"
+ "- In DMs: you link and pay for your own usage\n",
+ ephemeral=True,
+ )
+
+
+async def _handle_unlink(interaction: discord.Interaction) -> None:
+ config = Settings().config
+ base_url = config.frontend_base_url or config.platform_base_url
+ message = (
+ "Unlinking requires authentication, so it has to be done "
+ "from the web. Click below to manage your linked accounts."
+ )
+
+ if not base_url:
+ await interaction.response.send_message(
+ f"{message}\n\nOpen your AutoGPT settings and visit "
+ "Profile → Linked accounts.",
+ ephemeral=True,
+ )
+ return
+
+ view = discord.ui.View()
+ view.add_item(
+ discord.ui.Button(
+ style=discord.ButtonStyle.link,
+ label="Open Settings",
+ url=f"{base_url}/profile/settings",
+ )
+ )
+ await interaction.response.send_message(message, ephemeral=True, view=view)
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py
new file mode 100644
index 0000000000..c390173fd9
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py
@@ -0,0 +1,165 @@
+"""Tests for Discord slash command handlers.
+
+Targets the ``_handle_*`` functions directly — sidesteps ``CommandTree``
+registration since it requires a live ``discord.Client``.
+"""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.util.exceptions import LinkAlreadyExistsError
+
+from ...bot_backend import LinkTokenResult
+from .commands import _handle_help, _handle_setup, _handle_unlink
+
+
+def _interaction(*, guild: bool = True) -> MagicMock:
+ interaction = MagicMock()
+ interaction.response.send_message = AsyncMock()
+ interaction.response.defer = AsyncMock()
+ interaction.followup.send = AsyncMock()
+ if guild:
+ # MagicMock treats `name` as a constructor kwarg for the mock's repr,
+ # not as an attribute — so set it after construction.
+ interaction.guild = MagicMock(id=123)
+ interaction.guild.name = "Test Guild"
+ interaction.user = MagicMock(id=456, display_name="Bently")
+ interaction.channel_id = 789
+ else:
+ interaction.guild = None
+ interaction.user = MagicMock(id=456, display_name="Bently")
+ interaction.channel_id = None
+ return interaction
+
+
+def _api_with_token() -> MagicMock:
+ api = MagicMock()
+ api.create_link_token = AsyncMock(
+ return_value=LinkTokenResult(
+ token="abc",
+ link_url="https://example.com/link/abc",
+ expires_at="2099-01-01T00:00:00Z",
+ )
+ )
+ return api
+
+
+class TestHandleSetup:
+ @pytest.mark.asyncio
+ async def test_dm_invocation_rejects_early(self):
+ interaction = _interaction(guild=False)
+ api = _api_with_token()
+ await _handle_setup(interaction, api)
+
+ interaction.response.send_message.assert_awaited_once()
+ api.create_link_token.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_guild_invocation_creates_token_and_posts_button(self):
+ interaction = _interaction()
+ api = _api_with_token()
+ await _handle_setup(interaction, api)
+
+ interaction.response.defer.assert_awaited_once_with(ephemeral=True)
+ api.create_link_token.assert_awaited_once()
+ call_kwargs = api.create_link_token.await_args.kwargs
+ assert call_kwargs["platform"] == "discord"
+ assert call_kwargs["platform_server_id"] == "123"
+ assert call_kwargs["server_name"] == "Test Guild"
+
+ interaction.followup.send.assert_awaited_once()
+ sent = interaction.followup.send.await_args
+ assert "Set up AutoPilot for Test Guild" in sent.args[0]
+ assert sent.kwargs["view"] is not None
+
+ @pytest.mark.asyncio
+ async def test_already_linked_gets_friendly_message(self):
+ interaction = _interaction()
+ api = _api_with_token()
+ api.create_link_token = AsyncMock(side_effect=LinkAlreadyExistsError("already"))
+
+ await _handle_setup(interaction, api)
+
+ interaction.followup.send.assert_awaited_once()
+ msg = interaction.followup.send.await_args.args[0]
+ assert "already linked" in msg
+
+ @pytest.mark.asyncio
+ async def test_backend_error_surfaces_generic_message(self):
+ interaction = _interaction()
+ api = _api_with_token()
+ api.create_link_token = AsyncMock(side_effect=RuntimeError("boom"))
+
+ await _handle_setup(interaction, api)
+
+ interaction.followup.send.assert_awaited_once()
+ msg = interaction.followup.send.await_args.args[0]
+ assert "went wrong" in msg.lower()
+
+
+class TestHandleHelp:
+ @pytest.mark.asyncio
+ async def test_help_sends_ephemeral_message(self):
+ interaction = _interaction()
+ await _handle_help(interaction)
+ interaction.response.send_message.assert_awaited_once()
+ assert interaction.response.send_message.await_args.kwargs["ephemeral"] is True
+ body = interaction.response.send_message.await_args.args[0]
+ assert "/setup" in body
+ assert "/help" in body
+ assert "/unlink" in body
+
+
+class TestHandleUnlink:
+ @pytest.mark.asyncio
+ async def test_with_frontend_url_posts_button(self):
+ interaction = _interaction()
+ fake_settings = MagicMock()
+ fake_settings.config.frontend_base_url = "http://localhost:3000"
+ fake_settings.config.platform_base_url = ""
+ with patch(
+ "backend.copilot.bot.adapters.discord.commands.Settings",
+ return_value=fake_settings,
+ ):
+ await _handle_unlink(interaction)
+
+ interaction.response.send_message.assert_awaited_once()
+ sent = interaction.response.send_message.await_args
+ assert sent.kwargs["view"] is not None
+ assert sent.kwargs["ephemeral"] is True
+
+ @pytest.mark.asyncio
+ async def test_falls_back_to_platform_base_url(self):
+ interaction = _interaction()
+ fake_settings = MagicMock()
+ fake_settings.config.frontend_base_url = ""
+ fake_settings.config.platform_base_url = "http://other"
+ with patch(
+ "backend.copilot.bot.adapters.discord.commands.Settings",
+ return_value=fake_settings,
+ ):
+ await _handle_unlink(interaction)
+
+ # Button uses the fallback URL.
+ sent = interaction.response.send_message.await_args
+ view = sent.kwargs["view"]
+ assert any(
+ "http://other" in getattr(child, "url", "") for child in view.children
+ )
+
+ @pytest.mark.asyncio
+ async def test_no_urls_configured_sends_plain_text(self):
+ interaction = _interaction()
+ fake_settings = MagicMock()
+ fake_settings.config.frontend_base_url = ""
+ fake_settings.config.platform_base_url = ""
+ with patch(
+ "backend.copilot.bot.adapters.discord.commands.Settings",
+ return_value=fake_settings,
+ ):
+ await _handle_unlink(interaction)
+
+ sent = interaction.response.send_message.await_args
+ assert "view" not in sent.kwargs or sent.kwargs.get("view") is None
+ assert "Profile" in sent.args[0]
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py
new file mode 100644
index 0000000000..d2b3518eed
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py
@@ -0,0 +1,15 @@
+"""Discord-specific configuration."""
+
+from backend.util.settings import Settings
+
+
+def get_bot_token() -> str:
+ return Settings().secrets.autopilot_bot_discord_token
+
+
+# Discord message content limit (hard platform cap)
+MAX_MESSAGE_LENGTH = 2000
+
+# Flush the streaming buffer at 1900 — leaves 100-char headroom under the
+# 2000 cap so the boundary-splitter has room to reach a natural break point.
+CHUNK_FLUSH_AT = 1900
diff --git a/autogpt_platform/backend/backend/copilot/bot/app.py b/autogpt_platform/backend/backend/copilot/bot/app.py
new file mode 100644
index 0000000000..277eda50f4
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/app.py
@@ -0,0 +1,156 @@
+"""CoPilot Chat Bridge — AppService that runs the configured chat-platform
+adapters (Discord, Telegram, Slack) and exposes outbound message RPC for
+other services to push messages into chat platforms.
+"""
+
+import asyncio
+import logging
+from concurrent.futures import Future
+
+from backend.platform_linking.models import Platform
+from backend.util.service import (
+ AppService,
+ AppServiceClient,
+ UnhealthyServiceError,
+ endpoint_to_async,
+ expose,
+)
+from backend.util.settings import Settings
+
+from .adapters.base import PlatformAdapter
+from .adapters.discord import config as discord_config
+from .adapters.discord.adapter import DiscordAdapter
+from .bot_backend import BotBackend
+from .handler import MessageHandler
+
+logger = logging.getLogger(__name__)
+
+# Stay up for health-checks and runtime reconfiguration when no adapter is
+# configured (e.g. deployed without a Discord token).
+_NO_ADAPTER_SLEEP_SECONDS = 3600
+
+
+class CoPilotChatBridge(AppService):
+ """Bridges AutoPilot to external chat platforms via per-platform adapters."""
+
+ def __init__(self):
+ super().__init__()
+ # Flipped to True once `_run_adapters` reaches its blocking gather
+ # (or the no-adapter idle loop), and back to False if the task exits
+ # for any reason. Consumed by `health_check` so orchestrators can
+ # restart the pod when the bridge is dead-but-listening.
+ self._adapters_healthy = False
+
+ @classmethod
+ def get_port(cls) -> int:
+ return Settings().config.copilot_chat_bridge_port
+
+ def run_service(self) -> None:
+ future = asyncio.run_coroutine_threadsafe(
+ self._run_adapters(), self.shared_event_loop
+ )
+ future.add_done_callback(self._on_adapters_exit)
+ super().run_service()
+
+ async def _run_adapters(self) -> None:
+ api = BotBackend()
+ adapters = _build_adapters(api)
+
+ if not adapters:
+ logger.info(
+ "CoPilotChatBridge: no platform adapters configured — idling. "
+ "Set AUTOPILOT_BOT_DISCORD_TOKEN (or another platform token) to "
+ "enable an adapter."
+ )
+ self._adapters_healthy = True
+ try:
+ while True:
+ await asyncio.sleep(_NO_ADAPTER_SLEEP_SECONDS)
+ finally:
+ await api.close()
+
+ handler = MessageHandler(api)
+ for adapter in adapters:
+ adapter.on_message(handler.handle)
+
+ self._adapters_healthy = True
+ try:
+ await asyncio.gather(*(a.start() for a in adapters))
+ finally:
+ await asyncio.gather(*(a.stop() for a in adapters), return_exceptions=True)
+ await api.close()
+
+ def _on_adapters_exit(self, future: "Future[None]") -> None:
+ """Surface exceptions from `_run_adapters` and flip the health flag.
+
+ `run_coroutine_threadsafe` would otherwise swallow the exception
+ into the returned future, leaving the FastAPI health endpoint
+ cheerfully reporting OK on a dead bridge.
+ """
+ self._adapters_healthy = False
+ exc = future.exception()
+ if exc is not None:
+ logger.error("CoPilotChatBridge adapters crashed: %r", exc, exc_info=exc)
+ else:
+ logger.warning("CoPilotChatBridge adapters exited without error")
+
+ async def health_check(self) -> str:
+ if not self._adapters_healthy:
+ raise UnhealthyServiceError("CoPilotChatBridge adapter task is not running")
+ return await super().health_check()
+
+ @expose
+ async def send_message_to_channel(
+ 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.
+ """
+ raise ValueError(f"send_message_to_channel not yet wired for {platform.value}")
+
+ @expose
+ async def send_dm(
+ self,
+ platform: Platform,
+ platform_user_id: str,
+ content: str,
+ ) -> bool:
+ """Deliver a DM to a user on the given platform.
+
+ Stub — scaffolding for the inbound-RPC pattern. See
+ :meth:`send_message_to_channel` for the retry caveat.
+ """
+ raise ValueError(f"send_dm not yet wired for {platform.value}")
+
+
+class CoPilotChatBridgeClient(AppServiceClient):
+ @classmethod
+ def get_service_type(cls):
+ return CoPilotChatBridge
+
+ send_message_to_channel = endpoint_to_async(
+ CoPilotChatBridge.send_message_to_channel
+ )
+ send_dm = endpoint_to_async(CoPilotChatBridge.send_dm)
+
+
+def _build_adapters(api: BotBackend) -> list[PlatformAdapter]:
+ """Instantiate adapters based on which platform tokens are configured."""
+ adapters: list[PlatformAdapter] = []
+ if discord_config.get_bot_token():
+ adapters.append(DiscordAdapter(api))
+ logger.info("Discord adapter enabled")
+ # Future:
+ # if telegram_config.get_bot_token():
+ # adapters.append(TelegramAdapter(api))
+ # if slack_config.get_bot_token():
+ # adapters.append(SlackAdapter(api))
+ return adapters
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
new file mode 100644
index 0000000000..f2df877041
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -0,0 +1,194 @@
+"""Bot-side facade over `PlatformLinkingManagerClient` + `stream_registry`.
+
+The `BotBackend` class is the bot's single entry point into the AutoGPT
+backend — it wraps the linking RPC client and the copilot stream registry
+behind plain string-typed methods. Adapters import this directly so the
+discord/telegram/slack code never touches Pyro / Redis Streams plumbing.
+"""
+
+import asyncio
+import logging
+from dataclasses import dataclass
+from typing import AsyncGenerator, Awaitable, Callable, Optional
+
+from backend.copilot import stream_registry
+from backend.copilot.response_model import StreamError, StreamFinish, StreamTextDelta
+from backend.platform_linking.models import (
+ BotChatRequest,
+ CreateLinkTokenRequest,
+ CreateUserLinkTokenRequest,
+ Platform,
+)
+from backend.util.clients import get_platform_linking_manager_client
+from backend.util.exceptions import (
+ DuplicateChatMessageError,
+ LinkAlreadyExistsError,
+ NotFoundError,
+)
+
+# How long to wait for a single chunk from the copilot stream before giving
+# up. Covers the case where the backend crashes mid-stream and never sends
+# ``StreamFinish`` — without this, the bot would hang forever on ``queue.get()``.
+STREAM_CHUNK_TIMEOUT_SECONDS = 120
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "BotBackend",
+ "DuplicateChatMessageError",
+ "LinkAlreadyExistsError",
+ "LinkTokenResult",
+ "NotFoundError",
+ "ResolveResult",
+]
+
+
+@dataclass
+class ResolveResult:
+ linked: bool
+
+
+@dataclass
+class LinkTokenResult:
+ token: str
+ link_url: str
+ expires_at: str
+
+
+class BotBackend:
+ """Bot-side linking + chat operations, routed over cluster-internal RPC."""
+
+ def __init__(self):
+ self._client = get_platform_linking_manager_client()
+
+ async def close(self) -> None:
+ # The client's lifecycle is owned by the thread-cached factory; nothing
+ # to close here. Kept for API compatibility with older bot code.
+ pass
+
+ async def resolve_server(
+ self, platform: str, platform_server_id: str
+ ) -> ResolveResult:
+ resp = await self._client.resolve_server_link(
+ platform=Platform(platform.upper()),
+ platform_server_id=platform_server_id,
+ )
+ return ResolveResult(linked=resp.linked)
+
+ async def resolve_user(self, platform: str, platform_user_id: str) -> ResolveResult:
+ resp = await self._client.resolve_user_link(
+ platform=Platform(platform.upper()),
+ platform_user_id=platform_user_id,
+ )
+ return ResolveResult(linked=resp.linked)
+
+ async def create_link_token(
+ self,
+ platform: str,
+ platform_server_id: str,
+ platform_user_id: str,
+ platform_username: str,
+ server_name: str,
+ channel_id: str = "",
+ ) -> LinkTokenResult:
+ resp = await self._client.create_server_link_token(
+ request=CreateLinkTokenRequest(
+ platform=Platform(platform.upper()),
+ platform_server_id=platform_server_id,
+ platform_user_id=platform_user_id,
+ platform_username=platform_username or None,
+ server_name=server_name or None,
+ channel_id=channel_id or None,
+ )
+ )
+ return LinkTokenResult(
+ token=resp.token,
+ link_url=resp.link_url,
+ expires_at=resp.expires_at.isoformat(),
+ )
+
+ async def create_user_link_token(
+ self,
+ platform: str,
+ platform_user_id: str,
+ platform_username: str,
+ ) -> LinkTokenResult:
+ resp = await self._client.create_user_link_token(
+ request=CreateUserLinkTokenRequest(
+ platform=Platform(platform.upper()),
+ platform_user_id=platform_user_id,
+ platform_username=platform_username or None,
+ )
+ )
+ return LinkTokenResult(
+ token=resp.token,
+ link_url=resp.link_url,
+ expires_at=resp.expires_at.isoformat(),
+ )
+
+ async def stream_chat(
+ self,
+ platform: str,
+ platform_user_id: str,
+ message: str,
+ session_id: Optional[str] = None,
+ platform_server_id: Optional[str] = None,
+ on_session_id: Optional[Callable[[str], Awaitable[None]]] = None,
+ ) -> AsyncGenerator[str, None]:
+ """Start a copilot turn and yield text deltas from the stream.
+
+ Raises :class:`DuplicateChatMessageError` if the same message is
+ already in flight for this session.
+ """
+ handle = await self._client.start_chat_turn(
+ request=BotChatRequest(
+ platform=Platform(platform.upper()),
+ platform_user_id=platform_user_id,
+ message=message,
+ session_id=session_id,
+ platform_server_id=platform_server_id,
+ )
+ )
+ if on_session_id:
+ await on_session_id(handle.session_id)
+
+ queue = await stream_registry.subscribe_to_session(
+ session_id=handle.session_id,
+ user_id=handle.user_id,
+ last_message_id=handle.subscribe_from,
+ )
+ if queue is None:
+ yield "\n[Error: failed to subscribe to response stream]"
+ return
+
+ try:
+ while True:
+ try:
+ chunk = await asyncio.wait_for(
+ queue.get(), timeout=STREAM_CHUNK_TIMEOUT_SECONDS
+ )
+ except asyncio.TimeoutError:
+ logger.warning(
+ "Stream idle timeout after %ss for session %s",
+ STREAM_CHUNK_TIMEOUT_SECONDS,
+ handle.session_id,
+ )
+ yield "\n[Error: response timed out]"
+ return
+ if isinstance(chunk, StreamTextDelta):
+ if chunk.delta:
+ yield chunk.delta
+ elif isinstance(chunk, StreamFinish):
+ return
+ elif isinstance(chunk, StreamError):
+ logger.error("Stream error from backend: %s", chunk.errorText)
+ yield f"\n[Error: {chunk.errorText}]"
+ return
+ # Other StreamX types (StreamStart, StreamTextStart, tool events,
+ # etc.) are emitted by the executor for the frontend UI and
+ # aren't useful for the plain-text bot transcript.
+ finally:
+ await stream_registry.unsubscribe_from_session(
+ session_id=handle.session_id,
+ subscriber_queue=queue,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
new file mode 100644
index 0000000000..24b5df7dee
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
@@ -0,0 +1,216 @@
+"""Tests for the bot's thin facade over PlatformLinkingManagerClient."""
+
+import asyncio
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.response_model import StreamError, StreamFinish, StreamTextDelta
+from backend.platform_linking.models import (
+ ChatTurnHandle,
+ LinkTokenResponse,
+ ResolveResponse,
+)
+from backend.util.exceptions import (
+ DuplicateChatMessageError,
+ LinkAlreadyExistsError,
+ NotFoundError,
+)
+
+from .bot_backend import BotBackend
+
+
+def api() -> BotBackend:
+ with patch("backend.copilot.bot.bot_backend.get_platform_linking_manager_client"):
+ instance = BotBackend()
+ # Swap in a MagicMock whose RPC methods are AsyncMocks — simpler than
+ # patching each call site.
+ instance._client = MagicMock()
+ return instance
+
+
+class TestResolve:
+ @pytest.mark.asyncio
+ async def test_resolve_server(self, api: BotBackend):
+ api._client.resolve_server_link = AsyncMock(
+ return_value=ResolveResponse(linked=True)
+ )
+ result = await api.resolve_server("discord", "g1")
+ assert result.linked is True
+ api._client.resolve_server_link.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_resolve_user(self, api: BotBackend):
+ api._client.resolve_user_link = AsyncMock(
+ return_value=ResolveResponse(linked=False)
+ )
+ result = await api.resolve_user("discord", "u1")
+ assert result.linked is False
+
+
+class TestCreateLinkTokens:
+ @pytest.mark.asyncio
+ async def test_create_server_link_token(self, api: BotBackend):
+ api._client.create_server_link_token = AsyncMock(
+ return_value=LinkTokenResponse(
+ token="abc",
+ expires_at=datetime.now(timezone.utc),
+ link_url="https://example.com/link/abc",
+ )
+ )
+ result = await api.create_link_token(
+ platform="discord",
+ platform_server_id="g1",
+ platform_user_id="u1",
+ platform_username="Bently",
+ server_name="Test",
+ )
+ assert result.token == "abc"
+ assert result.link_url.endswith("/link/abc")
+
+ @pytest.mark.asyncio
+ async def test_create_server_link_token_propagates_already_exists(
+ self, api: BotBackend
+ ):
+ api._client.create_server_link_token = AsyncMock(
+ side_effect=LinkAlreadyExistsError("already linked")
+ )
+ with pytest.raises(LinkAlreadyExistsError):
+ await api.create_link_token(
+ platform="discord",
+ platform_server_id="g1",
+ platform_user_id="u1",
+ platform_username="",
+ server_name="",
+ )
+
+ @pytest.mark.asyncio
+ async def test_create_user_link_token(self, api: BotBackend):
+ api._client.create_user_link_token = AsyncMock(
+ return_value=LinkTokenResponse(
+ token="xyz",
+ expires_at=datetime.now(timezone.utc),
+ link_url="https://example.com/link/xyz",
+ )
+ )
+ result = await api.create_user_link_token(
+ platform="discord", platform_user_id="u1", platform_username="Bently"
+ )
+ assert result.token == "xyz"
+
+
+class TestStreamChat:
+ @pytest.mark.asyncio
+ async def test_yields_text_deltas_and_terminates_on_finish(self, api: BotBackend):
+ handle = ChatTurnHandle(session_id="sess", turn_id="turn", user_id="u1")
+ api._client.start_chat_turn = AsyncMock(return_value=handle)
+
+ queue: asyncio.Queue = asyncio.Queue()
+ await queue.put(StreamTextDelta(id="1", delta="Hello "))
+ await queue.put(StreamTextDelta(id="2", delta="world"))
+ await queue.put(StreamFinish())
+
+ captured_session_ids: list[str] = []
+
+ async def capture(sid: str) -> None:
+ captured_session_ids.append(sid)
+
+ with (
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",
+ new=AsyncMock(return_value=queue),
+ ),
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.unsubscribe_from_session",
+ new=AsyncMock(),
+ ),
+ ):
+ chunks: list[str] = []
+ async for chunk in api.stream_chat(
+ platform="discord",
+ platform_user_id="u1",
+ message="hi",
+ on_session_id=capture,
+ ):
+ chunks.append(chunk)
+
+ assert "".join(chunks) == "Hello world"
+ assert captured_session_ids == ["sess"]
+
+ @pytest.mark.asyncio
+ async def test_surfaces_stream_error(self, api: BotBackend):
+ handle = ChatTurnHandle(session_id="sess", turn_id="turn", user_id="u1")
+ api._client.start_chat_turn = AsyncMock(return_value=handle)
+
+ queue: asyncio.Queue = asyncio.Queue()
+ await queue.put(StreamError(errorText="executor crashed"))
+
+ with (
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",
+ new=AsyncMock(return_value=queue),
+ ),
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.unsubscribe_from_session",
+ new=AsyncMock(),
+ ),
+ ):
+ chunks: list[str] = []
+ async for chunk in api.stream_chat(
+ platform="discord", platform_user_id="u1", message="hi"
+ ):
+ chunks.append(chunk)
+
+ assert any("executor crashed" in c for c in chunks)
+
+ @pytest.mark.asyncio
+ async def test_duplicate_message_propagates(self, api: BotBackend):
+ api._client.start_chat_turn = AsyncMock(
+ side_effect=DuplicateChatMessageError("in flight")
+ )
+
+ with pytest.raises(DuplicateChatMessageError):
+ async for _ in api.stream_chat(
+ platform="discord", platform_user_id="u1", message="hi"
+ ):
+ pass
+
+ @pytest.mark.asyncio
+ async def test_session_not_found_propagates(self, api: BotBackend):
+ api._client.start_chat_turn = AsyncMock(
+ side_effect=NotFoundError("session gone")
+ )
+
+ with pytest.raises(NotFoundError):
+ async for _ in api.stream_chat(
+ platform="discord",
+ platform_user_id="u1",
+ message="hi",
+ session_id="missing",
+ ):
+ pass
+
+ @pytest.mark.asyncio
+ async def test_subscribe_returns_none_yields_error(self, api: BotBackend):
+ handle = ChatTurnHandle(session_id="sess", turn_id="turn", user_id="u1")
+ api._client.start_chat_turn = AsyncMock(return_value=handle)
+
+ with (
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.unsubscribe_from_session",
+ new=AsyncMock(),
+ ),
+ ):
+ chunks: list[str] = []
+ async for chunk in api.stream_chat(
+ platform="discord", platform_user_id="u1", message="hi"
+ ):
+ chunks.append(chunk)
+
+ assert any("failed to subscribe" in c.lower() for c in chunks)
diff --git a/autogpt_platform/backend/backend/copilot/bot/config.py b/autogpt_platform/backend/backend/copilot/bot/config.py
new file mode 100644
index 0000000000..cff751cb52
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/config.py
@@ -0,0 +1,4 @@
+"""Platform-agnostic bot config."""
+
+# Cache TTL for AutoPilot session IDs (per channel/thread)
+SESSION_TTL = 86400 # 24 hours
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.py
new file mode 100644
index 0000000000..130107c793
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py
@@ -0,0 +1,280 @@
+"""Platform-agnostic message handler.
+
+Receives a MessageContext from any adapter and drives the full AutoPilot
+interaction: link resolution, thread routing, batched streaming with a
+persistent typing indicator.
+"""
+
+import asyncio
+import logging
+from dataclasses import dataclass, field
+
+from backend.data.redis_client import get_redis_async
+from backend.util.exceptions import (
+ DuplicateChatMessageError,
+ LinkAlreadyExistsError,
+ NotFoundError,
+)
+
+from . import threads
+from .adapters.base import MessageContext, PlatformAdapter
+from .bot_backend import BotBackend
+from .config import SESSION_TTL
+from .text import format_batch, split_at_boundary
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class TargetState:
+ """Per-target streaming state.
+
+ A "target" is wherever the bot replies — a thread ID, a DM channel ID.
+ `pending` holds messages that arrived while a stream was running; they
+ get drained as a single batched follow-up turn when the stream ends.
+ """
+
+ processing: bool = False
+ pending: list[tuple[str, str, str]] = field(default_factory=list)
+ # Each entry: (username, user_id, text)
+
+
+class MessageHandler:
+ def __init__(self, api: BotBackend):
+ self._api = api
+ self._targets: dict[str, TargetState] = {}
+
+ async def handle(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:
+ if not ctx.text.strip():
+ if ctx.channel_type == "channel":
+ await adapter.send_reply(
+ ctx.channel_id,
+ "You mentioned me but didn't say anything. How can I help?",
+ ctx.message_id,
+ )
+ return
+
+ if not await self._ensure_linked(ctx, adapter):
+ return
+
+ target_id = await self._resolve_target(ctx, adapter)
+ if not target_id:
+ return # Thread not subscribed, ignore silently
+
+ await self._enqueue_and_process(ctx, adapter, target_id)
+
+ # -- Target resolution --
+
+ async def _resolve_target(
+ self, ctx: MessageContext, adapter: PlatformAdapter
+ ) -> str | None:
+ if ctx.channel_type == "dm":
+ return ctx.channel_id
+
+ if ctx.channel_type == "thread":
+ if await threads.is_subscribed(ctx.platform, ctx.channel_id):
+ return ctx.channel_id
+ return None
+
+ # channel_type == "channel" — create a thread and subscribe
+ thread_name = f"{ctx.username} × AutoPilot"
+ thread_id = await adapter.create_thread(
+ ctx.channel_id, ctx.message_id, thread_name
+ )
+ if not thread_id:
+ logger.warning("Thread creation failed, falling back to channel reply")
+ return ctx.channel_id
+ await threads.subscribe(ctx.platform, thread_id)
+ return thread_id
+
+ # -- Batched streaming --
+
+ async def _enqueue_and_process(
+ self, ctx: MessageContext, adapter: PlatformAdapter, target_id: str
+ ) -> None:
+ state = self._targets.setdefault(target_id, TargetState())
+ state.pending.append((ctx.username, ctx.user_id, ctx.text))
+
+ if state.processing:
+ # Another invocation is streaming for this target — it will pick
+ # up the message we just appended when its current stream ends.
+ return
+
+ state.processing = True
+ try:
+ while state.pending:
+ batch = list(state.pending)
+ state.pending.clear()
+ await self._stream_batch(batch, ctx, adapter, target_id)
+ finally:
+ state.processing = False
+ # Drop the empty state so the dict doesn't grow unbounded across
+ # the bot's lifetime.
+ if not state.pending:
+ self._targets.pop(target_id, None)
+
+ async def _stream_batch(
+ self,
+ batch: list[tuple[str, str, str]],
+ ctx: MessageContext,
+ adapter: PlatformAdapter,
+ target_id: str,
+ ) -> None:
+ prefixed = format_batch(batch, ctx.platform)
+
+ redis = await get_redis_async()
+ cache_key = f"copilot-bot:session:{ctx.platform}:{target_id}"
+ cached_session_id = await redis.get(cache_key)
+
+ async def _on_session_id(sid: str) -> None:
+ try:
+ await redis.set(cache_key, sid, ex=SESSION_TTL)
+ except Exception:
+ logger.warning("Failed to cache session id for target %s", target_id)
+
+ flush_at = adapter.chunk_flush_at
+ buffer = ""
+ sent_any_content = False
+
+ typing_task = asyncio.create_task(_keep_typing(adapter, target_id))
+ try:
+ async for chunk in self._api.stream_chat(
+ platform=ctx.platform,
+ platform_user_id=ctx.user_id,
+ message=prefixed,
+ session_id=cached_session_id,
+ platform_server_id=ctx.server_id,
+ on_session_id=_on_session_id,
+ ):
+ buffer += chunk
+ if len(buffer) >= flush_at:
+ post, buffer = split_at_boundary(buffer, flush_at)
+ if post:
+ await adapter.send_message(target_id, post)
+ if post.strip():
+ sent_any_content = True
+ except DuplicateChatMessageError:
+ # Another in-flight turn is already processing this exact message —
+ # stay quiet so the user doesn't get a double response.
+ logger.info("Duplicate message dropped for target %s", target_id)
+ return
+ except NotFoundError:
+ logger.exception("Chat turn rejected")
+ await adapter.send_message(
+ target_id, "AutoPilot ran into an error. Try again later."
+ )
+ return
+ except Exception:
+ logger.exception(
+ "Unexpected error during streaming for target %s", target_id
+ )
+ await adapter.send_message(
+ target_id,
+ "Something went wrong. Try again in a moment.",
+ )
+ return
+ finally:
+ typing_task.cancel()
+ try:
+ await typing_task
+ except asyncio.CancelledError:
+ pass
+ await adapter.stop_typing(target_id)
+
+ if buffer.strip():
+ await adapter.send_message(target_id, buffer)
+ sent_any_content = True
+
+ if not sent_any_content:
+ await adapter.send_message(
+ target_id,
+ "AutoPilot didn't produce a response. Try rephrasing your question.",
+ )
+
+ # -- Linking --
+
+ async def _ensure_linked(
+ self, ctx: MessageContext, adapter: PlatformAdapter
+ ) -> bool:
+ try:
+ if ctx.is_dm:
+ result = await self._api.resolve_user(ctx.platform, ctx.user_id)
+ if not result.linked:
+ await self._prompt_user_link(ctx, adapter)
+ return False
+ else:
+ if not ctx.server_id:
+ logger.error("Non-DM message missing server_id: %r", ctx)
+ return False
+ result = await self._api.resolve_server(ctx.platform, ctx.server_id)
+ if not result.linked:
+ await adapter.send_message(
+ ctx.channel_id,
+ "This server isn't linked to an AutoGPT account yet. "
+ "Ask a server admin to run `/setup` first.",
+ )
+ return False
+ except ValueError:
+ # ValueError-based domain exceptions (NotFoundError etc.) arrive
+ # over RPC with this base type.
+ logger.exception("Failed to check link status")
+ await adapter.send_message(
+ ctx.channel_id, "Something went wrong. Try again later."
+ )
+ return False
+ except Exception:
+ logger.exception("Unexpected error while checking link status")
+ await adapter.send_message(
+ ctx.channel_id,
+ "Something went wrong. Try again in a moment.",
+ )
+ return False
+ return True
+
+ async def _prompt_user_link(
+ self, ctx: MessageContext, adapter: PlatformAdapter
+ ) -> None:
+ try:
+ result = await self._api.create_user_link_token(
+ platform=ctx.platform,
+ platform_user_id=ctx.user_id,
+ platform_username=ctx.username,
+ )
+ platform_display = ctx.platform.capitalize()
+ await adapter.send_link(
+ ctx.channel_id,
+ f"Your {platform_display} DMs aren't linked to an AutoGPT "
+ "account yet. Click below to connect — once linked, you can "
+ "chat with AutoPilot right here.",
+ link_label="Link Account",
+ link_url=result.link_url,
+ )
+ except LinkAlreadyExistsError:
+ # Race: user got linked between resolve_user and create. Re-check
+ # — if still not linked, the backend returned a stale error and
+ # we shouldn't spam the user.
+ re_check = await self._api.resolve_user(ctx.platform, ctx.user_id)
+ if re_check.linked:
+ return
+ logger.exception(
+ "create_user_link_token raised 'already exists' "
+ "but user isn't actually linked"
+ )
+ except Exception:
+ logger.exception("Failed to create user link token")
+ await adapter.send_message(
+ ctx.channel_id,
+ "Something went wrong setting up the link. Try again later.",
+ )
+
+
+async def _keep_typing(adapter: PlatformAdapter, target_id: str) -> None:
+ """Re-fire the typing indicator every 8s so it doesn't expire mid-stream."""
+ try:
+ while True:
+ await adapter.start_typing(target_id)
+ await asyncio.sleep(8)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.debug("Typing loop error", exc_info=True)
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
new file mode 100644
index 0000000000..0462af9aeb
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
@@ -0,0 +1,338 @@
+"""Tests for the platform-agnostic message handler."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
+
+from .adapters.base import ChannelType, MessageContext
+from .bot_backend import LinkTokenResult, ResolveResult
+from .handler import MessageHandler, TargetState
+
+
+def _ctx(
+ *,
+ channel_type: ChannelType = "channel",
+ server_id: str | None = "guild-1",
+ channel_id: str = "chan-1",
+ message_id: str = "msg-1",
+ user_id: str = "user-1",
+ username: str = "Bently",
+ text: str = "hello bot",
+) -> MessageContext:
+ return MessageContext(
+ platform="discord",
+ channel_type=channel_type,
+ server_id=server_id,
+ channel_id=channel_id,
+ message_id=message_id,
+ user_id=user_id,
+ username=username,
+ text=text,
+ )
+
+
+def _adapter() -> MagicMock:
+ adapter = MagicMock()
+ adapter.chunk_flush_at = 1900
+ adapter.send_message = AsyncMock()
+ adapter.send_reply = AsyncMock()
+ adapter.send_link = AsyncMock()
+ adapter.start_typing = AsyncMock()
+ adapter.stop_typing = AsyncMock()
+ adapter.create_thread = AsyncMock(return_value="thread-new")
+ return adapter
+
+
+def _api(*, server_linked: bool = True, user_linked: bool = True) -> MagicMock:
+ api = MagicMock()
+ api.resolve_server = AsyncMock(return_value=ResolveResult(linked=server_linked))
+ api.resolve_user = AsyncMock(return_value=ResolveResult(linked=user_linked))
+ api.create_user_link_token = AsyncMock(
+ return_value=LinkTokenResult(
+ token="t",
+ link_url="https://example.com/link/t",
+ expires_at="2099-01-01T00:00:00Z",
+ )
+ )
+
+ async def _empty_stream(*args, **kwargs):
+ if False:
+ yield ""
+
+ api.stream_chat = _empty_stream
+ return api
+
+
+class TestEmptyMessage:
+ @pytest.mark.asyncio
+ async def test_channel_mention_without_text_gets_nudge(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ await handler.handle(_ctx(text=" "), adapter)
+ adapter.send_reply.assert_awaited_once()
+ adapter.send_message.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_empty_dm_is_silently_dropped(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ await handler.handle(_ctx(channel_type="dm", text=""), adapter)
+ adapter.send_reply.assert_not_awaited()
+ adapter.send_message.assert_not_awaited()
+
+
+class TestEnsureLinked:
+ @pytest.mark.asyncio
+ async def test_unlinked_server_tells_user_to_setup(self):
+ handler = MessageHandler(_api(server_linked=False))
+ adapter = _adapter()
+ await handler.handle(_ctx(), adapter)
+ call_args = adapter.send_message.await_args.args
+ assert "isn't linked" in call_args[1]
+ assert "/setup" in call_args[1]
+
+ @pytest.mark.asyncio
+ async def test_unlinked_dm_prompts_link_flow(self):
+ handler = MessageHandler(_api(user_linked=False))
+ adapter = _adapter()
+ await handler.handle(_ctx(channel_type="dm", server_id=None), adapter)
+ adapter.send_link.assert_awaited_once()
+ assert adapter.send_link.await_args.kwargs["link_url"].startswith(
+ "https://example.com/link/"
+ )
+
+ @pytest.mark.asyncio
+ async def test_non_dm_without_server_id_is_rejected(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ await handler.handle(_ctx(server_id=None), adapter)
+ # Guard short-circuits before calling resolve_server.
+ handler._api.resolve_server.assert_not_awaited()
+ adapter.send_message.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_backend_error_in_resolve_produces_message(self):
+ api = _api()
+ api.resolve_server = AsyncMock(side_effect=NotFoundError("boom"))
+ handler = MessageHandler(api)
+ adapter = _adapter()
+ await handler.handle(_ctx(), adapter)
+ adapter.send_message.assert_awaited_once()
+ assert "went wrong" in adapter.send_message.await_args.args[1].lower()
+
+
+class TestResolveTarget:
+ @pytest.mark.asyncio
+ async def test_dm_reuses_channel_id(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ ctx = _ctx(channel_type="dm", server_id=None, channel_id="dm-42")
+ result = await handler._resolve_target(ctx, adapter)
+ assert result == "dm-42"
+
+ @pytest.mark.asyncio
+ async def test_unsubscribed_thread_returns_none(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ ctx = _ctx(channel_type="thread", channel_id="thread-old")
+ with patch(
+ "backend.copilot.bot.handler.threads.is_subscribed",
+ new=AsyncMock(return_value=False),
+ ):
+ assert await handler._resolve_target(ctx, adapter) is None
+
+ @pytest.mark.asyncio
+ async def test_subscribed_thread_keeps_channel(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ ctx = _ctx(channel_type="thread", channel_id="thread-ok")
+ with patch(
+ "backend.copilot.bot.handler.threads.is_subscribed",
+ new=AsyncMock(return_value=True),
+ ):
+ assert await handler._resolve_target(ctx, adapter) == "thread-ok"
+
+ @pytest.mark.asyncio
+ async def test_channel_creates_and_subscribes_thread(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ adapter.create_thread = AsyncMock(return_value="thread-created")
+ with patch(
+ "backend.copilot.bot.handler.threads.subscribe", new=AsyncMock()
+ ) as subscribe:
+ result = await handler._resolve_target(_ctx(), adapter)
+ assert result == "thread-created"
+ subscribe.assert_awaited_once_with("discord", "thread-created")
+
+ @pytest.mark.asyncio
+ async def test_channel_falls_back_to_parent_when_thread_creation_fails(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ adapter.create_thread = AsyncMock(return_value=None)
+ result = await handler._resolve_target(_ctx(channel_id="parent-chan"), adapter)
+ assert result == "parent-chan"
+
+
+class TestBatching:
+ @pytest.mark.asyncio
+ async def test_concurrent_message_queues_when_processing(self):
+ """Second caller with processing=True returns without starting a new stream."""
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+ state = TargetState(processing=True)
+ handler._targets["target-1"] = state
+
+ await handler._enqueue_and_process(_ctx(text="second"), adapter, "target-1")
+
+ assert state.processing is True
+ assert state.pending == [("Bently", "user-1", "second")]
+
+ @pytest.mark.asyncio
+ async def test_target_state_cleared_after_drain(self):
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+
+ stream_calls: list[list] = []
+
+ async def fake_stream_batch(batch, ctx, ad, tid):
+ stream_calls.append(list(batch))
+
+ handler._stream_batch = fake_stream_batch # type: ignore[method-assign]
+
+ await handler._enqueue_and_process(_ctx(text="hello"), adapter, "target-1")
+ assert stream_calls == [[("Bently", "user-1", "hello")]]
+ # Dict entry should be gone once processing finishes with empty pending.
+ assert "target-1" not in handler._targets
+
+ @pytest.mark.asyncio
+ async def test_drain_loop_picks_up_appended_messages(self):
+ """Messages appended to pending mid-drain are processed in the next iter."""
+ handler = MessageHandler(_api())
+ adapter = _adapter()
+
+ state = TargetState()
+ handler._targets["target-1"] = state
+
+ seen: list[list] = []
+
+ async def fake_stream_batch(batch, ctx, ad, tid):
+ seen.append(list(batch))
+ if len(seen) == 1:
+ # Simulate another caller appending during the first stream.
+ state.pending.append(("Later", "u2", "follow-up"))
+
+ handler._stream_batch = fake_stream_batch # type: ignore[method-assign]
+ await handler._enqueue_and_process(_ctx(text="first"), adapter, "target-1")
+
+ assert seen == [
+ [("Bently", "user-1", "first")],
+ [("Later", "u2", "follow-up")],
+ ]
+ assert "target-1" not in handler._targets
+
+ @pytest.mark.asyncio
+ async def test_duplicate_message_is_silently_dropped(self):
+ api = _api()
+
+ async def duplicate_stream(*args, **kwargs):
+ raise DuplicateChatMessageError("in flight")
+ yield "" # pragma: no cover
+
+ api.stream_chat = duplicate_stream
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ with patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ adapter.send_message.assert_not_awaited()
+
+
+class TestStreamFallback:
+ """Covers the empty-response fallback, including the boundary-flush bug
+ where prior code posted 'AutoPilot didn't produce a response' even though
+ content had already been flushed mid-stream.
+ """
+
+ @staticmethod
+ def _redis_patch():
+ return patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),
+ )
+
+ @pytest.mark.asyncio
+ async def test_empty_stream_sends_fallback(self):
+ api = _api()
+
+ async def empty(*args, **kwargs):
+ if False:
+ yield ""
+
+ api.stream_chat = empty
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ with TestStreamFallback._redis_patch():
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ msgs = [c.args[1] for c in adapter.send_message.await_args_list]
+ assert any("didn't produce a response" in m for m in msgs)
+
+ @pytest.mark.asyncio
+ async def test_whitespace_only_stream_sends_fallback(self):
+ api = _api()
+
+ async def whitespace(*args, **kwargs):
+ yield " "
+ yield "\n\n"
+
+ api.stream_chat = whitespace
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ with TestStreamFallback._redis_patch():
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ msgs = [c.args[1] for c in adapter.send_message.await_args_list]
+ assert any("didn't produce a response" in m for m in msgs)
+
+ @pytest.mark.asyncio
+ async def test_content_flushed_mid_stream_does_not_trigger_fallback(self):
+ """Regression: before the fix, a response that flushed exactly at a
+ boundary left buffer == "" and the fallback fired after real content
+ had already been posted.
+ """
+ api = _api()
+ adapter = _adapter()
+ adapter.chunk_flush_at = 50
+
+ async def streaming_content(*args, **kwargs):
+ # Exactly flush_at chars → split_at_boundary returns the whole
+ # payload as the post and an empty remainder, so the stream ends
+ # with buffer == "". That USED to fall into the `elif not buffer`
+ # branch and send the "didn't produce a response" fallback.
+ yield "x" * 50
+
+ api.stream_chat = streaming_content
+ handler = MessageHandler(api)
+
+ with TestStreamFallback._redis_patch():
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ msgs = [c.args[1] for c in adapter.send_message.await_args_list]
+ assert not any("didn't produce a response" in m for m in msgs)
+ assert msgs == ["x" * 50]
diff --git a/autogpt_platform/backend/backend/copilot/bot/text.py b/autogpt_platform/backend/backend/copilot/bot/text.py
new file mode 100644
index 0000000000..9c38a92dbe
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/text.py
@@ -0,0 +1,80 @@
+"""Text formatting helpers — message batching and chunk splitting."""
+
+import re
+
+# Matches a triple-backtick fence with an optional language tag. Used to tell
+# whether a cut falls inside an open Markdown code block.
+_CODE_FENCE = re.compile(r"```(\w*)")
+
+
+def format_batch(batch: list[tuple[str, str, str]], platform: str) -> str:
+ """Format one or more pending messages into a single prompt for AutoPilot.
+
+ Each batch entry is (username, user_id, text). When multiple messages are
+ batched together (because they arrived while the bot was streaming a prior
+ response), they're labelled individually so the LLM can address each.
+ """
+ platform_display = platform.capitalize()
+ if len(batch) == 1:
+ username, user_id, text = batch[0]
+ return (
+ f"[Message sent by {username} ({platform_display} user ID: {user_id})]\n"
+ f"{text}"
+ )
+
+ lines = ["[Multiple messages — please address them together]"]
+ for username, user_id, text in batch:
+ lines.append(
+ f"\n[From {username} ({platform_display} user ID: {user_id})]\n{text}"
+ )
+ return "\n".join(lines)
+
+
+def split_at_boundary(text: str, flush_at: int) -> tuple[str, str]:
+ """Split text at a natural boundary to fit within a length limit.
+
+ Returns (postable_chunk, remaining_text).
+ Prefers: paragraph > newline > sentence end > space > hard cut.
+ If the cut lands inside a Markdown code fence (``\\`\\`\\``), the fence is
+ closed in the chunk and reopened at the start of the remainder so both
+ sides render correctly.
+ """
+ if len(text) <= flush_at:
+ return text, ""
+
+ search_start = max(0, flush_at - 200)
+ search_region = text[search_start:flush_at]
+
+ for sep in ("\n\n", "\n"):
+ idx = search_region.rfind(sep)
+ if idx != -1:
+ cut = search_start + idx
+ return _balance_code_fences(text[:cut].rstrip(), text[cut:].lstrip("\n"))
+
+ for sep in (". ", "! ", "? "):
+ idx = search_region.rfind(sep)
+ if idx != -1:
+ cut = search_start + idx + len(sep)
+ return _balance_code_fences(text[:cut], text[cut:])
+
+ idx = search_region.rfind(" ")
+ if idx != -1:
+ cut = search_start + idx
+ return _balance_code_fences(text[:cut], text[cut:].lstrip())
+
+ return _balance_code_fences(text[:flush_at], text[flush_at:])
+
+
+def _balance_code_fences(before: str, after: str) -> tuple[str, str]:
+ """If ``before`` ends inside an open ``\\`\\`\\`` fence, close and reopen it.
+
+ Preserves the language tag from the opening fence so syntax highlighting
+ survives the split.
+ """
+ fences = _CODE_FENCE.findall(before)
+ if len(fences) % 2 == 0:
+ return before, after
+ lang = fences[-1]
+ closed_before = f"{before.rstrip()}\n```"
+ reopened_after = f"```{lang}\n{after.lstrip()}"
+ return closed_before, reopened_after
diff --git a/autogpt_platform/backend/backend/copilot/bot/text_test.py b/autogpt_platform/backend/backend/copilot/bot/text_test.py
new file mode 100644
index 0000000000..e4f771fcea
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/text_test.py
@@ -0,0 +1,105 @@
+"""Tests for message batching + boundary splitting."""
+
+from .text import _balance_code_fences, format_batch, split_at_boundary
+
+
+class TestFormatBatch:
+ def test_single_message_has_header(self):
+ result = format_batch([("Bently", "123", "hello")], "discord")
+ assert result == "[Message sent by Bently (Discord user ID: 123)]\nhello"
+
+ def test_multi_message_labels_each_sender(self):
+ result = format_batch(
+ [
+ ("Alice", "a1", "first"),
+ ("Bob", "b2", "second"),
+ ],
+ "discord",
+ )
+ assert "[Multiple messages" in result
+ assert "[From Alice (Discord user ID: a1)]\nfirst" in result
+ assert "[From Bob (Discord user ID: b2)]\nsecond" in result
+
+ def test_platform_name_is_capitalized(self):
+ result = format_batch([("u", "1", "x")], "telegram")
+ assert "Telegram user ID" in result
+
+
+class TestSplitAtBoundary:
+ def test_short_text_returns_unchanged(self):
+ before, after = split_at_boundary("short", 100)
+ assert before == "short"
+ assert after == ""
+
+ def test_splits_at_paragraph_boundary(self):
+ text = "first paragraph.\n\nsecond paragraph that is long enough"
+ before, after = split_at_boundary(text, 20)
+ assert before == "first paragraph."
+ assert after == "second paragraph that is long enough"
+
+ def test_splits_at_newline_when_no_paragraph(self):
+ text = "line one\nline two line three line four line five"
+ before, after = split_at_boundary(text, 15)
+ assert before == "line one"
+ assert after == "line two line three line four line five"
+
+ def test_splits_at_sentence_when_no_newline(self):
+ text = "First sentence. Second sentence is quite a bit longer here."
+ before, after = split_at_boundary(text, 20)
+ assert before == "First sentence. "
+ assert after == "Second sentence is quite a bit longer here."
+
+ def test_falls_back_to_space_split(self):
+ text = "word " * 50
+ before, after = split_at_boundary(text, 30)
+ assert not before.endswith(" ")
+ # Rejoining drops one space at the cut, but no characters other
+ # than whitespace should be lost.
+ rejoined = (before + " " + after).replace(" ", " ").strip()
+ assert rejoined == text.strip()
+
+ def test_hard_cut_on_single_long_token(self):
+ text = "a" * 500
+ before, after = split_at_boundary(text, 100)
+ assert len(before) == 100
+ assert after == "a" * 400
+
+
+class TestBalanceCodeFences:
+ def test_balanced_code_unchanged(self):
+ before = "prose\n```py\nprint('x')\n```\ntail"
+ after = "more"
+ b, a = _balance_code_fences(before, after)
+ assert b == before
+ assert a == after
+
+ def test_open_fence_gets_closed_and_reopened(self):
+ before = "prose\n```py\nprint('x')"
+ after = "print('y')\n```\ntail"
+ b, a = _balance_code_fences(before, after)
+ assert b.endswith("```")
+ assert a.startswith("```py\n")
+
+ def test_reopens_with_no_lang_when_opener_had_none(self):
+ before = "```\nsome code here"
+ after = "more code\n```"
+ b, a = _balance_code_fences(before, after)
+ assert b.endswith("\n```")
+ assert a.startswith("```\n")
+
+ def test_preserves_latest_language_when_multiple_fences(self):
+ before = "```py\nprint()\n```\nmiddle\n```ts\nconst x = 1"
+ after = "const y = 2\n```"
+ b, a = _balance_code_fences(before, after)
+ assert b.endswith("```")
+ assert a.startswith("```ts\n")
+
+
+class TestSplitAtBoundaryWithCodeFences:
+ def test_split_inside_fence_rebalances(self):
+ code_block = "```python\n" + ("line\n" * 500) + "```\nafter"
+ before, after = split_at_boundary(code_block, 300)
+ # ``before`` must close the fence it opened.
+ assert before.count("```") % 2 == 0
+ # ``after`` must reopen with the same language tag.
+ assert after.lstrip().startswith("```python")
diff --git a/autogpt_platform/backend/backend/copilot/bot/threads.py b/autogpt_platform/backend/backend/copilot/bot/threads.py
new file mode 100644
index 0000000000..f42a708570
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/threads.py
@@ -0,0 +1,25 @@
+"""Thread subscription tracking.
+
+When the bot creates a thread in response to an @mention, we record the
+thread ID so subsequent messages in it don't require another mention.
+Subscriptions live in Redis with a 7-day TTL — stale threads age out
+automatically.
+"""
+
+from backend.data.redis_client import get_redis_async
+
+THREAD_SUBSCRIPTION_TTL = 7 * 86400 # 7 days
+
+
+def _key(platform: str, thread_id: str) -> str:
+ return f"copilot-bot:thread:{platform}:{thread_id}"
+
+
+async def is_subscribed(platform: str, thread_id: str) -> bool:
+ redis = await get_redis_async()
+ return bool(await redis.get(_key(platform, thread_id)))
+
+
+async def subscribe(platform: str, thread_id: str) -> None:
+ redis = await get_redis_async()
+ await redis.set(_key(platform, thread_id), "1", ex=THREAD_SUBSCRIPTION_TTL)
diff --git a/autogpt_platform/backend/backend/copilot/bot/threads_test.py b/autogpt_platform/backend/backend/copilot/bot/threads_test.py
new file mode 100644
index 0000000000..d1f041c4a9
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/threads_test.py
@@ -0,0 +1,55 @@
+"""Tests for Redis-backed thread subscription tracking."""
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from . import threads
+
+
+def redis_mock():
+ mock = AsyncMock()
+ mock.get = AsyncMock()
+ mock.set = AsyncMock()
+ with patch("backend.copilot.bot.threads.get_redis_async", return_value=mock):
+ yield mock
+
+
+class TestSubscribe:
+ @pytest.mark.asyncio
+ async def test_writes_key_with_ttl(self, redis_mock):
+ await threads.subscribe("discord", "thread-123")
+ redis_mock.set.assert_awaited_once_with(
+ "copilot-bot:thread:discord:thread-123",
+ "1",
+ ex=threads.THREAD_SUBSCRIPTION_TTL,
+ )
+
+ @pytest.mark.asyncio
+ async def test_key_includes_platform(self, redis_mock):
+ await threads.subscribe("telegram", "t-1")
+ key = redis_mock.set.await_args.args[0]
+ assert "telegram" in key
+ assert "t-1" in key
+
+
+class TestIsSubscribed:
+ @pytest.mark.asyncio
+ async def test_returns_true_when_present(self, redis_mock):
+ redis_mock.get.return_value = "1"
+ assert await threads.is_subscribed("discord", "thread-1") is True
+
+ @pytest.mark.asyncio
+ async def test_returns_false_when_missing(self, redis_mock):
+ redis_mock.get.return_value = None
+ assert await threads.is_subscribed("discord", "thread-1") is False
+
+ @pytest.mark.asyncio
+ async def test_uses_same_key_as_subscribe(self, redis_mock):
+ redis_mock.get.return_value = None
+ await threads.is_subscribed("discord", "thread-1")
+ await threads.subscribe("discord", "thread-1")
+ read_key = redis_mock.get.await_args.args[0]
+ write_key = redis_mock.set.await_args.args[0]
+ assert read_key == write_key
diff --git a/autogpt_platform/backend/backend/util/clients.py b/autogpt_platform/backend/backend/util/clients.py
index 391142b214..a1dc1f966e 100644
--- a/autogpt_platform/backend/backend/util/clients.py
+++ b/autogpt_platform/backend/backend/util/clients.py
@@ -15,6 +15,7 @@ if TYPE_CHECKING:
from openai import AsyncOpenAI
from supabase import AClient, Client
+ from backend.copilot.bot.app import CoPilotChatBridgeClient
from backend.data.db_manager import (
DatabaseManagerAsyncClient,
DatabaseManagerClient,
@@ -77,6 +78,15 @@ def get_platform_linking_manager_client() -> "PlatformLinkingManagerClient":
return get_service_client(PlatformLinkingManagerClient)
+@thread_cached
+def get_copilot_chat_bridge_client() -> "CoPilotChatBridgeClient":
+ """Get a thread-cached CoPilotChatBridgeClient."""
+ from backend.copilot.bot.app import CoPilotChatBridgeClient
+ from backend.util.service import get_service_client
+
+ return get_service_client(CoPilotChatBridgeClient)
+
+
# ============ Execution Event Bus Helpers ============ #
diff --git a/autogpt_platform/backend/backend/util/service.py b/autogpt_platform/backend/backend/util/service.py
index 48cefa26c0..5b218f25ea 100644
--- a/autogpt_platform/backend/backend/util/service.py
+++ b/autogpt_platform/backend/backend/util/service.py
@@ -23,6 +23,7 @@ from typing import (
Type,
TypeVar,
cast,
+ overload,
)
import httpx
@@ -850,15 +851,28 @@ def endpoint_to_sync(
return cast(Callable[Concatenate[Any, P], R], _stub)
+@overload
+def endpoint_to_async(
+ func: Callable[Concatenate[Any, P], Coroutine[Any, Any, R]],
+) -> Callable[Concatenate[Any, P], Awaitable[R]]: ...
+
+
+@overload
def endpoint_to_async(
func: Callable[Concatenate[Any, P], R],
-) -> Callable[Concatenate[Any, P], Awaitable[R]]:
- """
- The async mirror of `to_sync`.
+) -> Callable[Concatenate[Any, P], Awaitable[R]]: ...
+
+
+def endpoint_to_async(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]:
+ """Typed async stub for a service endpoint.
+
+ The first overload unwraps `Coroutine[Any, Any, R]` (for `async def`
+ service methods); the second keeps sync server methods returning `R`.
+ Both resolve to `Awaitable[R]` on the client.
"""
- async def _stub(*args: P.args, **kwargs: P.kwargs) -> R: # pragma: no cover
+ async def _stub(*args: Any, **kwargs: Any) -> Any: # pragma: no cover
raise RuntimeError("should be intercepted by __getattr__")
update_wrapper(_stub, func)
- return cast(Callable[Concatenate[Any, P], Awaitable[R]], _stub)
+ return _stub
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index 43b0af6bc3..486953fdaa 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -264,6 +264,12 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="The port for the platform_linking manager daemon to run on",
)
+ copilot_chat_bridge_port: int = Field(
+ default=8010,
+ description="The port for the CoPilot chat bridge (multi-platform bot) "
+ "service daemon to run on",
+ )
+
otto_api_url: str = Field(
default="",
description="The URL for the Otto API service",
@@ -668,6 +674,11 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
did_api_key: str = Field(default="", description="D-ID API Key")
revid_api_key: str = Field(default="", description="revid.ai API key")
discord_bot_token: str = Field(default="", description="Discord bot token")
+ autopilot_bot_discord_token: str = Field(
+ default="",
+ description="Discord bot token for the CoPilot chat bridge. When set, "
+ "the bridge enables its Discord adapter.",
+ )
smtp_server: str = Field(default="", description="SMTP server IP")
smtp_port: str = Field(default="", description="SMTP server port")
diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.toml
index 8555fb2c9a..6b02a120a4 100644
--- a/autogpt_platform/backend/pyproject.toml
+++ b/autogpt_platform/backend/pyproject.toml
@@ -134,6 +134,7 @@ executor = "backend.exec:main"
analytics-setup = "scripts.generate_views:main_setup"
analytics-views = "scripts.generate_views:main_views"
copilot-executor = "backend.copilot.executor.__main__:main"
+copilot-bot = "backend.copilot.bot.__main__:main"
cli = "backend.cli:main"
format = "scripts.linter:format"
lint = "scripts.linter:lint"