Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(discord): map native slash commands to Switch in-room commands (CHOO-1879) (#142)

Christian McDermotta07807d5fba9
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.py
index 372c27c24..8f28d9287 100644
--- a/core/switch_core/bridges/agent/commands.py
+++ b/core/switch_core/bridges/agent/commands.py
@@ -177,11 +177,41 @@ async def _check_control_target(
)
+@dataclass(frozen=True)
+class CommandArg:
+ """One positional argument of a command, declared for bridges that need it.
+
+ The `!` path does not read this: it free-text parses `event.args` exactly as
+ it always has, and every handler still pulls its arguments out of that
+ string via `_mention_tokens`. The spec exists for platforms whose native
+ commands are *registered* with a declared signature — Discord application
+ commands — so the argument surface is described once, here, instead of
+ being restated per bridge and drifting from the handlers.
+
+ Every argument declared today is a mention-style token (`@agent`, `@role`,
+ `@alias`) matching `mentions.NAME_CHAR`, so a bridge can round-trip a
+ declared value back into the positional `args` string the handlers parse.
+ A command taking genuine free text is not representable here and would need
+ a kind/type field adding before it could be declared.
+
+ `name` is what the user sees as the field label on platforms that render
+ one, so it must be lowercase and match Discord's `^[-_a-z0-9]{1,32}$`.
+ """
+
+ name: str
+ description: str
+ required: bool
+
+
@dataclass(frozen=True)
class Command:
name: str
description: str
handler: CommandHandler | None = None
+ # Declared positional arguments, in the order the handlers parse them out
+ # of `args`. Empty for the many commands that take none. Only consumed by
+ # bridges that register native commands (see CommandArg).
+ args_spec: tuple[CommandArg, ...] = ()
# (client, args, room_id) -> bool. Whether this agent is addressed. Default:
# name- or held-role match (or everyone when no `@`).
addressed: CommandTargeting = field(default=_addressed_by_name_or_role)
@@ -983,6 +1013,9 @@ COMMANDS: list[Command] = [
"Usage: `!reset @agent-name` or `!reset @role` (the role's holder). "
"A target is required — use `!reset-all-agents` to reset everyone.",
_cmd_reset,
+ args_spec=(
+ CommandArg("target", "Agent name, alias, or role to reset", required=True),
+ ),
# The first @token names the agent to reset (by name or held role). A
# bare `!reset` (no target) addresses NO ONE, so it can never
# accidentally reset every agent — that is the explicit
@@ -1003,6 +1036,11 @@ COMMANDS: list[Command] = [
"Usage: `!compact @agent-name` or `!compact @role` (the role's holder). "
"A target is required — use `!compact-all-agents` for everyone.",
_cmd_compact,
+ args_spec=(
+ CommandArg(
+ "target", "Agent name, alias, or role to compact", required=True
+ ),
+ ),
# Require an explicit target — see `reset` — so a bare `!compact` never
# fans out to the whole room by accident.
addressed=_addressed_by_required_first_mention,
@@ -1021,6 +1059,11 @@ COMMANDS: list[Command] = [
"Usage: `!interrupt @agent-name` or `!interrupt @role` (the role's holder). "
"A target is required — use `!interrupt-all-agents` for everyone.",
_cmd_interrupt,
+ args_spec=(
+ CommandArg(
+ "target", "Agent name, alias, or role to interrupt", required=True
+ ),
+ ),
addressed=_addressed_by_required_first_mention,
admin_check=_check_control_target,
),
@@ -1073,18 +1116,32 @@ COMMANDS: list[Command] = [
"set-alias",
"Give an agent a room alias. Usage: `!set-alias @agent-name @alias`.",
_cmd_set_alias,
+ args_spec=(
+ CommandArg("agent", "The agent to give an alias to", required=True),
+ CommandArg("alias", "The alias to use for it in this room", required=True),
+ ),
admin_owned=True,
),
Command(
"remove-alias",
"Remove a room alias. Usage: `!remove-alias @alias` (or `@agent-name`).",
_cmd_remove_alias,
+ args_spec=(
+ CommandArg(
+ "alias", "The alias to clear (or the agent's name)", required=True
+ ),
+ ),
admin_owned=True,
),
Command(
"invite-agent",
"Add an existing agent to this room. Usage: `!invite-agent @agent-name`.",
_cmd_invite,
+ args_spec=(
+ CommandArg(
+ "agent", "The registered agent to add to this room", required=True
+ ),
+ ),
admin_owned=True,
),
Command(
@@ -1110,6 +1167,16 @@ COMMANDS: list[Command] = [
"Usage: `!run-cmd @agent-name`, `!run-cmd @role` (the role's holder), "
"or `!run-cmd @agent-name @role` to also assume that role on connect.",
_cmd_run_cmd,
+ # `role` is second because the handler reads it from the second token,
+ # so it cannot be given without `agent` — see the positional-gap check
+ # in the Discord adapter, which rejects that combination loudly rather
+ # than silently shifting the role into the agent slot.
+ args_spec=(
+ CommandArg("agent", "Agent to show the start command for", required=False),
+ CommandArg(
+ "role", "Role for that agent to assume on connect", required=False
+ ),
+ ),
# Only the first @token targets; a second @token is the role to assume,
# not an address — so it doesn't pull in whoever else holds that role.
addressed=_addressed_by_first_mention,
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 910b4ba83..264d2dcf0 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -116,6 +116,21 @@ class CollaborationAdapter(ABC):
def _bridge_display_name(self) -> str:
return "Switch"
+ def slash_invite_hint(self) -> str | None:
+ """How to run `invite-agent` as a native slash command here, if at all.
+
+ Native slash commands are per-platform: Slack declares them in its app
+ manifest and Discord registers them per guild, while Mattermost and
+ Teams have none — so the no-agents notice must not advertise a `/` form
+ on a bridge that has none to offer. The invocation differs too, since
+ Slack takes a free-text tail where Discord names each argument as its
+ own field, so each adapter spells out its own.
+
+ Returns the body of the bullet; the caller owns the list formatting.
+ None means this platform has no slash commands.
+ """
+ return None
+
async def send_attachment(
self,
channel_id: str,
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index cb362cb35..cc09816a7 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -78,15 +78,24 @@ _LOBBY_DEPRECATION_NOTICE = (
"there to start collaborating."
)
-_NO_AGENTS_NOTICE = (
- "👋 I've linked this channel to a new Switch room, but there are no agents "
- "in it yet — so no one is here to respond to messages.\n\n"
- "*To add an agent*, invite one by name (swap in the agent you want):\n"
- "• `!invite-agent @agent-name` — type it here in the channel, or\n"
- "• `/invite-agent @agent-name` — the Slack slash command.\n\n"
- "Once an agent is in the room, @-mention it here and it'll pick up the "
- "conversation."
-)
+
+def _no_agents_notice(slash_hint: str | None) -> str:
+ """The agentless-room notice, carrying only the invite forms this bridge has.
+
+ The `!` form works everywhere. The slash form does not — whether it exists
+ at all, and how an argument is spelled, are both per-platform — so the
+ adapter supplies that line, or none on a platform with no slash commands.
+ """
+ typed = "• `!invite-agent @agent-name` — type it here in the channel"
+ invites = f"{typed}, or\n• {slash_hint}." if slash_hint else f"{typed}."
+ return (
+ "👋 I've linked this channel to a new Switch room, but there are no agents "
+ "in it yet — so no one is here to respond to messages.\n\n"
+ "*To add an agent*, invite one by name (swap in the agent you want):\n"
+ f"{invites}\n\n"
+ "Once an agent is in the room, @-mention it here and it'll pick up the "
+ "conversation."
+ )
class BridgeCore:
@@ -738,7 +747,9 @@ class BridgeCore:
"Auto-created room %s for channel %s has no agents", room.id, channel_id
)
await self._adapter.admin_message(
- channel_id, _NO_AGENTS_NOTICE, message_type=AdminMessageType.NO_AGENTS
+ channel_id,
+ _no_agents_notice(self._adapter.slash_invite_hint()),
+ message_type=AdminMessageType.NO_AGENTS,
)
return (room.id, room.matrix_room_id)
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 88ec7a3fc..627d5191c 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -10,11 +10,20 @@ from dataclasses import replace
from typing import Any
import discord
+from discord import app_commands
+from switch_core.bridges.agent.commands import COMMANDS_BY_NAME
+from switch_core.bridges.agent.commands import Command as InRoomCommand
from switch_core.bridges.collaboration.adapter import (
CollaborationAdapter,
LiveRuntimeIndicator,
)
+from switch_core.bridges.collaboration.discord.chunking import chunk_message
+from switch_core.bridges.collaboration.discord.slash import (
+ SlashArgError,
+ build_app_commands,
+ reassemble_args,
+)
from switch_core.bridges.collaboration.models import (
Attachment,
AttachmentFailure,
@@ -62,6 +71,7 @@ class DiscordAdapter(CollaborationAdapter):
self._config = config
self._guild_id = int(config.guild_id)
self._client: discord.Client | None = None
+ self._tree: app_commands.CommandTree[Any] | None = None
self._connect_task: asyncio.Task[None] | None = None
self._bot_user_id: int = 0
# channel id -> webhook the bridge posts through in that channel.
@@ -107,6 +117,13 @@ class DiscordAdapter(CollaborationAdapter):
client = discord.Client(intents=intents)
client.event(self._make_on_message())
+ self._tree = app_commands.CommandTree(client)
+ guild = discord.Object(id=self._guild_id)
+ for app_command in build_app_commands(self._handle_slash_command):
+ # Bound to the guild, not global — see _sync_slash_commands. Adding
+ # them globally here would leave the guild-scoped sync below with an
+ # empty payload, registering nothing at all.
+ self._tree.add_command(app_command, guild=guild)
self._client = client
await client.login(self._config.bot_token)
@@ -135,6 +152,42 @@ class DiscordAdapter(CollaborationAdapter):
client.user,
self._config.guild_id,
)
+ await self._sync_slash_commands()
+
+ async def _sync_slash_commands(self) -> None:
+ """Publish the in-room command set as guild-scoped application commands.
+
+ Guild-scoped rather than global, because the adapter is single-guild by
+ construction (`DiscordConnectionConfig.guild_id` is required and every
+ lookup is scoped to it). Guild commands also apply immediately, where
+ global ones propagate for up to an hour, and global registration is
+ per-application — so on an instance running several Discord bridges it
+ would leak each bridge's commands into the others' guilds, where they
+ could only fail. Syncing is a bulk overwrite, so re-running it on every
+ start reconciles renames and removals rather than accumulating them.
+
+ Any sync failure is logged and left non-fatal — hence the broad catch:
+ the bridge still works over `!`-commands and messages, and dropping the
+ whole bridge over a missing `applications.commands` scope is a worse
+ outcome than running without the slash surface. The degradation is
+ visible in the logs rather than silent.
+ """
+ if self._tree is None:
+ return
+ try:
+ synced = await self._tree.sync(guild=discord.Object(id=self._guild_id))
+ except Exception:
+ logger.exception(
+ "Failed to sync Discord slash commands for guild %s — the bridge "
+ "will run without them (check the bot's applications.commands scope)",
+ self._config.guild_id,
+ )
+ return
+ logger.info(
+ "Synced %d Discord slash commands to guild %s",
+ len(synced),
+ self._config.guild_id,
+ )
def _make_on_message(
self,
@@ -164,6 +217,7 @@ class DiscordAdapter(CollaborationAdapter):
except (asyncio.CancelledError, Exception):
pass
self._client = None
+ self._tree = None
self._webhooks.clear()
logger.info("Discord adapter stopped")
@@ -197,14 +251,11 @@ class DiscordAdapter(CollaborationAdapter):
if self._channel_type_of(target) == "lobby":
# DM channels have no webhooks, so no per-message identity — fall
# back to a bot post with the agent name inlined.
- try:
- msg = await target.send(
- f"**{sender_name}**: {content}", suppress_embeds=True
- )
- return f"{msg.channel.id}:{msg.id}"
- except discord.HTTPException:
- logger.exception("Failed to send Discord DM in %s", channel_id)
- return None
+ return await self._send_chunked(
+ f"**{sender_name}**: {content}",
+ lambda part: target.send(part, suppress_embeds=True),
+ where=f"DM {channel_id}",
+ )
thread: Any = None
if thread_root_id:
@@ -218,23 +269,78 @@ class DiscordAdapter(CollaborationAdapter):
try:
webhook = await self._get_webhook(int(channel_id))
- kwargs: dict[str, Any] = {}
- if thread is not None:
- kwargs["thread"] = thread
- sent: Any = await webhook.send(
- content=content,
+ except discord.HTTPException as e:
+ logger.error(
+ "Failed to resolve webhook for Discord channel %s: %s", channel_id, e
+ )
+ return None
+
+ kwargs: dict[str, Any] = {}
+ if thread is not None:
+ kwargs["thread"] = thread
+ return await self._send_chunked(
+ content,
+ lambda part: webhook.send(
+ content=part,
username=sender_name,
avatar_url=self._get_agent_icon(sender_name),
suppress_embeds=True,
wait=True,
**kwargs,
+ ),
+ where=f"channel {channel_id}",
+ )
+
+ async def _send_chunked(
+ self,
+ content: str,
+ send: Callable[[str], Awaitable[Any]],
+ *,
+ where: str,
+ ) -> str | None:
+ """Post `content` as however many messages Discord's 2,000-char cap needs.
+
+ Returns the ref of the FIRST message. That is the one the bridge maps
+ the Matrix event to, so a reply threads under the start of what was
+ said rather than its tail, and a thread created from it opens where the
+ message begins.
+
+ A part failing mid-sequence leaves the message *visibly* truncated
+ rather than silently so: what was posted stays, and a short notice says
+ the rest did not make it.
+ """
+ chunks = chunk_message(content)
+ first_ref: str | None = None
+
+ for index, chunk in enumerate(chunks):
+ try:
+ sent = await send(chunk)
+ except discord.HTTPException as e:
+ logger.error(
+ "Failed to send part %d of %d to Discord %s: %s",
+ index + 1,
+ len(chunks),
+ where,
+ e,
+ )
+ await self._note_truncation(send, index, len(chunks))
+ return first_ref
+ if first_ref is None:
+ first_ref = f"{sent.channel.id}:{sent.id}"
+
+ return first_ref
+
+ @staticmethod
+ async def _note_truncation(
+ send: Callable[[str], Awaitable[Any]], delivered: int, total: int
+ ) -> None:
+ try:
+ await send(
+ f"⚠️ Only {delivered} of {total} parts of this message could be "
+ "delivered — the rest was rejected by Discord."
)
- return f"{sent.channel.id}:{sent.id}"
- except discord.HTTPException as e:
- logger.error(
- "Failed to send message to Discord channel %s: %s", channel_id, e
- )
- return None
+ except discord.HTTPException:
+ logger.exception("Failed to post Discord truncation notice")
async def send_attachment(
self,
@@ -334,6 +440,13 @@ class DiscordAdapter(CollaborationAdapter):
thread_root_id,
)
+ def slash_invite_hint(self) -> str:
+ # Discord declares each argument as its own named field, so the option
+ # name is part of the invocation. Read from the registry the commands
+ # are registered from, so a renamed argument cannot leave this stale.
+ option = COMMANDS_BY_NAME["invite-agent"].args_spec[0].name
+ return f"`/invite-agent {option}:agent-name` — the Discord slash command"
+
async def admin_message(
self,
channel_id: str,
@@ -354,8 +467,6 @@ class DiscordAdapter(CollaborationAdapter):
logger.exception(
"Failed to resolve Discord thread for admin message — posting at channel root"
)
- msg = await target.send(content, suppress_embeds=True)
- return f"{msg.channel.id}:{msg.id}"
except (discord.HTTPException, RuntimeError) as e:
logger.error(
"Failed to post admin message to Discord channel %s: %s",
@@ -364,6 +475,12 @@ class DiscordAdapter(CollaborationAdapter):
)
return None
+ return await self._send_chunked(
+ content,
+ lambda part: target.send(part, suppress_embeds=True),
+ where=f"channel {channel_id}",
+ )
+
async def update_message(
self, channel_id: str, message_ref: str, new_content: str
) -> None:
@@ -771,6 +888,135 @@ class DiscordAdapter(CollaborationAdapter):
)
)
+ # ── Slash commands ───────────────────────────────────────────────────────
+
+ async def _handle_slash_command(
+ self,
+ interaction: discord.Interaction,
+ command: InRoomCommand,
+ values: dict[str, Any],
+ ) -> None:
+ """Translate a native Discord slash command into a Switch in-room command.
+
+ `/reset @agent` maps 1:1 onto `!reset @agent`: the slash name IS the
+ in-room command name, and the declared options are reassembled into the
+ same positional args string, so the invocation reaches the very same
+ dispatcher a typed `!`-command reaches.
+
+ Two Discord constraints set the order of what follows. An interaction
+ must be acknowledged within ~3 seconds; and a command's result never
+ comes back down this call — the admin client answers with a room message
+ that reaches the channel later, outbound. So there is nothing to defer
+ *for*: the ack goes out first, before any Switch work, and the message it
+ posts doubles as the thread root the result is filed under. That mirrors
+ the Slack slash path, which posts the same visible notice because a
+ slash invocation is otherwise invisible to the channel.
+ """
+ shown = self._format_invocation(command, values)
+
+ # Reassembly is pure and instant, so it runs before the ack: a bad
+ # argument is the invoker's typo, and it reads better as an ephemeral
+ # refusal than as a "Running…" notice the channel sees and then watches
+ # turn into an error.
+ try:
+ args = reassemble_args(command.args_spec, values)
+ except SlashArgError as e:
+ await self._reject_slash(interaction, shown, str(e))
+ return
+
+ try:
+ await interaction.response.send_message(
+ f"⚙️ Running `{shown}` — result will appear in this thread."
+ )
+ except discord.HTTPException:
+ logger.exception("Failed to acknowledge Discord slash command %s", shown)
+ return
+
+ try:
+ await self._dispatch_slash_command(interaction, command.name, args)
+ except Exception as e:
+ logger.exception("Failed to dispatch Discord slash command %s", shown)
+ await self._report_slash_failure(interaction, shown, e)
+
+ async def _dispatch_slash_command(
+ self, interaction: discord.Interaction, command_name: str, args: str
+ ) -> None:
+ if self._on_command is None:
+ raise RuntimeError("Discord adapter is not started")
+ channel = interaction.channel
+ if channel is None:
+ raise RuntimeError("Discord interaction carried no channel")
+
+ # A slash command run inside a thread bridges into the PARENT channel's
+ # room and threads under the thread's root, exactly as a typed command
+ # in that thread does.
+ parent_id = getattr(channel, "parent_id", None)
+ if parent_id is not None:
+ channel_id = str(parent_id)
+ root_id: str | None = f"{parent_id}:{channel.id}"
+ channel_name = getattr(getattr(channel, "parent", None), "name", None)
+ else:
+ channel_id = str(channel.id)
+ root_id = None
+ channel_name = getattr(channel, "name", None)
+
+ original = await interaction.original_response()
+ user = interaction.user
+ username = str(user.name)
+ self._user_names[user.id] = username
+ self._username_to_id[username] = user.id
+
+ await self._on_command(
+ InboundCommand(
+ channel_id=channel_id,
+ channel_type=self._channel_type_of(channel),
+ sender_id=str(user.id),
+ sender_name=username,
+ command=command_name,
+ args=args,
+ message_ref=f"{original.channel.id}:{original.id}",
+ root_id=root_id,
+ channel_name=channel_name,
+ )
+ )
+
+ @staticmethod
+ def _format_invocation(command: InRoomCommand, values: dict[str, Any]) -> str:
+ """Render the invocation for echoing back, in declared argument order."""
+ given = [
+ str(values[arg.name]).strip()
+ for arg in command.args_spec
+ if values.get(arg.name) is not None and str(values[arg.name]).strip()
+ ]
+ return f"/{command.name}" + (f" {' '.join(given)}" if given else "")
+
+ async def _reject_slash(
+ self, interaction: discord.Interaction, shown: str, reason: str
+ ) -> None:
+ """Refuse an invocation before dispatch, visibly to whoever ran it."""
+ try:
+ await interaction.response.send_message(
+ f"⚠️ Could not run `{shown}` — {reason}", ephemeral=True
+ )
+ except discord.HTTPException:
+ logger.exception("Failed to report bad arguments for %s", shown)
+
+ async def _report_slash_failure(
+ self, interaction: discord.Interaction, shown: str, error: Exception
+ ) -> None:
+ """Rewrite the posted "Running…" notice into a visible failure.
+
+ A slash command that appears to do nothing is worse than one that
+ errors; the ack has already gone out by this point, so there is always a
+ message sitting in the channel to turn into the error.
+ """
+ try:
+ await interaction.edit_original_response(
+ content=f"⚠️ Failed to run `{shown}`: {error}"
+ )
+ except discord.HTTPException:
+ logger.exception("Failed to report failure of %s back to Discord", shown)
+
# ── Attachments ──────────────────────────────────────────────────────────
async def _fetch_attachments(
diff --git a/core/switch_core/bridges/collaboration/discord/chunking.py b/core/switch_core/bridges/collaboration/discord/chunking.py
new file mode 100644
index 000000000..536a59f40
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/discord/chunking.py
@@ -0,0 +1,93 @@
+"""Split outbound text to fit Discord's per-message character limit.
+
+Discord caps a message at 2,000 characters and rejects anything longer with a
+400 — an order of magnitude tighter than Slack, Mattermost or Teams, and well
+under what an agent writes when it answers a real question. Without splitting,
+the adapter's `HTTPException` handler logs the rejection and returns, so the
+message never reaches the channel and the user is shown nothing at all.
+"""
+
+from __future__ import annotations
+
+MAX_MESSAGE = 2000
+
+_FENCE = "```"
+
+
+def _hard_wrap(line: str, budget: int) -> list[str]:
+ """Break one over-long line, preferring a space over cutting a word."""
+ if len(line) <= budget:
+ return [line]
+
+ pieces: list[str] = []
+ rest = line
+ while len(rest) > budget:
+ cut = rest.rfind(" ", 0, budget + 1)
+ if cut <= 0:
+ cut = budget
+ pieces.append(rest[:cut])
+ rest = rest[cut:].lstrip(" ")
+ if rest:
+ pieces.append(rest)
+ return pieces
+
+
+def chunk_message(content: str, limit: int = MAX_MESSAGE) -> list[str]:
+ """Split `content` into pieces that each fit `limit`.
+
+ Breaks on line boundaries where it can, and on a word where a single line
+ is itself too long, so the split lands somewhere the reader would have
+ paused anyway.
+
+ A split that lands inside a fenced code block closes the fence at the end
+ of one chunk and reopens it — with the same language — at the start of the
+ next. Agents post code constantly, and a fence torn in half renders the
+ whole remainder as unformatted text with a stray ``` in it.
+ """
+ if len(content) <= limit:
+ return [content]
+
+ # Leave room for a closing fence on this chunk and a reopening one on the
+ # next, so honouring a code block can never push a chunk over the limit.
+ budget = limit - (2 * len(_FENCE) + 2)
+
+ chunks: list[str] = []
+ buf: list[str] = []
+ used = 0
+ language: str | None = None
+
+ def flush() -> None:
+ nonlocal buf, used
+ if not buf:
+ return
+ body = "\n".join(buf)
+ if language is not None:
+ body += f"\n{_FENCE}"
+ chunks.append(body)
+ buf = []
+ used = 0
+ if language is not None:
+ opener = f"{_FENCE}{language}"
+ buf.append(opener)
+ used = len(opener) + 1
+
+ for raw_line in content.split("\n"):
+ for line in _hard_wrap(raw_line, budget):
+ if used + len(line) + 1 > budget and buf:
+ flush()
+ buf.append(line)
+ used += len(line) + 1
+
+ stripped = line.strip()
+ if stripped.startswith(_FENCE):
+ if language is None:
+ language = stripped[len(_FENCE) :].strip()
+ else:
+ language = None
+
+ if buf:
+ # The tail is emitted as-is: an unclosed fence here was unclosed in the
+ # original too, and inventing a terminator would change the content.
+ chunks.append("\n".join(buf))
+
+ return chunks
diff --git a/core/switch_core/bridges/collaboration/discord/slash.py b/core/switch_core/bridges/collaboration/discord/slash.py
new file mode 100644
index 000000000..c72411e77
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/discord/slash.py
@@ -0,0 +1,234 @@
+"""Native Discord application commands, built from the shared command registry.
+
+Discord registers commands with a declared signature: each argument is named,
+typed and marked required up front, unlike the free-text tail a typed
+`!command` carries. This module is the translation layer between the two.
+
+It does NOT implement any command. Every declared argument is turned straight
+back into the positional `@token` string that `bridges.agent.commands` already
+parses, so a slash invocation reaches the identical handler a typed `!command`
+reaches — one implementation, two entry points. The argument surface itself is
+declared once, in that registry's `Command.args_spec`, rather than restated
+here where it could drift from the handlers.
+"""
+
+from __future__ import annotations
+
+import inspect
+import logging
+import re
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+import discord
+from discord import app_commands
+
+from switch_core.bridges.agent.commands import COMMANDS, Command, CommandArg
+from switch_core.clients.mentions import NAME_CHAR
+
+logger = logging.getLogger(__name__)
+
+# Discord's hard caps on an application command's declared text.
+MAX_DESCRIPTION = 100
+
+# A declared argument is a mention token, with or without the `@` the user may
+# have typed out of habit. Anchored: a value with a space or a stray character
+# would silently lose part of itself once reassembled into the args string.
+_TOKEN = re.compile(rf"^@?({NAME_CHAR}+)$")
+
+# What Discord accepts as an option name.
+_OPTION_NAME = re.compile(r"^[-_a-z0-9]{1,32}$")
+
+SlashInvoke = Callable[[discord.Interaction, Command, dict[str, Any]], Awaitable[None]]
+"""(interaction, command, option_values) -> None.
+
+Handed the raw option values rather than a finished args string: reassembly can
+fail on input Discord itself considers valid (see `reassemble_args`), and the
+adapter is what owns replying to the user, so it does the conversion where it
+can turn a failure into a visible message.
+"""
+
+
+class SlashArgError(ValueError):
+ """A declared argument cannot be expressed as a positional `!command` arg.
+
+ Carries user-facing text: it is shown back in the channel rather than only
+ logged, so an invocation never appears to do nothing.
+ """
+
+
+def truncate_description(text: str, limit: int = MAX_DESCRIPTION) -> str:
+ """Fit a registry description into Discord's cap, breaking on a word.
+
+ Registry descriptions are written for `!help`, where they carry full usage
+ prose and run well past Discord's 100 characters. The full text stays
+ available there; this is only what the Discord command picker shows.
+ """
+ if len(text) <= limit:
+ return text
+ cut = text[: limit - 1]
+ space = cut.rfind(" ")
+ if space > limit // 2:
+ cut = cut[:space]
+ return cut.rstrip(" .,;:—-") + "…"
+
+
+def summarise_description(text: str) -> str:
+ """The part of a registry description worth showing in Discord's picker.
+
+ Registry descriptions are written for `!help`, so they end in a `Usage:`
+ clause spelling out the `!`-prefixed form and its arguments. Registering
+ that verbatim is worse than redundant: it tells someone who has just typed
+ `/reset` to type `!reset` instead, and Discord already renders the
+ arguments itself as named fields marked required or optional. What the
+ clause adds beyond that ("a target is required", "use `!reset-all-agents`
+ for everyone") is likewise already in the UI — as a required field, and as
+ the sibling `/reset-all-agents` in the same picker.
+
+ So only the leading summary is registered. The full text, `!` forms and
+ all, still shows in `!help`, which is where it is accurate.
+ """
+ summary = text.split("Usage:", 1)[0].strip()
+ return truncate_description(summary or text)
+
+
+def reassemble_args(spec: tuple[CommandArg, ...], values: dict[str, Any]) -> str:
+ """Turn declared, named option values back into a positional args string.
+
+ The handlers read their arguments by *position* out of the mention tokens in
+ `args`, so the declared values are re-emitted in `spec` order, each with
+ exactly one leading `@` — whether or not the user typed one.
+
+ Raises SlashArgError when a value is supplied after an earlier optional one
+ was left out. Discord submits options by name and happily allows that, but
+ the positional form cannot express it: the later value would slide into the
+ earlier one's slot and the command would do something plausible and wrong.
+ """
+ parts: list[str] = []
+ skipped: str | None = None
+
+ for arg in spec:
+ raw = values.get(arg.name)
+ if raw is None or not str(raw).strip():
+ if arg.required:
+ raise SlashArgError(f"`{arg.name}` is required.")
+ if skipped is None:
+ skipped = arg.name
+ continue
+
+ if skipped is not None:
+ raise SlashArgError(
+ f"`{arg.name}` can only be given together with `{skipped}` — "
+ f"the command reads its arguments in order, so `{skipped}` "
+ f"cannot be left out while `{arg.name}` is set."
+ )
+
+ token = str(raw).strip()
+ match = _TOKEN.match(token)
+ if match is None:
+ raise SlashArgError(
+ f"`{arg.name}` must be a single name (letters, digits, `.`, `-`, "
+ f"`_`), optionally written with a leading `@` — got `{token}`."
+ )
+ parts.append(f"@{match.group(1)}")
+
+ return " ".join(parts)
+
+
+def validate_args_spec(command: Command) -> None:
+ """Reject an `args_spec` that cannot be declared or cannot round-trip.
+
+ Both failures below would otherwise surface as a `ValueError` from deep
+ inside `inspect.Signature` or discord.py's option machinery, naming neither
+ the command nor the argument at fault, and would take the whole bridge's
+ startup with them.
+ """
+ seen_optional: str | None = None
+ for arg in command.args_spec:
+ if not _OPTION_NAME.match(arg.name):
+ raise ValueError(
+ f"Command '{command.name}' declares argument '{arg.name}', which "
+ "Discord cannot accept as an option name (lowercase letters, "
+ "digits, `-` and `_` only, at most 32 characters)."
+ )
+ if arg.required and seen_optional is not None:
+ raise ValueError(
+ f"Command '{command.name}' declares required argument "
+ f"'{arg.name}' after optional '{seen_optional}'. Arguments are "
+ "reassembled positionally, so an optional one can only be "
+ "followed by other optional ones."
+ )
+ if not arg.required:
+ seen_optional = arg.name
+
+
+def _make_callback(command: Command, invoke: SlashInvoke) -> Any:
+ """Build a callback whose signature declares `command`'s arguments.
+
+ discord.py derives a command's options from its callback signature, so the
+ signature has to carry the real argument names — they are what Discord
+ renders as field labels. A fresh closure is built per command so the
+ `describe` decorator below never mutates a shared function.
+ """
+
+ async def callback(interaction: discord.Interaction, **values: Any) -> None:
+ await invoke(interaction, command, values)
+
+ params = [
+ inspect.Parameter(
+ "interaction",
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ annotation=discord.Interaction,
+ )
+ ]
+ for arg in command.args_spec:
+ params.append(
+ inspect.Parameter(
+ arg.name,
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ annotation=str,
+ default=inspect.Parameter.empty if arg.required else None,
+ )
+ )
+ callback.__signature__ = inspect.Signature(params) # type: ignore[attr-defined]
+ callback.__annotations__ = {"interaction": discord.Interaction} | {
+ arg.name: str for arg in command.args_spec
+ }
+
+ if command.args_spec:
+ callback = app_commands.describe(
+ **{
+ arg.name: truncate_description(arg.description)
+ for arg in command.args_spec
+ }
+ )(callback)
+ return callback
+
+
+def build_app_commands(
+ invoke: SlashInvoke,
+) -> list[app_commands.Command[Any, ..., Any]]:
+ """Build one Discord application command per registered in-room command.
+
+ Hidden commands are skipped: they are absent from `!help` for a reason, and
+ Discord rejects the empty description they carry anyway.
+ """
+ built: list[app_commands.Command[Any, ..., Any]] = []
+ for command in COMMANDS:
+ if command.hidden:
+ continue
+ if not command.description:
+ logger.warning(
+ "Skipping Discord registration for '%s': no description to declare",
+ command.name,
+ )
+ continue
+ validate_args_spec(command)
+ built.append(
+ app_commands.Command(
+ name=command.name,
+ description=summarise_description(command.description),
+ callback=_make_callback(command, invoke),
+ )
+ )
+ return built
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 6ad45df86..2a0dd65ad 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -174,6 +174,11 @@ class SlackAdapter(CollaborationAdapter):
)
return None
+ def slash_invite_hint(self) -> str:
+ # Slack passes a slash command's whole tail through as free text, so the
+ # invocation reads exactly like the `!` form.
+ return "`/invite-agent @agent-name` — the Slack slash command"
+
async def admin_message(
self,
channel_id: str,
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py
index 733097c73..d7e9dbc38 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py
@@ -4,6 +4,10 @@ from types import SimpleNamespace
from typing import Any
from switch_core.bridges.collaboration.bridge_core import BridgeCore
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
# When the Switch app is invited to (or addressed in) a bridged channel that has
# no room yet, a room is auto-created even if no agent can be associated with it
@@ -13,11 +17,14 @@ from switch_core.bridges.collaboration.bridge_core import BridgeCore
# client's invite into the room.
-def _fake_bridge(*, agent_ids: list[str]): # noqa: ANN202
+def _fake_bridge(*, agent_ids: list[str], slash_hint: str | None = None): # noqa: ANN202
notices: list[tuple[str, str, str | None]] = []
room = SimpleNamespace(id="room-uuid", matrix_room_id="!m:switch.local")
class _Adapter:
+ def slash_invite_hint(self) -> str | None:
+ return slash_hint
+
async def admin_message(
self,
channel_id: str,
@@ -85,6 +92,57 @@ async def test_agentless_auto_create_posts_notice() -> None:
assert "!invite-agent" in content
+async def test_notice_carries_this_bridge_s_own_slash_syntax() -> None:
+ bridge = _fake_bridge(
+ agent_ids=[],
+ slash_hint="`/invite-agent agent:agent-name` — the Discord slash command",
+ )
+
+ await BridgeCore._create_room_for_channel(
+ bridge,
+ channel_id="C1",
+ channel_type="channel_public",
+ channel_name="general",
+ )
+
+ content = bridge.notices[0][1]
+ assert "• `/invite-agent agent:agent-name` — the Discord slash command." in content
+ # The typed form is still offered alongside it.
+ assert "• `!invite-agent @agent-name` — type it here in the channel, or" in content
+
+
+async def test_notice_omits_the_slash_form_where_there_is_none() -> None:
+ # Mattermost and Teams register no slash commands, so advertising one
+ # would point the user at something that does not exist.
+ bridge = _fake_bridge(agent_ids=[], slash_hint=None)
+
+ await BridgeCore._create_room_for_channel(
+ bridge,
+ channel_id="C1",
+ channel_type="channel_public",
+ channel_name="general",
+ )
+
+ content = bridge.notices[0][1]
+ assert "/invite-agent" not in content
+ # The remaining bullet closes the sentence rather than dangling on "or".
+ assert "• `!invite-agent @agent-name` — type it here in the channel." in content
+ assert ", or" not in content
+
+
+def test_each_adapter_advertises_a_syntax_it_actually_accepts() -> None:
+ discord_adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="t", guild_id="1")
+ )
+ hint = discord_adapter.slash_invite_hint()
+ # Discord names each argument, and the name has to be the one actually
+ # registered — `agent:`, not the command's own name.
+ assert hint is not None
+ assert "agent:agent-name" in hint
+ assert "Discord slash command" in hint
+ assert "@agent-name" not in hint
+
+
async def test_auto_create_with_agents_posts_no_notice() -> None:
bridge = _fake_bridge(agent_ids=["a1"])
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
index 1546c00e6..c9aa94550 100644
--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
import discord
import pytest
+from switch_core.bridges.agent.commands import COMMANDS
from switch_core.bridges.collaboration.discord import adapter as adapter_module
from switch_core.bridges.collaboration.discord.adapter import (
DiscordAdapter,
@@ -532,6 +533,67 @@ def test_send_message_posts_via_webhook_with_agent_identity() -> None:
assert ref == f"{CHANNEL_ID}:901"
+def test_long_message_is_split_across_posts_not_dropped() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+ body = "\n".join(f"line {i}" for i in range(1000))
+
+ ref = _run(adapter.send_message(str(CHANNEL_ID), "my-agent", body))
+
+ # Discord rejects anything over 2,000 characters outright, so before this
+ # the whole message was logged and thrown away.
+ assert len(webhook.sent) > 1
+ assert all(len(c["content"]) <= 2000 for c in webhook.sent)
+ assert "\n".join(c["content"] for c in webhook.sent) == body
+ # Every part keeps the agent's identity.
+ assert {c["username"] for c in webhook.sent} == {"my-agent"}
+ # The ref is the FIRST part: replies thread under where the message starts.
+ assert ref == f"{CHANNEL_ID}:901"
+
+
+def test_long_admin_message_is_split_across_posts() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ body = "\n".join(f"- `!cmd-{i}` — does a thing" for i in range(200))
+
+ ref = _run(adapter.admin_message(str(CHANNEL_ID), body))
+
+ assert len(channel.sent) > 1
+ assert all(len(c["content"]) <= 2000 for c in channel.sent)
+ assert "\n".join(c["content"] for c in channel.sent) == body
+ assert ref == f"{CHANNEL_ID}:501"
+
+
+def test_failed_part_leaves_a_visible_truncation_notice() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+ body = "\n".join(f"line {i}" for i in range(1000))
+
+ sends = {"n": 0}
+ original = webhook.send
+
+ async def flaky(**kwargs: Any) -> Any:
+ sends["n"] += 1
+ if sends["n"] == 2:
+ raise discord.HTTPException(_FakeResponse(), "too long")
+ return await original(**kwargs)
+
+ webhook.send = flaky # type: ignore[method-assign]
+ ref = _run(adapter.send_message(str(CHANNEL_ID), "my-agent", body))
+
+ # Part 1 landed, part 2 failed: the reader is told rather than left with a
+ # message that just stops.
+ assert "Only 1 of" in webhook.sent[-1]["content"]
+ assert ref == f"{CHANNEL_ID}:901"
+
+
def test_send_message_with_thread_root_posts_into_thread() -> None:
adapter = _adapter()
channel = _FakeChannel()
@@ -1004,6 +1066,29 @@ class _BotUser:
return f"bot#{self.id}"
+class _FakeConnectionState:
+ """The two client-state attributes ``discord.app_commands.CommandTree``
+ reads: it parks itself on ``_command_tree`` and consults ``_translator``
+ when rendering a command payload."""
+
+ def __init__(self) -> None:
+ self._command_tree: Any = None
+ self._translator: Any = None
+
+
+class _FakeCommandHTTP:
+ """Captures the guild-scoped slash-command sync ``start()`` performs."""
+
+ def __init__(self) -> None:
+ self.bulk_upserts: list[tuple[int, int, list[Any]]] = []
+
+ async def bulk_upsert_guild_commands(
+ self, application_id: int, guild_id: int, payload: list[Any]
+ ) -> list[Any]:
+ self.bulk_upserts.append((application_id, guild_id, payload))
+ return []
+
+
class _FakeGatewayClient:
"""Controllable stand-in for ``discord.Client`` used by ``start()``.
@@ -1018,6 +1103,11 @@ class _FakeGatewayClient:
self.logged_in = False
self.closed = False
self.registered_events: list[Any] = []
+ # start() builds an app-command tree on the client and syncs it to the
+ # guild, so the stand-in has to carry what CommandTree reaches for.
+ self.application_id = 555
+ self.http = _FakeCommandHTTP()
+ self._connection = _FakeConnectionState()
self.connect_behavior = "hang"
self.connect_exc: BaseException = RuntimeError("gateway boom")
self._ready_event = asyncio.Event()
@@ -1065,9 +1155,22 @@ def test_start_becomes_ready_then_stop_closes_client() -> None:
assert fake.registered_events # on_message handler registered
assert adapter._bot_user_id == BOT_USER_ID
+ # Slash commands are published to the configured GUILD, never
+ # globally: the adapter is single-guild by construction, guild
+ # commands apply immediately, and a global registration is
+ # per-application so it would leak into other bridges' guilds.
+ assert len(fake.http.bulk_upserts) == 1
+ application_id, guild_id, payload = fake.http.bulk_upserts[0]
+ assert application_id == fake.application_id
+ assert guild_id == GUILD_ID
+ assert {c["name"] for c in payload} == {
+ c.name for c in COMMANDS if not c.hidden and c.description
+ }
+
await adapter.stop()
assert fake.closed
assert adapter._client is None
+ assert adapter._tree is None
_run(scenario())
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_chunking.py b/core/tests/switch_core/bridges/collaboration/test_discord_chunking.py
new file mode 100644
index 000000000..e4af10d00
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_chunking.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+import pytest
+
+from switch_core.bridges.agent.commands import COMMANDS
+from switch_core.bridges.collaboration.discord.chunking import (
+ MAX_MESSAGE,
+ chunk_message,
+)
+
+
+def _rejoin(chunks: list[str]) -> str:
+ return "\n".join(chunks)
+
+
+def test_short_message_is_one_chunk_untouched() -> None:
+ assert chunk_message("hello") == ["hello"]
+
+
+def test_message_at_the_limit_is_not_split() -> None:
+ exact = "x" * MAX_MESSAGE
+ assert chunk_message(exact) == [exact]
+
+
+def test_every_chunk_fits_the_limit() -> None:
+ body = "\n".join(f"line {i} " + "y" * 60 for i in range(200))
+ chunks = chunk_message(body)
+ assert len(chunks) > 1
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+
+
+def test_nothing_is_lost_when_splitting_on_lines() -> None:
+ body = "\n".join(f"line {i}" for i in range(1000))
+ assert _rejoin(chunk_message(body)) == body
+
+
+def test_splits_prefer_line_boundaries() -> None:
+ body = "\n".join(f"line {i}" for i in range(1000))
+ for chunk in chunk_message(body):
+ # No chunk starts or ends mid-line.
+ assert chunk.startswith("line ")
+ assert chunk.splitlines()[-1].startswith("line ")
+
+
+def test_single_over_long_line_is_split_on_a_word() -> None:
+ body = " ".join(["word"] * 2000)
+ chunks = chunk_message(body)
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+ # Broken between words, never through one.
+ for chunk in chunks:
+ assert "wor\n" not in chunk
+ assert set(chunk.split()) == {"word"}
+
+
+def test_unbroken_run_with_no_spaces_is_hard_split() -> None:
+ body = "z" * 5000
+ chunks = chunk_message(body)
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+ assert "".join(chunks).replace("\n", "") == body
+
+
+def test_code_fence_is_closed_and_reopened_across_a_split() -> None:
+ body = "intro\n```python\n" + "\n".join(f"x = {i}" for i in range(400)) + "\n```"
+ chunks = chunk_message(body)
+
+ assert len(chunks) > 1
+ for chunk in chunks:
+ # A torn fence would render the rest of the message as plain text.
+ assert chunk.count("```") % 2 == 0, chunk[:80]
+ # The reopened fence keeps the language so highlighting survives.
+ assert chunks[1].startswith("```python")
+ assert chunks[0].endswith("```")
+
+
+def test_reopened_fence_still_respects_the_limit() -> None:
+ body = "```\n" + "\n".join("a" * 100 for _ in range(100)) + "\n```"
+ assert all(len(c) <= MAX_MESSAGE for c in chunk_message(body))
+
+
+def test_code_content_survives_the_fence_rewrite() -> None:
+ lines = [f"x = {i}" for i in range(400)]
+ body = "```python\n" + "\n".join(lines) + "\n```"
+ chunks = chunk_message(body)
+ # Every original code line still appears exactly once.
+ rendered = _rejoin(chunks)
+ for line in lines:
+ assert rendered.count(f"\n{line}\n") + rendered.count(f"\n{line}") >= 1
+
+
+def test_text_after_a_closed_fence_is_not_treated_as_code() -> None:
+ body = "```\nshort\n```\n" + "\n".join(f"prose line {i}" for i in range(400))
+ chunks = chunk_message(body)
+ # The fence closed before the prose, so no chunk should reopen one.
+ assert not chunks[-1].startswith("```")
+ assert all(c.count("```") % 2 == 0 for c in chunks)
+
+
[email protected]("size", [1, 100, 1999, 2000, 2001, 4001, 10000])
+def test_round_trips_at_a_range_of_sizes(size: int) -> None:
+ body = "\n".join("abcdefgh" for _ in range(size // 9 + 1))
+ chunks = chunk_message(body)
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+ assert _rejoin(chunks) == body
+
+
+def test_help_output_now_fits() -> None:
+ # The concrete regression: `!help` / `/help` renders every command and
+ # overshot Discord's cap, so the send was rejected and the user saw
+ # nothing at all.
+ lines = ["**Available commands:**"]
+ for command in COMMANDS:
+ if command.hidden:
+ continue
+ lines.append(f"- `!{command.name}` — {command.description}")
+ body = "\n".join(lines)
+
+ assert len(body) > MAX_MESSAGE
+ chunks = chunk_message(body)
+ assert len(chunks) == 2
+ assert all(len(c) <= MAX_MESSAGE for c in chunks)
+ assert _rejoin(chunks) == body
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py
new file mode 100644
index 000000000..214785d4b
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py
@@ -0,0 +1,452 @@
+from __future__ import annotations
+
+import asyncio
+import re
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.agent.commands import (
+ COMMANDS,
+ COMMANDS_BY_NAME,
+ Command,
+ CommandArg,
+)
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
+from switch_core.bridges.collaboration.discord.slash import (
+ MAX_DESCRIPTION,
+ SlashArgError,
+ build_app_commands,
+ reassemble_args,
+ summarise_description,
+ truncate_description,
+ validate_args_spec,
+)
+from switch_core.bridges.collaboration.models import InboundCommand
+
+GUILD_ID = 900
+CHANNEL_ID = 100
+BOT_USER_ID = 42
+
+
+def _adapter() -> DiscordAdapter:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ adapter._bot_user_id = BOT_USER_ID
+ return adapter
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeRole:
+ pass
+
+
+class _FakeGuild:
+ def __init__(self) -> None:
+ self.id = GUILD_ID
+ self.default_role = _FakeRole()
+
+
+class _FakeOverwrite:
+ def __init__(self, view_channel: bool | None) -> None:
+ self.view_channel = view_channel
+
+
+class _FakeChannel:
+ def __init__(
+ self,
+ channel_id: int = CHANNEL_ID,
+ *,
+ name: str | None = "general",
+ everyone_can_view: bool | None = True,
+ ) -> None:
+ self.id = channel_id
+ self.guild = _FakeGuild()
+ self.name = name
+ self._everyone_can_view = everyone_can_view
+
+ def overwrites_for(self, role: Any) -> _FakeOverwrite:
+ return _FakeOverwrite(self._everyone_can_view)
+
+
+class _FakeThread:
+ def __init__(self, parent: _FakeChannel, thread_id: int) -> None:
+ self.id = thread_id
+ self.parent = parent
+ self.parent_id = parent.id
+ self.guild = parent.guild
+ self.name = "a thread"
+
+
+class _FakeUser:
+ def __init__(self, user_id: int = 7, name: str = "doe.jane") -> None:
+ self.id = user_id
+ self.name = name
+
+
+class _FakeOriginalMessage:
+ def __init__(self, channel: Any, message_id: int) -> None:
+ self.channel = channel
+ self.id = message_id
+
+
+class _FakeInteractionResponse:
+ def __init__(self, interaction: _FakeInteraction) -> None:
+ self._interaction = interaction
+
+ async def send_message(self, content: str, *, ephemeral: bool = False) -> None:
+ self._interaction.responses.append({"content": content, "ephemeral": ephemeral})
+
+
+class _FakeInteraction:
+ """Enough of discord.Interaction for the slash path.
+
+ Records what was sent and when, so a test can assert the acknowledgement
+ goes out BEFORE any Switch work — the ~3s interaction deadline depends on
+ that ordering, not on how fast the dispatch happens to be.
+ """
+
+ def __init__(self, channel: Any, *, original_id: int = 999) -> None:
+ self.channel = channel
+ self.user = _FakeUser()
+ self.responses: list[dict[str, Any]] = []
+ self.edits: list[str] = []
+ self.response = _FakeInteractionResponse(self)
+ self._original_id = original_id
+
+ async def original_response(self) -> _FakeOriginalMessage:
+ return _FakeOriginalMessage(self.channel, self._original_id)
+
+ async def edit_original_response(self, *, content: str) -> None:
+ self.edits.append(content)
+
+
+def _capture_commands(adapter: DiscordAdapter) -> list[InboundCommand]:
+ captured: list[InboundCommand] = []
+
+ async def on_command(cmd: InboundCommand) -> None:
+ captured.append(cmd)
+
+ adapter._on_command = on_command
+ return captured
+
+
+def _invoke(
+ adapter: DiscordAdapter, interaction: Any, name: str, **values: Any
+) -> None:
+ _run(adapter._handle_slash_command(interaction, COMMANDS_BY_NAME[name], values))
+
+
+# ── Registration ─────────────────────────────────────────────────────────────
+
+
+async def _noop(interaction: Any, command: Any, values: Any) -> None:
+ return None
+
+
+def test_every_visible_registry_command_is_registered() -> None:
+ built = {c.name for c in build_app_commands(_noop)}
+ expected = {c.name for c in COMMANDS if not c.hidden and c.description}
+ # The registry is the single source of truth — a command added there must
+ # appear as a slash command without anyone editing a second list.
+ assert built == expected
+
+
+def test_registry_command_names_are_valid_discord_names() -> None:
+ # Discord command names share the option-name rules. A registry command
+ # that breaks them would only fail when a Discord bridge starts.
+ for command in COMMANDS:
+ if command.hidden:
+ continue
+ assert re.match(r"^[-_a-z0-9]{1,32}$", command.name), command.name
+
+
+def test_every_registry_args_spec_is_declarable() -> None:
+ # Guards the whole registry, not just the 7 commands that have arguments
+ # today: an 8th added with a bad name or a required-after-optional order
+ # fails here rather than inside discord.py at bridge startup.
+ for command in COMMANDS:
+ validate_args_spec(command)
+
+
+def test_bad_option_name_is_rejected_with_a_useful_message() -> None:
+ bad = Command("x", "d", args_spec=(CommandArg("Agent Name", "d", required=True),))
+ with pytest.raises(ValueError, match="Agent Name"):
+ validate_args_spec(bad)
+
+
+def test_required_after_optional_is_rejected() -> None:
+ # Reassembly is positional, so this ordering cannot round-trip.
+ bad = Command(
+ "x",
+ "d",
+ args_spec=(
+ CommandArg("first", "d", required=False),
+ CommandArg("second", "d", required=True),
+ ),
+ )
+ with pytest.raises(ValueError, match="second"):
+ validate_args_spec(bad)
+
+
+def test_hidden_command_is_not_registered() -> None:
+ # `admin` exists only to absorb Slack's manifest-declared `/admin`; it is
+ # hidden and carries an empty description, which Discord would reject.
+ assert COMMANDS_BY_NAME["admin"].hidden
+ assert "admin" not in {c.name for c in build_app_commands(_noop)}
+
+
+def test_registered_descriptions_fit_discord_cap() -> None:
+ for command in build_app_commands(_noop):
+ assert 1 <= len(command.description) <= MAX_DESCRIPTION, command.name
+ for param in command.parameters:
+ assert 1 <= len(param.description) <= MAX_DESCRIPTION, param.name
+
+
+def test_declared_options_match_the_registry_spec() -> None:
+ built = {c.name: c for c in build_app_commands(_noop)}
+ for command in COMMANDS:
+ if command.hidden or not command.description:
+ continue
+ params = built[command.name].parameters
+ assert [p.name for p in params] == [a.name for a in command.args_spec]
+ assert [p.required for p in params] == [a.required for a in command.args_spec]
+
+
+def test_long_description_truncated_on_word_boundary() -> None:
+ long = COMMANDS_BY_NAME["reset"].description
+ assert len(long) > MAX_DESCRIPTION
+ out = truncate_description(long)
+ assert len(out) <= MAX_DESCRIPTION
+ assert out.endswith("…")
+ # Cut at a word boundary, not mid-word.
+ assert not out[:-1].endswith(" ")
+ assert long.startswith(out[:-1].rstrip(" .,;:—-"))
+
+
+def test_short_description_left_alone() -> None:
+ assert truncate_description("Short one.") == "Short one."
+
+
+def test_registered_descriptions_never_teach_the_bang_form() -> None:
+ # These render in Discord's command picker. Registry descriptions are
+ # written for `!help` and end in a `Usage:` clause naming the `!` form —
+ # telling someone who just typed `/reset` to type `!reset` instead.
+ for command in build_app_commands(_noop):
+ assert "!" not in command.description, command.name
+ assert "Usage:" not in command.description, command.name
+
+
+def test_usage_clause_dropped_from_registered_description() -> None:
+ full = COMMANDS_BY_NAME["set-alias"].description
+ assert "Usage:" in full # the registry still carries it for `!help`
+ assert summarise_description(full) == "Give an agent a room alias."
+
+
+def test_summarise_falls_back_rather_than_registering_nothing() -> None:
+ # Discord rejects an empty description, so a pathological all-usage entry
+ # keeps its text instead of being silently registered blank.
+ assert summarise_description("Usage: `!x`") == "Usage: `!x`"
+
+
+# ── Argument reassembly ──────────────────────────────────────────────────────
+
+
+def test_declared_options_reassembled_into_positional_args() -> None:
+ spec = COMMANDS_BY_NAME["set-alias"].args_spec
+ # The handlers read positionally out of the args string, so declared,
+ # named options must come back out in spec order.
+ assert reassemble_args(spec, {"agent": "worker", "alias": "w"}) == "@worker @w"
+
+
+def test_at_prefix_is_optional_and_never_doubled() -> None:
+ spec = COMMANDS_BY_NAME["set-alias"].args_spec
+ expected = "@worker @w"
+ assert reassemble_args(spec, {"agent": "@worker", "alias": "@w"}) == expected
+ assert reassemble_args(spec, {"agent": "worker", "alias": "w"}) == expected
+ assert reassemble_args(spec, {"agent": " @worker ", "alias": "w "}) == expected
+
+
+def test_omitted_trailing_optional_is_dropped() -> None:
+ spec = COMMANDS_BY_NAME["run-cmd"].args_spec
+ assert reassemble_args(spec, {"agent": "worker", "role": None}) == "@worker"
+ assert reassemble_args(spec, {"agent": None, "role": None}) == ""
+
+
+def test_value_after_omitted_optional_is_rejected() -> None:
+ # Discord submits options by name and allows role-without-agent, but the
+ # positional form cannot express it: `@manager` would land in the agent
+ # slot and run-cmd would answer for the wrong target.
+ spec = COMMANDS_BY_NAME["run-cmd"].args_spec
+ with pytest.raises(SlashArgError) as excinfo:
+ reassemble_args(spec, {"agent": None, "role": "manager"})
+ assert "agent" in str(excinfo.value)
+
+
+def test_missing_required_value_is_rejected() -> None:
+ spec = COMMANDS_BY_NAME["set-alias"].args_spec
+ with pytest.raises(SlashArgError):
+ reassemble_args(spec, {"agent": "worker", "alias": ""})
+
+
[email protected]("bad", ["two words", "@a@b", "we!rd", ""])
+def test_non_token_value_is_rejected_not_silently_truncated(bad: str) -> None:
+ # A value with a space would lose everything after it once tokenised —
+ # silently running a different command than the user asked for.
+ spec = COMMANDS_BY_NAME["invite-agent"].args_spec
+ with pytest.raises(SlashArgError):
+ reassemble_args(spec, {"agent": bad})
+
+
+# ── Dispatch ─────────────────────────────────────────────────────────────────
+
+
+def test_slash_command_maps_to_in_room_command() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+ channel = _FakeChannel()
+ interaction = _FakeInteraction(channel)
+
+ _invoke(adapter, interaction, "reset", target="@worker")
+
+ assert len(commands) == 1
+ cmd = commands[0]
+ # The slash name IS the in-room command name, so it reaches the same
+ # dispatcher a typed `!reset @worker` reaches.
+ assert cmd.command == "reset"
+ assert cmd.args == "@worker"
+ assert cmd.channel_id == str(CHANNEL_ID)
+ assert cmd.channel_type == "channel_public"
+ assert cmd.sender_name == "doe.jane"
+ assert cmd.root_id is None
+ # A visible "Running …" message is posted and its ref routes the result
+ # into that message's thread.
+ assert len(interaction.responses) == 1
+ assert interaction.responses[0]["ephemeral"] is False
+ assert "/reset @worker" in interaction.responses[0]["content"]
+ assert cmd.message_ref == f"{CHANNEL_ID}:999"
+
+
+def test_slash_command_acknowledges_before_dispatching() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ interaction = _FakeInteraction(channel)
+ acked_first: list[bool] = []
+
+ async def on_command(cmd: InboundCommand) -> None:
+ acked_first.append(bool(interaction.responses))
+
+ adapter._on_command = on_command
+ _invoke(adapter, interaction, "list-agents")
+
+ # The ~3s interaction deadline is met by ordering, not by speed: nothing
+ # touching Switch may run before the acknowledgement.
+ assert acked_first == [True]
+
+
+def test_zero_argument_command_sends_empty_args() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+ _invoke(adapter, _FakeInteraction(_FakeChannel()), "list-agents")
+
+ assert commands[0].command == "list-agents"
+ assert commands[0].args == ""
+
+
+def test_declared_options_reach_dispatch_as_positional_args() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+
+ _invoke(
+ adapter,
+ _FakeInteraction(_FakeChannel()),
+ "set-alias",
+ agent="worker",
+ alias="w",
+ )
+
+ assert commands[0].command == "set-alias"
+ assert commands[0].args == "@worker @w"
+
+
+def test_slash_command_in_thread_bridges_into_parent_channel() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+ parent = _FakeChannel()
+ thread = _FakeThread(parent=parent, thread_id=3000)
+ interaction = _FakeInteraction(thread, original_id=3001)
+
+ _invoke(adapter, interaction, "invite-agent", agent="helper")
+
+ cmd = commands[0]
+ # Same shape as a typed command inside a thread: bridged into the parent
+ # channel's room, with the thread itself as the result's root.
+ assert cmd.channel_id == str(CHANNEL_ID)
+ assert cmd.root_id == f"{CHANNEL_ID}:3000"
+ assert cmd.message_ref == "3000:3001"
+
+
+def test_private_channel_type_resolved() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+ channel = _FakeChannel(everyone_can_view=False)
+
+ _invoke(adapter, _FakeInteraction(channel), "roles")
+
+ assert commands[0].channel_type == "channel_private"
+
+
+# ── Failure is always visible ────────────────────────────────────────────────
+
+
+def test_bad_arguments_rejected_ephemerally_without_dispatch() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+ interaction = _FakeInteraction(_FakeChannel())
+
+ _invoke(adapter, interaction, "run-cmd", agent=None, role="manager")
+
+ # Refused before anything is dispatched, and privately: it is the
+ # invoker's typo, not something the whole channel needs to watch fail.
+ assert commands == []
+ assert len(interaction.responses) == 1
+ assert interaction.responses[0]["ephemeral"] is True
+ assert "Could not run" in interaction.responses[0]["content"]
+ assert interaction.edits == []
+
+
+def test_dispatch_failure_rewrites_running_message_visibly() -> None:
+ adapter = _adapter()
+ interaction = _FakeInteraction(_FakeChannel())
+
+ async def on_command(cmd: InboundCommand) -> None:
+ raise RuntimeError("matrix room is gone")
+
+ adapter._on_command = on_command
+ _invoke(adapter, interaction, "reset", target="worker")
+
+ # A slash command that appears to do nothing is worse than one that errors.
+ assert len(interaction.edits) == 1
+ assert "Failed to run" in interaction.edits[0]
+ assert "matrix room is gone" in interaction.edits[0]
+
+
+def test_dispatch_failure_when_adapter_not_started_is_reported() -> None:
+ adapter = _adapter()
+ interaction = _FakeInteraction(_FakeChannel())
+ # _on_command is None until start() runs — must surface, not pass silently.
+ _invoke(adapter, interaction, "list-agents")
+
+ assert len(interaction.edits) == 1
+ assert "Failed to run" in interaction.edits[0]
diff --git a/docs/bridges/DISCORD_SETUP.md b/docs/bridges/DISCORD_SETUP.md
index 84db30fa7..a346ccb3e 100644
--- a/docs/bridges/DISCORD_SETUP.md
+++ b/docs/bridges/DISCORD_SETUP.md
@@ -39,7 +39,11 @@ single-workspace deployment does not.)
Build an OAuth2 invite URL (Developer Portal → **OAuth2 → URL Generator**):
-- **Scopes:** `bot`.
+- **Scopes:** `bot` **and `applications.commands`**. The second one lets the
+ bridge register Switch's in-room commands as native slash commands (see
+ [Slash commands](#slash-commands)). Without it the bridge still runs, but the
+ slash sync fails at startup — logged, not fatal — and only `!`-prefixed
+ commands work.
- **Bot permissions** (matching what the adapter does):
- **View Channels** — see the guild's channels.
- **Send Messages** + **Send Messages in Threads** — post agent replies.
@@ -73,6 +77,38 @@ On success the bridge opens its Gateway WebSocket to that guild. Post in a
channel the bot can see (or have an agent post) and the Switch room is created on
the first bridged message.
+## Slash commands
+
+Switch's in-room commands are also registered as native Discord slash commands,
+so `/reset @agent` does exactly what typing `!reset @agent` does — same
+handler, same result. Nothing to configure beyond the `applications.commands`
+scope above: the set is published from the command registry when the bridge
+starts, and re-published on every start, so renames and removals reconcile
+themselves.
+
+Two things behave differently from a typed `!command`, both from Discord:
+
+- **Arguments are declared fields, not free text.** Discord shows named inputs
+ (`/set-alias agent: … alias: …`) and will not submit until the required ones
+ are filled. The `@` is optional — `worker` and `@worker` are equivalent. An
+ argument that is not a single name is rejected rather than silently truncated
+ at the first space.
+- **The result arrives in a thread.** A slash invocation is invisible to the
+ channel, so the bridge posts a short `⚙️ Running …` message and files the
+ command's result in that message's thread. If a command fails, that message is
+ rewritten into the error — a slash command never silently does nothing.
+
+Commands are registered **per guild**, not globally: each bridge is scoped to one
+guild, guild-scoped commands apply immediately (global registration propagates
+for up to an hour), and because global commands are per-*application* they would
+otherwise appear in every guild the bot has joined, including ones with no Switch
+rooms.
+
+If the slash commands do not appear, check the bridge's startup logs for a sync
+failure — the usual cause is a bot invited before `applications.commands` was
+added to its OAuth2 scopes. Re-inviting with the corrected URL and restarting the
+bridge fixes it.
+
## Clickable "Open in Switch Console" links (`GATEWAY_PUBLIC_URL`)
Discord only linkifies `http(s)`, so a raw `switchdash://session?…` deeplink
@@ -88,7 +124,7 @@ GATEWAY_PUBLIC_URL=https://switch-api.acme.com
When set, Switch rewrites the deeplink to a clickable
`https://<switch-api-host>/deeplink/session?…` redirect (a `302` back to the
`switchdash://` scheme) at runtime-state ingestion — so both the bridged
-working/awaiting-input status message **and** the `!status` command surface a
+working/awaiting-input status message **and** the `!agents-status` command surface a
clickable link, on every platform at once. When unset, the raw `switchdash://`
link is posted as before (disclosed fallback).
diff --git a/docs/bridges/README.md b/docs/bridges/README.md
index 3aa431fbd..e895d9c57 100644
--- a/docs/bridges/README.md
+++ b/docs/bridges/README.md
@@ -47,8 +47,11 @@ the live set and the fields each one requires.
first bridged message (Discord — it has no "app added to channel" signal).
Existing Switch rooms can also be bound to a channel at room-creation time.
- **Addressing agents.** Users `@mention` an agent by name in the channel to
- address it; unaddressed chatter is bridged as context. Bridge in-room commands
- (e.g. `!invite-agent`) and slash commands work per platform.
+ address it; unaddressed chatter is bridged as context. In-room commands (e.g.
+ `!invite-agent`) work on every platform. Slack and Discord additionally expose
+ them as **native slash commands** (`/invite-agent`) routed into the same
+ handler — declared in the app manifest on Slack, registered automatically per
+ guild on Discord.
- **"Open in Switch Console" links.** Agents surface a `switchdash://…` deeplink with
their runtime status. Platforms that only linkify `http(s)` (notably Discord)
need `GATEWAY_PUBLIC_URL` set so Switch can rewrite it to a clickable