Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions docs/howto-discord-approval-notify.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# How to: Discord Approval Notification (Mention User)

## Problem
When Hermes needs user approval for dangerous commands, clarify questions, or slash command confirmations on Discord — it sends the prompt into a thread silently. The user doesn't get notified and may miss the request entirely.

## Solution
Hermes now automatically mentions (`<@USER_ID>`) the user in all approval/clarify prompts sent via Discord. This triggers a Discord notification so you see the request immediately.

## What Gets Mentioned

| Feature | Trigger | Notification |
|---------|---------|--------------|
| **Exec Approval** | Dangerous command execution | ✅ Yes — `<@USER_ID>` prepended to embed |
| **Slash Confirm** | Expensive slash commands (`/browser`, `/terminal`, etc.) | ✅ Yes — `<@USER_ID>` prepended to embed |
| **Clarify Prompt** | Agent needs clarification (multi-choice or open-ended) | ✅ Yes — `<@USER_ID>` prepended to embed |
| **Update Prompt** | `hermes update --gateway` needs input | ✅ Yes — `<@USER_ID>` prepended to embed |

## How It Works

### Architecture
```
Agent Thread → Gateway (run.py) → Discord Adapter (adapter.py) → Discord API
↓ ↓ ↓
approval/ Build <@user_id> Prepend mention to
clarify for Discord embed description
callback only with ping
```

### Code Flow

**1. Gateway (`gateway/run.py`)** — Detects platform and builds user mention:
```python
# In _approval_notify_sync(), _clarify_callback_sync(), _request_slash_confirm()
_user_mention = None
if source.platform.value == "discord" and source.user_id:
_user_mention = f"<@{source.user_id}>"
```

**2. Discord Adapter (`plugins/platforms/discord/adapter.py`)** — Prepends mention to embed:
```python
# In send_exec_approval(), send_slash_confirm(), send_clarify(), send_update_prompt()
if user_mention:
body = f"{user_mention}\n\n{body}" # Prepend for notification ping
```

### What the User Sees
When a prompt is sent, the embed description looks like:
```
<@123456789012345678>

⚠️ Command Approval Required
[command details...]
```

The `<@...>` syntax triggers Discord's native notification ping.

## Platform Scope

This feature is **Discord-only**. Other platforms (Telegram, Slack, etc.) are unaffected because the mention logic checks `source.platform.value == "discord"` before building the user mention.

## No Configuration Needed

This is a code-level fix — no config changes required. It works automatically for all Discord users once the gateway is restarted after applying these changes.

## Files Changed

| File | Changes |
|------|---------|
| `gateway/run.py` | Added `_user_mention` building in 3 callback functions |
| `plugins/platforms/discord/adapter.py` | Added `user_mention` parameter to 4 send methods |

## Restart Required

After applying these changes, restart the gateway:
```bash
launchctl kickstart gui/$(id -u)/ai.hermes.gateway
```

Or use:
```bash
hermes gateway restart
```

---

*Created for Hermes Agent community sharing.*
23 changes: 22 additions & 1 deletion gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10698,6 +10698,11 @@ async def _request_slash_confirm(
adapter = self.adapters.get(source.platform)
metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))

# Build user mention for platforms that support it (Discord).
_user_mention = None
if source.platform.value == "discord" and source.user_id:
_user_mention = f"<@{source.user_id}>"

used_buttons = False
if adapter is not None:
try:
Expand All @@ -10708,6 +10713,7 @@ async def _request_slash_confirm(
session_key=session_key,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This call is generic: non-Discord adapters are invoked too, but their shared send_slash_confirm contract has no user_mention keyword (gateway/platforms/base.py:3076-3084). Passing it even as None can raise TypeError and discard the native-button path. Scope this argument to Discord or extend the contract consistently.

confirm_id=confirm_id,
metadata=metadata,
user_mention=_user_mention,
)
if button_result and getattr(button_result, "success", False):
used_buttons = True
Expand Down Expand Up @@ -13966,6 +13972,11 @@ def _clarify_callback_sync(question: str, choices) -> str:
except Exception:
pass

# Build user mention for platforms that support it (Discord).
_user_mention = None
if source.platform.value == "discord" and source.user_id:
_user_mention = f"<@{source.user_id}>"

