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
76 changes: 62 additions & 14 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -8362,6 +8362,49 @@ async def _deliver_platform_notice(self, source, content: str) -> None:

await adapter.send(source.chat_id, content, metadata=metadata)

async def _dispatch_plugin_command(
self,
command: str,
event: MessageEvent,
session_key: str,
) -> Optional[str]:
"""Dispatch a plugin slash command with gateway context, if registered."""
try:
from hermes_cli.plugins import invoke_plugin_command

plugin_result = invoke_plugin_command(
command.replace("_", "-"),
event.get_command_args().strip(),
event=event,
gateway=self,
source=event.source,
session_key=session_key,
)
if asyncio.iscoroutine(plugin_result):
plugin_result = await plugin_result
return str(plugin_result) if plugin_result else None
except Exception as e:
logger.warning("Plugin command dispatch failed: %s", e)
return None

async def _dispatch_active_session_plugin_command(
self,
command: str,
event: MessageEvent,
session_key: str,
) -> Optional[str]:
"""Dispatch a plugin command during an active session when it opts in."""
try:
from hermes_cli.plugins import plugin_command_allows_active_session_bypass

normalized = command.replace("_", "-")
if not plugin_command_allows_active_session_bypass(normalized):
return None
return await self._dispatch_plugin_command(normalized, event, session_key)
except Exception as e:
logger.warning("Active-session plugin command dispatch failed: %s", e)
return None

async def _handle_message(self, event: MessageEvent) -> Optional[str]:
"""
Handle an incoming message from any platform.
Expand Down Expand Up @@ -8740,6 +8783,15 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]:
_evt_cmd = event.get_command()

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 dispatcher is not reached for normal busy-session plugin commands: BasePlatformAdapter.handle_message() queues an active-session event unless should_bypass_active_session(cmd) succeeds (gateway/platforms/base.py:4675-4731), and that predicate only uses built-in resolve_command() (hermes_cli/commands.py:389-409). Please wire a shared metadata-aware predicate into the adapter guard and add an adapter-level integration test.

_cmd_def_inner = _resolve_cmd_inner(_evt_cmd) if _evt_cmd else None

if _evt_cmd:
_plugin_busy_result = await self._dispatch_active_session_plugin_command(
_evt_cmd,
event,
_quick_key,
)
if _plugin_busy_result is not None:
return _plugin_busy_result

# Slash command access control on the running-agent fast-path.
# Mirrors the cold-path gate further below so non-admin users
# can't bypass gating just because an agent happens to be busy.
Expand Down Expand Up @@ -9552,20 +9604,16 @@ async def _do_undo():

# Plugin-registered slash commands
if command:
try:
from hermes_cli.plugins import get_plugin_command_handler
# Normalize underscores to hyphens so Telegram's underscored
# autocomplete form matches plugin commands registered with
# hyphens. See hermes_cli/commands.py:_build_telegram_menu.
plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
if plugin_handler:
user_args = event.get_command_args().strip()
result = plugin_handler(user_args)
if asyncio.iscoroutine(result):
result = await result
return str(result) if result else None
except Exception as e:
logger.warning("Plugin command dispatch failed: %s", e)
# Normalize underscores to hyphens so Telegram's underscored
# autocomplete form matches plugin commands registered with
# hyphens. See hermes_cli/commands.py:_build_telegram_menu.
plugin_result = await self._dispatch_plugin_command(
command,
event,
_quick_key,
)
if plugin_result is not None:
return plugin_result

# Skill slash commands: /skill-name loads the skill and sends to agent.
# resolve_skill_command_key() handles the Telegram underscore/hyphen
Expand Down
40 changes: 38 additions & 2 deletions hermes_cli/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,10 +530,15 @@ def register_command(
handler: Callable,
description: str = "",
args_hint: str = "",
*,
active_session_bypass: bool = False,
wants_context: bool = False,
) -> None:
"""Register a slash command (e.g. ``/lcm``) available in CLI and gateway sessions.

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 public registration option also needs to be accepted and stored by the context-engine collector (plugins/context_engine/__init__.py:216-262), which independently implements register_command() and directly constructs plugin-command metadata.


The handler signature is ``fn(raw_args: str) -> str | None``.
The default handler signature is ``fn(raw_args: str) -> str | None``.
Commands that set ``wants_context=True`` are called as
``fn(raw_args: str, **gateway_context)`` by gateway dispatchers.
It may also be an async callable β€” the gateway dispatch handles both.

