From efe87f7f341fca4d6048455ca977d6a6bcd9987f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 05:11:00 +0000 Subject: [PATCH 1/3] feat(actions): react, list server emoji, and post embeds in the current channel Three tools join Hermes' own `discord` toolset: - discord_list_emojis: this server's usable custom emoji with ready usage strings - discord_react: any Unicode emoji, or this server's emoji, on the message being answered or another message in the same channel - discord_send_embed: one embed card in this channel, held to Discord's embed limits, mentions suppressed The channel, server and triggering message come from the Hermes session (HERMES_SESSION_*), never from model arguments. Actions refuse on other platforms and in cron runs, keep custom emoji to the current server, and spend from a per-message budget (5 reactions, 2 embeds). Joining the core `discord` toolset (not `messaging`, not a new plugin toolset) means only profiles whose config names that toolset see them; Hermes turns unseen plugin toolsets on by default. Tests cover the pure pieces directly, the impls against an in-memory client, embeds round-tripped through discord.py's Embed, and, with HERMES_AGENT_PATH set, Hermes' real set_session_vars, registry and toolsets. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 27 +- README.md | 44 ++- __init__.py | 9 +- actions.py | 638 ++++++++++++++++++++++++++++++ plugin.yaml | 16 +- pyproject.toml | 6 +- schemas.py | 21 + tests/test_actions.py | 608 ++++++++++++++++++++++++++++ tests/test_hermes_contract.py | 26 +- tests/test_plugin_registration.py | 22 +- uv.lock | 2 +- 11 files changed, 1379 insertions(+), 40 deletions(-) create mode 100644 actions.py create mode 100644 tests/test_actions.py diff --git a/AGENTS.md b/AGENTS.md index de56112..b7f84f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,17 @@ # hermes-plugin-discord-tools -Read-only Discord inspection tools for Hermes Discord-facing agents. +Discord reading tools, plus three channel-scoped actions, for Hermes +Discord-facing agents. ## Current surface - `discord_read_channel`, `discord_read_thread`, `discord_get_message`, and - `discord_read_story` are the only tools. They return JSON and must only read - Discord content the configured bot token can already access. + `discord_read_story` (toolset `messaging`) return JSON and only read Discord + content the configured bot token can already access. +- `discord_list_emojis`, `discord_react`, and `discord_send_embed` (toolset + `discord`, in `actions.py`) are the only write paths. They act only in the + channel the bot is replying in, taken from the Hermes session + (`HERMES_SESSION_*`), never from model arguments. - `discord_read_story` reads preconfigured story threads from `DISCORD_TOOLS_STORY_THREADS_JSON` or `DISCORD_TOOLS_STORY_THREAD_ID`; keep that configuration static and env/file backed. @@ -15,8 +20,16 @@ Read-only Discord inspection tools for Hermes Discord-facing agents. ## Guardrails -- This plugin must stay read-only. Do not add send, edit, delete, react, pin, - retain, or memory-write behavior here. +- The read tools stay read-only. The three actions in `actions.py` are the + whole write surface: no edit, delete, pin, role, member, retain, or + memory-write behavior, and no action that takes its channel from a model + argument. +- Actions register into Hermes' own `discord` toolset, never `messaging` or a + new plugin toolset: Hermes turns unseen plugin toolsets on by default, while + `discord` is on only where a profile's config names it. +- Every action refuses outside a live Discord turn (other platforms, cron runs), + holds custom emoji to the current server's palette, sends embeds with no + mentions, and spends from a per-message budget (`schemas.TURN_BUDGET`). - Reuse the profile's existing `DISCORD_BOT_TOKEN` (the token the Hermes gateway loads); do not introduce a second token. `DISCORD_TOKEN` is an optional standalone fallback alias only. @@ -37,6 +50,10 @@ make install make test ``` +Run the real-Hermes layer too when a Hermes checkout is at hand: +`HERMES_AGENT_PATH= make test`. It binds sessions with Hermes' own +`set_session_vars` and registers into its real registry and toolsets. + The tests include a Hermes contract check against the real `PluginContext.register_tool` / `register_hook` signatures when a local Hermes checkout is available. Registration tests also reject direct lifecycle wiring diff --git a/README.md b/README.md index dd26f39..ac80bfa 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # hermes-plugin-discord-tools -Read-only Discord tools for Hermes Discord-facing agents. +Discord tools for Hermes Discord-facing agents: reads, plus three small +actions held to the channel the bot is replying in. The plugin lets a bot use its existing Discord bot token to read a channel, thread, or linked message that the bot can already access. It is intended as a @@ -21,8 +22,35 @@ truth before answering. thread ID comes from env config, so the agent never has to supply a snowflake it does not have. See `DISCORD_TOOLS_STORY_THREADS_JSON` below. -All tools return JSON with a `success` flag. They never write to Discord or to -memory. Each tool's required argument name is repeated in its description (not +These four never write to Discord or to memory. + +### Channel-scoped actions + +- `discord_list_emojis`: this server's own custom emoji the bot can use, each + with a ready `usage` string (`<:name:id>`). Optional `query`, `limit`. +- `discord_react`: react with one emoji (`emoji`), any standard emoji or one of + this server's as `:name:` or `<:name:id>`. Reacts to the message being + answered, or to `message_id` when that message is in this same channel. +- `discord_send_embed`: post one embed card (`title` and/or `description`, + optional `url`, `color`, `fields`, `footer`, `image_url`, `thumbnail_url`) in + this channel, held to Discord's embed limits, with mentions suppressed. + +The channel, server and triggering message come from the Hermes session the +gateway binds for the turn, never from model arguments, so a model cannot aim +one of these at another channel. They refuse on other platforms and in +scheduled runs. Custom emoji from other servers are refused. One incoming +message can cause at most 5 reactions and 2 embeds. + +They join Hermes' own `discord` toolset, so a profile gets them only where its +config turns that toolset on for Discord (`platform_toolsets.discord`), the same +switch as Hermes' built-in Discord tool. + +Bot permissions they need in the channel: **Add Reactions** and **Read Message +History** (react), **Send Messages** and **Embed Links** (embeds). Listing +emoji needs none beyond being in the server. Use External Emojis is not needed, +since only the server's own emoji are allowed. + +All tools return JSON with a `success` flag. Each tool's required argument name is repeated in its description (not only the JSON schema) so the agent can call it correctly even when a runtime surfaces the schema's `properties` as empty. @@ -31,7 +59,7 @@ surfaces the schema's `properties` as empty. The plugin logs under the `discord-tools` logger. On a rejected argument it logs a `WARNING` with the offending value (truncated, never the token), and on a successful read an `INFO` line with the resolved target. At startup, -`hermes-plugin-kit` emits one lifecycle receipt listing the four tools and +`hermes-plugin-kit` emits one lifecycle receipt listing the seven tools and `pre_llm_call` hook that it registered. To watch it in a pod: ```bash @@ -62,10 +90,11 @@ it is a filesystem path, the hook reads that local JSON file. ## Environment - `DISCORD_BOT_TOKEN`: the bot token the Hermes gateway already loads β€” reused - for live Discord reads. `DISCORD_TOKEN` is accepted as a fallback alias for + for live Discord reads and the channel-scoped actions. `DISCORD_TOKEN` is accepted as a fallback alias for standalone use. -- `DISCORD_TOOLS_ALLOWED_GUILDS`: optional comma-separated guild allowlist. If - unset, Discord access is bounded only by the bot token's existing visibility. +- `DISCORD_TOOLS_ALLOWED_GUILDS`: optional comma-separated guild allowlist for + reads and actions. If unset, Discord access is bounded only by the bot + token's existing visibility. - `DISCORD_TOOLS_MAX_MESSAGES`: optional default/max message limit, default 100. - `DISCORD_TOOLS_MAX_CHARS`: optional result character budget, default 12000. - `DISCORD_TOOLS_TIMEOUT_SECONDS`: optional live API timeout, default 20. @@ -91,4 +120,5 @@ registration inventory under one contract. ```bash make install make test +HERMES_AGENT_PATH= make test # adds the real-Hermes layer ``` diff --git a/__init__.py b/__init__.py index fbb8cd3..91ec647 100644 --- a/__init__.py +++ b/__init__.py @@ -1,4 +1,4 @@ -"""discord-tools - read-only Discord inspection for Hermes agents.""" +"""discord-tools - Discord reads plus three channel-scoped actions for Hermes agents.""" from __future__ import annotations @@ -6,7 +6,7 @@ from hermes_plugin_kit import RegistrationSummary, register_plugin -from . import hooks, tools +from . import actions, hooks, tools logger = logging.getLogger("discord-tools") @@ -15,12 +15,15 @@ tools.discord_read_thread, tools.discord_get_message, tools.discord_read_story, + actions.discord_list_emojis, + actions.discord_react, + actions.discord_send_embed, hooks.inject_discord_read_hint, ) def register(ctx) -> RegistrationSummary: - """Register read-only Discord tools and hint hook with Hermes.""" + """Register the Discord read tools, the channel-scoped actions and the hint hook.""" return register_plugin( ctx, _DECLARATIONS, diff --git a/actions.py b/actions.py new file mode 100644 index 0000000..413665c --- /dev/null +++ b/actions.py @@ -0,0 +1,638 @@ +"""Channel-scoped Discord actions: react, list this server's emoji, send an embed. + +Every action works only where the bot is talking right now. The channel, server +and triggering message come from the Hermes session (``HERMES_SESSION_*``, which +the gateway binds per turn), never from model arguments, so a model cannot aim +a reaction or an embed at another channel. These tools join Hermes' own +``discord`` toolset, so a profile gets them only where its config already turns +that toolset on. + +The pure pieces (``current_scope``, ``parse_emoji``, ``resolve_emoji``, +``build_embed``, ``TurnBudget``) do no I/O. Live Discord calls are isolated in +``DiscordLiveActions``. +""" + +from __future__ import annotations + +import os +import re +import threading +import unicodedata +from collections import Counter, OrderedDict +from dataclasses import dataclass +from typing import Any, Callable, Mapping, Protocol +from urllib.parse import urlparse + +from hermes_plugin_kit import arg, int_arg, str_arg, tool + +from . import schemas +from .tools import ( + SNOWFLAKE_RE, + DiscordLiveFetcher, + _allowed_guilds, + _clamp, + _err, + _guard_guild, + _ok, + _parse_message_ref, + _run_async, + logger, +) + +Lookup = Callable[[str], str] + +EMOJI_NAME = r"[A-Za-z0-9_]{2,32}" +CUSTOM_TAG_RE = re.compile(rf"^<(?Pa)?:(?P{EMOJI_NAME}):(?P\d{{15,25}})>$") +NAME_ID_RE = re.compile(rf"^(?P{EMOJI_NAME}):(?P\d{{15,25}})$") +COLON_NAME_RE = re.compile(rf"^:(?P{EMOJI_NAME}):$") +BARE_NAME_RE = re.compile(rf"^(?P{EMOJI_NAME})$") +HEX_COLOUR_RE = re.compile(r"^#?([0-9A-Fa-f]{6})$") +# Longest Unicode emoji sequences (families, flags with modifiers) stay under this. +MAX_UNICODE_EMOJI_CODEPOINTS = 10 +CRON_TRUE = {"1", "true", "yes", "on"} + + +class Refusal(str): + """A reason an action will not run. A ``str`` so it drops into ``_err``.""" + + +class MessageNotFound(Exception): + def __init__(self, channel_id: str, message_id: str) -> None: + super().__init__(f"message {message_id} not in channel {channel_id}") + self.channel_id = channel_id + self.message_id = message_id + + +@dataclass(frozen=True) +class ChannelScope: + guild_id: str | None + channel_id: str + message_id: str | None + parent_channel_id: str | None + + +@dataclass(frozen=True) +class EmojiRef: + unicode: str | None = None + name: str | None = None + id: str | None = None + + +class ActionClient(Protocol): + def list_emojis(self, guild_id: str) -> list[dict[str, Any]]: + ... + + def add_reaction(self, channel_id: str, message_id: str, emoji: str) -> None: + """Raise ``MessageNotFound`` when the message is not in that channel.""" + ... + + def send_embed(self, channel_id: str, embed: dict[str, Any]) -> str: + """Send one embed; return the new message id.""" + ... + + +# -- session scope ----------------------------------------------------------- + + +def session_lookup(environ: Mapping[str, str] | None = None) -> Lookup: + """Read session vars the way Hermes tools do. + + With an explicit mapping, read that. Otherwise use Hermes' + ``get_session_env`` (task-local ContextVars, falling back to the process + env), or the process env when running outside Hermes. + """ + if environ is not None: + return lambda name: str(environ.get(name, "") or "") + try: + from gateway.session_context import get_session_env + except ImportError: + return lambda name: os.environ.get(name, "") + return lambda name: get_session_env(name, "") + + +def _snowflake(value: str) -> str | None: + text = (value or "").strip() + return text if SNOWFLAKE_RE.match(text) else None + + +def current_scope(lookup: Lookup) -> ChannelScope | Refusal: + if lookup("HERMES_SESSION_PLATFORM") != "discord": + return Refusal("This only works while replying in a Discord channel.") + if lookup("HERMES_CRON_SESSION").strip().lower() in CRON_TRUE: + return Refusal("This doesn't run in a scheduled job; there is no channel being replied in.") + channel_id = _snowflake(lookup("HERMES_SESSION_CHAT_ID")) + if not channel_id: + return Refusal("The current Discord channel is unknown.") + return ChannelScope( + guild_id=_snowflake(lookup("HERMES_SESSION_SCOPE_ID")), + channel_id=channel_id, + message_id=_snowflake(lookup("HERMES_SESSION_MESSAGE_ID")), + parent_channel_id=_snowflake(lookup("HERMES_SESSION_PARENT_CHAT_ID")), + ) + + +def _scope_or_refusal(lookup: Lookup, env: Mapping[str, str]) -> ChannelScope | Refusal: + scope = current_scope(lookup) + if isinstance(scope, Refusal): + return scope + guard = _guard_guild(scope.guild_id, _allowed_guilds(dict(env))) + return Refusal(guard) if guard else scope + + +# -- emoji ------------------------------------------------------------------- + + +def _looks_like_unicode_emoji(text: str) -> bool: + if len(text) > MAX_UNICODE_EMOJI_CODEPOINTS: + return False + if any(ch.isspace() or ch in "<>@:`" or (ch.isascii() and ch.isalpha()) for ch in text): + return False + return any(unicodedata.category(ch) in ("So", "Me") for ch in text) + + +def parse_emoji(value: Any) -> EmojiRef | None: + """Parse what a model wrote into a Unicode emoji or a custom-emoji reference.""" + if not isinstance(value, str): + return None + text = value.strip() + if not text: + return None + for pattern in (CUSTOM_TAG_RE, NAME_ID_RE): + match = pattern.match(text) + if match: + return EmojiRef(name=match.group("name"), id=match.group("id")) + for pattern in (COLON_NAME_RE, BARE_NAME_RE): + match = pattern.match(text) + if match: + return EmojiRef(name=match.group("name")) + if _looks_like_unicode_emoji(text): + return EmojiRef(unicode=text) + return None + + +def _usable(entry: Mapping[str, Any]) -> bool: + # Emoji lost with a boost tier are unavailable; role-locked ones may not be + # usable by the bot, so leave them out rather than fail at Discord. + return entry.get("available", True) is not False and not entry.get("roles") + + +def resolve_emoji(ref: EmojiRef, palette: list[Mapping[str, Any]] | None) -> str | Refusal: + """The string Discord's reaction endpoint takes, or why it can't be used. + + Custom emoji must come from this server's own palette. + """ + if ref.unicode: + return ref.unicode + if palette is None: + return Refusal("Custom server emoji only work in a server channel.") + if ref.id: + matches = [e for e in palette if str(e.get("id")) == ref.id] + else: + matches = [e for e in palette if e.get("name") == ref.name] + if not matches: + wanted = (ref.name or "").lower() + matches = [e for e in palette if str(e.get("name", "")).lower() == wanted] + if len(matches) > 1: + names = ", ".join(sorted(str(e.get("name")) for e in matches)) + return Refusal(f"More than one server emoji matches {ref.name!r}: {names}.") + if not matches: + return Refusal("That emoji isn't one of this server's emoji.") + entry = matches[0] + if not _usable(entry): + return Refusal(f"The server emoji {entry.get('name')!r} isn't usable by the bot right now.") + return f"{entry['name']}:{entry['id']}" + + +def emoji_usage(entry: Mapping[str, Any]) -> str: + prefix = "a" if entry.get("animated") else "" + return f"<{prefix}:{entry['name']}:{entry['id']}>" + + +# -- embeds ------------------------------------------------------------------ + + +def _text(value: Any) -> str: + return value.strip() if isinstance(value, str) else "" + + +def _https(value: Any) -> str | None | Refusal: + text = _text(value) + if not text: + return None + parsed = urlparse(text) + if parsed.scheme != "https" or not parsed.netloc: + return Refusal("Embed links and images must be https:// URLs.") + return text + + +def _colour(value: Any) -> int | None | Refusal: + if value is None or value == "": + return None + if isinstance(value, bool) or isinstance(value, float): + return Refusal("color must be a hex colour like #FF8800.") + if isinstance(value, int): + return value if 0 <= value <= 0xFFFFFF else Refusal("color must be between 0 and 0xFFFFFF.") + match = HEX_COLOUR_RE.match(_text(value)) + if not match: + return Refusal("color must be a hex colour like #FF8800.") + return int(match.group(1), 16) + + +def build_embed(args: Mapping[str, Any]) -> dict[str, Any] | Refusal: + """A Discord embed object from tool arguments, held to Discord's limits.""" + limits = schemas.EMBED_LIMITS + title = _text(args.get("title")) + description = _text(args.get("description")) + footer = _text(args.get("footer")) + if not title and not description: + return Refusal("An embed needs a title or a description.") + for name, value in (("title", title), ("description", description), ("footer", footer)): + if len(value) > limits[name]: + return Refusal(f"Embed {name} is over Discord's {limits[name]}-character limit.") + + raw_fields = args.get("fields") + if raw_fields is None: + raw_fields = [] + if not isinstance(raw_fields, list): + return Refusal("fields must be a list of {name, value, inline}.") + if len(raw_fields) > limits["fields"]: + return Refusal(f"An embed holds at most {limits['fields']} fields.") + fields: list[dict[str, Any]] = [] + for raw in raw_fields: + if not isinstance(raw, Mapping): + return Refusal("Each field needs a name and a value.") + name, value, inline = _text(raw.get("name")), _text(raw.get("value")), raw.get("inline", False) + if not name or not value: + return Refusal("Each field needs a name and a value.") + if len(name) > limits["field_name"]: + return Refusal(f"A field name is over Discord's {limits['field_name']}-character limit.") + if len(value) > limits["field_value"]: + return Refusal(f"A field value is over Discord's {limits['field_value']}-character limit.") + if not isinstance(inline, bool): + return Refusal("A field's inline must be true or false.") + fields.append({"name": name, "value": value, "inline": inline}) + + total = len(title) + len(description) + len(footer) + sum(len(f["name"]) + len(f["value"]) for f in fields) + if total > limits["total"]: + return Refusal(f"The embed's text adds up to more than Discord's {limits['total']}-character limit.") + + links: dict[str, str | None] = {} + for key in ("url", "image_url", "thumbnail_url"): + link = _https(args.get(key)) + if isinstance(link, Refusal): + return link + links[key] = link + colour = _colour(args.get("color")) + if isinstance(colour, Refusal): + return colour + + embed: dict[str, Any] = {} + if title: + embed["title"] = title + if description: + embed["description"] = description + if links["url"]: + embed["url"] = links["url"] + if colour is not None: + embed["color"] = colour + if fields: + embed["fields"] = fields + if footer: + embed["footer"] = {"text": footer} + if links["image_url"]: + embed["image"] = {"url": links["image_url"]} + if links["thumbnail_url"]: + embed["thumbnail"] = {"url": links["thumbnail_url"]} + return embed + + +# -- per-message budget ------------------------------------------------------ + + +class TurnBudget: + """How many writes of each kind one incoming message may still cause.""" + + def __init__(self, limits: Mapping[str, int], remember: int = schemas.TURN_BUDGET_REMEMBER) -> None: + self._limits = dict(limits) + self._remember = remember + self._spent: OrderedDict[tuple, Counter] = OrderedDict() + self._lock = threading.Lock() + + def spend(self, kind: str, key: tuple) -> bool: + with self._lock: + spent = self._spent.get(key) + if spent is None: + spent = self._spent[key] = Counter() + while len(self._spent) > self._remember: + self._spent.popitem(last=False) + self._spent.move_to_end(key) + if spent[kind] >= self._limits.get(kind, 0): + return False + spent[kind] += 1 + return True + + def refund(self, kind: str, key: tuple) -> None: + with self._lock: + spent = self._spent.get(key) + if spent and spent[kind] > 0: + spent[kind] -= 1 + + +_BUDGET = TurnBudget(schemas.TURN_BUDGET) + + +# -- live error mapping ------------------------------------------------------ + +_PERMISSION_FOR = { + "react": "Add Reactions (and Read Message History)", + "embed": "Send Messages and Embed Links", + "emojis": "View Channel", +} + + +def is_not_found(exc: BaseException) -> bool: + try: + import discord + except ImportError: # pragma: no cover - discord.py is a runtime dependency + return False + return isinstance(exc, discord.NotFound) + + +def describe_discord_error(exc: BaseException, kind: str) -> str: + try: + import discord + except ImportError: # pragma: no cover + discord = None # type: ignore[assignment] + if discord is not None: + if isinstance(exc, discord.Forbidden): + return f"The bot is missing a Discord permission here: {_PERMISSION_FOR[kind]}." + if isinstance(exc, discord.NotFound): + return "Discord couldn't find that message or channel." + if isinstance(exc, discord.HTTPException) and getattr(exc, "code", 0) == 10014: + return "Discord doesn't know that emoji." + if isinstance(exc, TimeoutError): + return "Discord didn't answer in time." + return f"Discord request failed: {type(exc).__name__}" + + +# -- tool impls -------------------------------------------------------------- + + +def list_emojis_impl( + args: Mapping[str, Any], client: ActionClient, lookup: Lookup, env: Mapping[str, str] +) -> str: + scope = _scope_or_refusal(lookup, env) + if isinstance(scope, Refusal): + return _err(scope) + if not scope.guild_id: + return _err("Server emoji only exist in a server channel, not here.") + try: + palette = client.list_emojis(scope.guild_id) + except Exception as exc: # noqa: BLE001 + logger.warning("discord-tools: emoji list failed in guild %s: %s", scope.guild_id, type(exc).__name__) + return _err(describe_discord_error(exc, "emojis")) + query = _text((args or {}).get("query")).lower() + limit = _clamp((args or {}).get("limit"), schemas.DEFAULT_EMOJI_LIST, 1, schemas.MAX_EMOJI_LIST) + matching = [e for e in palette if _usable(e) and query in str(e.get("name", "")).lower()] + shown = [ + {"name": e["name"], "id": str(e["id"]), "animated": bool(e.get("animated")), "usage": emoji_usage(e)} + for e in matching[:limit] + ] + return _ok(guild_id=scope.guild_id, emojis=shown, count=len(matching), truncated=len(matching) > limit) + + +def _reaction_target(args: Mapping[str, Any], scope: ChannelScope) -> tuple[str, list[str]] | Refusal: + raw = _text(args.get("message_id")) + if not raw: + if not scope.message_id: + return Refusal("There is no message here to react to; pass message_id.") + target, named_channel = scope.message_id, None + else: + ref = _parse_message_ref(raw, scope.channel_id) + if ref is None or not ref.message_id: + return Refusal("message_id must be a message ID or link from this channel.") + target, named_channel = ref.message_id, ref.channel_id + channels = [scope.channel_id] + # An auto-created thread answers a message that sits in its parent channel. + if target == scope.message_id and scope.parent_channel_id and scope.parent_channel_id != scope.channel_id: + channels.append(scope.parent_channel_id) + if named_channel and named_channel not in channels: + return Refusal("You can only react to messages in this channel.") + return target, channels + + +def react_impl( + args: Mapping[str, Any], + client: ActionClient, + lookup: Lookup, + env: Mapping[str, str], + budget: TurnBudget = _BUDGET, +) -> str: + args = args or {} + scope = _scope_or_refusal(lookup, env) + if isinstance(scope, Refusal): + return _err(scope) + ref = parse_emoji(args.get("emoji")) + if ref is None: + return _err("emoji must be one emoji, like πŸ”₯, or a server emoji, like :name: or <:name:id>.") + target = _reaction_target(args, scope) + if isinstance(target, Refusal): + return _err(target) + message_id, channels = target + + palette = None + if not ref.unicode and scope.guild_id: + try: + palette = client.list_emojis(scope.guild_id) + except Exception as exc: # noqa: BLE001 + return _err(describe_discord_error(exc, "emojis")) + emoji = resolve_emoji(ref, palette) + if isinstance(emoji, Refusal): + return _err(emoji) + + key = (scope.channel_id, scope.message_id) + if not budget.spend("react", key): + return _err(f"Already reacted {schemas.TURN_BUDGET['react']} times for this message.") + for channel_id in channels: + try: + client.add_reaction(channel_id, message_id, emoji) + except MessageNotFound: + continue + except Exception as exc: # noqa: BLE001 + budget.refund("react", key) + logger.warning("discord-tools: reaction failed in %s: %s", channel_id, type(exc).__name__) + return _err(describe_discord_error(exc, "react")) + logger.info("discord-tools: reacted %s on %s/%s", emoji, channel_id, message_id) + return _ok(channel_id=channel_id, message_id=message_id, emoji=emoji) + budget.refund("react", key) + return _err("That message isn't in this channel.") + + +def send_embed_impl( + args: Mapping[str, Any], + client: ActionClient, + lookup: Lookup, + env: Mapping[str, str], + budget: TurnBudget = _BUDGET, +) -> str: + scope = _scope_or_refusal(lookup, env) + if isinstance(scope, Refusal): + return _err(scope) + embed = build_embed(args or {}) + if isinstance(embed, Refusal): + return _err(embed) + key = (scope.channel_id, scope.message_id) + if not budget.spend("embed", key): + return _err(f"Already sent {schemas.TURN_BUDGET['embed']} embeds for this message.") + try: + message_id = client.send_embed(scope.channel_id, embed) + except Exception as exc: # noqa: BLE001 + budget.refund("embed", key) + logger.warning("discord-tools: embed failed in %s: %s", scope.channel_id, type(exc).__name__) + return _err(describe_discord_error(exc, "embed")) + logger.info("discord-tools: sent embed %s in %s", message_id, scope.channel_id) + return _ok(channel_id=scope.channel_id, message_id=str(message_id)) + + +# -- live client ------------------------------------------------------------- + + +class DiscordLiveActions(DiscordLiveFetcher): + """REST-only Discord client for the three actions; reuses the fetcher's login.""" + + def list_emojis(self, guild_id: str) -> list[dict[str, Any]]: + async def _operation(client: Any, _discord: Any) -> list[dict[str, Any]]: + raw = await client.http.get_all_custom_emojis(int(guild_id)) + return [ + { + "id": str(e.get("id")), + "name": e.get("name"), + "animated": bool(e.get("animated")), + "available": e.get("available", True), + "roles": [str(r) for r in e.get("roles") or []], + } + for e in raw + if e.get("id") and e.get("name") + ] + + return _run_async(self._with_client(_operation)) + + def add_reaction(self, channel_id: str, message_id: str, emoji: str) -> None: + async def _operation(client: Any, discord: Any) -> None: + try: + await client.http.add_reaction(int(channel_id), int(message_id), emoji) + except discord.NotFound as exc: + if getattr(exc, "code", 0) == 10008: # Unknown Message + raise MessageNotFound(channel_id, message_id) from exc + raise + + _run_async(self._with_client(_operation)) + + def send_embed(self, channel_id: str, embed: dict[str, Any]) -> str: + async def _operation(client: Any, discord: Any) -> str: + channel = client.get_partial_messageable(int(channel_id)) + message = await channel.send( + embed=discord.Embed.from_dict(embed), + allowed_mentions=discord.AllowedMentions.none(), + ) + return str(message.id) + + return _run_async(self._with_client(_operation)) + + +def _live_actions(env: Mapping[str, str]) -> DiscordLiveActions | str: + token = env.get("DISCORD_BOT_TOKEN") or env.get("DISCORD_TOKEN") + if not token: + return "DISCORD_BOT_TOKEN is required for Discord actions" + try: + timeout = float(env.get("DISCORD_TOOLS_TIMEOUT_SECONDS", schemas.DEFAULT_TIMEOUT_SECONDS)) + except ValueError: + timeout = schemas.DEFAULT_TIMEOUT_SECONDS + return DiscordLiveActions(token=token, timeout_seconds=timeout) + + +def _run(impl: Callable[..., str], args: Mapping[str, Any]) -> str: + lookup = session_lookup() + scope = _scope_or_refusal(lookup, os.environ) + if isinstance(scope, Refusal): + return _err(scope) + client = _live_actions(os.environ) + if isinstance(client, str): + return _err(client) + return impl(args or {}, client, lookup, os.environ) + + +@tool( + toolset="discord", + requires_env=["DISCORD_BOT_TOKEN"], + description=( + "List this Discord server's own custom emoji you can react with. Works only " + "in the server you are replying in. Each entry's usage string can be passed " + "to discord_react." + ), + params={ + "query": str_arg("Optional part of an emoji name to filter by."), + "limit": int_arg( + f"Emoji to return, capped at {schemas.MAX_EMOJI_LIST}.", + minimum=1, + maximum=schemas.MAX_EMOJI_LIST, + ), + }, +) +def discord_list_emojis(args: dict[str, Any], **_kwargs: Any) -> str: + return _run(list_emojis_impl, args) + + +@tool( + toolset="discord", + requires_env=["DISCORD_BOT_TOKEN"], + description=( + "React with one emoji to the message you are replying to, or to another " + "message in this same channel. Takes any standard emoji, or one of this " + "server's emoji as :name: or <:name:id>." + ), + params={ + "emoji": str_arg("One emoji, like πŸ”₯, or a server emoji like :name:.", required=True, example="πŸ”₯"), + "message_id": str_arg( + "Optional message ID or link in this channel. Leave out to react to the message you are replying to." + ), + }, +) +def discord_react(args: dict[str, Any], **_kwargs: Any) -> str: + return _run(react_impl, args) + + +@tool( + toolset="discord", + requires_env=["DISCORD_BOT_TOKEN"], + description=( + "Post one embed card in the channel you are replying in. Use for a tidy " + "card such as a now-playing note or a schedule, not for ordinary replies. " + "It never mentions or pings anyone." + ), + params={ + "title": str_arg(f"Card title, up to {schemas.EMBED_LIMITS['title']} characters."), + "description": str_arg(f"Card body, up to {schemas.EMBED_LIMITS['description']} characters."), + "url": str_arg("Optional https link for the title."), + "color": str_arg("Optional hex colour for the side bar, like #FF8800."), + "fields": arg( + "array", + f"Optional fields, at most {schemas.EMBED_LIMITS['fields']}.", + maxItems=schemas.EMBED_LIMITS["fields"], + items={ + "type": "object", + "properties": { + "name": {"type": "string"}, + "value": {"type": "string"}, + "inline": {"type": "boolean"}, + }, + "required": ["name", "value"], + }, + ), + "footer": str_arg("Optional small footer text."), + "image_url": str_arg("Optional https image shown large."), + "thumbnail_url": str_arg("Optional https image shown small in the corner."), + }, +) +def discord_send_embed(args: dict[str, Any], **_kwargs: Any) -> str: + return _run(send_embed_impl, args) diff --git a/plugin.yaml b/plugin.yaml index bd122e0..2513016 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -1,9 +1,10 @@ name: discord-tools -version: 0.1.0 +version: 0.3.0 description: >- - Read-only Discord channel, thread, and message inspection tools for Hermes - Discord-facing agents. Reuses the profile's existing DISCORD_BOT_TOKEN and - only reads content the bot can already access. + Discord channel, thread, and message reading tools for Hermes Discord-facing + agents, plus three actions held to the channel the bot is replying in: react + with any emoji, list this server's emoji, and post an embed. Reuses the + profile's existing DISCORD_BOT_TOKEN. author: offendingcommit kind: standalone provides_tools: @@ -11,17 +12,20 @@ provides_tools: - discord_read_thread - discord_get_message - discord_read_story + - discord_list_emojis + - discord_react + - discord_send_embed provides_hooks: - pre_llm_call requires_env: - name: DISCORD_BOT_TOKEN - description: Existing Discord bot token loaded by the Hermes gateway. Reused for reads. + description: Existing Discord bot token loaded by the Hermes gateway. Reused for reads and the channel-scoped actions. secret: true - name: DISCORD_TOKEN description: Optional fallback alias for the bot token when running standalone. secret: true - name: DISCORD_TOOLS_ALLOWED_GUILDS - description: Optional comma-separated guild IDs allowed for reads. + description: Optional comma-separated guild IDs allowed for reads and actions. secret: false - name: DISCORD_TOOLS_STORY_HINTS description: Optional inline JSON story hint config for the hint hook. diff --git a/pyproject.toml b/pyproject.toml index 4cd74cb..018fba9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,11 +4,11 @@ # pod's bootstrap installs into the gateway's PYTHONPATH. [project] name = "discord-tools" -version = "0.2.0" -description = "Read-only Discord channel, thread, and message inspection tools for Hermes Discord-facing agents." +version = "0.3.0" +description = "Discord reading tools plus channel-scoped react, server emoji, and embed actions for Hermes Discord-facing agents." requires-python = ">=3.13" dependencies = [ - "discord.py>=2.4", # DiscordLiveFetcher β€” live reads + "discord.py>=2.4", # DiscordLiveFetcher / DiscordLiveActions β€” live I/O "hermes-plugin-kit", # Decorated tools/hooks + lifecycle registration ] diff --git a/schemas.py b/schemas.py index 66bac59..a71b664 100644 --- a/schemas.py +++ b/schemas.py @@ -14,3 +14,24 @@ DEFAULT_MAX_CHARS = 12000 MAX_MAX_CHARS = 30000 DEFAULT_TIMEOUT_SECONDS = 20.0 + +# Discord's documented embed limits (https://discord.com/developers/docs/resources/message#embed-object-embed-limits). +# "total" is the sum of every text part a single embed carries. +EMBED_LIMITS = { + "title": 256, + "description": 4096, + "fields": 25, + "field_name": 256, + "field_value": 1024, + "footer": 2048, + "total": 6000, +} + +# Most writes one incoming message may cause, per kind. Stops a model loop from +# carpeting a channel in reactions or embeds off a single prompt. +TURN_BUDGET = {"react": 5, "embed": 2} +# Incoming messages the budget remembers before the oldest is forgotten. +TURN_BUDGET_REMEMBER = 512 + +DEFAULT_EMOJI_LIST = 100 +MAX_EMOJI_LIST = 250 diff --git a/tests/test_actions.py b/tests/test_actions.py new file mode 100644 index 0000000..074c0a3 --- /dev/null +++ b/tests/test_actions.py @@ -0,0 +1,608 @@ +"""Channel-scoped Discord actions: react, list the server's emoji, send an embed. + +The pure pieces (session scope, emoji parsing and resolution, embed building, +the per-message budget) are exercised directly. The tool impls run against +``RecordingClient``, an in-memory ``ActionClient`` that holds messages by +channel so "is this message in this channel" is answered the way Discord +answers it: a 404 for the wrong channel. Embeds are round-tripped through +discord.py's own ``Embed`` type, the one the live client sends. +""" + +from __future__ import annotations + +import json +import os +import sys +import threading +import unittest +from pathlib import Path + +import discord + +from hermes_plugin_loader import load_plugin_module + +plugin = load_plugin_module() +actions = plugin.actions +schemas = plugin.schemas + +GUILD = "111111111111111111" +CHANNEL = "222222222222222222" +PARENT = "444444444444444444" +TRIGGER = "333333333333333333" +OTHER_MESSAGE = "555555555555555555" +ELSEWHERE = "666666666666666666" + +PALETTE = [ + {"id": "900000000000000001", "name": "dsl_hype", "animated": False, "available": True, "roles": []}, + {"id": "900000000000000002", "name": "spin", "animated": True, "available": True, "roles": []}, + {"id": "900000000000000003", "name": "lost_boost", "animated": False, "available": False, "roles": []}, + {"id": "900000000000000004", "name": "mods_only", "animated": False, "available": True, "roles": ["7"]}, + {"id": "900000000000000005", "name": "Tea", "animated": False, "available": True, "roles": []}, + {"id": "900000000000000006", "name": "tea", "animated": False, "available": True, "roles": []}, +] + + +def session(**overrides: str): + values = { + "HERMES_SESSION_PLATFORM": "discord", + "HERMES_SESSION_CHAT_ID": CHANNEL, + "HERMES_SESSION_SCOPE_ID": GUILD, + "HERMES_SESSION_MESSAGE_ID": TRIGGER, + "HERMES_SESSION_PARENT_CHAT_ID": "", + "HERMES_CRON_SESSION": "", + } + values.update(overrides) + return lambda name: values.get(name, "") + + +class RecordingClient: + """In-memory ActionClient: messages live in channels, like on Discord.""" + + def __init__(self, messages: dict[str, str] | None = None, palette: list[dict] | None = None) -> None: + self.messages = {TRIGGER: CHANNEL, OTHER_MESSAGE: CHANNEL} if messages is None else messages + self.palette = PALETTE if palette is None else palette + self.reactions: list[tuple[str, str, str]] = [] + self.attempts: list[tuple[str, str]] = [] + self.embeds: list[tuple[str, dict]] = [] + self.palette_reads: list[str] = [] + + def list_emojis(self, guild_id: str) -> list[dict]: + self.palette_reads.append(guild_id) + return [dict(e) for e in self.palette] + + def add_reaction(self, channel_id: str, message_id: str, emoji: str) -> None: + self.attempts.append((channel_id, message_id)) + if self.messages.get(message_id) != channel_id: + raise actions.MessageNotFound(channel_id, message_id) + self.reactions.append((channel_id, message_id, emoji)) + + def send_embed(self, channel_id: str, embed: dict) -> str: + # The live client builds discord.Embed.from_dict(embed); do the same so + # a shape discord.py would drop or reject fails here too. + sent = discord.Embed.from_dict(embed).to_dict() + self.embeds.append((channel_id, sent)) + return "777777777777777777" + + +def decoded(raw: str) -> dict: + return json.loads(raw) + + +class ScopeTests(unittest.TestCase): + def test_reads_current_discord_channel(self) -> None: + scope = actions.current_scope(session(HERMES_SESSION_PARENT_CHAT_ID=PARENT)) + self.assertEqual(scope, actions.ChannelScope(GUILD, CHANNEL, TRIGGER, PARENT)) + + def test_refuses_other_platforms(self) -> None: + for platform in ("telegram", "cli", "", "Discord "): + with self.subTest(platform=platform): + self.assertIsInstance(actions.current_scope(session(HERMES_SESSION_PLATFORM=platform)), str) + + def test_refuses_cron_runs(self) -> None: + for flag in ("1", "true", "yes"): + with self.subTest(flag=flag): + self.assertIn("scheduled", actions.current_scope(session(HERMES_CRON_SESSION=flag))) + self.assertIsInstance(actions.current_scope(session(HERMES_CRON_SESSION="0")), actions.ChannelScope) + + def test_refuses_missing_or_malformed_channel(self) -> None: + for chat in ("", "general", "12345", f"{CHANNEL}x"): + with self.subTest(chat=chat): + self.assertIsInstance(actions.current_scope(session(HERMES_SESSION_CHAT_ID=chat)), str) + + def test_malformed_optional_ids_collapse_to_none(self) -> None: + scope = actions.current_scope( + session(HERMES_SESSION_SCOPE_ID="dm", HERMES_SESSION_MESSAGE_ID="", HERMES_SESSION_PARENT_CHAT_ID="x") + ) + self.assertEqual(scope, actions.ChannelScope(None, CHANNEL, None, None)) + + def test_session_lookup_reads_an_explicit_mapping(self) -> None: + lookup = actions.session_lookup({"HERMES_SESSION_PLATFORM": "discord"}) + self.assertEqual(lookup("HERMES_SESSION_PLATFORM"), "discord") + self.assertEqual(lookup("HERMES_SESSION_CHAT_ID"), "") + + +class EmojiParseTests(unittest.TestCase): + def test_unicode_emoji(self) -> None: + for text in ("πŸ”₯", "πŸ‘πŸ½", "1️⃣", "πŸ³οΈβ€πŸŒˆ", "πŸ‡ΊπŸ‡Έ", "❀️", " πŸŽ‰ "): + with self.subTest(text=text): + ref = actions.parse_emoji(text) + self.assertEqual(ref, actions.EmojiRef(unicode=text.strip())) + + def test_custom_emoji_forms(self) -> None: + cases = { + "<:dsl_hype:900000000000000001>": actions.EmojiRef(name="dsl_hype", id="900000000000000001"), + "": actions.EmojiRef(name="spin", id="900000000000000002"), + "dsl_hype:900000000000000001": actions.EmojiRef(name="dsl_hype", id="900000000000000001"), + ":dsl_hype:": actions.EmojiRef(name="dsl_hype"), + "dsl_hype": actions.EmojiRef(name="dsl_hype"), + } + for text, expected in cases.items(): + with self.subTest(text=text): + self.assertEqual(actions.parse_emoji(text), expected) + + def test_rejects_text_that_is_not_an_emoji(self) -> None: + for text in ("", " ", "x", "hello world", "πŸ”₯πŸ”₯ lit", "<:bad name:1>", "@everyone", + "<@123456789012345678>", "a" * 33, "πŸ”₯lit", "okπŸ‘", "πŸ”₯" * 20, None, 42): + with self.subTest(text=text): + self.assertIsNone(actions.parse_emoji(text)) + + +class EmojiResolveTests(unittest.TestCase): + def test_unicode_needs_no_palette(self) -> None: + self.assertEqual(actions.resolve_emoji(actions.EmojiRef(unicode="πŸ”₯"), None), "πŸ”₯") + + def test_custom_by_id_and_by_name(self) -> None: + by_id = actions.resolve_emoji(actions.EmojiRef(name="whatever", id="900000000000000002"), PALETTE) + by_name = actions.resolve_emoji(actions.EmojiRef(name="dsl_hype"), PALETTE) + self.assertEqual(by_id, "spin:900000000000000002") + self.assertEqual(by_name, "dsl_hype:900000000000000001") + + def test_exact_name_wins_over_case_insensitive(self) -> None: + self.assertEqual(actions.resolve_emoji(actions.EmojiRef(name="Tea"), PALETTE), "Tea:900000000000000005") + self.assertEqual(actions.resolve_emoji(actions.EmojiRef(name="tea"), PALETTE), "tea:900000000000000006") + + def test_case_insensitive_only_when_unique(self) -> None: + self.assertEqual( + actions.resolve_emoji(actions.EmojiRef(name="DSL_HYPE"), PALETTE), "dsl_hype:900000000000000001" + ) + self.assertIsInstance(actions.resolve_emoji(actions.EmojiRef(name="TEA"), PALETTE), actions.Refusal) + + def test_refuses_emoji_from_other_servers_and_unusable_ones(self) -> None: + for ref in ( + actions.EmojiRef(name="foreign", id="912345678901234567"), + actions.EmojiRef(name="lost_boost"), + actions.EmojiRef(name="mods_only"), + actions.EmojiRef(name="nope"), + ): + with self.subTest(ref=ref): + self.assertIsInstance(actions.resolve_emoji(ref, PALETTE), actions.Refusal) + + def test_custom_without_a_server_is_refused(self) -> None: + self.assertIsInstance(actions.resolve_emoji(actions.EmojiRef(name="dsl_hype"), None), actions.Refusal) + + +class EmbedBuildTests(unittest.TestCase): + def test_builds_discord_shape_that_discord_py_round_trips(self) -> None: + embed = actions.build_embed( + { + "title": "Tonight on Amber", + "description": "New hour at 9.", + "url": "https://example.com/amber", + "color": "#FF8800", + "fields": [{"name": "Host", "value": "Amber", "inline": True}], + "footer": "Dopamine Sound Labs", + "image_url": "https://example.com/a.png", + "thumbnail_url": "https://example.com/t.png", + } + ) + self.assertIsInstance(embed, dict) + self.assertEqual(embed["color"], 0xFF8800) + self.assertEqual(embed["footer"], {"text": "Dopamine Sound Labs"}) + rebuilt = discord.Embed.from_dict(embed).to_dict() + for key, value in embed.items(): + self.assertEqual(rebuilt[key], value, key) + + def test_colour_forms(self) -> None: + for given, expected in (("ff8800", 0xFF8800), ("#00ff00", 0x00FF00), (255, 255), (0, 0), ("", None), (None, None)): + with self.subTest(given=given): + embed = actions.build_embed({"title": "t", "color": given}) + self.assertEqual(embed.get("color"), expected) + for bad in ("orange", "#12345", -1, 0x1000000, True, 1.5): + with self.subTest(bad=bad): + self.assertIsInstance(actions.build_embed({"title": "t", "color": bad}), actions.Refusal) + + def test_needs_title_or_description(self) -> None: + self.assertIsInstance(actions.build_embed({}), actions.Refusal) + self.assertIsInstance(actions.build_embed({"title": " ", "description": ""}), actions.Refusal) + self.assertIsInstance(actions.build_embed({"description": "only text"}), dict) + + def test_discord_limits_hold_at_the_boundary(self) -> None: + limits = schemas.EMBED_LIMITS + at_limit = { + "title": "t" * limits["title"], + "fields": [{"name": "n", "value": "v"}] * limits["fields"], + } + self.assertIsInstance(actions.build_embed(at_limit), dict) + for key, args in ( + ("title", {"title": "t" * (limits["title"] + 1)}), + ("description", {"description": "d" * (limits["description"] + 1)}), + ("footer", {"title": "t", "footer": "f" * (limits["footer"] + 1)}), + ("fields", {"title": "t", "fields": [{"name": "n", "value": "v"}] * (limits["fields"] + 1)}), + ("field_name", {"title": "t", "fields": [{"name": "n" * (limits["field_name"] + 1), "value": "v"}]}), + ("field_value", {"title": "t", "fields": [{"name": "n", "value": "v" * (limits["field_value"] + 1)}]}), + ("total", {"description": "d" * limits["description"], "fields": [{"name": "n" * 256, "value": "v" * 1024}] * 2}), + ): + with self.subTest(limit=key): + self.assertIsInstance(actions.build_embed(args), actions.Refusal) + + def test_total_counts_every_text_part(self) -> None: + limits = schemas.EMBED_LIMITS + description = "d" * limits["description"] + # 1 + 4096 + 1 + (1 + 1024) + (1 + 876) == 6000: title, description, + # footer, both field names and values all count toward the total. + fields = [{"name": "n", "value": "v" * 1024}, {"name": "n", "value": "v" * 876}] + exact = {"title": "t", "description": description, "footer": "f", "fields": fields} + self.assertIsInstance(actions.build_embed(exact), dict) + for grown in ("title", "footer"): + with self.subTest(grown=grown): + self.assertIsInstance(actions.build_embed({**exact, grown: exact[grown] * 2}), actions.Refusal) + longer_name = [{"name": "nn", "value": "v" * 1024}, fields[1]] + self.assertIsInstance(actions.build_embed({**exact, "fields": longer_name}), actions.Refusal) + + def test_fields_need_name_and_value(self) -> None: + for field in ({"name": "", "value": "v"}, {"name": "n", "value": " "}, {"name": "n"}, "not a field"): + with self.subTest(field=field): + self.assertIsInstance(actions.build_embed({"title": "t", "fields": [field]}), actions.Refusal) + self.assertIsInstance(actions.build_embed({"title": "t", "fields": "nope"}), actions.Refusal) + + def test_links_must_be_https(self) -> None: + for key in ("url", "image_url", "thumbnail_url"): + for bad in ("http://example.com/x", "javascript:alert(1)", "example.com", "https://"): + with self.subTest(key=key, bad=bad): + self.assertIsInstance(actions.build_embed({"title": "t", key: bad}), actions.Refusal) + + def test_inline_defaults_false_and_must_be_bool(self) -> None: + embed = actions.build_embed({"title": "t", "fields": [{"name": "n", "value": "v"}]}) + self.assertIs(embed["fields"][0]["inline"], False) + self.assertIsInstance( + actions.build_embed({"title": "t", "fields": [{"name": "n", "value": "v", "inline": "yes"}]}), + actions.Refusal, + ) + + +class BudgetTests(unittest.TestCase): + def test_spends_per_message_and_kind(self) -> None: + budget = actions.TurnBudget({"react": 2, "embed": 1}) + key = (CHANNEL, TRIGGER) + self.assertTrue(budget.spend("react", key)) + self.assertTrue(budget.spend("react", key)) + self.assertFalse(budget.spend("react", key)) + self.assertTrue(budget.spend("embed", key)) + self.assertFalse(budget.spend("embed", key)) + self.assertTrue(budget.spend("react", (CHANNEL, OTHER_MESSAGE))) + + def test_forgets_old_messages(self) -> None: + budget = actions.TurnBudget({"react": 1}, remember=2) + for message in ("1", "2", "3"): + self.assertTrue(budget.spend("react", (CHANNEL, message))) + self.assertTrue(budget.spend("react", (CHANNEL, "1"))) + self.assertFalse(budget.spend("react", (CHANNEL, "3"))) + + def test_forgets_least_recently_used(self) -> None: + budget = actions.TurnBudget({"react": 2}, remember=2) + self.assertTrue(budget.spend("react", (CHANNEL, "1"))) + self.assertTrue(budget.spend("react", (CHANNEL, "2"))) + self.assertTrue(budget.spend("react", (CHANNEL, "1"))) # "1" is now the freshest + self.assertTrue(budget.spend("react", (CHANNEL, "3"))) # so "2" is forgotten + self.assertFalse(budget.spend("react", (CHANNEL, "1"))) + + def test_no_message_shares_one_bucket(self) -> None: + budget = actions.TurnBudget({"embed": 1}) + self.assertTrue(budget.spend("embed", (CHANNEL, None))) + self.assertFalse(budget.spend("embed", (CHANNEL, None))) + + +class ListEmojisTests(unittest.TestCase): + def test_lists_usable_palette_with_usage_strings(self) -> None: + client = RecordingClient() + result = decoded(actions.list_emojis_impl({}, client, session(), {})) + self.assertTrue(result["success"]) + self.assertEqual(client.palette_reads, [GUILD]) + names = [e["name"] for e in result["data"]["emojis"]] + self.assertEqual(names, ["dsl_hype", "spin", "Tea", "tea"]) + self.assertEqual(result["data"]["emojis"][1]["usage"], "") + self.assertEqual(result["data"]["emojis"][0]["usage"], "<:dsl_hype:900000000000000001>") + self.assertEqual(result["data"]["count"], 4) + self.assertFalse(result["data"]["truncated"]) + + def test_query_and_limit(self) -> None: + result = decoded(actions.list_emojis_impl({"query": "TEA", "limit": 1}, RecordingClient(), session(), {})) + self.assertEqual([e["name"] for e in result["data"]["emojis"]], ["Tea"]) + self.assertEqual(result["data"]["count"], 2) + self.assertTrue(result["data"]["truncated"]) + + def test_needs_a_server(self) -> None: + client = RecordingClient() + result = decoded(actions.list_emojis_impl({}, client, session(HERMES_SESSION_SCOPE_ID=""), {})) + self.assertFalse(result["success"]) + self.assertEqual(client.palette_reads, []) + + def test_respects_guild_allowlist(self) -> None: + client = RecordingClient() + env = {"DISCORD_TOOLS_ALLOWED_GUILDS": ELSEWHERE} + self.assertFalse(decoded(actions.list_emojis_impl({}, client, session(), env))["success"]) + self.assertEqual(client.palette_reads, []) + env = {"DISCORD_TOOLS_ALLOWED_GUILDS": f"{ELSEWHERE}, {GUILD}"} + self.assertTrue(decoded(actions.list_emojis_impl({}, client, session(), env))["success"]) + + def test_outside_discord_does_nothing(self) -> None: + client = RecordingClient() + result = decoded(actions.list_emojis_impl({}, client, session(HERMES_SESSION_PLATFORM="telegram"), {})) + self.assertFalse(result["success"]) + self.assertEqual(client.palette_reads, []) + + +class ReactTests(unittest.TestCase): + def setUp(self) -> None: + self.budget = actions.TurnBudget(schemas.TURN_BUDGET) + + def react(self, args, client, lookup=None, env=None): + return decoded(actions.react_impl(args, client, lookup or session(), env or {}, self.budget)) + + def test_reacts_to_the_triggering_message_by_default(self) -> None: + client = RecordingClient() + result = self.react({"emoji": "πŸ”₯"}, client) + self.assertTrue(result["success"], result) + self.assertEqual(client.reactions, [(CHANNEL, TRIGGER, "πŸ”₯")]) + self.assertEqual(client.palette_reads, [], "unicode needs no palette read") + + def test_custom_emoji_resolves_through_this_servers_palette(self) -> None: + client = RecordingClient() + self.assertTrue(self.react({"emoji": ":dsl_hype:"}, client)["success"]) + self.assertEqual(client.reactions, [(CHANNEL, TRIGGER, "dsl_hype:900000000000000001")]) + self.assertEqual(client.palette_reads, [GUILD]) + + def test_foreign_custom_emoji_is_refused_before_any_write(self) -> None: + client = RecordingClient() + self.assertFalse(self.react({"emoji": "<:foreign:912345678901234567>"}, client)["success"]) + self.assertEqual(client.reactions, []) + + def test_other_message_in_this_channel(self) -> None: + client = RecordingClient() + self.assertTrue(self.react({"emoji": "πŸ‘", "message_id": OTHER_MESSAGE}, client)["success"]) + self.assertTrue( + self.react( + {"emoji": "πŸ‘", "message_id": f"https://discord.com/channels/{GUILD}/{CHANNEL}/{OTHER_MESSAGE}"}, + RecordingClient(), + )["success"] + ) + self.assertEqual(client.reactions, [(CHANNEL, OTHER_MESSAGE, "πŸ‘")]) + + def test_message_in_another_channel_is_refused(self) -> None: + client = RecordingClient(messages={TRIGGER: CHANNEL, OTHER_MESSAGE: ELSEWHERE}) + by_id = self.react({"emoji": "πŸ‘", "message_id": OTHER_MESSAGE}, client) + by_url = self.react( + {"emoji": "πŸ‘", "message_id": f"https://discord.com/channels/{GUILD}/{ELSEWHERE}/{OTHER_MESSAGE}"}, + client, + ) + self.assertFalse(by_id["success"]) + self.assertFalse(by_url["success"]) + self.assertEqual(client.reactions, []) + # A link naming another channel is refused without asking Discord. + self.assertEqual(client.attempts, [(CHANNEL, OTHER_MESSAGE)]) + + def test_triggering_message_in_parent_of_auto_thread(self) -> None: + client = RecordingClient(messages={TRIGGER: PARENT}) + result = self.react({"emoji": "βœ…"}, client, session(HERMES_SESSION_PARENT_CHAT_ID=PARENT)) + self.assertTrue(result["success"], result) + self.assertEqual(client.reactions, [(PARENT, TRIGGER, "βœ…")]) + + def test_parent_fallback_is_only_for_the_triggering_message(self) -> None: + client = RecordingClient(messages={TRIGGER: CHANNEL, OTHER_MESSAGE: PARENT}) + result = self.react( + {"emoji": "βœ…", "message_id": OTHER_MESSAGE}, client, session(HERMES_SESSION_PARENT_CHAT_ID=PARENT) + ) + self.assertFalse(result["success"]) + self.assertEqual(client.reactions, []) + + def test_no_message_to_react_to(self) -> None: + client = RecordingClient() + self.assertFalse(self.react({"emoji": "πŸ”₯"}, client, session(HERMES_SESSION_MESSAGE_ID=""))["success"]) + self.assertFalse(self.react({"emoji": "πŸ”₯", "message_id": "not-an-id"}, client)["success"]) + self.assertEqual(client.reactions, []) + + def test_bad_emoji_and_platform_are_refused_before_any_write(self) -> None: + client = RecordingClient() + self.assertFalse(self.react({"emoji": "hello there"}, client)["success"]) + self.assertFalse(self.react({}, client)["success"]) + self.assertFalse(self.react({"emoji": "πŸ”₯"}, client, session(HERMES_SESSION_PLATFORM="telegram"))["success"]) + self.assertFalse(self.react({"emoji": "πŸ”₯"}, client, env={"DISCORD_TOOLS_ALLOWED_GUILDS": ELSEWHERE})["success"]) + self.assertEqual(client.reactions, []) + + def test_budget_caps_reactions_per_message(self) -> None: + client = RecordingClient() + cap = schemas.TURN_BUDGET["react"] + outcomes = [self.react({"emoji": "πŸ”₯"}, client)["success"] for _ in range(cap + 1)] + self.assertEqual(outcomes, [True] * cap + [False]) + self.assertEqual(len(client.reactions), cap) + + def test_refused_reaction_does_not_spend_budget(self) -> None: + client = RecordingClient() + for _ in range(schemas.TURN_BUDGET["react"] + 2): + self.react({"emoji": "nope nope"}, client) + self.assertTrue(self.react({"emoji": "πŸ”₯"}, client)["success"]) + + def test_message_not_found_refunds_budget(self) -> None: + client = RecordingClient(messages={TRIGGER: CHANNEL, OTHER_MESSAGE: ELSEWHERE}) + for _ in range(schemas.TURN_BUDGET["react"] + 1): + self.assertFalse(self.react({"emoji": "πŸ”₯", "message_id": OTHER_MESSAGE}, client)["success"]) + self.assertTrue(self.react({"emoji": "πŸ”₯"}, client)["success"]) + + +class SendEmbedTests(unittest.TestCase): + def setUp(self) -> None: + self.budget = actions.TurnBudget(schemas.TURN_BUDGET) + + def send(self, args, client, lookup=None, env=None): + return decoded(actions.send_embed_impl(args, client, lookup or session(), env or {}, self.budget)) + + def test_sends_to_the_current_channel_only(self) -> None: + client = RecordingClient() + result = self.send({"title": "Now playing", "description": "Track one", "channel_id": ELSEWHERE}, client) + self.assertTrue(result["success"], result) + self.assertEqual(result["data"], {"channel_id": CHANNEL, "message_id": "777777777777777777"}) + [(channel, sent)] = client.embeds + self.assertEqual(channel, CHANNEL) + self.assertEqual((sent["title"], sent["description"]), ("Now playing", "Track one")) + + def test_invalid_embed_is_refused_before_any_write(self) -> None: + client = RecordingClient() + self.assertFalse(self.send({"title": "t", "url": "http://insecure.example"}, client)["success"]) + self.assertFalse(self.send({"title": "t"}, client, session(HERMES_SESSION_PLATFORM="cli"))["success"]) + self.assertEqual(client.embeds, []) + + def test_discord_failure_is_reported_and_refunded(self) -> None: + class Refusing(RecordingClient): + def send_embed(self, channel_id: str, embed: dict) -> str: + response = type("R", (), {"status": 403, "reason": "x"})() + raise discord.Forbidden(response, {"code": 50013, "message": "x"}) + + failing = Refusing() + for _ in range(schemas.TURN_BUDGET["embed"] + 1): + result = self.send({"title": "t"}, failing) + self.assertFalse(result["success"]) + self.assertIn("Embed Links", result["error"]) + self.assertTrue(self.send({"title": "t"}, RecordingClient())["success"]) + + def test_budget_caps_embeds_per_message(self) -> None: + client = RecordingClient() + cap = schemas.TURN_BUDGET["embed"] + outcomes = [self.send({"title": "t"}, client)["success"] for _ in range(cap + 1)] + self.assertEqual(outcomes, [True] * cap + [False]) + + +class LiveErrorMappingTests(unittest.TestCase): + """discord.py's own exceptions map to plain refusals naming the permission.""" + + def _http_error(self, cls, status: int, code: int = 0): + response = type("R", (), {"status": status, "reason": "x"})() + return cls(response, {"code": code, "message": "x"}) + + def test_forbidden_names_the_permission(self) -> None: + err = self._http_error(discord.Forbidden, 403, 50013) + self.assertIn("Add Reactions", actions.describe_discord_error(err, "react")) + self.assertIn("Embed Links", actions.describe_discord_error(err, "embed")) + + def test_unknown_emoji(self) -> None: + err = self._http_error(discord.HTTPException, 400, 10014) + self.assertIn("emoji", actions.describe_discord_error(err, "react").lower()) + + def test_not_found_becomes_message_not_found(self) -> None: + err = self._http_error(discord.NotFound, 404, 10008) + self.assertTrue(actions.is_not_found(err)) + self.assertFalse(actions.is_not_found(self._http_error(discord.Forbidden, 403))) + + +# --------------------------------------------------------------------------- +# Optional layer: the real Hermes session context, registry and toolsets. +# Runs when HERMES_AGENT_PATH points at a Hermes checkout; these three modules +# need only the standard library. +# --------------------------------------------------------------------------- + + +def _real_hermes(): + root = os.environ.get("HERMES_AGENT_PATH") + if not root or not (Path(root) / "gateway" / "session_context.py").exists(): + return None + if root not in sys.path: + sys.path.insert(0, root) + try: + import toolsets as real_toolsets + from gateway import session_context + from tools.registry import registry + from tools.thread_context import propagate_context_to_thread + except Exception: + return None + return session_context, registry, real_toolsets, propagate_context_to_thread + + +_HERMES = _real_hermes() +ACTION_TOOLS = {"discord_list_emojis", "discord_react", "discord_send_embed"} +READ_TOOLS = {"discord_read_channel", "discord_read_thread", "discord_get_message", "discord_read_story"} + + +class _RegistryCtx: + """Forwards the plugin's register_tool calls to Hermes' real registry.""" + + def __init__(self, registry) -> None: + self.registry = registry + self.names: list[str] = [] + + def register_tool(self, **kwargs) -> None: + self.registry.register(**kwargs) + self.names.append(kwargs["name"]) + + def register_hook(self, *_args) -> None: + pass + + +@unittest.skipUnless(_HERMES is not None, "set HERMES_AGENT_PATH to a Hermes checkout") +class RealHermesActionTests(unittest.TestCase): + def setUp(self) -> None: + self.session_context, self.registry, self.toolsets, self.propagate = _HERMES # type: ignore[misc] + + def bind(self, **values): + self.session_context.set_session_vars(**values) + # Back to "never bound" so later tests fall through to os.environ. + self.addCleanup(self.session_context.reset_session_vars) + + def test_actions_join_hermes_discord_toolset_and_nothing_else(self) -> None: + ctx = _RegistryCtx(self.registry) + plugin.register(ctx) + for name in ctx.names: + self.addCleanup(self.registry.deregister, name) + resolve = self.toolsets.resolve_toolset + + self.assertEqual(set(resolve("discord")), {"discord"} | ACTION_TOOLS) + self.assertEqual(resolve("discord", include_registry=False), ["discord"]) + # `discord` is a core toolset, so Hermes never treats it as a plugin + # toolset that defaults on; a profile must name it to get it. + self.assertNotIn("discord", self.toolsets._get_plugin_toolset_names()) + self.assertTrue(READ_TOOLS <= set(resolve("messaging"))) + self.assertFalse(ACTION_TOOLS & set(resolve("messaging"))) + for composite in ("hermes-telegram", "hermes-cli", "hermes-api-server"): + with self.subTest(composite=composite): + self.assertFalse(ACTION_TOOLS & set(resolve(composite))) + # No other static toolset carries the actions. (A profile whose config + # names a bundle such as hermes-discord still gets them: Hermes maps the + # bundle's `discord` tool back to the `discord` toolset, exactly as it + # does for its own discord tool.) + for composite in self.toolsets.TOOLSETS: + if composite == "discord": + continue + with self.subTest(composite=composite): + self.assertFalse(ACTION_TOOLS & set(resolve(composite))) + self.assertTrue(ACTION_TOOLS <= set(resolve("all"))) + + def test_scope_reads_the_session_the_gateway_binds(self) -> None: + self.bind(platform="discord", chat_id=CHANNEL, scope_id=GUILD, message_id=TRIGGER, parent_chat_id=PARENT) + scope = actions.current_scope(actions.session_lookup()) + self.assertEqual(scope, actions.ChannelScope(GUILD, CHANNEL, TRIGGER, PARENT)) + + def test_scope_follows_the_turn_into_tool_worker_threads(self) -> None: + self.bind(platform="discord", chat_id=CHANNEL, scope_id=GUILD, message_id=TRIGGER) + seen: list = [] + worker = threading.Thread(target=self.propagate(lambda: seen.append(actions.current_scope(actions.session_lookup())))) + worker.start() + worker.join() + self.assertEqual(seen, [actions.ChannelScope(GUILD, CHANNEL, TRIGGER, None)]) + + def test_other_platforms_and_cron_are_refused(self) -> None: + self.bind(platform="telegram", chat_id=CHANNEL) + self.assertIsInstance(actions.current_scope(actions.session_lookup()), actions.Refusal) + self.bind(platform="discord", chat_id=CHANNEL, cron_session="1") + self.assertIsInstance(actions.current_scope(actions.session_lookup()), actions.Refusal) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hermes_contract.py b/tests/test_hermes_contract.py index c3651f8..cba4707 100644 --- a/tests/test_hermes_contract.py +++ b/tests/test_hermes_contract.py @@ -142,18 +142,20 @@ def setUp(self) -> None: def test_register_binds_to_real_tool_signature(self) -> None: # register() ran in setUp through ContractCtx without TypeError, which # already proves signature compatibility. Assert the surface explicitly. - names = {c["name"] for c in self.ctx.tool_calls} + toolsets = {c["name"]: c["toolset"] for c in self.ctx.tool_calls} self.assertEqual( - names, + toolsets, { - "discord_read_channel", - "discord_read_thread", - "discord_get_message", - "discord_read_story", + "discord_read_channel": "messaging", + "discord_read_thread": "messaging", + "discord_get_message": "messaging", + "discord_read_story": "messaging", + "discord_list_emojis": "discord", + "discord_react": "discord", + "discord_send_embed": "discord", }, ) for call in self.ctx.tool_calls: - self.assertEqual(call["toolset"], "messaging") schema = call["schema"] self.assertIsInstance(schema, dict) # Hermes convention: args live under `parameters`, NOT at the top @@ -185,8 +187,16 @@ def test_tool_handlers_accept_args_dict_plus_kwargs_and_return_json(self) -> Non "message_id_or_url": "https://discord.com/channels/1/2/3" }, "discord_read_story": {}, + "discord_list_emojis": {}, + "discord_react": {"emoji": "πŸ”₯"}, + "discord_send_embed": {"title": "t"}, } - with _cleared_token_env(): + with _cleared_token_env() as env: + # A Discord session is bound so the actions get past their + # channel-scope check and reach the token check, offline. + env["HERMES_SESSION_PLATFORM"] = "discord" + env["HERMES_SESSION_CHAT_ID"] = "2" * 18 + env["HERMES_SESSION_MESSAGE_ID"] = "3" * 18 for call in self.ctx.tool_calls: handler = call["handler"] # hermes invokes handlers as handler(args, **kwargs); extra diff --git a/tests/test_plugin_registration.py b/tests/test_plugin_registration.py index 2e39281..eb187ae 100644 --- a/tests/test_plugin_registration.py +++ b/tests/test_plugin_registration.py @@ -25,31 +25,39 @@ def register_hook(self, name, handler) -> None: class RegistrationTests(unittest.TestCase): - def test_registers_read_only_tools_and_hook(self) -> None: + def test_registers_reads_actions_and_hook(self) -> None: plugin = load_plugin_module() ctx = FakeCtx() summary = plugin.register(ctx) + # Reads join the public `messaging` toolset. The three actions join + # Hermes' own `discord` toolset, so only profiles that already turn + # that toolset on for Discord ever see them. self.assertEqual( - {tool["name"] for tool in ctx.tools}, + {tool["name"]: tool["toolset"] for tool in ctx.tools}, { - "discord_read_channel", - "discord_read_thread", - "discord_get_message", - "discord_read_story", + "discord_read_channel": "messaging", + "discord_read_thread": "messaging", + "discord_get_message": "messaging", + "discord_read_story": "messaging", + "discord_list_emojis": "discord", + "discord_react": "discord", + "discord_send_embed": "discord", }, ) - self.assertEqual({tool["toolset"] for tool in ctx.tools}, {"messaging"}) self.assertIn(("pre_llm_call", plugin.hooks.inject_discord_read_hint), ctx.hooks) self.assertEqual( summary, RegistrationSummary( tools=( "discord_get_message", + "discord_list_emojis", + "discord_react", "discord_read_channel", "discord_read_story", "discord_read_thread", + "discord_send_embed", ), hooks=("pre_llm_call",), ), diff --git a/uv.lock b/uv.lock index 66f59fe..6ec6ec5 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "discord-tools" -version = "0.2.0" +version = "0.3.0" source = { virtual = "." } dependencies = [ { name = "discord-py" }, From 3abcebda1eca7e1bde817fdd57092c9728cd3ddc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 05:23:32 +0000 Subject: [PATCH 2/3] docs: fold README into AGENTS.md README now points to AGENTS.md, which holds the tools, hook, environment, logging, registration, guardrails and validation notes. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 156 ++++++++++++++++++++++++++++++++++++++++++++---------- README.md | 121 +----------------------------------------- 2 files changed, 131 insertions(+), 146 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b7f84f7..176cd4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,22 +1,128 @@ # hermes-plugin-discord-tools -Discord reading tools, plus three channel-scoped actions, for Hermes -Discord-facing agents. - -## Current surface - -- `discord_read_channel`, `discord_read_thread`, `discord_get_message`, and - `discord_read_story` (toolset `messaging`) return JSON and only read Discord - content the configured bot token can already access. -- `discord_list_emojis`, `discord_react`, and `discord_send_embed` (toolset - `discord`, in `actions.py`) are the only write paths. They act only in the - channel the bot is replying in, taken from the Hermes session - (`HERMES_SESSION_*`), never from model arguments. -- `discord_read_story` reads preconfigured story threads from - `DISCORD_TOOLS_STORY_THREADS_JSON` or `DISCORD_TOOLS_STORY_THREAD_ID`; keep - that configuration static and env/file backed. -- The plugin registers one `pre_llm_call` hint hook and no write hooks, - commands, skills, or memory integrations. +Discord tools for Hermes Discord-facing agents: reads, plus three small +actions held to the channel the bot is replying in. + +The plugin lets a bot use its existing Discord bot token to read a channel, +thread, or linked message that the bot can already access. It is intended as a +backstop when Hindsight or other memory processing is behind, especially for +story channels where the bot should be able to inspect the current source of +truth before answering. + +## Tools + +All tools return JSON with a `success` flag. Each tool's required argument name +is repeated in its description (not only the JSON schema) so the agent can call +it correctly even when a runtime surfaces the schema's `properties` as empty. + +### Reads (toolset `messaging`) + +- `discord_read_channel`: read recent messages from a Discord channel URL or ID + (`channel_id_or_url`). +- `discord_read_thread`: read recent messages from a Discord thread URL or ID + (`thread_id_or_url`). +- `discord_get_message`: fetch one linked message plus bounded prior context + (`message_id_or_url`). +- `discord_read_story`: read a **preconfigured** story thread by `name` (or with + no arguments when only one is configured). No Discord URL/ID needed: the + thread ID comes from `DISCORD_TOOLS_STORY_THREADS_JSON` or + `DISCORD_TOOLS_STORY_THREAD_ID`, so the agent never has to supply a snowflake + it does not have. Keep that configuration static and env/file backed. + +These four never write to Discord or to memory, and only read content the +configured bot token can already access. + +### Channel-scoped actions (toolset `discord`, in `actions.py`) + +- `discord_list_emojis`: this server's own custom emoji the bot can use, each + with a ready `usage` string (`<:name:id>`). Optional `query`, `limit`. +- `discord_react`: react with one emoji (`emoji`), any standard emoji or one of + this server's as `:name:` or `<:name:id>`. Reacts to the message being + answered, or to `message_id` when that message is in this same channel. +- `discord_send_embed`: post one embed card (`title` and/or `description`, + optional `url`, `color`, `fields`, `footer`, `image_url`, `thumbnail_url`) in + this channel, held to Discord's embed limits (`schemas.EMBED_LIMITS`), with + mentions suppressed. + +The channel, server and triggering message come from the Hermes session the +gateway binds for the turn (`HERMES_SESSION_*`), never from model arguments, so +a model cannot aim one of these at another channel. They refuse on other +platforms and in scheduled runs. Custom emoji from other servers are refused. +One incoming message can cause at most 5 reactions and 2 embeds +(`schemas.TURN_BUDGET`). + +They join Hermes' own `discord` toolset, so a profile gets them only where its +config turns that toolset on for Discord (`platform_toolsets.discord`), the same +switch as Hermes' built-in Discord tool. + +Bot permissions they need in the channel: **Add Reactions** and **Read Message +History** (react), **Send Messages** and **Embed Links** (embeds). Listing +emoji needs none beyond being in the server. Use External Emojis is not needed, +since only the server's own emoji are allowed. + +## Hook + +`pre_llm_call` injects a compact hint when the current turn mentions a Discord +channel/message link. It can also surface static story hints from +`DISCORD_TOOLS_STORY_HINTS` or `DISCORD_TOOLS_STORY_HINTS_JSON`. + +Example inline story hint config: + +```json +[ + { + "name": "Bea's House of Tea", + "keywords": ["bea's house of tea", "house of tea", "ember revealed"], + "hint": "Use discord_read_channel or discord_get_message on linked source channels before relying on stale memory." + } +] +``` + +If `DISCORD_TOOLS_STORY_HINTS_JSON` is a JSON string it is parsed directly. If +it is a filesystem path, the hook reads that local JSON file. + +This is the plugin's only hook. It registers no write hooks, commands, skills, +or memory integrations. + +## Environment + +- `DISCORD_BOT_TOKEN`: the bot token the Hermes gateway already loads, reused + for live Discord reads and the channel-scoped actions. `DISCORD_TOKEN` is + accepted as a fallback alias for standalone use. +- `DISCORD_TOOLS_ALLOWED_GUILDS`: optional comma-separated guild allowlist for + reads and actions. If unset, Discord access is bounded only by the bot + token's existing visibility. +- `DISCORD_TOOLS_MAX_MESSAGES`: optional default/max message limit, default 100. +- `DISCORD_TOOLS_MAX_CHARS`: optional result character budget, default 12000. +- `DISCORD_TOOLS_TIMEOUT_SECONDS`: optional live API timeout, default 20. +- `DISCORD_TOOLS_STORY_HINTS`: optional inline story hint JSON. +- `DISCORD_TOOLS_STORY_HINTS_JSON`: optional inline story hint JSON or path to a + local JSON file. +- `DISCORD_TOOLS_STORY_THREADS_JSON`: optional inline JSON (or path to a local + JSON file) listing preconfigured story threads for `discord_read_story`, e.g. + `[{"name":"House of Tea","thread_id":"123456789012345678","aliases":["bea"]}]`. +- `DISCORD_TOOLS_STORY_THREAD_ID`: optional single story thread ID for + `discord_read_story` when only one story is needed. + +## Logging + +The plugin logs under the `discord-tools` logger. On a rejected argument it logs +a `WARNING` with the offending value (truncated, never the token), and on a +successful read an `INFO` line with the resolved target. At startup, +`hermes-plugin-kit` emits one lifecycle receipt listing the seven tools and +`pre_llm_call` hook that it registered. To watch it in a pod: + +```bash +kubectl logs -f | grep discord-tools +``` + +## Registration + +Every tool uses `@tool`, the hint callback uses `@hook`, and +[`hermes-plugin-kit`](https://github.com/offendingcommit/hermes-plugin-kit) +owns the complete lifecycle through `register_plugin`. This keeps Hermes tool +schemas, handlers, validation, logging, JSON envelopes, and the startup +registration inventory under one contract. ## Guardrails @@ -40,23 +146,19 @@ Discord-facing agents. decorators. `register_plugin` owns the complete registration path and returns the exact `RegistrationSummary`; do not add direct `ctx.register_*` calls or legacy `register_all` wiring. -- The shared kit contract lives at: - https://github.com/offendingcommit/hermes-plugin-kit ## Validation ```bash make install make test +HERMES_AGENT_PATH= make test # adds the real-Hermes layer ``` -Run the real-Hermes layer too when a Hermes checkout is at hand: -`HERMES_AGENT_PATH= make test`. It binds sessions with Hermes' own -`set_session_vars` and registers into its real registry and toolsets. +The real-Hermes layer binds sessions with Hermes' own `set_session_vars` and +registers into its real registry and toolsets. It also checks the contract +against the real `PluginContext.register_tool` / `register_hook` signatures. +Registration tests reject direct lifecycle wiring and assert the exact kit +summary. Keep that coverage in place for registration changes. -The tests include a Hermes contract check against the real -`PluginContext.register_tool` / `register_hook` signatures when a local Hermes -checkout is available. Registration tests also reject direct lifecycle wiring -and assert the exact kit summary. Keep that coverage in place for registration -changes. Dev tooling is uv-native; dependencies live in `pyproject.toml`. diff --git a/README.md b/README.md index ac80bfa..c41aeef 100644 --- a/README.md +++ b/README.md @@ -3,122 +3,5 @@ Discord tools for Hermes Discord-facing agents: reads, plus three small actions held to the channel the bot is replying in. -The plugin lets a bot use its existing Discord bot token to read a channel, -thread, or linked message that the bot can already access. It is intended as a -backstop when Hindsight or other memory processing is behind, especially for -story channels where the bot should be able to inspect the current source of -truth before answering. - -## Tools - -- `discord_read_channel`: read recent messages from a Discord channel URL or ID - (`channel_id_or_url`). -- `discord_read_thread`: read recent messages from a Discord thread URL or ID - (`thread_id_or_url`). -- `discord_get_message`: fetch one linked message plus bounded prior context - (`message_id_or_url`). -- `discord_read_story`: read a **preconfigured** story thread by `name` (or with - no arguments when only one is configured). No Discord URL/ID needed β€” the - thread ID comes from env config, so the agent never has to supply a snowflake - it does not have. See `DISCORD_TOOLS_STORY_THREADS_JSON` below. - -These four never write to Discord or to memory. - -### Channel-scoped actions - -- `discord_list_emojis`: this server's own custom emoji the bot can use, each - with a ready `usage` string (`<:name:id>`). Optional `query`, `limit`. -- `discord_react`: react with one emoji (`emoji`), any standard emoji or one of - this server's as `:name:` or `<:name:id>`. Reacts to the message being - answered, or to `message_id` when that message is in this same channel. -- `discord_send_embed`: post one embed card (`title` and/or `description`, - optional `url`, `color`, `fields`, `footer`, `image_url`, `thumbnail_url`) in - this channel, held to Discord's embed limits, with mentions suppressed. - -The channel, server and triggering message come from the Hermes session the -gateway binds for the turn, never from model arguments, so a model cannot aim -one of these at another channel. They refuse on other platforms and in -scheduled runs. Custom emoji from other servers are refused. One incoming -message can cause at most 5 reactions and 2 embeds. - -They join Hermes' own `discord` toolset, so a profile gets them only where its -config turns that toolset on for Discord (`platform_toolsets.discord`), the same -switch as Hermes' built-in Discord tool. - -Bot permissions they need in the channel: **Add Reactions** and **Read Message -History** (react), **Send Messages** and **Embed Links** (embeds). Listing -emoji needs none beyond being in the server. Use External Emojis is not needed, -since only the server's own emoji are allowed. - -All tools return JSON with a `success` flag. Each tool's required argument name is repeated in its description (not -only the JSON schema) so the agent can call it correctly even when a runtime -surfaces the schema's `properties` as empty. - -## Logging - -The plugin logs under the `discord-tools` logger. On a rejected argument it logs -a `WARNING` with the offending value (truncated, never the token), and on a -successful read an `INFO` line with the resolved target. At startup, -`hermes-plugin-kit` emits one lifecycle receipt listing the seven tools and -`pre_llm_call` hook that it registered. To watch it in a pod: - -```bash -kubectl logs -f | grep discord-tools -``` - -## Hook - -`pre_llm_call` injects a compact hint when the current turn mentions a Discord -channel/message link. It can also surface static story hints from -`DISCORD_TOOLS_STORY_HINTS` or `DISCORD_TOOLS_STORY_HINTS_JSON`. - -Example inline story hint config: - -```json -[ - { - "name": "Bea's House of Tea", - "keywords": ["bea's house of tea", "house of tea", "ember revealed"], - "hint": "Use discord_read_channel or discord_get_message on linked source channels before relying on stale memory." - } -] -``` - -If `DISCORD_TOOLS_STORY_HINTS_JSON` is a JSON string it is parsed directly. If -it is a filesystem path, the hook reads that local JSON file. - -## Environment - -- `DISCORD_BOT_TOKEN`: the bot token the Hermes gateway already loads β€” reused - for live Discord reads and the channel-scoped actions. `DISCORD_TOKEN` is accepted as a fallback alias for - standalone use. -- `DISCORD_TOOLS_ALLOWED_GUILDS`: optional comma-separated guild allowlist for - reads and actions. If unset, Discord access is bounded only by the bot - token's existing visibility. -- `DISCORD_TOOLS_MAX_MESSAGES`: optional default/max message limit, default 100. -- `DISCORD_TOOLS_MAX_CHARS`: optional result character budget, default 12000. -- `DISCORD_TOOLS_TIMEOUT_SECONDS`: optional live API timeout, default 20. -- `DISCORD_TOOLS_STORY_HINTS`: optional inline story hint JSON. -- `DISCORD_TOOLS_STORY_HINTS_JSON`: optional inline story hint JSON or path to a - local JSON file. -- `DISCORD_TOOLS_STORY_THREADS_JSON`: optional inline JSON (or path to a local - JSON file) listing preconfigured story threads for `discord_read_story`, e.g. - `[{"name":"House of Tea","thread_id":"123456789012345678","aliases":["bea"]}]`. -- `DISCORD_TOOLS_STORY_THREAD_ID`: optional single story thread ID for - `discord_read_story` when only one story is needed. - -## Registration - -Every tool uses `@tool`, the hint callback uses `@hook`, and -[`hermes-plugin-kit`](https://github.com/offendingcommit/hermes-plugin-kit) -owns the complete lifecycle through `register_plugin`. This keeps Hermes tool -schemas, handlers, validation, logging, JSON envelopes, and the startup -registration inventory under one contract. - -## Validation - -```bash -make install -make test -HERMES_AGENT_PATH= make test # adds the real-Hermes layer -``` +Everything about the plugin (tools, hook, environment, logging, guardrails and +validation) lives in [AGENTS.md](AGENTS.md). From 432c6a2f62408a581ed49e4b3b12494fdd976275 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 05:23:32 +0000 Subject: [PATCH 3/3] chore(deps): pin hermes-plugin-kit to latest main (ca9e1c9) Moves from 90da8eb to ca9e1c9, which adds ToolError, reads reserved tool names without importing Hermes, and pins its contract lane to Hermes bf0203a7 (the revision this plugin's real-Hermes layer already runs on). Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 018fba9..7980888 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,4 +21,4 @@ dev = [ package = false [tool.uv.sources] -hermes-plugin-kit = { git = "https://github.com/offendingcommit/hermes-plugin-kit.git", rev = "90da8eb42526c71d22155ad84a0cd55cc2b444c8" } +hermes-plugin-kit = { git = "https://github.com/offendingcommit/hermes-plugin-kit.git", rev = "ca9e1c9ad95c6414bd26c7579ca22e25b40ec9d1" } diff --git a/uv.lock b/uv.lock index 6ec6ec5..869a0a8 100644 --- a/uv.lock +++ b/uv.lock @@ -199,7 +199,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "discord-py", specifier = ">=2.4" }, - { name = "hermes-plugin-kit", git = "https://github.com/offendingcommit/hermes-plugin-kit.git?rev=90da8eb42526c71d22155ad84a0cd55cc2b444c8" }, + { name = "hermes-plugin-kit", git = "https://github.com/offendingcommit/hermes-plugin-kit.git?rev=ca9e1c9ad95c6414bd26c7579ca22e25b40ec9d1" }, ] [package.metadata.requires-dev] @@ -281,7 +281,7 @@ wheels = [ [[package]] name = "hermes-plugin-kit" version = "0.9.0" -source = { git = "https://github.com/offendingcommit/hermes-plugin-kit.git?rev=90da8eb42526c71d22155ad84a0cd55cc2b444c8#90da8eb42526c71d22155ad84a0cd55cc2b444c8" } +source = { git = "https://github.com/offendingcommit/hermes-plugin-kit.git?rev=ca9e1c9ad95c6414bd26c7579ca22e25b40ec9d1#ca9e1c9ad95c6414bd26c7579ca22e25b40ec9d1" } dependencies = [ { name = "pyyaml" }, ]