send_ok = False
fut = safe_schedule_threadsafe(
_status_adapter.send_clarify(
Expand All @@ -13975,6 +13986,7 @@ def _clarify_callback_sync(question: str, choices) -> str:
clarify_id=clarify_id,
session_key=session_key or "",
metadata=_status_thread_metadata,
user_mention=_user_mention,
),
_loop_for_step,
logger=logger,
Expand Down Expand Up @@ -14081,6 +14093,13 @@ def _approval_notify_sync(approval_data: dict) -> None:
cmd = approval_data.get("command", "")
desc = approval_data.get("description", "dangerous command")

# Build user mention for platforms that support it (Discord).
# This ensures the user gets a notification ping when an
# approval prompt is sent, rather than silently waiting in a thread.
_user_mention = None
if source.platform.value == "discord" and source.user_id:
_user_mention = f"<@{source.user_id}>"

# Prefer button-based approval when the adapter supports it.
# Check the *class* for the method, not the instance — avoids
# false positives from MagicMock auto-attribute creation in tests.
Expand All @@ -14093,6 +14112,7 @@ def _approval_notify_sync(approval_data: dict) -> None:
session_key=_approval_session_key,
description=desc,
metadata=_status_thread_metadata,
user_mention=_user_mention,
),
_loop_for_step,
logger=logger,
Expand All @@ -14118,11 +14138,12 @@ def _approval_notify_sync(approval_data: dict) -> None:
# Slack threads and reserved by Matrix clients.
_p = getattr(_status_adapter, "typed_command_prefix", "/")
cmd_preview = cmd[:200] + "..." if len(cmd) > 200 else cmd
mention_text = f"{_user_mention} " if _user_mention else ""
msg = (
f"⚠️ **Dangerous command requires approval:**\n"
f"```\n{cmd_preview}\n```\n"
f"Reason: {desc}\n\n"
f"Reply `{_p}approve` to execute, `{_p}approve session` to approve this pattern "
f"{mention_text}Reply `{_p}approve` to execute, `{_p}approve session` to approve this pattern "
f"for the session, `{_p}approve always` to approve permanently, or `{_p}deny` to cancel."
)
try:
Expand Down
34 changes: 31 additions & 3 deletions plugins/platforms/discord/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4302,12 +4302,16 @@ async def send_exec_approval(
self, chat_id: str, command: str, session_key: str,
description: str = "dangerous command",
metadata: Optional[dict] = None,
user_mention: Optional[str] = None,
) -> SendResult:
"""
Send a button-based exec approval prompt for a dangerous command.

The buttons call ``resolve_gateway_approval()`` to unblock the waiting
agent thread — this replaces the text-based ``/approve`` flow on Discord.

If ``user_mention`` is provided (e.g. ``<@123456789>``), it's prepended
to the embed description so the user gets a Discord notification ping.
"""
if not self._client or not DISCORD_AVAILABLE:
return SendResult(success=False, error="Not connected")
Expand All @@ -4325,9 +4329,13 @@ async def send_exec_approval(
# Discord embed description limit is 4096; show full command up to that
max_desc = 4088
cmd_display = command if len(command) <= max_desc else command[: max_desc - 3] + "..."
desc_text = f"```\\n{cmd_display}\\n```"
# Prepend user mention for notification ping
if user_mention:
desc_text = f"{user_mention}\\n\\n{desc_text}"
embed = discord.Embed(
title="⚠️ Command Approval Required",
description=f"```\n{cmd_display}\n```",
description=desc_text,
color=discord.Color.orange(),
)
embed.add_field(name="Reason", value=description, inline=False)
Expand All @@ -4348,8 +4356,13 @@ async def send_exec_approval(
async def send_slash_confirm(
self, chat_id: str, title: str, message: str, session_key: str,
confirm_id: str, metadata: Optional[dict] = None,
user_mention: Optional[str] = None,
) -> SendResult:
"""Send a three-button slash-command confirmation prompt."""
"""Send a three-button slash-command confirmation prompt.

If ``user_mention`` is provided (e.g. ``<@123456789>``), it's prepended
to the embed description so the user gets a Discord notification ping.
"""
if not self._client or not DISCORD_AVAILABLE:
return SendResult(success=False, error="Not connected")

Expand All @@ -4365,6 +4378,8 @@ async def send_slash_confirm(
# Embed description limit is 4096; message usually fits easily.
max_desc = 4088
body = message if len(message) <= max_desc else message[: max_desc - 3] + "..."
if user_mention:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current main sends interactive-prompt payloads in ordinary content as well as embeds, and its existing exec-approval mention path prepends the mention to that content with scoped AllowedMentions. Put the notification marker in the content mirror rather than only this embed description.

body = f"{user_mention}\\n\\n{body}"
embed = discord.Embed(
title=title or "Confirm",
description=body,
Expand Down Expand Up @@ -4392,6 +4407,7 @@ async def send_clarify(
clarify_id: str,
session_key: str,
metadata: Optional[Dict[str, Any]] = None,
user_mention: Optional[str] = None,
) -> SendResult:
"""Render a clarify prompt with one Discord button per choice.

Expand All @@ -4404,6 +4420,9 @@ async def send_clarify(
Open-ended mode (``choices`` empty/None): renders the question as
plain embed text — no buttons. The gateway's text-intercept captures
the next message in this session and resolves the clarify.

If ``user_mention`` is provided (e.g. ``<@123456789>``), it's prepended
to the embed description so the user gets a Discord notification ping.
"""
if not self._client or not DISCORD_AVAILABLE:
return SendResult(success=False, error="Not connected")
Expand All @@ -4422,6 +4441,8 @@ async def send_clarify(
body = str(question or "").strip()
if len(body) > max_desc:
body = body[: max_desc - 3] + "..."
if user_mention:
body = f"{user_mention}\\n\\n{body}"

embed = discord.Embed(
title="❓ Hermes needs your input",
Expand Down Expand Up @@ -4468,11 +4489,15 @@ async def send_update_prompt(
self, chat_id: str, prompt: str, default: str = "",
session_key: str = "",
metadata: Optional[Dict[str, Any]] = None,
user_mention: Optional[str] = None,
) -> SendResult:
"""Send an interactive button-based update prompt (Yes / No).

Used by the gateway ``/update`` watcher when ``hermes update --gateway``
needs user input (stash restore, config migration).

If ``user_mention`` is provided (e.g. ``<@123456789>``), it's prepended
to the embed description so the user gets a Discord notification ping.
"""
if not self._client or not DISCORD_AVAILABLE:
return SendResult(success=False, error="Not connected")
Expand All @@ -4483,9 +4508,12 @@ async def send_update_prompt(
channel = await self._client.fetch_channel(int(target_id))

default_hint = f" (default: {default})" if default else ""
desc_text = f"{prompt}{default_hint}"
if user_mention:
desc_text = f"{user_mention}\\n\\n{desc_text}"
embed = discord.Embed(
title="⚕ Update Needs Your Input",
description=f"{prompt}{default_hint}",
description=desc_text,
color=discord.Color.gold(),
)
view = UpdatePromptView(
Expand Down