Unlike ``register_cli_command()`` (which creates ``hermes <subcommand>``
Expand Down Expand Up @@ -575,6 +580,8 @@ def register_command(
"description": description or "Plugin command",
"plugin": self.manifest.name,
"args_hint": (args_hint or "").strip(),
"active_session_bypass": bool(active_session_bypass),
"wants_context": bool(wants_context),
}
logger.debug("Plugin %s registered command: /%s", self.manifest.name, clean)

Expand Down Expand Up @@ -2162,12 +2169,41 @@ def get_plugin_context_engine():
return _ensure_plugins_discovered()._context_engine


def get_plugin_command_entry(name: str) -> Optional[dict]:
"""Return metadata for a plugin-registered slash command, if present."""
entry = _ensure_plugins_discovered()._plugin_commands.get(name)
return dict(entry) if entry else None


def get_plugin_command_handler(name: str) -> Optional[Callable]:
"""Return the handler for a plugin-registered slash command, or ``None``."""
entry = _ensure_plugins_discovered()._plugin_commands.get(name)
entry = get_plugin_command_entry(name)
return entry["handler"] if entry else None


def plugin_command_allows_active_session_bypass(name: str) -> bool:
"""Return True when a plugin command may run while a session is busy."""
entry = get_plugin_command_entry(name)
return bool(entry and entry.get("active_session_bypass"))


def invoke_plugin_command(name: str, raw_args: str, **gateway_context: Any) -> Any:
"""Invoke a plugin slash command with optional gateway context.

Legacy commands receive only ``raw_args``. Commands registered with
``wants_context=True`` receive ``raw_args`` plus the provided keyword
context, allowing gateway plugins to inspect the triggering event without
changing the default one-argument command contract.
"""
entry = get_plugin_command_entry(name)
if not entry:
return None
handler = entry["handler"]
if entry.get("wants_context"):
return handler(raw_args, **gateway_context)
return handler(raw_args)


_PLUGIN_COMMAND_AWAIT_TIMEOUT_SECS = 30.0


Expand Down
81 changes: 81 additions & 0 deletions tests/test_gateway_plugin_command_dispatch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import pytest

from gateway.config import Platform
from gateway.platforms.base import MessageEvent, MessageType
from gateway.run import GatewayRunner
from gateway.session import SessionSource
from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest


def _event(text="/context-cmd now"):
source = SessionSource(
platform=Platform.TELEGRAM,
chat_id="chat-1",
user_id="user-1",
user_name="User",
chat_type="dm",
)
return MessageEvent(text=text, message_type=MessageType.TEXT, source=source)


def _register_context_command(monkeypatch, *, active_session_bypass=False):
manager = PluginManager()
ctx = PluginContext(PluginManifest(name="example", key="example"), manager)
seen = {}

def handler(raw_args, *, event=None, gateway=None, source=None, session_key=None):
seen.update(
raw_args=raw_args,
event=event,
gateway=gateway,
source=source,
session_key=session_key,
)
return "plugin-ok"

ctx.register_command(
"context-cmd",
handler,
wants_context=True,
active_session_bypass=active_session_bypass,
)
monkeypatch.setattr("hermes_cli.plugins._ensure_plugins_discovered", lambda force=False: manager)
return seen


@pytest.mark.asyncio
async def test_gateway_dispatches_plugin_command_with_context(monkeypatch):
seen = _register_context_command(monkeypatch)
runner = object.__new__(GatewayRunner)
event = _event()

result = await runner._dispatch_plugin_command("context-cmd", event, "session-1")

assert result == "plugin-ok"
assert seen["raw_args"] == "now"
assert seen["event"] is event
assert seen["gateway"] is runner
assert seen["source"] is event.source
assert seen["session_key"] == "session-1"


@pytest.mark.asyncio
async def test_busy_path_plugin_command_bypasses_active_session_when_registered(monkeypatch):
_register_context_command(monkeypatch, active_session_bypass=True)
runner = object.__new__(GatewayRunner)
event = _event()

result = await runner._dispatch_active_session_plugin_command("context-cmd", event, "session-1")

assert result == "plugin-ok"


@pytest.mark.asyncio
async def test_busy_path_plugin_command_without_bypass_falls_through(monkeypatch):
_register_context_command(monkeypatch, active_session_bypass=False)
runner = object.__new__(GatewayRunner)
event = _event()

result = await runner._dispatch_active_session_plugin_command("context-cmd", event, "session-1")

assert result is None
89 changes: 89 additions & 0 deletions tests/test_plugin_command_dispatch_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest


def _context():
manager = PluginManager()
manifest = PluginManifest(name="example", key="example")
return PluginContext(manifest, manager), manager


def test_plugin_command_registration_records_active_session_bypass():
ctx, manager = _context()

def handler(raw_args):
return f"handled {raw_args}"

ctx.register_command("queue-status", handler, active_session_bypass=True)

assert manager._plugin_commands["queue-status"]["active_session_bypass"] is True


def test_plugin_command_registration_defaults_to_no_active_session_bypass():
ctx, manager = _context()

def handler(raw_args):
return f"handled {raw_args}"

ctx.register_command("ordinary", handler)

assert manager._plugin_commands["ordinary"]["active_session_bypass"] is False


def test_plugin_command_can_request_gateway_context(monkeypatch):
ctx, manager = _context()
monkeypatch.setattr("hermes_cli.plugins._ensure_plugins_discovered", lambda force=False: manager)
seen = {}

def handler(raw_args, *, event=None, gateway=None):
seen["raw_args"] = raw_args
seen["event"] = event
seen["gateway"] = gateway
return "ok"

ctx.register_command("context-cmd", handler, wants_context=True)

from hermes_cli.plugins import invoke_plugin_command

result = invoke_plugin_command("context-cmd", "now", event="event-object", gateway="gateway-object")

assert result == "ok"
assert seen == {
"raw_args": "now",
"event": "event-object",
"gateway": "gateway-object",
}


def test_plugin_command_without_context_keeps_legacy_one_arg_call(monkeypatch):
ctx, manager = _context()
monkeypatch.setattr("hermes_cli.plugins._ensure_plugins_discovered", lambda force=False: manager)
seen = []

def handler(raw_args):
seen.append(raw_args)
return "ok"

ctx.register_command("legacy", handler)

from hermes_cli.plugins import invoke_plugin_command

result = invoke_plugin_command("legacy", "args", event="ignored")

assert result == "ok"
assert seen == ["args"]


def test_async_plugin_command_context_result_can_be_resolved(monkeypatch):
ctx, manager = _context()
monkeypatch.setattr("hermes_cli.plugins._ensure_plugins_discovered", lambda force=False: manager)

async def handler(raw_args, *, event=None):
return f"{raw_args}:{event}"

ctx.register_command("async-cmd", handler, wants_context=True)

from hermes_cli.plugins import invoke_plugin_command, resolve_plugin_command_result

result = invoke_plugin_command("async-cmd", "go", event="evt")

assert resolve_plugin_command_result(result) == "go:evt"