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): split adapter base into Socket/Webhook + neutralize shared-core coupling (#13505)

Bently3706da0c7582
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index f1b1b37545..e259308915 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -63,6 +63,8 @@ from backend.api.features.library.exceptions import (
FolderValidationError,
)
from backend.blocks.llm import DEFAULT_LLM_MODEL
+from backend.copilot.bot.bot_backend import BotBackend
+from backend.copilot.bot.webhook_routes import register_webhook_adapters
from backend.copilot.rate_limit import UserPaywalledError
from backend.data.model import Credentials
from backend.integrations.providers import ProviderName
@@ -92,6 +94,11 @@ logger = logging.getLogger(__name__)
logging.getLogger("autogpt_libs").setLevel(logging.INFO)
+# Backing client for webhook chat adapters (Slack Events API, etc.) whose routes
+# mount on this API. Owned at module level so `lifespan_context` can close it on
+# shutdown; the routes themselves are mounted further down once `app` exists.
+_webhook_bot_backend = BotBackend()
+
@contextlib.contextmanager
def launch_darkly_context():
@@ -167,6 +174,11 @@ async def lifespan_context(app: fastapi.FastAPI):
# Each cleanup is wrapped so one failure doesn't block the rest. The
# Redis close in particular silences asyncio's "Unclosed ClusterNode"
# GC warning at interpreter shutdown.
+ try:
+ await _webhook_bot_backend.close()
+ except Exception:
+ logger.warning("webhook BotBackend.close() failed", exc_info=True)
+
try:
await backend.data.redis_client.disconnect_async()
except Exception:
@@ -486,6 +498,10 @@ app.include_router(
prefix="/api/platform-linking",
)
+# Mount inbound routes for webhook-driven chat adapters (Slack Events API, …).
+# No-op when no webhook platform is configured; errors surface at startup.
+register_webhook_adapters(app, _webhook_bot_backend)
+
app.mount("/external-api", external_api)
diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.md
index 991324cb74..792e8faa71 100644
--- a/autogpt_platform/backend/backend/copilot/bot/README.md
+++ b/autogpt_platform/backend/backend/copilot/bot/README.md
@@ -51,17 +51,31 @@ bot/
├── bot_backend.py # Thin facade over PlatformLinkingManagerClient + stream_registry
├── text.py # Text splitting + batch formatting
├── threads.py # Redis-backed thread subscription tracking
+├── webhook_routes.py # Mounts webhook adapters' inbound routes on the main API
└── adapters/
- ├── base.py # PlatformAdapter interface + MessageContext
+ ├── base.py # PlatformAdapter (outbound) + SocketAdapter / WebhookAdapter + MessageContext
└── discord/
├── adapter.py # Gateway connection, events, sends, thread creation
├── commands.py # Slash commands (/setup, /help, /unlink)
└── config.py # Discord token + platform limits
```
+**Connector taxonomy.** `PlatformAdapter` is the outbound contract the core
+handler speaks through. Concrete adapters extend one of two subtypes by how
+inbound events arrive:
+
+- **`SocketAdapter`** — owns a long-lived connection (Discord Gateway, Slack
+ Socket Mode). Driven by `start`/`stop`; runs in the `copilot-bot` pod.
+ Built in `app.py::_build_socket_adapters`.
+- **`WebhookAdapter`** — receives inbound HTTPS POSTs (Slack Events API,
+ Telegram, Teams, WhatsApp). Stateless; its `register_routes(app)` mounts onto
+ the main backend API (via `webhook_routes.register_webhook_adapters`), so it
+ rides the existing N-replica deployment — no dedicated pod. Built in
+ `webhook_routes._build_webhook_adapters`.
+
**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.
+The only files that name specific platforms are the two factories above, which
+decide which adapters to instantiate based on which tokens are set.
## How messaging works
@@ -82,14 +96,18 @@ that decides which adapters to instantiate based on which tokens are set.
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.
+2. `adapter.py` subclasses **`SocketAdapter`** (long-lived connection) or
+ **`WebhookAdapter`** (inbound HTTPS) and implements all the outbound
+ `PlatformAdapter` methods — `max_message_length`, `chunk_flush_at`,
+ `send_message`, `send_link`, `create_thread`, `send_file`, etc. — plus its
+ subtype's inbound method (`start`/`stop` or `register_routes`).
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`:
+4. Register it in the matching factory, gated on its token(s):
+ - Socket → `app.py::_build_socket_adapters`
+ - Webhook → `webhook_routes.py::_build_webhook_adapters`
```python
- if <platform>_config.BOT_TOKEN:
+ if <platform>_config.get_bot_token():
adapters.append(<Platform>Adapter(api))
```
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
index ed7517f85a..3af0291026 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
@@ -1,14 +1,18 @@
"""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.
+``PlatformAdapter`` is the outbound contract the platform-agnostic core handler
+(``handler.py``) speaks through — it never names a platform. Concrete adapters
+extend one of two subtypes depending on how inbound events arrive:
+``SocketAdapter`` (owns a long-lived connection — Discord Gateway, Slack Socket
+Mode) or ``WebhookAdapter`` (receives inbound HTTPS POSTs — Slack Events API,
+Telegram, Teams, WhatsApp).
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Awaitable, Callable, Literal, Optional
+from fastapi import FastAPI
from pydantic import BaseModel
# Callback signature: (ctx, adapter) -> awaitable None
@@ -135,7 +139,12 @@ class MessageContext:
class PlatformAdapter(ABC):
- """Interface that each chat platform must implement."""
+ """Outbound contract shared by every platform adapter.
+
+ The core handler only ever holds a ``PlatformAdapter`` — it speaks through
+ these methods and never cares whether events arrive over a socket or a
+ webhook. Inbound wiring lives on the two subtypes below.
+ """
@property
@abstractmethod
@@ -144,12 +153,6 @@ class PlatformAdapter(ABC):
@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,
@@ -236,6 +239,28 @@ class PlatformAdapter(ABC):
"""Hard platform cap on a single uploaded file's size in bytes."""
...
+ @property
+ @abstractmethod
+ def max_thread_name_length(self) -> int:
+ """Hard platform cap on a thread/topic name's length.
+
+ The shared thread-naming logic clamps candidate titles to this before
+ handing them to ``create_thread``/``rename_thread``. Platforms without
+ named threads (Slack) can return any value — the name is unused there.
+ """
+ ...
+
+ @property
+ @abstractmethod
+ def typing_refresh_interval(self) -> float:
+ """Seconds between typing-indicator refreshes while a turn streams.
+
+ Platform typing indicators auto-expire (Discord ~10s, Telegram ~5s);
+ the shared keep-alive loop re-fires at this cadence. Platforms with no
+ typing indicator can return any value — ``start_typing`` is a no-op.
+ """
+ ...
+
@abstractmethod
async def send_file(self, channel_id: str, text: str, file: FileAttachment) -> None:
"""Send a single file as an attachment, with optional accompanying text.
@@ -245,12 +270,36 @@ class PlatformAdapter(ABC):
"""
...
+ def localize_markup(self, text: str) -> str:
+ """Convert the bot's canonical markup into this platform's dialect.
+
+ The core handler and the model speak one canonical flavour (CommonMark:
+ ``**bold**``, ``[label](url)``, ``- bullets``). Each adapter converts
+ that to what its platform renders (Discord ≈ CommonMark, so the default
+ identity is correct; Slack overrides to mrkdwn). Adapters MUST apply
+ this to outbound text in their ``send_*`` methods so no send path
+ bypasses it — the default here keeps text unchanged.
+ """
+ return text
+
# -- 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
+ def looks_like_channel_id(self, ref: str) -> bool:
+ """Whether ``ref`` is one of this platform's channel IDs (vs a name).
+
+ The shared proactive-post resolver uses this to decide whether to treat
+ a target reference as a raw channel ID or a channel name to look up.
+ Each platform's ID grammar differs (Discord numeric snowflakes, Slack
+ ``C0123ABCD``, Telegram signed integers), so the discrimination can't
+ live in the platform-agnostic layer.
+ """
+ ...
+
@abstractmethod
async def list_text_channels(
self, server_ids: tuple[str, ...]
@@ -294,3 +343,33 @@ class PlatformAdapter(ABC):
the platform/channel doesn't support it.
"""
...
+
+
+class SocketAdapter(PlatformAdapter):
+ """Adapter that owns a long-lived connection (Discord Gateway, Slack Socket
+ Mode). The connection is a per-token singleton held open for the process's
+ lifetime, so each socket adapter runs in the ``copilot-bot`` pod and is
+ driven by ``start``/``stop``.
+ """
+
+ @abstractmethod
+ async def start(self) -> None: ...
+
+ @abstractmethod
+ async def stop(self) -> None: ...
+
+
+class WebhookAdapter(PlatformAdapter):
+ """Adapter driven by inbound HTTPS webhooks (Slack Events API, Telegram,
+ Teams, WhatsApp). Stateless — its routes mount on the main backend API and
+ ride the existing N-replica deployment, so no dedicated pod is needed.
+ """
+
+ @abstractmethod
+ def register_routes(self, app: FastAPI) -> None:
+ """Mount this adapter's inbound webhook route(s) onto ``app``.
+
+ The adapter owns its own request signature verification and must ACK
+ within the platform's timeout, scheduling the real work off-request.
+ """
+ ...
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base_test.py
new file mode 100644
index 0000000000..eaa035549f
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base_test.py
@@ -0,0 +1,22 @@
+"""Tests for the adapter base-class hierarchy."""
+
+from unittest.mock import MagicMock
+
+from .base import PlatformAdapter, SocketAdapter, WebhookAdapter
+from .discord.adapter import DiscordAdapter
+
+
+def test_socket_and_webhook_adapters_share_the_platform_contract():
+ assert issubclass(SocketAdapter, PlatformAdapter)
+ assert issubclass(WebhookAdapter, PlatformAdapter)
+
+
+def test_discord_is_a_socket_adapter():
+ assert issubclass(DiscordAdapter, SocketAdapter)
+
+
+def test_localize_markup_defaults_to_identity():
+ # Discord doesn't override the base seam, so it must leave canonical
+ # CommonMark untouched (the default `return text`).
+ adapter = DiscordAdapter(MagicMock())
+ assert adapter.localize_markup("**bold** [x](y)") == "**bold** [x](y)"
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 f16c0c6e12..3677c3d8b5 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -25,9 +25,9 @@ from ..base import (
MessageCallback,
MessageContext,
MessageHistoryEntry,
- PlatformAdapter,
PostedRef,
ReferencedConversation,
+ SocketAdapter,
)
from . import commands, config, intro
from .references import (
@@ -63,8 +63,12 @@ MAX_INBOUND_ATTACHMENTS = 10
# conversation leading up to it (rather than the channel's latest activity).
REFERENCED_MESSAGE_CONTEXT = 15
+# Discord IDs are numeric snowflakes — used to tell a raw channel ID from a
+# channel name in the proactive-post resolver (see ``looks_like_channel_id``).
+_SNOWFLAKE = re.compile(r"^\d{15,21}$")
-class DiscordAdapter(PlatformAdapter):
+
+class DiscordAdapter(SocketAdapter):
def __init__(self, api: BotBackend):
intents = discord.Intents.default()
intents.message_content = True
@@ -99,6 +103,17 @@ class DiscordAdapter(PlatformAdapter):
def max_attachment_bytes(self) -> int:
return config.MAX_ATTACHMENT_BYTES
+ @property
+ def max_thread_name_length(self) -> int:
+ return config.MAX_THREAD_NAME_LENGTH
+
+ @property
+ def typing_refresh_interval(self) -> float:
+ return config.TYPING_REFRESH_SECONDS
+
+ def looks_like_channel_id(self, ref: str) -> bool:
+ return bool(_SNOWFLAKE.match(ref))
+
def on_message(self, callback: MessageCallback) -> None:
self._on_message_callback = callback
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py
index 2c54e91030..ceea8e2523 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/config.py
@@ -31,6 +31,12 @@ CHUNK_FLUSH_AT = 1900
# link-to-chat button.
MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
+# Discord's hard cap on a thread name.
+MAX_THREAD_NAME_LENGTH = 100
+
+# Discord's typing indicator auto-expires after ~10s; refresh under that.
+TYPING_REFRESH_SECONDS = 8.0
+
# Sensible default Discord permissions for the "Add to server" invite URL —
# covers send messages, embed links, attach files, read history, add
# reactions, use external emoji, slash commands, public threads, and sending
diff --git a/autogpt_platform/backend/backend/copilot/bot/app.py b/autogpt_platform/backend/backend/copilot/bot/app.py
index 34bdfc6a6c..6822872465 100644
--- a/autogpt_platform/backend/backend/copilot/bot/app.py
+++ b/autogpt_platform/backend/backend/copilot/bot/app.py
@@ -18,7 +18,7 @@ from backend.util.service import (
from backend.util.settings import Settings
from . import outbound
-from .adapters.base import ChannelInfo, PlatformAdapter
+from .adapters.base import ChannelInfo, PlatformAdapter, SocketAdapter
from .adapters.discord import config as discord_config
from .adapters.discord.adapter import DiscordAdapter
from .bot_backend import BotBackend
@@ -63,7 +63,7 @@ class CoPilotChatBridge(AppService):
async def _run_adapters(self) -> None:
api = BotBackend()
self._api = api
- adapters = _build_adapters(api)
+ adapters = _build_socket_adapters(api)
self._adapters_by_platform = {a.platform_name: a for a in adapters}
if not adapters:
@@ -192,15 +192,15 @@ class CoPilotChatBridgeClient(AppServiceClient):
)
-def _build_adapters(api: BotBackend) -> list[PlatformAdapter]:
- """Instantiate adapters based on which platform tokens are configured."""
- adapters: list[PlatformAdapter] = []
+def _build_socket_adapters(api: BotBackend) -> list[SocketAdapter]:
+ """Instantiate socket adapters (start/stop-driven) whose tokens are set.
+
+ Webhook-driven adapters (Slack, Telegram, …) mount onto the main backend
+ API instead — see ``webhook_routes.register_webhook_adapters`` — so they
+ are not built here.
+ """
+ adapters: list[SocketAdapter] = []
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/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.py
index 2f10db754b..ff5fd38092 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py
@@ -38,7 +38,6 @@ from .text import format_batch, split_at_boundary
logger = logging.getLogger(__name__)
-THREAD_NAME_MAX_LENGTH = 100
THREAD_NAME_PREFIX = "AutoPilot: "
TITLE_RENAME_ATTEMPTS = 5
TITLE_RENAME_INTERVAL_SECONDS = 1.0
@@ -294,7 +293,9 @@ class MessageHandler:
return ctx.channel_id
# channel_type == "channel" — create a thread and subscribe
- thread_name = build_thread_name(ctx.text, ctx.username)
+ thread_name = build_thread_name(
+ ctx.text, ctx.username, adapter.max_thread_name_length
+ )
thread_id = await adapter.create_thread(
ctx.channel_id, ctx.message_id, thread_name
)
@@ -762,7 +763,9 @@ class MessageHandler:
)
title = None
if title:
- await adapter.rename_thread(thread_id, clamp_thread_name(title))
+ await adapter.rename_thread(
+ thread_id, clamp_thread_name(title, adapter.max_thread_name_length)
+ )
return
if attempt < TITLE_RENAME_ATTEMPTS - 1:
await asyncio.sleep(TITLE_RENAME_INTERVAL_SECONDS)
@@ -854,11 +857,15 @@ class MessageHandler:
async def _keep_typing(adapter: PlatformAdapter, target_id: str) -> None:
- """Re-fire the typing indicator every 8s so it doesn't expire mid-stream."""
+ """Re-fire the typing indicator so it doesn't expire mid-stream.
+
+ Cadence is the adapter's ``typing_refresh_interval`` — platform indicators
+ auto-expire at different rates.
+ """
try:
while True:
await adapter.start_typing(target_id)
- await asyncio.sleep(8)
+ await asyncio.sleep(adapter.typing_refresh_interval)
except asyncio.CancelledError:
raise
except Exception:
@@ -891,19 +898,25 @@ def _model_attachment_note(problems: list[tuple[str, str]]) -> str:
)
-def build_thread_name(text: str, username: str) -> str:
- """Build a Discord-safe thread name from the user's first prompt."""
+def build_thread_name(text: str, username: str, max_length: int) -> str:
+ """Build a thread name from the user's first prompt, clamped to the
+ platform's ``max_length``."""
cleaned = " ".join(text.split())
if not cleaned:
cleaned = f"{username} with AutoPilot"
- return clamp_thread_name(f"{THREAD_NAME_PREFIX}{cleaned}")
+ return clamp_thread_name(f"{THREAD_NAME_PREFIX}{cleaned}", max_length)
-def clamp_thread_name(name: str) -> str:
+def clamp_thread_name(name: str, max_length: int) -> str:
cleaned = " ".join(name.split()) or "AutoPilot Chat"
- if len(cleaned) > THREAD_NAME_MAX_LENGTH:
- return cleaned[: THREAD_NAME_MAX_LENGTH - 3].rstrip() + "..."
- return cleaned
+ if len(cleaned) <= max_length:
+ return cleaned
+ # Below the ellipsis width a tiny adapter cap can't fit "…", and a
+ # negative slice index would overrun the limit — hard-cut instead.
+ ellipsis = "..."
+ if max_length <= len(ellipsis):
+ return cleaned[:max_length]
+ return cleaned[: max_length - len(ellipsis)].rstrip() + ellipsis
def _copilot_session_url(session_id: str) -> str | None:
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
index a67aea6c92..594059ffb3 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
@@ -67,6 +67,8 @@ def _adapter() -> MagicMock:
adapter = MagicMock()
adapter.chunk_flush_at = 1900
adapter.max_attachment_bytes = 25 * 1024 * 1024
+ adapter.max_thread_name_length = 100
+ adapter.typing_refresh_interval = 8.0
adapter.send_message = AsyncMock()
adapter.send_reply = AsyncMock()
adapter.send_link = AsyncMock()
@@ -764,21 +766,32 @@ class TestStreamFallback:
class TestThreadNames:
def test_build_thread_name_from_prompt(self):
assert (
- build_thread_name(" tell me\nabout space ", "Bently")
+ build_thread_name(" tell me\nabout space ", "Bently", 100)
== "AutoPilot: tell me about space"
)
- def test_build_thread_name_truncates_to_discord_limit(self):
- name = build_thread_name("x" * 200, "Bently")
+ def test_build_thread_name_truncates_to_platform_limit(self):
+ name = build_thread_name("x" * 200, "Bently", 100)
assert len(name) <= 100
assert name.startswith("AutoPilot: ")
assert name.endswith("...")
+ def test_build_thread_name_respects_a_larger_limit(self):
+ name = build_thread_name("x" * 200, "Bently", 128)
+ assert 100 < len(name) <= 128
+
def test_clamp_thread_name_handles_generated_titles(self):
- assert clamp_thread_name(" Generated\nWeb Title ") == "Generated Web Title"
+ assert (
+ clamp_thread_name(" Generated\nWeb Title ", 100)
+ == "Generated Web Title"
+ )
def test_clamp_thread_name_falls_back_when_blank(self):
- assert clamp_thread_name(" ") == "AutoPilot Chat"
+ assert clamp_thread_name(" ", 100) == "AutoPilot Chat"
+
+ def test_clamp_thread_name_never_overruns_a_tiny_cap(self):
+ # A tiny adapter cap must not make the slice index go negative.
+ assert len(clamp_thread_name("x" * 50, 2)) <= 2
# ── Workspace artifact extraction & delivery ────────────────────────────
diff --git a/autogpt_platform/backend/backend/copilot/bot/outbound.py b/autogpt_platform/backend/backend/copilot/bot/outbound.py
index 81efe44bbf..a97aa5aca4 100644
--- a/autogpt_platform/backend/backend/copilot/bot/outbound.py
+++ b/autogpt_platform/backend/backend/copilot/bot/outbound.py
@@ -15,7 +15,6 @@ thread creation); this module never imports ``discord``.
"""
import logging
-import re
from typing import Literal, Optional
from pydantic import BaseModel
@@ -25,11 +24,6 @@ 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.
@@ -138,7 +132,7 @@ async def _resolve_target(
if not ref:
return None, "channel_not_found"
- if _SNOWFLAKE.match(ref):
+ if adapter.looks_like_channel_id(ref):
guild_id = await adapter.get_channel_server_id(ref)
if guild_id is None:
return None, "channel_not_found"
diff --git a/autogpt_platform/backend/backend/copilot/bot/outbound_test.py b/autogpt_platform/backend/backend/copilot/bot/outbound_test.py
index 5092d877e3..26b8969a50 100644
--- a/autogpt_platform/backend/backend/copilot/bot/outbound_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/outbound_test.py
@@ -1,6 +1,7 @@
"""Tests for proactive-output authorization + channel resolution."""
-from unittest.mock import AsyncMock
+import re
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -22,6 +23,11 @@ def _adapter(
thread: PostedRef | None = None,
) -> AsyncMock:
adapter = AsyncMock()
+ # Sync classifier — mirrors Discord's numeric-snowflake grammar so
+ # _resolve_target routes IDs vs names the way the real adapter would.
+ adapter.looks_like_channel_id = MagicMock(
+ side_effect=lambda ref: bool(re.fullmatch(r"\d{15,21}", ref))
+ )
adapter.list_text_channels.return_value = channels or []
adapter.get_channel_server_id.return_value = channel_server
adapter.post_channel_message.return_value = posted
diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
new file mode 100644
index 0000000000..d2807afcc2
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
@@ -0,0 +1,43 @@
+"""Mount webhook adapter routes onto the main backend API.
+
+Webhook-driven chat adapters (Slack Events API, Telegram, Teams, WhatsApp) are
+stateless HTTPS receivers, so they ride the existing N-replica main backend API
+rather than the single-connection ``copilot-bot`` pod. This helper wires each
+configured webhook adapter's routes onto the app, mirroring how ``app.py`` wires
+the socket adapters' ``on_message`` callback to the shared ``MessageHandler``.
+"""
+
+import logging
+
+from fastapi import FastAPI
+
+from .adapters.base import WebhookAdapter
+from .bot_backend import BotBackend
+from .handler import MessageHandler
+
+logger = logging.getLogger(__name__)
+
+
+def register_webhook_adapters(app: FastAPI, api: BotBackend) -> None:
+ """Wire every configured webhook adapter's routes onto ``app``.
+
+ The caller owns the ``api`` lifecycle (close it in the app's lifespan
+ cleanup) — matching the pattern used by the socket bridge in ``app.py``.
+ """
+ handler = MessageHandler(api)
+ adapters = _build_webhook_adapters(api)
+ for adapter in adapters:
+ adapter.on_message(handler.handle)
+ adapter.register_routes(app)
+ logger.info(f"Mounted {len(adapters)} webhook adapter(s) on the main backend API")
+
+
+def _build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:
+ """Instantiate webhook adapters from configured platform credentials.
+
+ Slack / Telegram / Teams / WhatsApp adapters slot in here as they land —
+ each gated on its own credentials being set, so an unconfigured platform
+ mounts nothing.
+ """
+ adapters: list[WebhookAdapter] = []
+ return adapters
diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
new file mode 100644
index 0000000000..81ed7af805
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
@@ -0,0 +1,27 @@
+"""Tests for the webhook adapter route-mounting helper."""
+
+from unittest.mock import MagicMock, patch
+
+from fastapi import FastAPI
+
+from .adapters.base import WebhookAdapter
+from .webhook_routes import _build_webhook_adapters, register_webhook_adapters
+
+
+def test_build_webhook_adapters_starts_empty():
+ assert _build_webhook_adapters(MagicMock()) == []
+
+
+def test_register_webhook_adapters_wires_each_adapter():
+ app = FastAPI()
+ adapter = MagicMock(spec=WebhookAdapter)
+ api = MagicMock()
+
+ with patch(
+ "backend.copilot.bot.webhook_routes._build_webhook_adapters",
+ return_value=[adapter],
+ ):
+ register_webhook_adapters(app, api)
+
+ adapter.on_message.assert_called_once()
+ adapter.register_routes.assert_called_once_with(app)