Files
hermes-agent/gateway/session_discovery.py
unsupportedpastels 4b6a8edd6a fix(plugins): fire pre_command in the gateway for every local command
After the cutover no local surface fired pre_command where the command runs.
slash.exec and command.dispatch (classic CLI forwards, Ink TUI, Desktop) never
fired it, and the classic CLI fired it from its own second copy of the plugin.

- The gateway fires pre_command for every recognized command a local session
  runs, under the session's profile: before the handler for commands it runs
  itself (slash.exec, command.dispatch; an accepted TUI read fires once inside
  the read path), and for commands the classic CLI runs in its own process
  through the new command.observe (plain data: the command as typed and its
  arguments). command.observe replies first, so the CLI never waits on a
  plugin. The hook arguments keep main's values: surface and platform "cli"
  on every local surface, session_key the session id.
- It fires only for commands that run. A busy rejection or a named refusal
  fires nothing; during a turn it fires when the busy dispatcher accepts the
  command, so a refused /goal, /loop or empty /queue or /steer fires nothing
  either. Every command that does run mid-turn fires, as main's CLI did,
  except messaging's escape hatches (/stop and the approval controls).
- Each delivery waits out its callback on its own thread, never the shared
  executor, with at most one delivery in flight per session: one session's
  deliveries fire in order and a slow callback never holds up another
  session's. The hook dispatcher's existing bounds apply
  (plugins.hook_callback_timeout and its abandoned-worker cap), and with
  plugins.isolation: host the hook runs in the plugin host. pre_command takes
  that bounded path everywhere, so off the gateway its callbacks also run on a
  worker thread.
- On a gateway session the classic CLI loads no plugin code. It reads skills,
  plugin commands and plugin toolsets from the gateway (commands.catalog,
  scoped to the session's own folder, and plugins.list) for /help, skill
  dispatch and completion, /tools and the status and banner fallbacks. -s and
  skills.auto_load are rendered in the gateway, and /reload-skills and
  /skills install rescan there and drop the CLI's cached catalog. These reads
  are cached per gateway life and never served once the connection has hung
  up. The "Unknown toolsets" warning comes from the gateway (a new
  unknown_toolsets field when the session opens). An older gateway without
  command.observe gets one named notice, and nothing fires locally.
- The canonical gateway connection serves plugins.list for its profile:
  loaded plugins with tool/hook/command counts, load error, toolsets and
  portable MCP server names (optional fields added to the contract; TS and
  OpenRPC regenerated). On a gateway session the CLI's /plugins reads it
  instead of this process's plugin manager. Off the gateway the in-process
  paths are unchanged.

Key-less inject_message (B2-11), which the classic CLI's own plugin copy
used to serve, is handled in the next commit.

Refs #134889 (PLG-7)
Refs #139523
2026-10-16 19:39:48 -04:00

65 lines
3.5 KiB
Python

"""Authenticated, profile-bound discovery without legacy execution dispatch."""
import asyncio
from pathlib import Path
from hermes_state_runtime import RuntimeStoreError
async def discover_commands(authority, actor, params, *, completion=False):
if 'session:read' not in actor.capabilities or actor.profile_id != authority.profile_id:
raise RuntimeStoreError('permission_denied')
allowed = {'profile', 'text', 'session_id'} if completion else {'profile', 'session_id'}
if (not isinstance(params, dict) or set(params) - allowed
or any(not isinstance(value, str) for value in params.values())):
raise RuntimeStoreError('invalid_params')
scope = None
if params.get('session_id'):
# Project skills resolve from the session's workspace, not the gateway process cwd.
from gateway.session_commands import _session_workspace
from gateway.session_contract import SessionRef
ref = SessionRef(authority.profile_id, params['session_id'])
authority.authorize(actor, ref, 'session:read')
scope = _session_workspace(authority.runner, authority.sessions[ref.session_id].source)
def discover():
from hermes_cli.profiles import profile_matches_home
home = Path(authority.profile_id)
if params.get('profile') and not profile_matches_home(params['profile'], home):
raise RuntimeStoreError('profile_mismatch')
from gateway.run import _profile_runtime_scope
from tui_gateway.command_discovery import command_catalog, slash_completions
with _profile_runtime_scope(home):
return (slash_completions(params.get('text', ''), scope=scope) if completion
else command_catalog(scope=scope))
return await asyncio.to_thread(discover)
async def list_plugins(authority, actor, params):
"""``plugins.list`` for this profile's own plugin manager: what the gateway loaded, with each
plugin's tool/hook/command counts and load error (the classic CLI's ``/plugins`` reads it, so the
CLI process imports no plugin code). Plain data only."""
if 'session:read' not in actor.capabilities or actor.profile_id != authority.profile_id:
raise RuntimeStoreError('permission_denied')
if params:
raise RuntimeStoreError('invalid_params')
def rows():
from gateway.run import _profile_runtime_scope
from hermes_cli.plugins import discover_plugins, get_plugin_manager
from hermes_cli.plugins import get_plugin_toolsets
with _profile_runtime_scope(Path(authority.profile_id)):
discover_plugins() # idempotent: the profile's plugins are normally loaded already
manager = get_plugin_manager()
loaded, toolsets = manager.list_plugins(), get_plugin_toolsets()
portable = sorted(manager.get_portable_mcp_servers())
return {'plugins': [{'name': str(p['name']), 'key': str(p['key']), 'version': str(p['version'] or ''),
'enabled': bool(p['enabled']), 'tools': int(p['tools']), 'hooks': int(p['hooks']),
'commands': int(p['commands']), 'error': str(p['error'] or '')} for p in loaded],
# The CLI's /tools and its completion validate plugin toolsets against these.
'toolsets': [{'key': str(key), 'label': str(label), 'description': str(desc or '')}
for key, label, desc in toolsets],
'portable_mcp_servers': [str(name) for name in portable]}
return await asyncio.to_thread(rows)