Skip to content

The agent that grows with you

fix(plugins): fire pre_command in the gateway for every local command

unsupportedpastels4b6a8edd6a43
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 5bd19e218b9..cb774dce133 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4338,11 +4338,23 @@ export interface McpOauthCallbackResult {
export type PluginsListParams = Record<string, never>
export interface PluginsListResult {
plugins: LegacyPluginRow[]
+ toolsets?: PluginToolsetRow[] | null
+ portable_mcp_servers?: string[] | null
}
export interface LegacyPluginRow {
name: string
version: string
enabled: boolean
+ key?: string | null
+ tools?: number | null
+ hooks?: number | null
+ commands?: number | null
+ error?: string | null
+}
+export interface PluginToolsetRow {
+ key: string
+ label: string
+ description: string
}
/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */
export interface PluginsManageParams {
@@ -4561,6 +4573,15 @@ export interface SessionPruneResult {
routing_deleted?: number | null
skipped?: number | null
}
+export interface CommandObserveParams {
+ session_id: string
+ name: string
+ arg?: string | null
+ profile?: string | null
+}
+export interface CommandObserveResult {
+ queued: boolean
+}
export interface CanonicalSessionInfoParams {
session_id: string
}
@@ -4582,6 +4603,7 @@ export interface CanonicalSessionInfo {
tool_availability?: Record<string, unknown> | null
tool_availability_warnings?: string[] | null
browser_backend_notice?: string | null
+ unknown_toolsets?: string[] | null
source: string
model?: string | null
lazy: boolean
@@ -4948,6 +4970,7 @@ export interface CanonicalSnapshotInfo {
tool_availability?: Record<string, unknown> | null
tool_availability_warnings?: string[] | null
browser_backend_notice?: string | null
+ unknown_toolsets?: string[] | null
desktop_protocol: 'hermes-gateway-v1'
source?: string | null
model?: string | null
@@ -6667,6 +6690,8 @@ export interface CanonicalRpcMethods {
'bot_relay.deliver': { params: CanonicalBotDeliverParams; result: CanonicalBotDeliverResult }
/** Generation-fenced answer to a pending clarify prompt (empty answer = skipped). */
'clarify.respond': { params: ClarifyRespondParams; result: PromptResponseResult }
+ /** Fire-only: a recognized command the classic CLI runs in its own process; the gateway fires `pre_command` for it in the session's profile after replying (`queued` false: not fired). */
+ 'command.observe': { params: CommandObserveParams; result: CommandObserveResult }
'config.get': { params: ConfigGetParams; result: CanonicalConfigGetResult }
'config.set': { params: CanonicalConfigSetParams; result: ConfigSetResult }
/** Cancel a queued cron admission or latch cancellation on a started one. */
@@ -6735,6 +6760,7 @@ export const CANONICAL_RPC_METHODS = [
'approval.respond',
'bot_relay.deliver',
'clarify.respond',
+ 'command.observe',
'config.get',
'config.set',
'cron.cancel',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 4659f80afed..03b89d25563 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -10016,6 +10016,21 @@
"default": null,
"title": "Browser Backend Notice"
},
+ "unknown_toolsets": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Unknown Toolsets"
+ },
"source": {
"title": "Source",
"type": "string"
@@ -10702,6 +10717,21 @@
"default": null,
"title": "Browser Backend Notice"
},
+ "unknown_toolsets": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Unknown Toolsets"
+ },
"desktop_protocol": {
"const": "hermes-gateway-v1",
"title": "Desktop Protocol",
@@ -11920,6 +11950,63 @@
"title": "CommandDispatchResult",
"type": "object"
},
+ "CommandObserveParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "arg": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Arg"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "required": [
+ "session_id",
+ "name"
+ ],
+ "title": "CommandObserveParams",
+ "type": "object"
+ },
+ "CommandObserveResult": {
+ "additionalProperties": false,
+ "properties": {
+ "queued": {
+ "title": "Queued",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "queued"
+ ],
+ "title": "CommandObserveResult",
+ "type": "object"
+ },
"CommandResolveParams": {
"additionalProperties": false,
"properties": {
@@ -21601,6 +21688,66 @@
"enabled": {
"title": "Enabled",
"type": "boolean"
+ },
+ "key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Key"
+ },
+ "tools": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tools"
+ },
+ "hooks": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Hooks"
+ },
+ "commands": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Commands"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Error"
}
},
"required": [
@@ -27074,6 +27221,30 @@
"title": "PluginSettingFieldType",
"type": "string"
},
+ "PluginToolsetRow": {
+ "additionalProperties": false,
+ "properties": {
+ "key": {
+ "title": "Key",
+ "type": "string"
+ },
+ "label": {
+ "title": "Label",
+ "type": "string"
+ },
+ "description": {
+ "title": "Description",
+ "type": "string"
+ }
+ },
+ "required": [
+ "key",
+ "label",
+ "description"
+ ],
+ "title": "PluginToolsetRow",
+ "type": "object"
+ },
"PluginsAction": {
"enum": [
"list",
@@ -27103,6 +27274,36 @@
},
"title": "Plugins",
"type": "array"
+ },
+ "toolsets": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/PluginToolsetRow"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Toolsets"
+ },
+ "portable_mcp_servers": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Portable Mcp Servers"
}
},
"required": [
@@ -46538,6 +46739,24 @@
}
}
},
+ {
+ "name": "command.observe",
+ "summary": "Fire-only: a recognized command the classic CLI runs in its own process; the gateway fires `pre_command` for it in the session's profile after replying (`queued` false: not fired).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CommandObserveParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CommandObserveResult"
+ }
+ }
+ },
{
"name": "config.get",
"summary": "",
diff --git a/cli.py b/cli.py
index fef3a45a7db..03bfb891792 100644
--- a/cli.py
+++ b/cli.py
@@ -425,7 +425,6 @@ _single_query_finalize_attempted_session_ids: set[str | None] = set()
# the handed-off session.
_handed_off_session_ids: set[str | None] = set()
_active_agent_ref = None # active AIAgent, for memory-provider shutdown at exit
-_deferred_agent_startup_done = False
# Set once the TUI app starts (focus reporting + mouse tracking on); gates the on-exit
# terminal reset so non-TUI one-shot runs never emit codes for modes they never enabled.
_tui_input_modes_active = False
@@ -440,23 +439,6 @@ def _mark_tui_input_modes_active() -> None:
_tui_input_modes_active = True
-def _prepare_deferred_agent_startup() -> None:
- """Run Termux-deferred plugin discovery before the first real agent turn. MCP servers, shell
- hooks and outbound webhooks belong to the gateway that runs the turn (session policy)."""
- global _deferred_agent_startup_done
- if _deferred_agent_startup_done:
- return
- if os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
- return
- _deferred_agent_startup_done = True
- try:
- from hermes_cli.plugins import discover_plugins
-
- discover_plugins()
- except Exception:
- logger.warning("plugin discovery failed at deferred CLI startup", exc_info=True)
-
-
_signal_watchdog_armed = False
@@ -735,6 +717,14 @@ def get_skill_commands() -> dict:
return _ensure_skill_commands()
+def _session_skill_commands(cli) -> dict:
+ """Skill commands for ``cli``: on its gateway session the gateway's (its plugin skills included), so
+ this process scans no plugin to list them; otherwise this process's own."""
+ from hermes_cli import gateway_plugin_commands
+ found = gateway_plugin_commands.skills(cli)
+ return _ensure_skill_commands() if found is None else found
+
+
build_skill_invocation_message = _lazy_shim("agent.skill_commands", "build_skill_invocation_message")
build_preloaded_skills_prompt = _lazy_shim("agent.skill_commands", "build_preloaded_skills_prompt")
@@ -1170,14 +1160,6 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
from hermes_cli.observability.shared_metrics_events import record_slash_command
record_slash_command(command=canonical, surface=self._slash_metrics_surface)
- # Observer-only pre_command plugin hook (return values ignored; never raises).
- if _cmd_def is not None:
- from hermes_cli.plugins import fire_pre_command_hook
- fire_pre_command_hook(
- surface="cli", command=canonical, alias_used=_base_word, args_raw=_slash_args(cmd_original),
- session_key=getattr(self, "session_id", None), platform="cli",
- )
-
# A bare `/resume` prompt is one-shot: any other command disarms it so a later
# number isn't swallowed as a stale selection.
# See #34584.
@@ -1189,11 +1171,22 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
self._pending_resume_sessions = None
entry = self._slash_handler(canonical)
+ from hermes_cli.gateway_setting_commands import run as run_gateway_setting
+ if entry is not None and run_gateway_setting(self, canonical, cmd_original):
+ return True # a per-session setting the gateway's handler applied (pre_command fired there)
+ # Observer-only pre_command plugin hook (return values ignored; never raises), fired by the gateway
+ # for a command this process runs (not a named refusal, not a command with no handler here).
+ from hermes_cli.gateway_cli_commands import REFUSED
+ from hermes_cli.gateway_plugin_commands import observe
+ runs = entry is not None and canonical not in REFUSED
+ if _cmd_def is not None and not observe(self, _base_word, _slash_args(cmd_original), runs=runs):
+ from hermes_cli.plugins import fire_pre_command_hook
+ fire_pre_command_hook(
+ surface="cli", command=canonical, alias_used=_base_word, args_raw=_slash_args(cmd_original),
+ session_key=getattr(self, "session_id", None), platform="cli",
+ )
if entry is None:
return self._process_unregistered_slash(cmd_original, cmd_lower)
- from hermes_cli.gateway_setting_commands import run as run_gateway_setting
- if run_gateway_setting(self, canonical, cmd_original):
- return True # a per-session setting the gateway's handler applied
from hermes_cli.gateway_cli_commands import run as run_gateway_command
if run_gateway_command(self, canonical, cmd_original):
return True # state the gateway session owns (checkpoints, .env, handoff)
@@ -1206,7 +1199,6 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
"""Slash input with no built-in handler; precedence: quick_commands -> plugins -> bundles -> skills -> prefix expansion."""
base_cmd = cmd_lower.split()[0]
bare = base_cmd.lstrip("/")
- skill_commands = _ensure_skill_commands()
skill_bundles = get_skill_bundles()
quick_commands = self.config.get("quick_commands", {})
user_args = cmd_original[len(base_cmd):].strip()
@@ -1218,6 +1210,7 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
except gateway_plugin_commands.CatalogUnavailable:
return True # printed; an unreadable catalog never selects a skill, bundle or expansion
gone = False
+ skill_commands = _session_skill_commands(self) # after lookup: the catalog its miss re-read
if plugin or (plugin is None and bare in _get_plugin_cmd_handler_names()):
gone = self._run_plugin_slash_command(base_cmd, user_args) is gateway_plugin_commands.GONE
if not gone:
@@ -1310,6 +1303,9 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
def _run_skill_slash_command(self, base_cmd: str, skill_info: dict, rest: str) -> None:
"""``/<skill> ...``; stacked ``/skill-a /skill-b do XYZ`` loads every leading skill (up to 5)."""
+ from hermes_cli import gateway_plugin_commands
+ if gateway_plugin_commands.run_skill(self, base_cmd, rest):
+ return # the gateway session's skill, loaded there
from agent.skill_commands import build_stacked_skill_invocation_message, split_stacked_skill_commands
# Interactive surface: stacked tokens resolve against the interactive
@@ -1518,16 +1514,14 @@ def _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url
for t in toolsets:
toolsets_list.extend([x.strip() for x in t.split(",")] if isinstance(t, str) else [str(t)])
elif not toolsets:
- # Coding posture inside a code workspace, else the shared platform resolver. Neither is a
- # pick: the gateway resolves both from the session's cwd, so this list only feeds the display.
+ # Coding posture inside a code workspace, else the profile default the gateway resolves (its
+ # platform resolver reads plugin toolsets, which only the gateway loads: adopted when the session
+ # opens). Neither is a pick: this list only feeds the display.
try:
from agent.coding_context import coding_selection
toolsets_list = coding_selection(platform="cli", config=CLI_CONFIG)
except Exception:
toolsets_list = None
- if toolsets_list is None:
- from hermes_cli.tools_config import _get_platform_tools
- toolsets_list = sorted(_get_platform_tools(CLI_CONFIG, "cli"))
parsed_skills = _parse_skills_argument(skills)
@@ -1568,6 +1562,12 @@ def _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url
if not auto_load_names:
cli._auto_load_skills_result = ("", [], [])
if parsed_skills or auto_load_names:
+ cli._preload_skills_requested = [*auto_load_names, *(s for s in parsed_skills if s not in auto_load_names)]
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ if isinstance(getattr(cli, "_session_db", None), GatewaySessionStore):
+ # The gateway session renders -s at creation and its agent loads skills.auto_load (plugin
+ # skills included); this process's prompt never reaches it, so nothing is loaded here.
+ return cli
# Load the skill payloads in the background: skill_view walks the full skills
# tree per skill (~0.5s for a large library) and the result is only consumed
# at agent init, not by the banner. finalize_preloaded_skills() joins the
@@ -1582,7 +1582,6 @@ def _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url
except Exception as exc: # surfaced by finalize
cli._preload_skills_error = exc
- cli._preload_skills_requested = [*auto_load_names, *(s for s in parsed_skills if s not in auto_load_names)]
cli._preload_skills_thread = threading.Thread(target=_load_preloaded_skills, name="skills-preload", daemon=True)
cli._preload_skills_thread.start()
return cli
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index 1528b62bd42..c4622a9a854 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -11,6 +11,7 @@ import logging
from typing import TYPE_CHECKING
import asyncio
import contextlib
+import contextvars
import json
import os
import time
@@ -47,6 +48,16 @@ def approval_input_words(input_key: str) -> tuple[str, ...]:
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
+# A local session's ``pre_command`` (gateway/session_commands.py), awaited by the mid-run dispatch once it
+# accepts a command and before it acts, so a refused one fires nothing. Unset on messaging.
+BUSY_ACCEPTED: contextvars.ContextVar = contextvars.ContextVar("busy_accepted", default=None)
+
+
+async def _busy_accepted() -> None:
+ hook = BUSY_ACCEPTED.get()
+ if hook is not None:
+ await hook()
+
def _strip_slot(text: str, slot: str) -> Optional[str]:
"""Remainder after ``slot`` when ``text`` starts with it as a WHOLE slot, else None.
@@ -1048,27 +1059,38 @@ class GatewayBusySessionMixin:
1. ``busy_handler`` — special mid-run variant (e.g. /goal's control-verb whitelist, /queue's FIFO
enqueue, /model's custom reject text). 2. 3. See #5057, #6252, #10370.
"""
- name = cmd_def.name
+ kind, target = self._busy_slash_route(cmd_def)
+ if kind == "special":
+ return await getattr(self, target)(event, quick_key, source)
+ if kind == "plain":
+ await _busy_accepted()
+ async with self._async_profile_scope_for_source(source):
+ return await target(event)
+ return t(target) if target else t("gateway.busy.slash_rejected", command=cmd_def.name)
+
+ def _busy_slash_route(self, cmd_def):
+ """``(kind, target)`` :meth:`_dispatch_busy_slash_command` takes mid-run: ``special`` (the
+ variant's method name), ``plain`` (the normal handler) or ``reject`` (its text key, None for the
+ catch-all). A ``special`` variant may still refuse its arguments: it awaits ``_busy_accepted``
+ only once it accepts."""
policy = getattr(cmd_def, "busy_policy", "reject")
handler_key = getattr(cmd_def, "busy_handler", None)
if handler_key:
special = self._BUSY_SPECIAL_HANDLERS.get(handler_key)
if special is not None:
- return await getattr(self, special)(event, quick_key, source)
+ return "special", special
reject_key = self._BUSY_REJECT_TEXT.get(handler_key)
if reject_key is not None:
- return t(reject_key)
+ return "reject", reject_key
if policy in ("dispatch", "interrupt_then_dispatch"):
- plain = self._gateway_plain_command_handlers().get(name)
+ plain = self._gateway_plain_command_handlers().get(cmd_def.name)
if plain is not None:
- async with self._async_profile_scope_for_source(source):
- return await plain(event)
+ return "plain", plain
logger.warning(
"busy_policy=%s for /%s has no mid-run handler — "
- "falling back to busy-reject", policy, name,
+ "falling back to busy-reject", policy, cmd_def.name,
)
-
- return t("gateway.busy.slash_rejected", command=name)
+ return "reject", None
async def _handle_pause_command(self, event: MessageEvent):
"""`/pause [reason]` engages the global emergency stop; `/pause off` lifts it (the estop gate
@@ -1089,16 +1111,19 @@ class GatewayBusySessionMixin:
async def _busy_start_command(self, event: MessageEvent, quick_key: str, source):
# Telegram's /start is a platform ping (bot launch/deep-link), not a user command.
+ await _busy_accepted()
logger.info("Ignoring /start platform ping for active session %s", quick_key)
return ""
async def _busy_egress_command(self, event: MessageEvent, quick_key: str, source):
from hermes_cli.proxy_cli import format_status_text
+ await _busy_accepted()
return format_status_text()
async def _busy_stop_command(self, event: MessageEvent, quick_key: str, source):
# Hard-kill: a soft interrupt can't reach a truly hung executor thread.
from gateway.run import _INTERRUPT_REASON_STOP
+ await _busy_accepted()
await self._interrupt_and_clear_session(
quick_key, source, interrupt_reason=_INTERRUPT_REASON_STOP, invalidation_reason="stop_command",
)
@@ -1109,6 +1134,7 @@ class GatewayBusySessionMixin:
# /reset and /new bypass the running-agent guard (else they'd queue as user text and replay
# into the same broken history); clear pending messages so the old text doesn't replay.
from gateway.run import _INTERRUPT_REASON_RESET
+ await _busy_accepted()
# Interrupt the agent first, then clear the adapter's pending queue so the stale "/reset" text
# doesn't get re-processed as a user message after the interrupt completes. See #2170.
await self._interrupt_and_clear_session(
@@ -1123,6 +1149,7 @@ class GatewayBusySessionMixin:
has_media = bool(getattr(event, "media_urls", None))
if not queued_text and not has_media:
return t("gateway.queue.usage")
+ await _busy_accepted()
adapter = self._delivery_adapter_for(source)
if adapter:
self._enqueue_fifo(quick_key, MessageEvent(
@@ -1148,6 +1175,7 @@ class GatewayBusySessionMixin:
steer_text = event.get_command_args().strip()
if not steer_text:
return t("gateway.steer.usage")
+ await _busy_accepted()
_steer_state = self._peek_session_state(quick_key)
running_agent = _steer_state.turn.agent if _steer_state else None
@@ -1185,6 +1213,7 @@ class GatewayBusySessionMixin:
from hermes_cli.goal_command import is_goal_control
if is_goal_control(event.get_command_args() or ""):
+ await _busy_accepted()
return await self._handle_goal_command(event)
return t("gateway.busy.reject_goal")
@@ -1192,6 +1221,7 @@ class GatewayBusySessionMixin:
# Mirrors /goal: control verbs are safe mid-run; a new loop is rejected.
_loop_arg = (event.get_command_args() or "").strip().lower()
if not _loop_arg or _loop_arg in {"status", "pause", "resume", "stop", "clear", "cancel", "help", "--help", "-h"}:
+ await _busy_accepted()
return await self._handle_loop_command(event)
return t("gateway.busy.reject_loop")
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index 528b4a1d7f0..9416328b23c 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -177,22 +177,31 @@ async def _run_runner_command(runner, live, name, arg, kind, shell):
def _skill_directive(name, arg, route):
+ """A local session's ``/skill`` (its plugin skills included, as on main's interactive surfaces),
+ stacked ``/skill-a /skill-b do X`` too: built here, so no client loads plugins to resolve one."""
+ from agent.i18n import t
from agent.skill_commands import (
- build_skill_invocation_message, describe_skill_invocation, get_skill_commands,
+ build_skill_invocation_message, build_stacked_skill_invocation_message, describe_skill_invocation,
+ get_interactive_skill_commands, resolve_slash_key, split_stacked_skill_commands,
)
- key = '/' + name
- skills = get_skill_commands()
- if key not in skills:
+ skills = get_interactive_skill_commands()
+ key = resolve_slash_key(name, skills)
+ if key is None:
raise RuntimeStoreError('unsupported_command')
- message = build_skill_invocation_message(key, arg, task_id=route)
+ extra, instruction = split_stacked_skill_commands(arg, interactive=True)
+ stacked = build_stacked_skill_invocation_message([key, *extra], instruction, task_id=route) if extra else None
+ message = stacked[0] if stacked else build_skill_invocation_message(key, arg, task_id=route)
if not message:
raise RuntimeStoreError('command_unavailable')
- return {'type': 'skill', 'name': skills[key]['name'], 'message': message,
- 'display': describe_skill_invocation(message, separator=' ')}
+ missing = stacked[2] if stacked else []
+ return {'type': 'skill', 'name': ', '.join(stacked[1]) if stacked else skills[key]['name'], 'message': message,
+ 'display': describe_skill_invocation(message, separator=' '),
+ **({'notice': t('cli.skills.skipped_missing', names=', '.join(missing))} if missing else {})}
-async def _tui_read(authority, actor, ref, name, arg):
- """Main's TUI sidecar text for a TUI session's /status, /context or /cron read, else None."""
+async def _tui_read(authority, actor, ref, name, arg, before):
+ """Main's TUI sidecar text for a TUI session's /status, /context or /cron read, else None;
+ ``before`` (its ``pre_command``) runs once the read is accepted."""
from gateway.session_local import authorize_local_source
from gateway.session_policy import policy_for_source
from gateway.session_tui_reads import run_tui_read, tui_read
@@ -204,9 +213,132 @@ async def _tui_read(authority, actor, ref, name, arg):
if render is None:
return None
authority.authorize(actor, ref, 'session:read')
+ await before()
return await run_tui_read(authority, ref, live, policy, render, arg)
+# Messaging's running-agent escape hatches (hooks.md ``pre_command``: ``/stop``, approval controls):
+# while a turn runs no plugin observer sits in front of them. Every other command that runs fires.
+_ESCAPE_HATCHES = frozenset({'stop'}) | _APPROVAL_COMMANDS
+_PRE_COMMAND_PENDING = 32 # one session's queued deliveries; past it a delivery is dropped (logged)
+_PRE_COMMAND_TAILS = {} # (profile, session id) -> (that session's last queued delivery, pending count)
+
+
+async def _on_own_thread(fn):
+ """``fn()`` on a daemon thread of its own (under the caller's contextvars), awaited on the loop: never
+ the loop's shared executor, and no shared worker a callback waiting out its bound
+ (``plugins.hook_callback_timeout``, enforced by the hook dispatcher: abandoned worker, suppression,
+ cap) holds from another session. One session runs one delivery at a time, so this is at most one
+ thread per session with a delivery in flight."""
+ from agent.memory_provider import spawn_context_thread
+ loop = asyncio.get_running_loop()
+ done = loop.create_future()
+
+ def settle():
+ if not done.done(): # else the delivery was cancelled
+ done.set_result(None)
+
+ def run():
+ try:
+ fn()
+ except Exception: # fire_pre_command_hook never raises: anything here is a bug, never the caller's
+ logger.exception('pre_command delivery failed')
+ finally:
+ try:
+ loop.call_soon_threadsafe(settle)
+ except RuntimeError: # the loop closed (gateway shutdown): nobody awaits it any more
+ pass
+ try:
+ spawn_context_thread(run, name='hermes-pre-command').start()
+ except RuntimeError as exc: # no thread available: this delivery is skipped, as the dispatcher skips
+ logger.warning('pre_command delivery skipped: %s', exc)
+ return
+ await done
+
+
+def _pre_command(authority, ref, canonical, alias, arg):
+ """Queue main's ``pre_command`` observer for a recognized command typed in a local session, fired
+ here for every surface (classic CLI, Ink, Desktop), so no client loads plugin code to fire it; the
+ delivery task, or None when not fired. One session's deliveries fire in arrival order; the hook
+ dispatcher bounds each callback, and one still running for this session (hung) is skipped for its
+ later commands, never run out of order, while other sessions' deliveries go on. ``surface`` and
+ ``platform`` keep main's ``cli`` on every local surface (Ink and Desktop fired it through the CLI
+ slash worker). During a turn every command that still runs fires, as main's CLI did, except the
+ escape hatches."""
+ from gateway.run import _profile_runtime_scope
+ from gateway.session_local import authorize_local_source
+ live = authority.sessions[ref.session_id]
+ if ((canonical in _ESCAPE_HATCHES and authority._handle(ref).execution_state != 'idle')
+ or authorize_local_source(authority.runner, live.source) is not True):
+ return None
+ home, key = Path(authority.profile_id), (authority.profile_id, ref.session_id)
+ previous, pending = _PRE_COMMAND_TAILS.get(key, (None, 0))
+ if previous is not None and previous.get_loop() is not asyncio.get_running_loop():
+ previous, pending = None, 0 # a retired loop's delivery (an in-process restart) never resolves on this one
+ if pending >= _PRE_COMMAND_PENDING:
+ logger.warning('pre_command for /%s dropped: %d deliveries already queued for this session', canonical, pending)
+ return None
+
+ def fire():
+ from hermes_cli.plugins import fire_pre_command_hook
+ with _profile_runtime_scope(home):
+ fire_pre_command_hook(surface='cli', command=canonical, alias_used=alias, args_raw=arg,
+ session_key=ref.session_id, platform='cli')
+
+ async def deliver():
+ if previous is not None:
+ await asyncio.wait({previous})
+ await _on_own_thread(fire)
+
+ def settle(done):
+ tail, count = _PRE_COMMAND_TAILS.get(key, (None, 0))
+ if tail is done:
+ _PRE_COMMAND_TAILS.pop(key)
+ elif count:
+ _PRE_COMMAND_TAILS[key] = (tail, count - 1)
+
+ task = asyncio.ensure_future(deliver())
+ _PRE_COMMAND_TAILS[key] = (task, pending + 1)
+ task.add_done_callback(settle)
+ return task
+
+
+async def _pre_command_before(authority, ref, canonical, alias, arg):
+ """``pre_command`` before the gateway runs the command itself (``slash.exec``/``command.dispatch``)."""
+ task = _pre_command(authority, ref, canonical, alias, arg)
+ if task is not None:
+ await asyncio.wait({task})
+
+
+async def observe_command(connection, ref, params):
+ """``command.observe``: a recognized command the classic CLI runs in its own process on this
+ session. ``pre_command`` fires here, in the session's profile, after the reply: the CLI never waits
+ on a plugin and never loads one. Plain data only (the command name as typed and its arguments)."""
+ from hermes_cli.commands import resolve_command
+ from hermes_cli.profiles import profile_matches_home
+ authority, actor = connection.authority, connection.actor
+ authority.authorize(actor, ref, 'session:read')
+ name, arg = _parse(params, True)
+ if params.get('profile') and not profile_matches_home(params['profile'], Path(authority.profile_id)):
+ raise RuntimeStoreError('profile_mismatch')
+ definition = resolve_command(name)
+ if definition is None:
+ raise RuntimeStoreError('unsupported_command')
+ return {'queued': _pre_command(authority, ref, definition.name, name.lower(), arg) is not None}
+
+
+@contextmanager
+def _accepting(before):
+ """``before`` as the busy dispatcher's acceptance hook: a mid-run variant that refuses its arguments
+ (``/goal <new text>``) never reaches it, so a refused command fires no ``pre_command``."""
+ from gateway.run_busy import BUSY_ACCEPTED
+ token = BUSY_ACCEPTED.set(before)
+ try:
+ yield
+ finally:
+ BUSY_ACCEPTED.reset(token)
+
+
@contextmanager
def _session_workspace(runner, source):
"""The session's frozen terminal policy (``TERMINAL_CWD`` = its launch cwd), so ``/diff``
@@ -246,7 +378,14 @@ async def execute_command(connection, ref, params, *, dispatch=False):
definition = resolve_command(name)
canonical = definition.name if definition else name
verdict = command_verdict(canonical, arg) if definition else None
- if definition is not None and (tui := await _tui_read(authority, actor, ref, canonical, arg)) is not None:
+
+ fired = []
+
+ async def before(): # pre_command, once, for a recognized command that is about to run
+ if not fired:
+ fired.append(canonical)
+ await _pre_command_before(authority, ref, canonical, name.lower(), arg)
+ if definition is not None and (tui := await _tui_read(authority, actor, ref, canonical, arg, before)) is not None:
return tui
runner_command = None
if definition is None:
@@ -266,12 +405,14 @@ async def execute_command(connection, ref, params, *, dispatch=False):
raise RuntimeStoreError('permission_denied')
if capability != 'session:read':
authority._require_admission_open()
+ if definition is not None and (canonical in _INFO_READS or authority._handle(ref).execution_state == 'idle'):
+ await before() # mid-run the busy dispatcher fires it once it accepts the command (``BUSY_ACCEPTED``)
if runner_command is not None:
with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):
output = await _run_runner_command(authority.runner, live, name, arg, *runner_command)
return {'type': 'exec', 'output': _text(output)}
if definition is None:
- def build():
+ def build(): # in the session's folder: its trusted project skills, as its catalog lists them
with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):
return _skill_directive(name, arg, live.route)
return await asyncio.to_thread(build)
@@ -287,15 +428,18 @@ async def execute_command(connection, ref, params, *, dispatch=False):
runner = authority.runner
prompt = None
# Use the registry's existing busy contract, not a local approximation.
- with _profile_runtime_scope(home), _session_workspace(runner, live.source), capture() as sink:
+ with (_profile_runtime_scope(home), _session_workspace(runner, live.source), capture() as sink,
+ _accepting(before)):
if authority._handle(ref).execution_state != 'idle':
output = await runner._dispatch_busy_slash_command(event, definition, live.route, live.source)
elif canonical in _PROMPT_COMMANDS:
+ await before() # a no-op unless the turn ended since the check above
handled, output = await getattr(runner, '_hm_cmd_' + canonical.replace('-', '_'))(
event, live.source, live.route)
if not handled:
prompt = event.text
else:
+ await before()
handler = runner._command_handler_table((canonical,))[canonical]
output = await handler(event)
if canonical in _APPROVAL_COMMANDS:
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 802b22ffd90..0477b2d8042 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -135,6 +135,7 @@ class AuthorityConnection:
name is declared in ``tui_gateway/contracts`` (``METHODS`` or ``CANONICAL_METHODS``)."""
handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,
'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,
+ 'plugins.list': self.plugins_list, 'command.observe': self.command_observe,
'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,
'session.list': self.list_sessions, 'session.info': self.info,
'session.mutate': self.mutate, 'bot_relay.deliver': self.bot_deliver,
@@ -324,10 +325,18 @@ class AuthorityConnection:
from gateway.session_commands import execute_command
return await execute_command(self, ref, params, dispatch=True)
+ async def command_observe(self, ref, params):
+ from gateway.session_commands import observe_command
+ return await observe_command(self, ref, params)
+
async def command_catalog(self, ref, params):
from gateway.session_discovery import discover_commands
return await discover_commands(self.authority, self.actor, params)
+ async def plugins_list(self, ref, params):
+ from gateway.session_discovery import list_plugins
+ return await list_plugins(self.authority, self.actor, params)
+
async def slash_completions(self, ref, params):
from gateway.session_discovery import discover_commands
return await discover_commands(self.authority, self.actor, params, completion=True)
diff --git a/gateway/session_discovery.py b/gateway/session_discovery.py
index 2c514b35d97..e584e32c309 100644
--- a/gateway/session_discovery.py
+++ b/gateway/session_discovery.py
@@ -33,3 +33,32 @@ async def discover_commands(authority, actor, params, *, completion=False):
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)
diff --git a/gateway/session_local_inventory.py b/gateway/session_local_inventory.py
index bfbe93e1705..9d34aa5d5a3 100644
--- a/gateway/session_local_inventory.py
+++ b/gateway/session_local_inventory.py
@@ -95,6 +95,19 @@ def _cli_startup_notices(enabled):
return notices
+def _unknown_toolsets(enabled, config):
+ """Main's "Unknown toolsets" startup warning (``HermesCLI._init_toolsets``), judged where the plugins
+ load: the session's toolset names the profile's registry, MCP servers, plugin toolsets and platform
+ bundles cannot place (an uninstalled plugin's stale ``platform_toolsets`` entry)."""
+ if "all" in enabled or "*" in enabled:
+ return []
+ with contextlib.suppress(Exception):
+ from hermes_cli.toolset_validation import saved_toolset_resolver
+ known = saved_toolset_resolver(config)
+ return [name for name in enabled if not known(name)]
+ return []
+
+
def _cli_skills():
"""``hermes_cli.banner.get_available_skills`` as main's classic CLI computed it: ``cmd_chat`` pins
``HERMES_KANBAN_BOARD`` before HermesCLI starts, so ``environments: [kanban]`` skills are offered.
@@ -152,7 +165,7 @@ def session_inventory(authority, policy, agent, cwd):
from hermes_cli.banner import compute_toolset_availability
info["tool_availability"] = compute_toolset_availability(enabled)
if policy is not None and policy.source == "cli":
- info.update(_cli_startup_notices(enabled))
+ info.update(_cli_startup_notices(enabled), unknown_toolsets=_unknown_toolsets(enabled, config))
with contextlib.suppress(Exception):
if policy is not None and policy.source == "cli":
info["skills"] = _cli_skills()
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 7302c8a8d6e..bd645da2850 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -611,7 +611,7 @@ class CLIAgentSetupMixin:
def _init_agent(self, *, model_override: str | None = None, runtime_override: dict | None = None, request_overrides: dict | None = None) -> bool:
"""Build the agent on first use; when resuming, restore history from SQLite.
Returns True on success."""
- from cli import ChatConsole, _cprint, _prepare_deferred_agent_startup, logger
+ from cli import ChatConsole, _cprint, logger
from hermes_cli.gateway_agent import GatewayAgent as AIAgent # the gateway runs the turn
if self.agent is not None:
return True
@@ -619,7 +619,7 @@ class CLIAgentSetupMixin:
# Join the background preloaded-skills load (--skills/-s) BEFORE the agent
# snapshots self.system_prompt below. No-op when nothing was requested.
self.finalize_preloaded_skills()
- _prepare_deferred_agent_startup()
+ # No deferred plugin discovery either: the gateway that runs the turn loads the plugins (PLG-7).
self._install_tool_callbacks()
if not self._ensure_runtime_credentials():
return False
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index de9a01c669e..16b08fdaf2d 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -1532,7 +1532,7 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):
if out is not None:
return print(out)
from hermes_cli.gateway_tools import handle_skills_slash # + the gateway's rescan
- handle_skills_slash(cmd, ChatConsole())
+ handle_skills_slash(cmd, ChatConsole(), cli=self)
def _handle_memory_command(self, cmd: str):
"""Handle /memory slash command — pending review + approval-gate toggle."""
diff --git a/hermes_cli/cli_commands_session_tools.py b/hermes_cli/cli_commands_session_tools.py
index e0c84cfae85..669cb7acc9b 100644
--- a/hermes_cli/cli_commands_session_tools.py
+++ b/hermes_cli/cli_commands_session_tools.py
@@ -253,7 +253,7 @@ class CLICommandsSessionToolsMixin:
self._run_tools_config(tools_action=subcommand, names=names, platform="cli")
from hermes_cli.tools_config import _get_platform_tools
from hermes_cli.config import load_config
- self.enabled_toolsets = _get_platform_tools(load_config(), "cli")
+ self.enabled_toolsets = sorted(_get_platform_tools(load_config(), "cli")) # plain data for session.create
self.new_session()
_cp(_dim(_t("tools.session_reset")))
diff --git a/hermes_cli/cli_info_mixin.py b/hermes_cli/cli_info_mixin.py
index 0d4c45e56c8..b02f5239645 100644
--- a/hermes_cli/cli_info_mixin.py
+++ b/hermes_cli/cli_info_mixin.py
@@ -122,13 +122,15 @@ class CLIInfoMixin:
self.console.clear()
ctx_len = None
gateway_inventory = getattr(getattr(self, "_session_db", None), "banner_inventory", lambda: None)()
+ from hermes_cli.gateway_tools_notify import gateway_store
+ on_gateway = gateway_store(self) is not None # its tools come from the gateway: never enumerated here
if hasattr(self, 'agent') and self.agent and hasattr(self.agent, 'context_compressor'):
ctx_len = self.agent.context_compressor.context_length
from agent.context_pin import is_context_pinned
ctx_pinned = is_context_pinned(ctx_len, getattr(getattr(self, "agent", None), "_config_context_length", None))
# Auto-compact for narrow terminals — the full banner needs ~80 columns to avoid wrapping.
- if self.compact or shutil.get_terminal_size().columns < 80:
+ if self.compact or shutil.get_terminal_size().columns < 80 or (on_gateway and gateway_inventory is None):
self._console_print(_build_compact_banner())
self._show_status()
else:
@@ -193,7 +195,7 @@ class CLIInfoMixin:
# the background and let its output land above the prompt (patch_stdout-safe).
if isinstance((gateway_inventory or {}).get("tool_availability_warnings"), list):
self._print_gateway_tool_warnings(gateway_inventory["tool_availability_warnings"])
- elif os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
+ elif not on_gateway and os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
if getattr(self, "_defer_tool_warnings", False):
threading.Thread(
target=self._show_tool_availability_warnings,
@@ -270,12 +272,12 @@ class CLIInfoMixin:
"""Display help. Bare /help shows categorized core commands with the skill list collapsed
to one line; /help skills lists all skill commands; /help <query> filters by substring."""
from cli import (
- ChatConsole, _BOLD, _DIM, _RST, _accent_hex, _cprint, _ensure_skill_commands,
+ ChatConsole, _BOLD, _DIM, _RST, _accent_hex, _cprint, _session_skill_commands,
_termux_example_image_path, get_skill_bundles)
from hermes_cli.commands import COMMAND_REGISTRY, HELP_SESSION_SUBGROUPS
arg = (arg or "").strip()
- skill_commands = _ensure_skill_commands()
+ skill_commands = _session_skill_commands(self)
def _row(cmd: str, desc: str, width: int = 15) -> None:
ChatConsole().print(
@@ -284,8 +286,7 @@ class CLIInfoMixin:
# /help skills — the full list, kept out of the default view so core commands don't
# scroll off screen.
if arg.lower() in ("skills", "skill"):
- from agent.skill_commands import skill_command_collision_note
- from tools.skills_tool import _find_all_skills
+ from hermes_cli import gateway_plugin_commands
if skill_commands:
_cprint(f"\n ⚡ {_BOLD}{t('cli.help.skill_commands')}{_RST} "
f"({t('cli.help.n_installed', count=str(len(skill_commands)))}):")
@@ -294,7 +295,7 @@ class CLIInfoMixin:
else:
_cprint(f"\n {t('cli.help.no_skill_commands')}")
# Skills whose name is a built-in command never get a /<name> (agent.skill_commands guard).
- for note in filter(None, (skill_command_collision_note(s["name"]) for s in _find_all_skills())):
+ for note in gateway_plugin_commands.skill_notes(self):
_cprint(f" {_DIM}⚠ {note}{_RST}")
_cprint("")
return
@@ -1025,12 +1026,17 @@ class CLIInfoMixin:
conversation_history, so message alternation stays intact.
"""
try:
- from agent.skill_commands import reload_skills
+ from hermes_cli.gateway_tools import process_view
if not self._command_running:
print(t("cli.reload_skills.reloading"))
- result = reload_skills()
- from hermes_cli.gateway_tools import reload_gateway_skills
- reload_gateway_skills() # the gateway that runs the turn rescans too; main's lines use the CLI diff
+ view = process_view()
+ if view is not None: # the gateway session's rescan (its plugin skills too): nothing is scanned here
+ result = (view.connection.call("skills.reload", session_id=view.session_id) or {}).get("result") or {}
+ from hermes_cli.gateway_plugin_commands import invalidate
+ invalidate(self) # /help, completion and dispatch read the rescanned list
+ else:
+ from agent.skill_commands import reload_skills
+ result = reload_skills()
added = result.get("added", []) # [{"name", "description"}, ...]
removed = result.get("removed", [])
total = result.get("total", 0)
diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.py
index 8476c536c3e..f9e113d549b 100644
--- a/hermes_cli/cli_init_mixin.py
+++ b/hermes_cli/cli_init_mixin.py
@@ -24,6 +24,19 @@ logger = logging.getLogger("cli")
_ROUTE_FLAGS = ("model", "provider", "api_key", "base_url")
+def _adopt_gateway_toolsets(cli, store):
+ """The profile default the gateway resolved for the opened session, when this process has no list to
+ show (display only), and main's "Unknown toolsets" warning as the gateway judged it against its own
+ plugins."""
+ info = (store.current or {}).get("info") or {}
+ if getattr(cli, "enabled_toolsets", None) is None and isinstance(info.get("enabled_toolsets"), list):
+ cli.enabled_toolsets = list(info["enabled_toolsets"])
+ if info.get("unknown_toolsets"):
+ from agent.i18n import t as _t
+ names = ", ".join(info["unknown_toolsets"])
+ cli._console_print(f"[bold red]{_t('cli.startup.unknown_toolsets', names=names)}[/]")
+
+
def _gateway_launch(cli):
"""This run's explicit launch flags as gateway ``session.create`` policy (main handed them to AIAgent)."""
explicit_model = getattr(cli, "_explicit_model_override", False)
@@ -269,7 +282,7 @@ class CLIInitMixin:
self._explicit_max_turns = max_turns
def _init_toolsets(self, toolsets):
- from cli import CLI_CONFIG, validate_toolset
+ from cli import CLI_CONFIG
self.enabled_toolsets = toolsets
# Only a picked list rides session.create; _build_cli_from_args clears this unless -t was typed (the
# gateway resolves the profile default and coding posture itself; a stale explicit name is refused, #138670).
@@ -277,23 +290,9 @@ class CLIInitMixin:
from agent.skill_utils import parse_config_string_list
self.disabled_toolsets = parse_config_string_list(CLI_CONFIG["agent"].get("disabled_toolsets"))
-
- if toolsets and "all" not in toolsets and "*" not in toolsets:
- # MCP server names only resolve after discover_mcp_tools runs; skip them here.
- mcp_names = set((CLI_CONFIG.get("mcp_servers") or {}).keys())
- # Plugin toolsets register during plugin discovery, which startup runs on a background thread
- # that has not necessarily landed yet; names it declared (or the previous launch persisted, which
- # get_plugin_toolset_keys_nowait serves) are not typos (#71650).
- try:
- from hermes_cli.plugins import get_plugin_toolset_keys_nowait
- plugin_ts_names = get_plugin_toolset_keys_nowait()
- except Exception:
- plugin_ts_names = set()
- invalid = [t for t in toolsets
- if not validate_toolset(t) and t not in mcp_names and t not in plugin_ts_names]
- if invalid:
- from agent.i18n import t as _t
- self._console_print(f"[bold red]{_t('cli.startup.unknown_toolsets', names=', '.join(invalid))}[/]")
+ # No local "Unknown toolsets" check: plugin toolsets are only known where plugins load. The gateway
+ # refuses an unknown picked name at session.create and reports a stale profile one with the session
+ # (``_adopt_gateway_toolsets``), so this process never discovers plugins to tell them apart (PLG-7).
def _init_checkpoints_and_rules(self, checkpoints, pass_session_id, ignore_rules):
from cli import CLI_CONFIG
@@ -439,6 +438,9 @@ class CLIInitMixin:
self._release_active_session()
sid = store.open_session(self, launch)
self._gateway_session_open = True
+ from hermes_cli import gateway_plugin_commands, tools_config
+ tools_config._gateway_plugin_toolsets = lambda: gateway_plugin_commands.toolsets(self)
+ _adopt_gateway_toolsets(self, store)
from hermes_cli.gateway_tools import bind_session
bind_session(self, store.connection) # the session's processes, before _init_agent's chat proxy
if sid and sid != self.session_id:
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.py
index c7a0a066d81..8e8c7e0418a 100644
--- a/hermes_cli/cli_loops_mixin.py
+++ b/hermes_cli/cli_loops_mixin.py
@@ -304,11 +304,14 @@ class CLILoopsMixin:
if bundled_count:
print(f" {t('cli.plugins.bundled_available', count=bundled_count)}")
return
- try: # loaded-plugin details (tools/hooks/commands counts, errors) by name
- from hermes_cli.plugins import get_plugin_manager
- loaded = {p["name"]: p for p in get_plugin_manager().list_plugins()}
- except Exception:
- loaded = {}
+ from hermes_cli import gateway_plugin_commands
+ loaded = gateway_plugin_commands.loaded(self) # the gateway's; None off the gateway
+ if loaded is None:
+ try: # loaded-plugin details (tools/hooks/commands counts, errors) by name
+ from hermes_cli.plugins import get_plugin_manager
+ loaded = {p["name"]: p for p in get_plugin_manager().list_plugins()}
+ except Exception:
+ loaded = {}
print(t("cli.plugins.user_plugins_header", count=len(user_entries)))
for name, version, _desc, source, _dir, key in sorted(user_entries):
state = _plugin_status(name, enabled, disabled, key=key)
diff --git a/hermes_cli/cli_modal_mixin.py b/hermes_cli/cli_modal_mixin.py
index 73b5f3afaef..b4917a55467 100644
--- a/hermes_cli/cli_modal_mixin.py
+++ b/hermes_cli/cli_modal_mixin.py
@@ -414,7 +414,7 @@ class CLIModalMixin:
"""Flat (command, category, desc) rows for the Ctrl+P palette: the COMMAND_REGISTRY behind
/help filtered to this surface, plus installed skill commands. Selecting inserts the exact
command string — never a fuzzy resolution."""
- from cli import _ensure_skill_commands
+ from cli import _session_skill_commands
from hermes_cli.commands import COMMANDS_BY_CATEGORY
entries: list[tuple[str, str, str]] = []
@@ -423,7 +423,7 @@ class CLIModalMixin:
if self._command_available(cmd):
entries.append((cmd, category, desc))
try:
- for cmd, info in sorted(_ensure_skill_commands().items()):
+ for cmd, info in sorted(_session_skill_commands(self).items()):
entries.append((cmd, t("cli.palette.category_skill"), info.get("description", "")))
except Exception:
pass
diff --git a/hermes_cli/cli_session_mixin.py b/hermes_cli/cli_session_mixin.py
index a180d482662..0c0aefeff63 100644
--- a/hermes_cli/cli_session_mixin.py
+++ b/hermes_cli/cli_session_mixin.py
@@ -202,9 +202,14 @@ class CLISessionMixin:
def _show_status(self):
"""Show compact startup status line."""
from cli import get_tool_definitions
+ from hermes_cli.gateway_tools_notify import gateway_store
+ store = gateway_store(self) # a gateway session's tools are the gateway's: never enumerated here
+ inventory = store.banner_inventory() if store is not None else None
# Avoid pulling the full tool registry into the bare Termux prompt path.
- if os.environ.get("HERMES_DEFER_AGENT_STARTUP") == "1":
+ if os.environ.get("HERMES_DEFER_AGENT_STARTUP") == "1" or (store is not None and inventory is None):
tool_status = t("cli.session.status_tools_deferred")
+ elif inventory is not None:
+ tool_status = t("cli.session.status_tools_count", count=len(inventory["tools"] or []))
else:
tools = get_tool_definitions(enabled_toolsets=self.enabled_toolsets,
disabled_toolsets=self.disabled_toolsets, quiet_mode=True)
diff --git a/hermes_cli/cli_single_query.py b/hermes_cli/cli_single_query.py
index 25544db4f48..5dd608c32b7 100644
--- a/hermes_cli/cli_single_query.py
+++ b/hermes_cli/cli_single_query.py
@@ -480,10 +480,8 @@ def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: bool
cli._seeded_first_message = _SeededQueryMessage(seeded_query, seeded_images)
return cli.run()
cli._single_query_mode = True # agent waits the full MCP cold-start before its only tool snapshot
- # Only the interactive run loop set this, so plugin tools dispatched from a `-q`/`-Q` turn got no
- # parent_agent (PluginContext.dispatch_tool reads it) — #67597.
- from hermes_cli.plugins import get_plugin_manager
- get_plugin_manager()._cli_ref = cli
+ # No PluginManager._cli_ref (#67597): the turn's plugin tools run in the gateway, and this process
+ # loads no plugins (PLG-7).
# No user can answer approval prompts: the approval gate takes the deterministic path.
# One-shot mode: no between-turns MCP late-binding refresh, so the agent must wait the full MCP
# cold-start bound before its first (and only) tool snapshot. See #51316.
diff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.py
index 912367a5343..3f2d293f034 100644
--- a/hermes_cli/cli_tui_mixin.py
+++ b/hermes_cli/cli_tui_mixin.py
@@ -16,7 +16,7 @@ import time
from agent.i18n import t
from agent.interrupt_compat import request_hard_interrupt
-from hermes_cli.commands_completion import SlashCommandAutoSuggest, SlashCommandCompleter
+from hermes_cli.commands_completion import SlashCommandAutoSuggest, cli_slash_completer
from pathlib import Path
from prompt_toolkit.filters import Condition
from prompt_toolkit.history import FileHistory
@@ -1854,9 +1854,7 @@ class CLITuiMixin:
self._should_exit = False
self._last_ctrl_c_time = 0 # double Ctrl+C force-exit tracking
- # Plugins get a CLI reference so they can inject messages.
- from hermes_cli.plugins import get_plugin_manager
- get_plugin_manager()._cli_ref = self
+ # No PluginManager._cli_ref: plugins load in the gateway, not here (PLG-7).
# Config file watcher — detect mcp_servers changes and auto-reload.
from hermes_cli.config import get_config_path as _get_config_path
@@ -2209,19 +2207,15 @@ class CLITuiMixin:
def _tui_build_input_area(self):
"""Multi-line prompt TextArea with slash completion, paste-collapse tracking and
placeholder/password processors."""
- from cli import _estimate_tui_input_height, get_skill_bundles, get_skill_commands
+ from cli import _estimate_tui_input_height
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import ThreadedCompleter
- from hermes_cli import gateway_plugin_commands
cli_ref = self
def get_prompt():
return cli_ref._get_tui_prompt_fragments()
- _completer = SlashCommandCompleter(
- skill_commands_provider=lambda: get_skill_commands(),
- command_filter=cli_ref._command_available,
- skill_bundles_provider=lambda: get_skill_bundles(), plugin_commands_provider=lambda: gateway_plugin_commands.names(cli_ref))
+ _completer = cli_slash_completer(self)
input_area = TextArea(
height=Dimension(min=1, max=8, preferred=1),
prompt=get_prompt,
diff --git a/hermes_cli/commands_completion.py b/hermes_cli/commands_completion.py
index 09bb5ab9e90..56b2cb34b6a 100644
--- a/hermes_cli/commands_completion.py
+++ b/hermes_cli/commands_completion.py
@@ -523,3 +523,13 @@ class SlashCommandAutoSuggest(AutoSuggest):
if sub.startswith(sub_lower) and sub != sub_lower:
return Suggestion(sub[len(sub_text):])
return self._history_suggestion(buffer, document)
+
+
+def cli_slash_completer(cli):
+ """The classic CLI prompt's slash completer; on a gateway session its skills and plugin commands are
+ the gateway's (``commands.catalog``), so completing loads no plugin in the CLI process."""
+ from cli import _session_skill_commands, get_skill_bundles
+ from hermes_cli import gateway_plugin_commands
+ return SlashCommandCompleter(
+ skill_commands_provider=lambda: _session_skill_commands(cli), command_filter=cli._command_available,
+ skill_bundles_provider=lambda: get_skill_bundles(), plugin_commands_provider=lambda: gateway_plugin_commands.names(cli))
diff --git a/hermes_cli/gateway_cli_commands.py b/hermes_cli/gateway_cli_commands.py
index d2ce0665446..4a546047bfb 100644
--- a/hermes_cli/gateway_cli_commands.py
+++ b/hermes_cli/gateway_cli_commands.py
@@ -46,6 +46,8 @@ def _handoff(cli, connection, cmd):
_ROUTES = {"diff": _diff, "reload": _reload, "handoff": _handoff}
+# Named refusals: nothing runs, so the gateway is not told (no ``pre_command``).
+REFUSED = frozenset({"handoff"})
def run(cli, canonical, cmd):
diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.py
index 3f0c9de2539..b66247db760 100644
--- a/hermes_cli/gateway_plugin_commands.py
+++ b/hermes_cli/gateway_plugin_commands.py
@@ -13,10 +13,13 @@ them, not because there are none: it is treated as a failed read and never cache
"""
from __future__ import annotations
+import logging
import threading
from hermes_cli.gateway_client import GatewayClientError
+logger = logging.getLogger(__name__)
+
_CATEGORY = "Plugin commands" # tui_gateway/command_discovery.py
GONE = object() # run(): the gateway no longer has the command; the caller dispatches the name again
_GONE_LINE = " /{}: the gateway no longer has this plugin command; nothing was run."
@@ -37,7 +40,7 @@ def _read(cli, connection):
result is published only if neither moved during the call: a reply from epoch E that arrives after
a concurrent redial is never relabelled E+1 (``call_tagged``)."""
session = getattr(cli, "session_id", None)
- catalog, epoch = connection.call_tagged("commands.catalog")
+ catalog, epoch = _catalog(cli, connection, session)
catalog = catalog or {}
if catalog.get("plugin_discovery_error"): # absent on older gateways: today's behaviour
raise GatewayClientError(f"plugin command discovery failed: {catalog['plugin_discovery_error']}")
@@ -51,19 +54,129 @@ def _read(cli, connection):
for row in category.get("pairs") or []:
if isinstance(row, (list, tuple)) and len(row) == 2 and isinstance(row[0], str):
found[row[0].lstrip("/")] = str(row[1] or "")
+ # The session's skill commands as the gateway resolved them (its plugin skills included): /help,
+ # completion and dispatch read these, so this process never scans plugin skills to list them.
+ descriptions = {row[0]: str(row[1] or "") for row in catalog.get("pairs") or []
+ if isinstance(row, (list, tuple)) and len(row) == 2 and isinstance(row[0], str)}
+ skills = {key: {"name": key.lstrip("/"), "description": descriptions.get(key) or "Skill"}
+ for key in catalog.get("skills") or {} if isinstance(key, str)}
served = (connection, epoch, session)
if _boundary(cli, connection) == served:
cli._gateway_plugin_commands = (served, found)
+ cli._gateway_skills = (served, skills, str(catalog.get("warning") or ""))
return found
+def _catalog(cli, connection, session):
+ """``(commands.catalog, epoch)`` for the open gateway session, so its skills come from the session's
+ folder (its trusted project skills), not the gateway's. A gateway older than this CLI refuses the
+ ``session_id`` (``invalid_params``): it is asked again without it, as before."""
+ from hermes_cli.gateway_client import GatewayRPCError
+ if session and getattr(cli, "_gateway_session_open", False):
+ try:
+ return connection.call_tagged("commands.catalog", session_id=session)
+ except GatewayRPCError as exc:
+ if str(exc) != "invalid_params":
+ raise
+ return connection.call_tagged("commands.catalog")
+
+
+def invalidate(cli):
+ """Drop ``cli``'s copy of the gateway's catalog after a skill rescan (``/reload-skills``, ``/skills
+ install``): the next read asks the gateway again."""
+ cli._gateway_plugin_commands = cli._gateway_skills = None
+
+
+def _hung_up(connection):
+ """A closed connection keeps its epoch until the next call redials, maybe to another life: no
+ cache it labelled is served."""
+ return getattr(connection, "closed", False)
+
+
def _cached(cli, connection):
- if getattr(connection, "closed", False): # hung up: the next call redials, maybe to another life
+ if _hung_up(connection):
return None
boundary, found = getattr(cli, "_gateway_plugin_commands", None) or (None, None)
return found if boundary == _boundary(cli, connection) else None
+def skills(cli, *, notes=False):
+ """``{"/key": {name, description}}`` of the session's skill commands from the gateway's catalog
+ (``notes``: its one-line notice instead, e.g. skills a built-in command shadows), or None off the
+ gateway. A failed read is printed once per input and lists none; nothing is scanned here."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return None
+ boundary, found, warning = getattr(cli, "_gateway_skills", None) or (None, None, "")
+ if _hung_up(connection) or boundary != _boundary(cli, connection):
+ try:
+ _read(cli, connection)
+ except GatewayClientError as exc:
+ logger.debug("commands.catalog unavailable: %s", exc)
+ return "" if notes else {}
+ _seen, found, warning = getattr(cli, "_gateway_skills", None) or (None, {}, "")
+ return warning if notes else found
+
+
+def skill_notes(cli):
+ """``/help skills`` notes (skills a built-in command shadows): the gateway's notice on its session,
+ else this process's own scan."""
+ notice = skills(cli, notes=True)
+ if notice is not None:
+ return [notice] if notice else []
+ from agent.skill_commands import skill_command_collision_note
+ from tools.skills_tool import _find_all_skills
+ return list(filter(None, (skill_command_collision_note(s["name"]) for s in _find_all_skills())))
+
+
+def run_skill(cli, base_cmd, rest):
+ """``/skill ...`` on the gateway session: the gateway resolves and loads the skill (its plugin
+ skills and stacked skills too) and returns the message, which is queued as main queued it; True
+ when answered there (False off the gateway: main's local load)."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return False
+ from agent.i18n import t
+ from cli import _cprint
+ command = base_cmd.lstrip("/") + (" " + rest if rest else "")
+ try:
+ reply = connection.call("slash.exec", session_id=cli.session_id, command=command) or {}
+ except GatewayClientError as exc:
+ _cprint(f" {base_cmd}: {exc}")
+ return True
+ if reply.get("type") == "skill" and reply.get("message"):
+ cli._queue_loaded_skills(reply["message"], t("cli.skills.loading_skill", name=reply.get("name") or command), None)
+ if reply.get("notice") or reply.get("output"):
+ _cprint(f" {reply.get('notice') or reply.get('output')}")
+ return True
+
+
+def toolsets(cli):
+ """``([(key, label, description)], {portable MCP server})`` the gateway's plugins provide for this
+ profile (``plugins.list``), or None off the gateway (this process's own registry applies). An older
+ gateway or a failed read gives none, never a local scan. Read once per gateway life."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return None
+ boundary = (connection, getattr(connection, "epoch", None))
+ cached = getattr(cli, "_gateway_plugin_toolsets", None)
+ if cached and cached[0] == boundary and not _hung_up(connection):
+ return cached[1]
+ try:
+ reply = connection.call("plugins.list") or {}
+ except GatewayClientError as exc:
+ logger.debug("plugins.list unavailable: %s", exc)
+ return [], set()
+ rows = [(str(r.get("key")), str(r.get("label") or r.get("key")), str(r.get("description") or ""))
+ for r in reply.get("toolsets") or [] if isinstance(r, dict) and isinstance(r.get("key"), str)]
+ found = (rows, {str(n) for n in reply.get("portable_mcp_servers") or [] if isinstance(n, str)})
+ cli._gateway_plugin_toolsets = (boundary, found)
+ return found
+
+
def names(cli):
"""``{name: description}`` of the gateway's plugin commands for completion, or None off the
gateway. A failed read degrades quietly to none; dispatch uses :func:`lookup`."""
@@ -163,3 +276,61 @@ def report_gone(name, *known):
from cli import _cprint
_cprint(_GONE_LINE.format(name))
return True
+
+
+def observe(cli, name, arg, *, runs=True):
+ """Tell the gateway about a recognized command this process runs itself (``command.observe``), so
+ ``pre_command`` fires there, in the session's profile, and never here; False off the gateway (main's
+ in-process hook applies). A command that ``runs`` nothing here (a refusal) is not reported. The
+ gateway replies before any plugin runs. One older than this CLI (no such method) gets one printed
+ line, and is not asked again on that connection life: local commands then reach no ``pre_command``
+ observer, and this process still fires none itself."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return False
+ if not runs:
+ return True
+ epoch = getattr(connection, "epoch", None)
+ if getattr(cli, "_observe_unsupported", None) == (connection, epoch):
+ return True
+ from hermes_cli.gateway_client import GatewayRPCError
+ try:
+ connection.call("command.observe", session_id=cli.session_id, name=name, arg=arg)
+ except GatewayRPCError as exc:
+ if exc.code != -32601 and str(exc) != "unknown_method":
+ logger.debug("command.observe /%s refused: %s", name, exc)
+ return True
+ cli._observe_unsupported = (connection, epoch)
+ if not getattr(cli, "_observe_notice_shown", False):
+ cli._observe_notice_shown = True
+ from cli import _cprint
+ _cprint(" This gateway predates this CLI: plugin pre_command hooks don't see the commands the CLI "
+ "runs itself until it restarts.")
+ except GatewayClientError as exc:
+ logger.debug("command.observe /%s not delivered: %s", name, exc)
+ return True
+
+
+def loaded(cli):
+ """``{name: row}`` of the plugins the gateway loaded (tool/hook/command counts, load error) for
+ ``/plugins``, or None off the gateway. A gateway without ``plugins.list`` on this socket (older
+ than this CLI) or one that can't answer gets one printed line and ``{}``: the listing then shows
+ no load details, and this process never loads plugins to fill them in."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return None
+ from cli import _cprint
+ from hermes_cli.gateway_client import GatewayRPCError
+ try:
+ rows = (connection.call("plugins.list") or {}).get("plugins") or []
+ except GatewayRPCError as exc:
+ older = exc.code == -32601 or str(exc) == "unknown_method"
+ _cprint(" This gateway doesn't report its loaded plugins (it predates this CLI); restart it for load details."
+ if older else f" The gateway's plugin list is unavailable ({exc}).")
+ return {}
+ except GatewayClientError as exc:
+ _cprint(f" The gateway's plugin list is unavailable ({exc}).")
+ return {}
+ return {row["name"]: row for row in rows if isinstance(row, dict) and isinstance(row.get("name"), str)}
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index c09b78ffb28..1d3c1192afb 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -61,6 +61,8 @@ class GatewaySessionStore:
"""Truthy until the viewer's gateway connection is final (main's ``if self._session_db:`` guards);
a gateway hang-up stays truthy, and the next call redials."""
+ current: dict | None = None # the opened session's snapshot; never ``__getattr__``'s refusal
+
def __init__(self, connection=None):
self.connection = connection or GatewayConnection.shared()
self.snapshots: dict[str, dict] = {}
diff --git a/hermes_cli/gateway_tools.py b/hermes_cli/gateway_tools.py
index 7764fa149ff..8efbe3b2eab 100644
--- a/hermes_cli/gateway_tools.py
+++ b/hermes_cli/gateway_tools.py
@@ -216,9 +216,13 @@ def reload_gateway_skills():
return None
-def handle_skills_slash(cmd, console):
+def handle_skills_slash(cmd, console, cli=None):
"""Main's ``/skills`` (hub search / install / uninstall write the local skills tree), then the
- gateway's rescan so an install reaches the skill map the session's turns use."""
+ gateway's rescan so an install reaches the skill map the session's turns use, and ``cli``'s copy of
+ the gateway's skill list is read again."""
from hermes_cli.skills_hub import handle_skills_slash as local
local(cmd, console)
reload_gateway_skills()
+ if cli is not None:
+ from hermes_cli.gateway_plugin_commands import invalidate
+ invalidate(cli)
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index db8d14c6ef0..dd20e420276 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2922,8 +2922,8 @@ def _prepare_agent_startup(args) -> None:
return
_accept_hooks = bool(getattr(args, "accept_hooks", False))
- if not _is_tui_chat_launch(args):
- # The TUI backend does its own discovery; the launcher only spawns Node.
+ if not (_is_tui_chat_launch(args) or _chat_runs_at_gateway(args)):
+ # The TUI backend and the gateway (chat turns, plugin commands, pre_command) discover their own.
try:
from hermes_cli.plugins import start_background_plugin_discovery
diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.py
index 8ea5cb31be3..17c1a59bd0f 100644
--- a/hermes_cli/plugins_dispatch.py
+++ b/hermes_cli/plugins_dispatch.py
@@ -45,7 +45,12 @@ _HOOK_TIMEOUT_BOUNDED_HOOKS: set[str] = {
"pre_auxiliary_call", "post_auxiliary_call", "pre_verify", "on_session_start", "on_session_end",
# Fail-open consumer on every inbound gateway message: a hung plugin must not stall the profile.
"post_gateway_admission",
+ # Observer on every local session's commands, fired by the gateway (gateway/session_commands.py).
+ "pre_command",
}
+# Hooks whose calls are told apart by another payload field: one session's commands are one
+# sequence, so a still-running callback skips that session's next command, not another session's.
+_HOOK_CALL_IDENTITY_FIELDS: dict[str, tuple[str, ...]] = {"pre_command": ("session_key",)}
# Policy hooks: timeout / still-running must fail closed (block the tool).
_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS: set[str] = {"pre_tool_call"}
@@ -157,7 +162,7 @@ _MAX_HOOK_CALLBACK_TIMEOUT_SECS = 600.0
_HOOK_SKIPPED = object() # returned by _run_hook_callback_bounded on skip/timeout
-def _hook_call_identity(kwargs: dict[str, Any]) -> Optional[str]:
+def _hook_call_identity(kwargs: dict[str, Any], hook_name: str = "") -> Optional[str]:
"""Identity of the call this callback fires for, or ``None`` when the event has none.
Concurrent invocations of the same tool in one session must not collapse into one
@@ -166,7 +171,7 @@ def _hook_call_identity(kwargs: dict[str, Any]) -> Optional[str]:
payload; nothing new is plumbed. Deliberately not ``api_request_id`` — one API request
carries many tool calls, which would re-collapse the keys.
"""
- for field in ("tool_call_id", "turn_id"):
+ for field in _HOOK_CALL_IDENTITY_FIELDS.get(hook_name, ("tool_call_id", "turn_id")):
value = kwargs.get(field)
if isinstance(value, str) and value:
return value
@@ -319,7 +324,7 @@ class PluginDispatchMixin:
# Suppression is a fact about the CALLBACK — a hung one must keep its back-off —
# so that key stays coarse. The gate must instead tell CONCURRENT CALLS apart.
suppression_key = (hook_name, id(cb))
- gate_key = (*suppression_key, _hook_call_identity(kwargs))
+ gate_key = (*suppression_key, _hook_call_identity(kwargs, hook_name))
token = object()
with self._hook_timeout_lock:
suppressed_until = self._hook_timeout_suppressed_until.get(suppression_key)
diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.py
index 5421d10ec2b..e003741b081 100644
--- a/hermes_cli/tools_config.py
+++ b/hermes_cli/tools_config.py
@@ -139,14 +139,27 @@ def _toolset_configuration_platform(ts_key: str, default: str = "cli") -> str:
return default if not allowed or default in allowed else min(allowed)
+# A classic CLI on a gateway session reads plugin toolsets from the gateway instead of loading plugins
+# (installed by ``_ensure_gateway_session``): ``() -> ([(key, label, description)], {portable MCP})`` or
+# None (off the gateway: this process's own registry).
+_gateway_plugin_toolsets = None
+
+
+def _projected_plugin_toolsets():
+ provider = _gateway_plugin_toolsets
+ return provider() if provider is not None else None
+
+
def _get_effective_configurable_toolsets():
"""CONFIGURABLE_TOOLSETS + plugin toolsets (appended after built-ins; a plugin key already built-in is skipped)."""
result = list(CONFIGURABLE_TOOLSETS)
seen = {ts_key for ts_key, _, _ in result}
try:
- from hermes_cli.plugins import discover_plugins, get_plugin_toolsets
- discover_plugins() # idempotent — ensures plugins are loaded
- for entry in get_plugin_toolsets():
+ projected = _projected_plugin_toolsets()
+ if projected is None:
+ from hermes_cli.plugins import discover_plugins, get_plugin_toolsets
+ discover_plugins() # idempotent — ensures plugins are loaded
+ for entry in projected[0] if projected is not None else get_plugin_toolsets():
if entry[0] not in seen:
seen.add(entry[0])
result.append(entry)
@@ -158,6 +171,8 @@ def _get_effective_configurable_toolsets():
def _get_plugin_toolset_keys() -> set:
"""Return the set of toolset keys provided by plugins."""
try:
+ if (projected := _projected_plugin_toolsets()) is not None:
+ return {key for key, _, _ in projected[0]}
# Non-blocking on CLI startup: while background discovery is still importing, serve last
# launch's persisted key set instead of joining the discovery thread.
from hermes_cli.plugins import get_plugin_toolset_keys_nowait
@@ -403,8 +418,10 @@ def enabled_mcp_server_names(config: dict) -> set[str]:
if isinstance(server_cfg, dict) and mcp_server_enabled(server_cfg)
}
try:
- from hermes_cli.plugins import get_portable_mcp_server_names_nowait
- portable = get_portable_mcp_server_names_nowait()
+ projected = _projected_plugin_toolsets()
+ if projected is None:
+ from hermes_cli.plugins import get_portable_mcp_server_names_nowait
+ portable = projected[1] if projected is not None else get_portable_mcp_server_names_nowait()
names |= portable - set(mcp_servers) # native config wins on a name collision (mirrors _load_mcp_config)
except Exception:
logger.debug("Failed to include portable MCP servers", exc_info=True)
diff --git a/hermes_cli/tools_config_mcp.py b/hermes_cli/tools_config_mcp.py
index f20ae10cf34..407d5324dd8 100644
--- a/hermes_cli/tools_config_mcp.py
+++ b/hermes_cli/tools_config_mcp.py
@@ -246,7 +246,8 @@ def tools_disable_enable_command(args):
platform = getattr(args, "platform", "cli")
config = load_config()
- valid_platforms = _known_tool_platforms()
+ from hermes_cli.tools_config import PLATFORMS
+ valid_platforms = PLATFORMS if platform in PLATFORMS else _known_tool_platforms() # built-ins load no plugin
if platform not in valid_platforms:
_print_error(f"Unknown platform '{platform}'. Valid: {', '.join(sorted(valid_platforms))}")
return
diff --git a/tests/conftest.py b/tests/conftest.py
index b9307476540..56422616f6a 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -375,6 +375,10 @@ def _hermetic_environment(tmp_path, tmp_path_factory, monkeypatch):
tui_server_mod = sys.modules.get("tui_gateway.server")
if tui_server_mod is not None and hasattr(tui_server_mod, "_served_profile_homes"):
monkeypatch.setattr(tui_server_mod, "_served_profile_homes", set())
+ # A classic CLI's gateway-session toolset reader is process-global too (``_ensure_gateway_session``).
+ tools_config_mod = sys.modules.get("hermes_cli.tools_config")
+ if tools_config_mod is not None and hasattr(tools_config_mod, "_gateway_plugin_toolsets"):
+ monkeypatch.setattr(tools_config_mod, "_gateway_plugin_toolsets", None)
hermes_state_mod = sys.modules.get("hermes_state")
if hermes_state_mod is not None and hasattr(hermes_state_mod, "DEFAULT_DB_PATH"):
diff --git a/tests/gateway/fixtures/cli_plugin_free_startup.py b/tests/gateway/fixtures/cli_plugin_free_startup.py
new file mode 100644
index 00000000000..20ad67a43fd
--- /dev/null
+++ b/tests/gateway/fixtures/cli_plugin_free_startup.py
@@ -0,0 +1,111 @@
+"""The classic CLI's real startup and command dispatch, in a fresh process, recording every plugin
+discovery / execution entry point it reaches (#134889 PLG-7).
+
+``argv[1]`` is the launch: ``oneshot`` (``_prepare_agent_startup``, as ``hermes chat -q`` runs it) or
+``interactive`` (main's fast path: discovery deferred to the first turn). The rest of argv are the
+chat flags (``-t terminal``, ``-s <skill>``). The gateway for ``HERMES_HOME`` must already run, with the probe plugin
+(a ``pre_command`` hook, a command, a skill and a toolset) loaded. Prints one JSON line.
+"""
+import io
+import json
+import os
+import queue
+import sys
+import traceback
+from contextlib import redirect_stdout
+from pathlib import Path
+
+from agent import skill_commands
+from hermes_cli import plugins
+
+calls = []
+
+
+def _spy(module, name):
+ real = getattr(module, name)
+
+ def spy(*args, **kwargs):
+ caller = next((f for f in traceback.extract_stack()[-2::-1] if not f.filename.endswith('plugins.py')), None)
+ calls.append(f'{name} <- {Path(caller.filename).name}:{caller.lineno}' if caller else name)
+ return real(*args, **kwargs)
+ setattr(module, name, spy)
+
+
+for _name in ('discover_plugins', 'start_background_plugin_discovery', 'fire_pre_command_hook', 'invoke_hook',
+ 'get_plugin_manager', 'get_plugin_toolset_keys_nowait', 'get_portable_mcp_server_names_nowait',
+ 'get_plugin_toolsets', 'get_plugin_commands'):
+ _spy(plugins, _name)
+_spy(skill_commands, 'get_plugin_skill_commands')
+
+
+def _add_skill(name):
+ path = Path(os.environ['HERMES_HOME'], 'skills', name)
+ path.mkdir(parents=True)
+ (path / 'SKILL.md').write_text(f'---\nname: {name}\ndescription: Added mid-run\n---\nSay {name.upper()}_BODY.\n')
+
+
+def _added_here(_cli): # installed in the profile, then /reload-skills here
+ _add_skill('fresh-skill')
+
+
+def _added_elsewhere(cli): # installed, then another client of this gateway rescans its session
+ _add_skill('other-skill')
+ cli._session_db.connection.call('skills.reload', session_id=cli.session_id)
+
+
+# Typed in this order after startup: the original probe, then the paths that used to discover
+# plugins in this process (help, a plugin skill, /tools and its toolset validation). ``/repo-skill`` is
+# the trusted repo's own skill in this process's cwd, which the gateway does not run from. A callable
+# step changes the profile's skills between commands; a repeated command's output is keyed ``<cmd> #2``.
+COMMANDS = ('/plugins', '/history', '/busy queue', '/help', '/help skills', '/probe-hook:probe check it',
+ '/repo-skill from the repo', _added_here, '/reload-skills', '/help skills', _added_elsewhere,
+ '/other-skill go now', '/tools', '/tools disable probe_tools')
+COMPLETE = ('/probe', '/tools enable ', '/tools disable ')
+
+
+def main():
+ mode, flags = sys.argv[1], sys.argv[2:]
+ from hermes_cli import main as hermes_main
+ args = hermes_main._light_chat_parser().parse_args(['chat', *flags])
+ if mode == 'interactive':
+ os.environ['HERMES_DEFER_AGENT_STARTUP'] = '1'
+ else:
+ hermes_main._prepare_agent_startup(args)
+ import cli
+ from prompt_toolkit.document import Document
+ outputs, errors, completions = {}, [], {}
+ with redirect_stdout(io.StringIO()) as out:
+ c = cli._build_cli_from_args(None, args.toolsets, None, None, None, None, None, None, None, True, None,
+ False, False, False, args.skills)
+ c._ensure_gateway_session()
+ agent = c._init_agent()
+ c._pending_input = queue.Queue()
+ for command in COMMANDS:
+ if callable(command):
+ command(c)
+ continue
+ start = out.tell()
+ try:
+ c.process_command(command)
+ except Exception:
+ errors.append(f'{command}: {traceback.format_exc()}')
+ outputs[command if command not in outputs else f'{command} #2'] = out.getvalue()[start:]
+ try:
+ from hermes_cli.commands_completion import cli_slash_completer
+ completer = cli_slash_completer(c) # the prompt's own completer
+ for text in COMPLETE:
+ completions[text] = sorted({x.text for x in completer.get_completions(Document(text), None)})
+ except Exception:
+ errors.append(f'completion: {traceback.format_exc()}')
+ queued = []
+ while not c._pending_input.empty():
+ queued.append(str(c._pending_input.get()))
+ print(json.dumps({'calls': calls, 'agent': agent, 'session_id': c.session_id, 'output': out.getvalue(),
+ 'outputs': outputs, 'errors': errors, 'completions': completions, 'queued': queued,
+ 'model_tools': 'model_tools' in sys.modules,
+ 'plugin_modules': sorted(m for m in sys.modules if m.startswith('hermes_plugins'))}),
+ file=sys.__stdout__, flush=True)
+ os._exit(0)
+
+
+main()
diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.py
index f1dfc42c65f..ed619289935 100644
--- a/tests/gateway/test_cli_plugin_command_in_gateway.py
+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py
@@ -286,7 +286,8 @@ def test_a_redial_to_a_restarted_gateway_and_slash_new_reread_the_plugin_command
# B's catalog has no /alpha: one refresh on the miss, never a slash.exec, no plugin output
assert stale[1] == ['commands.catalog'] and 'RAN_alpha' not in stale[0], stale
assert c.session_id != first and conn.epoch == epoch_b
- assert new_calls == [('commands.catalog', None), ('slash.exec', c.session_id)], new_calls
+ # /new reads the new session's own catalog (its skills come from that session's folder)
+ assert new_calls == [('commands.catalog', c.session_id), ('slash.exec', c.session_id)], new_calls
assert f'RAN_beta PID={b.pid}' in after_new, after_new
diff --git a/tests/gateway/test_pre_command_in_gateway.py b/tests/gateway/test_pre_command_in_gateway.py
new file mode 100644
index 00000000000..13c78c52cb5
--- /dev/null
+++ b/tests/gateway/test_pre_command_in_gateway.py
@@ -0,0 +1,605 @@
+"""``pre_command`` fires once, in the gateway, for every local surface, and the classic CLI's ``/plugins``
+reads the gateway's loaded plugins (#134889 PLG-7).
+
+A real daemon (``gateway.run``) loads a user plugin whose ``pre_command`` hook appends one JSON line per
+call to a log. Commands reach the gateway the way each client sends them: ``slash.exec`` (classic CLI,
+Ink TUI, Desktop) and ``command.dispatch`` (Ink TUI). The classic CLI runs in this test process, where
+any plugin-manager read fails the test.
+"""
+from contextlib import contextmanager
+import json
+import os
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import threading
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon
+from tests.gateway.test_cli_plugin_command_in_gateway import _Wire
+from tests.waiting import wait_until
+
+_PLUGIN = '''import json
+import os
+from pathlib import Path
+
+
+def register(ctx):
+ def seen(**kw):
+ from hermes_constants import get_hermes_home
+ with open(%r, "a") as log:
+ log.write(json.dumps(dict(kw, pid=os.getpid(), home=str(get_hermes_home()))) + "\\n")
+ ctx.register_hook("pre_command", seen)
+ ctx.register_command("probe-hook-cmd", lambda arg: "ok", description="Probe command")
+ ctx.register_skill("probe", Path(__file__).with_name("SKILL.md"), "Probe plugin skill")
+ ctx.register_tool(name="probe_ping", toolset="probe_tools", schema={"name": "probe_ping",
+ "description": "d", "parameters": {"type": "object", "properties": {}}}, handler=lambda args, **kw: "pong")
+'''
+_SKILL = "---\nname: probe\ndescription: Probe plugin skill\n---\nSay PROBE_SKILL_BODY.\n"
+
+
+def _hook_lines(log):
+ return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
+
+
+def _wait_hooks(log, count):
+ """The hook log once it holds ``count`` lines (a notice fires after its reply)."""
+ def landed():
+ lines = _hook_lines(log)
+ return lines if len(lines) >= count else []
+ return wait_until(landed, timeout=20, what=f'{count} pre_command lines in {log.name}')
+
+
+def _hooks_through(log, command):
+ """The hook log once ``command``'s line landed. One session's deliveries fire in arrival order, so
+ every delivery queued before it has landed too: an observed command sent last is the barrier."""
+ def landed():
+ lines = _hook_lines(log)
+ return lines if any(r['command'] == command for r in lines) else []
+ return wait_until(landed, timeout=20, what=f'the pre_command line for /{command} in {log.name}')
+
+
+def _probe_plugin(home, log):
+ plugin = home / 'plugins' / 'probe-hook'
+ plugin.mkdir(parents=True)
+ (plugin / 'plugin.yaml').write_text("name: probe-hook\nversion: '1.0'\n")
+ (plugin / '__init__.py').write_text(_PLUGIN % str(log))
+ (plugin / 'SKILL.md').write_text(_SKILL)
+
+
+@contextmanager
+def _gateway(tmp_path, *, isolation=None, beta=False, project=False):
+ """A real daemon whose profile loads the probe plugin: ``(proc, desc, home, work, env, log)``.
+ ``isolation`` sets ``plugins.isolation``; ``beta`` also serves profile ``beta`` (multiplexed), whose
+ own copy of the plugin logs to ``beta.jsonl``; ``project`` makes ``work`` a trusted repo with its own
+ ``repo-skill`` (the daemon runs from the checkout, not from ``work``) and auto-loads the plugin skill."""
+ root = Path(__file__).resolve().parents[2]
+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ work.mkdir()
+ log = tmp_path / 'pre_command.jsonl'
+ _probe_plugin(home, log)
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ profile = {'model': {'provider': 'custom', 'default': 'plugin-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'plugins': {'enabled': ['probe-hook'], **({'isolation': isolation} if isolation else {})}}
+ if project:
+ (work / '.git').mkdir()
+ (work / '.hermes' / 'skills' / 'repo-skill').mkdir(parents=True)
+ (work / '.hermes' / 'skills' / 'repo-skill' / 'SKILL.md').write_text(
+ '---\nname: repo-skill\ndescription: Repo-only skill\n---\nSay REPO_SKILL_BODY.\n')
+ profile['skills'] = {'trusted_project_dirs': [str(work)], 'auto_load': ['probe-hook:probe']}
+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': beta}, **profile}))
+ if beta:
+ (home / 'profiles' / 'beta').mkdir(parents=True)
+ (home / 'profiles' / 'beta' / 'config.yaml').write_text(json.dumps(profile))
+ _probe_plugin(home / 'profiles' / 'beta', tmp_path / 'beta.jsonl')
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
+ try:
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ yield proc, desc, home, work, env, log, peer
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ finally:
+ peer.release.set()
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+
+
[email protected]('mode, flags', [('oneshot', ['-t', 'terminal', '-s', 'probe-hook:probe']), ('interactive', [])])
+def test_real_cli_startup_and_commands_run_no_plugin_code_in_the_cli(tmp_path, mode, flags):
+ """Real startup (launch discovery, toolset validation, deferred startup, agent init) and real
+ ``process_command`` dispatch in a fresh CLI process: no plugin entry point is reached there, not even
+ for ``-s``/``skills.auto_load`` naming a plugin skill, ``/help``, a plugin skill, ``/reload-skills``,
+ ``/tools`` (and its toolset validation) or completion, which read the gateway's lists, refreshed
+ after a rescan here or by another client; each recognized command fires ``pre_command`` once, in the gateway, in typed order,
+ with main's values. The CLI starts in a trusted repo the gateway does not run from: its project skill
+ is listed and loaded from the session's folder."""
+ from agent.i18n import t
+ root = Path(__file__).resolve().parents[2]
+ with _gateway(tmp_path, project=True) as (proc, _desc, home, work, env, log, _peer):
+ probe = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/cli_plugin_free_startup.py'),
+ mode, *flags], cwd=work, env=env, capture_output=True, text=True, timeout=180, check=False)
+ assert probe.returncode == 0, probe.stdout + probe.stderr
+ result = json.loads(probe.stdout.strip().splitlines()[-1])
+ fired = _wait_hooks(log, 9)
+ config = (home / 'config.yaml').read_text()
+ assert result['calls'] == [], result['calls']
+ assert result['plugin_modules'] == [] and result['model_tools'] is False
+ assert result['errors'] == [], result['errors']
+ assert result['agent'] is True, result['output']
+ first = fired[0]['session_key']
+ assert [(r['pid'], r['surface'], r['platform'], r['command'], r['args_raw']) for r in fired] == [
+ (proc.pid, 'cli', 'cli', 'plugins', ''), (proc.pid, 'cli', 'cli', 'history', ''),
+ (proc.pid, 'cli', 'cli', 'busy', 'queue'), (proc.pid, 'cli', 'cli', 'help', ''),
+ (proc.pid, 'cli', 'cli', 'help', 'skills'), (proc.pid, 'cli', 'cli', 'reload-skills', ''),
+ (proc.pid, 'cli', 'cli', 'help', 'skills'), (proc.pid, 'cli', 'cli', 'tools', ''),
+ (proc.pid, 'cli', 'cli', 'tools', 'disable probe_tools'),
+ ], fired
+ assert {r['session_key'] for r in fired} == {first} # (``/tools disable`` then starts a new session)
+ outputs = result['outputs']
+ detail = (f"(1 {t('cli.plugins.count_noun_tools')}, 1 {t('cli.plugins.count_noun_hooks')}, "
+ f"1 {t('cli.plugins.count_noun_commands')})")
+ assert f'probe-hook v1.0 {detail}' in outputs['/plugins'], outputs['/plugins']
+ assert '/probe-hook:probe' in outputs['/help skills'] and 'Probe plugin skill' in outputs['/help skills']
+ assert '/repo-skill' in outputs['/help skills'], outputs['/help skills']
+ assert t('cli.skills.loading_skill', name='probe-hook:probe') in outputs['/probe-hook:probe check it']
+ plugin_skill, repo_skill, *later = result['queued']
+ assert 'PROBE_SKILL_BODY' in plugin_skill and 'check it' in plugin_skill
+ assert 'REPO_SKILL_BODY' in repo_skill and 'from the repo' in repo_skill, outputs['/repo-skill from the repo']
+ assert 'fresh-skill' in outputs['/reload-skills'], outputs['/reload-skills'] # the gateway's rescan
+ assert '/fresh-skill' in outputs['/help skills #2'], outputs['/help skills #2'] # not the list /help cached
+ # Rescanned by another client: the first invocation already resolves it
+ assert len(later) == 1 and 'OTHER-SKILL_BODY' in later[0] and 'go now' in later[0], outputs['/other-skill go now']
+ disabled = outputs['/tools disable probe_tools'] # the gateway's plugin toolset is recognised and saved
+ assert 'Disabled: probe_tools' in disabled and 'Unknown toolset' not in disabled, disabled
+ assert 'probe_tools' in config
+ assert result['completions']['/probe'] == ['probe-hook-cmd', 'probe-hook:probe'] # the gateway's command and skill
+ assert 'probe_tools' in result['completions']['/tools enable ']
+ assert 'probe_tools' not in result['completions']['/tools disable ']
+
+
+def test_pre_command_fires_once_in_the_gateway_and_cli_plugins_reads_its_list(tmp_path, monkeypatch, capsys):
+ import hermes_cli.plugins as plugins_mod
+ from agent.i18n import t
+ from cli import HermesCLI
+ root = Path(__file__).resolve().parents[2]
+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ work.mkdir()
+ log = tmp_path / 'pre_command.jsonl'
+ _probe_plugin(home, log)
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'plugin-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'plugins': {'enabled': ['probe-hook']},
+ }))
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
+
+ def no_local_plugin(*_a, **_k):
+ pytest.fail('the CLI process loaded, read or fired plugin code')
+ for name in ('get_plugin_manager', 'discover_plugins', 'fire_pre_command_hook', 'get_plugin_commands'):
+ monkeypatch.setattr(plugins_mod, name, no_local_plugin)
+ sent = {}
+ try:
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ wire = _Wire(home, desc)
+ try:
+ for source in ('cli', 'tui', 'gui'):
+ sent[source] = wire.call('session.create', request_id=f'pre-{source}', source=source,
+ toolsets=[], cwd=str(work))['session_id']
+ for source, sid in sent.items():
+ wire.call('slash.exec', session_id=sid, command='/help')
+ wire.call('command.dispatch', session_id=sent['tui'], name='status', arg='') # Ink's own read
+ fired = _hook_lines(log)
+ assert [(r['pid'], r['surface'], r['platform'], r['command'], r['alias_used'], r['session_key'])
+ for r in fired] == [
+ # Main's values on every local surface (Ink and Desktop fired it through the CLI
+ # slash worker): surface and platform "cli"; session_key tells the sessions apart.
+ (proc.pid, 'cli', 'cli', 'help', 'help', sent['cli']),
+ (proc.pid, 'cli', 'cli', 'help', 'help', sent['tui']),
+ (proc.pid, 'cli', 'cli', 'help', 'help', sent['gui']),
+ (proc.pid, 'cli', 'cli', 'status', 'status', sent['tui']),
+ ], fired
+
+ # The classic CLI: a command it forwards fires once, in the gateway; /plugins lists
+ # the gateway's loaded plugins. Both read this profile's home as the CLI process does.
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: wire)
+ c = HermesCLI.__new__(HermesCLI)
+ c.config, c.session_id = {}, sent['cli']
+ assert c.process_command('/busy queue') is True
+ assert [(r['pid'], r['command'], r['args_raw'], r['session_key'])
+ for r in _hook_lines(log)[len(fired):]] == [(proc.pid, 'busy', 'queue', sent['cli'])]
+ capsys.readouterr()
+ c._cmd_plugins('/plugins')
+ listing = capsys.readouterr().out
+ finally:
+ wire.close()
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+
+ assert proc.pid != os.getpid()
+ assert not [m for m in sys.modules if m.startswith('hermes_plugins.')]
+ assert 'plugins.list' in wire.calls
+ detail = (f"(1 {t('cli.plugins.count_noun_tools')}, 1 {t('cli.plugins.count_noun_hooks')}, "
+ f"1 {t('cli.plugins.count_noun_commands')})")
+ assert f'probe-hook v1.0 {detail}' in listing, listing
+
+
+def test_accepted_tui_cron_reads_fire_once_and_refused_writes_fire_nothing(tmp_path):
+ """A TUI session's ``/cron`` reads (main's sidecar text) fire once through both RPCs; a refused
+ ``/cron`` write, and ``/cron`` on a classic CLI session (refused there), fire nothing."""
+ from hermes_cli.gateway_client import GatewayClientError
+ with _gateway(tmp_path) as (_proc, desc, home, work, _env, log, _peer):
+ wire = _Wire(home, desc)
+ try:
+ tui = wire.call('session.create', request_id='cron-tui', source='tui', toolsets=[], cwd=str(work))['session_id']
+ cli = wire.call('session.create', request_id='cron-cli', source='cli', toolsets=[], cwd=str(work))['session_id']
+ wire.call('slash.exec', session_id=tui, command='/cron')
+ wire.call('command.dispatch', session_id=tui, name='cron', arg='list')
+ wire.call('slash.exec', session_id=tui, command='/cron list --all')
+ wire.call('slash.exec', session_id=tui, command='/status')
+ for sid, command in ((tui, '/cron add 1h ping'), (cli, '/cron'), (cli, '/cron list')):
+ with pytest.raises(GatewayClientError):
+ wire.call('slash.exec', session_id=sid, command=command)
+ with pytest.raises(GatewayClientError):
+ wire.call('command.dispatch', session_id=tui, name='cron', arg='remove job-1')
+ fired = _hook_lines(log)
+ finally:
+ wire.close()
+ assert [(r['command'], r['args_raw'], r['session_key']) for r in fired] == [
+ ('cron', '', tui), ('cron', 'list', tui), ('cron', 'list --all', tui), ('status', '', tui)], fired
+
+
+def test_commands_that_still_run_during_a_turn_fire_except_the_escape_hatches(tmp_path):
+ """Main's CLI fired ``pre_command`` for every command it ran during a turn. Kept: ``/footer`` and
+ ``/busy`` (``busy_policy='dispatch'``) and a CLI-local command fire; only messaging's escape
+ hatches (``/stop``, ``/approve``, ``/deny``) stay outside plugin reach while the turn runs."""
+ with _gateway(tmp_path) as (_proc, desc, home, work, _env, log, peer):
+ wire = _Wire(home, desc)
+ try:
+ sid = wire.call('session.create', request_id='busy', source='cli', toolsets=[], cwd=str(work))['session_id']
+ wire.call('prompt.submit', session_id=sid, input_id='busy-turn', text='BLOCK_STARTED')
+ assert peer.blocked.wait(30)
+ wire.call('slash.exec', session_id=sid, command='/footer status')
+ wire.call('slash.exec', session_id=sid, command='/busy queue')
+ assert wire.call('command.observe', session_id=sid, name='history', arg='') == {'queued': True}
+ assert wire.call('command.observe', session_id=sid, name='stop', arg='') == {'queued': False}
+ assert wire.call('command.observe', session_id=sid, name='approve', arg='') == {'queued': False}
+ wire.call('slash.exec', session_id=sid, command='/deny')
+ # The barrier: one session's deliveries land in arrival order, so once this last one has,
+ # every earlier one has too (and an escape hatch's, had it fired, would be in the log).
+ assert wire.call('command.observe', session_id=sid, name='version', arg='') == {'queued': True}
+ fired = _hooks_through(log, 'version')
+ peer.release.set()
+ finally:
+ wire.close()
+ assert [(r['command'], r['args_raw']) for r in fired] == [('footer', 'status'), ('busy', 'queue'),
+ ('history', ''), ('version', '')], fired
+
+
+class _ProfileWire(_Wire):
+ """``_Wire`` on a ticket minted for ``profile`` (a served profile's home)."""
+
+ def __init__(self, home, desc, profile):
+ import asyncio
+ from websockets.asyncio.client import connect
+ from tests.gateway.test_normal_runtime_boot import control
+ self.loop = asyncio.new_event_loop()
+ self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
+ self.thread.start()
+ self.calls = []
+ grant = control(home, 'session-ticket', {'profile_id': str(profile), 'instance_id': desc['instance_id'],
+ 'purpose': 'interactive'})
+
+ async def _open():
+ return await connect(desc['api_origin'].replace('http:', 'ws:') + '/api/ws',
+ subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']])
+ self.ws = self._run(_open())
+
+
+def test_pre_command_runs_in_the_plugin_host_under_host_isolation(tmp_path):
+ """``plugins.isolation: host``: the hook fires where the dispatcher runs the plugin, the profile's
+ plugin host, never inside the gateway process; same values and order as in-process."""
+ with _gateway(tmp_path, isolation='host') as (proc, desc, home, work, _env, log, _peer):
+ wire = _Wire(home, desc)
+ try:
+ sid = wire.call('session.create', request_id='host', source='cli', toolsets=[], cwd=str(work))['session_id']
+ wire.call('slash.exec', session_id=sid, command='/help')
+ assert wire.call('command.observe', session_id=sid, name='history', arg='') == {'queued': True}
+ fired = _hooks_through(log, 'history')
+ finally:
+ wire.close()
+ assert [(r['surface'], r['platform'], r['command'], r['session_key']) for r in fired] == [
+ ('cli', 'cli', 'help', sid), ('cli', 'cli', 'history', sid)], fired
+ hosts = {r['pid'] for r in fired}
+ assert len(hosts) == 1 and proc.pid not in hosts, (proc.pid, hosts)
+
+
+def test_pre_command_fires_in_the_sessions_own_profile(tmp_path):
+ """A multiplexing gateway: a ``beta`` session's commands reach ``beta``'s plugin, under ``beta``'s
+ home, and never the launch profile's copy; the launch profile's session the reverse."""
+ with _gateway(tmp_path, beta=True) as (_proc, desc, home, work, _env, log, _peer):
+ beta_home = (home / 'profiles' / 'beta').resolve()
+ root, beta = _Wire(home, desc), _ProfileWire(home, desc, beta_home)
+ try:
+ root_sid = root.call('session.create', request_id='root', source='cli', toolsets=[], cwd=str(work))['session_id']
+ beta_sid = beta.call('session.create', request_id='beta', source='tui', toolsets=[], cwd=str(work))['session_id']
+ beta.call('slash.exec', session_id=beta_sid, command='/help')
+ assert beta.call('command.observe', session_id=beta_sid, name='history', arg='') == {'queued': True}
+ root.call('slash.exec', session_id=root_sid, command='/status')
+ beta_fired = _hooks_through(tmp_path / 'beta.jsonl', 'history')
+ root_fired = _hooks_through(log, 'status')
+ finally:
+ root.close()
+ beta.close()
+ assert [(r['command'], r['session_key'], r['home']) for r in beta_fired] == [
+ ('help', beta_sid, str(beta_home)), ('history', beta_sid, str(beta_home))], beta_fired
+ assert [(r['command'], r['session_key'], r['home']) for r in root_fired] == [
+ ('status', root_sid, str(home.resolve()))], root_fired
+
+
+def test_commands_refused_during_a_turn_fire_nothing(tmp_path):
+ """``/reasoning`` is a settings control the busy dispatcher rejects during a turn (default
+ ``busy_policy``): through ``slash.exec`` and ``command.dispatch`` it is refused and fires nothing.
+ A mid-run variant that refuses its arguments (``/goal <new text>``, ``/loop <new loop>``) fires
+ nothing either; the same variant accepting a control verb (``/goal status``) fires once."""
+ from agent.i18n import t
+ with _gateway(tmp_path) as (_proc, desc, home, work, _env, log, peer):
+ wire = _Wire(home, desc)
+ try:
+ sid = wire.call('session.create', request_id='refused', source='cli', toolsets=[], cwd=str(work))['session_id']
+ wire.call('prompt.submit', session_id=sid, input_id='refused-turn', text='BLOCK_STARTED')
+ assert peer.blocked.wait(30)
+ replies = [wire.call('slash.exec', session_id=sid, command='/reasoning high'),
+ wire.call('command.dispatch', session_id=sid, name='reasoning', arg='high')]
+ variants = [wire.call('slash.exec', session_id=sid, command='/goal ship the release'),
+ wire.call('command.dispatch', session_id=sid, name='loop', arg='every 5m check ci')]
+ wire.call('slash.exec', session_id=sid, command='/goal status')
+ assert wire.call('command.observe', session_id=sid, name='history', arg='') == {'queued': True}
+ fired = _hooks_through(log, 'history')
+ peer.release.set()
+ finally:
+ wire.close()
+ assert [r['output'] for r in replies] == [t('gateway.busy.slash_rejected', command='reasoning')] * 2
+ assert [r['output'] for r in variants] == [t('gateway.busy.reject_goal'), t('gateway.busy.reject_loop')]
+ assert [(r['command'], r['args_raw']) for r in fired] == [('goal', 'status'), ('history', '')], fired
+
+
+def test_commands_the_cli_refuses_on_the_gateway_fire_nothing(monkeypatch, capsys):
+ """A named refusal (``/handoff``) and a registry command with no classic CLI handler run nothing in
+ the CLI, so no ``command.observe`` goes out; a command the CLI runs is still reported."""
+ from cli import HermesCLI
+ from hermes_cli.commands import COMMAND_REGISTRY
+
+ class Connection:
+ epoch, final, closed = 1, False, False
+ calls = []
+
+ def call(self, method, **params):
+ self.calls.append((method, params.get('name')))
+ return {}
+
+ def call_tagged(self, method, **params):
+ return self.call(method, **params), self.epoch
+ connection = Connection()
+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: connection)
+ monkeypatch.setattr('hermes_cli.plugins.fire_pre_command_hook', lambda **_k: pytest.fail('fired locally'))
+ unhandled = next(cmd.name for cmd in COMMAND_REGISTRY
+ if HermesCLI._slash_handler(cmd.name) is None and cmd.name != 'handoff')
+ c = HermesCLI.__new__(HermesCLI)
+ c.config, c.session_id = {}, 's1'
+ c.process_command('/handoff telegram')
+ c.process_command('/' + unhandled)
+ assert [call for call in connection.calls if call[0] == 'command.observe'] == []
+ c.process_command('/reload')
+ assert ('command.observe', 'reload') in connection.calls
+
+
+def _authority(state):
+ from types import SimpleNamespace
+ live = SimpleNamespace(source=object())
+ return SimpleNamespace(sessions={'s1': live}, runner=object(), profile_id='/tmp/home',
+ _handle=lambda _ref: SimpleNamespace(execution_state=state))
+
+
[email protected]('state, command, expected', [
+ ('idle', 'status', 1), ('running', 'status', 1), ('idle', 'stop', 1),
+ ('running', 'stop', 0), ('running', 'approve', 0), ('running', 'deny', 0)])
+def test_only_the_escape_hatches_skip_pre_command_during_a_turn(monkeypatch, state, command, expected):
+ import asyncio
+ from contextlib import nullcontext
+ from types import SimpleNamespace
+ from gateway import session_commands
+ calls = []
+ monkeypatch.setattr('gateway.session_local.authorize_local_source', lambda _r, _s: True)
+ monkeypatch.setattr('gateway.session_policy.policy_for_source', lambda _r, _s: SimpleNamespace(platform='tui'))
+ monkeypatch.setattr('gateway.run._profile_runtime_scope', lambda _home: nullcontext())
+ monkeypatch.setattr('hermes_cli.plugins.fire_pre_command_hook', lambda **kw: calls.append(kw))
+ asyncio.run(session_commands._pre_command_before(_authority(state), SimpleNamespace(session_id='s1'),
+ command, command, ''))
+ assert calls == [dict(surface='cli', command=command, alias_used=command, args_raw='',
+ session_key='s1', platform='cli')] * expected
+
+
+def test_a_hung_pre_command_callback_is_bounded_and_each_session_keeps_its_order(monkeypatch):
+ """``pre_command`` runs through the hook dispatcher's bounded path (``plugins.hook_callback_timeout``,
+ abandoned worker, suppression), on the gateway's own observer workers, never the loop's shared
+ executor. A callback that hangs for session A's first command: session B's observers run at once,
+ A's next command waits only for the bound and skips the still-running callback (never overlapping
+ or reordering it), later commands skip it, no extra worker piles up, and a session's backlog is capped."""
+ import asyncio
+ from concurrent.futures import ThreadPoolExecutor
+ from contextlib import nullcontext
+ from types import SimpleNamespace
+ from gateway import session_commands
+ from hermes_cli.plugins import PluginManager
+ release, seen = threading.Event(), []
+
+ def hung(session_key, command, **_kw):
+ if (session_key, command) == ('A', 'first'):
+ release.wait()
+
+ def record(session_key, command, **_kw):
+ seen.append((session_key, command, threading.current_thread().name.split('-')[1]))
+ manager = PluginManager()
+ manager._hooks['pre_command'] = [hung, record]
+ monkeypatch.setattr('hermes_cli.plugins.get_plugin_manager', lambda: manager)
+ monkeypatch.setattr('hermes_cli.plugins._resolve_hook_callback_timeout', lambda: 0.5)
+ monkeypatch.setattr('gateway.session_local.authorize_local_source', lambda _r, _s: True)
+ monkeypatch.setattr('gateway.run._profile_runtime_scope', lambda _home: nullcontext())
+ live = SimpleNamespace(source=object())
+ authority = SimpleNamespace(sessions=dict.fromkeys('ABC', live), runner=object(), profile_id='/tmp/home',
+ _handle=lambda _ref: SimpleNamespace(execution_state='idle'))
+
+ class SharedExecutor(ThreadPoolExecutor):
+ def submit(self, *_a, **_k):
+ raise AssertionError('pre_command ran on the loop\'s shared default executor')
+
+ def deliver(session, command):
+ return session_commands._pre_command(authority, SimpleNamespace(session_id=session), command, command, '')
+
+ async def run():
+ asyncio.get_running_loop().set_default_executor(SharedExecutor(1))
+ a1, b1 = deliver('A', 'first'), deliver('B', 'b1')
+ await asyncio.wait({b1}) # B is not queued behind A's hung callback
+ assert seen == [('B', 'b1', 'hook')] and not a1.done()
+ a2 = deliver('A', 'second')
+ await asyncio.wait({a1, a2}) # A1 returns at the bound; A2 after it, skipping the hung call
+ assert seen[1:] == [('A', 'first', 'hook'), ('A', 'second', 'hook')]
+ later = [deliver(s, 'first') for s in 'AB' * 10] # the hung callback is suppressed now
+ await asyncio.wait(later)
+ assert len(seen) == 23
+ backlog = [deliver('C', str(n)) for n in range(session_commands._PRE_COMMAND_PENDING + 5)]
+ assert backlog.count(None) == 5 # past the cap a delivery is dropped (logged), not queued
+ await asyncio.wait([task for task in backlog if task is not None])
+ try:
+ asyncio.run(run())
+ assert list(manager._hook_abandoned.values()) == [{('pre_command', id(hung), 'A')}] # one, ever
+ finally:
+ release.set()
+
+
+def test_callbacks_waiting_out_their_bound_hold_no_worker_another_session_needs(monkeypatch):
+ """Six sessions whose ``pre_command`` callback is still inside ``plugins.hook_callback_timeout`` hold
+ no shared observer worker: another session's delivery runs at once, not when a slot frees."""
+ import asyncio
+ from contextlib import nullcontext
+ from types import SimpleNamespace
+ from gateway import session_commands
+ from hermes_cli.plugins import PluginManager
+ slow, inside, seen, lock = [f'S{n}' for n in range(6)], [], [], threading.Lock()
+ release, all_in = threading.Event(), threading.Event()
+
+ def callback(session_key, **_kw):
+ if session_key not in slow:
+ seen.append(session_key)
+ return
+ with lock:
+ inside.append(session_key)
+ if len(inside) == len(slow):
+ all_in.set()
+ release.wait()
+ manager = PluginManager()
+ manager._hooks['pre_command'] = [callback]
+ monkeypatch.setattr('hermes_cli.plugins.get_plugin_manager', lambda: manager)
+ monkeypatch.setattr('hermes_cli.plugins._resolve_hook_callback_timeout', lambda: 30)
+ monkeypatch.setattr('gateway.session_local.authorize_local_source', lambda _r, _s: True)
+ monkeypatch.setattr('gateway.run._profile_runtime_scope', lambda _home: nullcontext())
+ live = SimpleNamespace(source=object())
+ authority = SimpleNamespace(sessions=dict.fromkeys([*slow, 'fresh'], live), runner=object(),
+ profile_id='/tmp/home', _handle=lambda _ref: SimpleNamespace(execution_state='idle'))
+
+ def deliver(session):
+ return session_commands._pre_command(authority, SimpleNamespace(session_id=session), 'help', 'help', '')
+
+ async def run():
+ stuck = [deliver(s) for s in slow]
+ try:
+ fresh = deliver('fresh')
+ done, _ = await asyncio.wait({fresh}, timeout=10) # a deadline: GREEN returns at once
+ assert done == {fresh} and seen == ['fresh'], (done, seen, inside)
+ assert await asyncio.to_thread(all_in.wait, 10), inside # every slow session entered its callback
+ finally:
+ release.set()
+ await asyncio.wait(stuck)
+ try:
+ asyncio.run(run())
+ finally:
+ release.set()
+
+
+def test_an_older_gateway_without_plugins_list_is_named_and_loads_nothing(monkeypatch, capsys):
+ from hermes_cli import gateway_plugin_commands
+ from hermes_cli.gateway_client import GatewayRPCError
+
+ class Older:
+ def call(self, method, **_params):
+ raise GatewayRPCError('unknown_method', code=-32601)
+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: Older())
+ monkeypatch.setattr('hermes_cli.plugins.get_plugin_manager', lambda: pytest.fail('loaded plugins locally'))
+ assert gateway_plugin_commands.loaded(object()) == {}
+ assert "predates this CLI" in capsys.readouterr().out
+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: None)
+ assert gateway_plugin_commands.loaded(object()) is None # off the gateway: main's in-process listing
+
+
+def test_an_older_gateway_without_command_observe_is_named_once_and_nothing_fires_locally(monkeypatch, capsys):
+ from hermes_cli import gateway_plugin_commands
+ from hermes_cli.gateway_client import GatewayRPCError
+
+ class Older:
+ epoch = 1
+ calls = []
+
+ def call(self, method, **params):
+ self.calls.append((method, params))
+ raise GatewayRPCError('unknown_method', code=-32601)
+ older = Older()
+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: older)
+ monkeypatch.setattr('hermes_cli.plugins.fire_pre_command_hook', lambda **_k: pytest.fail('fired locally'))
+ monkeypatch.setattr('hermes_cli.plugins.get_plugin_manager', lambda: pytest.fail('loaded plugins locally'))
+ cli = type('CLI', (), {'session_id': 's1'})()
+ assert gateway_plugin_commands.observe(cli, 'history', '') is True
+ assert gateway_plugin_commands.observe(cli, 'version', '') is True
+ assert older.calls == [('command.observe', {'session_id': 's1', 'name': 'history', 'arg': ''})]
+ assert capsys.readouterr().out.count('predates this CLI') == 1
+ older.epoch = 2 # a redial (maybe to a restarted, newer gateway) asks again, without a second notice
+ assert gateway_plugin_commands.observe(cli, 'history', 'x') is True
+ assert len(older.calls) == 2 and 'predates' not in capsys.readouterr().out
+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: None)
+ assert gateway_plugin_commands.observe(cli, 'history', '') is False # off the gateway: main's own hook
diff --git a/tests/hermes_cli/test_cli_init.py b/tests/hermes_cli/test_cli_init.py
index 96eb002d983..d5e6061b8e0 100644
--- a/tests/hermes_cli/test_cli_init.py
+++ b/tests/hermes_cli/test_cli_init.py
@@ -759,51 +759,23 @@ class TestRootLevelProviderOverride:
class TestPluginToolsetStartupValidation:
- """A toolset that is merely *not registered yet* must not be reported as unknown.
+ """Plugin toolsets are only known where plugins load (the gateway), so the CLI's toolset init
+ neither probes plugins nor judges names (#71650, PLG-7): the gateway refuses an unknown picked
+ name at session.create and reports a stale profile one with the session
+ (tests/hermes_cli/test_cli_profile_toolsets.py)."""
- Plugins register their toolsets during background discovery, while the CLI validates
- the configured list during construction -- i.e. before that thread has landed. Judging
- by the live registry alone therefore flags every configured plugin toolset as a typo on
- every launch, including one-shot/quiet runs whose stdout is machine-parsed.
- """
-
- @staticmethod
- def _init_toolsets(monkeypatch, toolsets, *, registry, plugin_keys):
+ def test_init_probes_no_plugins_and_keeps_the_list(self, monkeypatch):
import cli as _cli_mod
stub = object.__new__(_cli_mod.HermesCLI)
printed: list[str] = []
stub._console_print = printed.append
- monkeypatch.setattr(_cli_mod, "validate_toolset", lambda name: name in registry)
monkeypatch.setattr(_cli_mod, "CLI_CONFIG", {"agent": {}})
- monkeypatch.setattr(
- "hermes_cli.plugins.get_plugin_toolset_keys_nowait",
- lambda: set(plugin_keys),
- )
- stub._init_toolsets(list(toolsets))
- return stub, printed
-
- def test_plugin_toolset_not_yet_registered_is_not_flagged(self, monkeypatch):
- stub, printed = self._init_toolsets(
- monkeypatch,
- ["terminal", "voice_stack"],
- registry={"terminal"},
- plugin_keys={"voice_stack"},
- )
+ for name in ("get_plugin_toolset_keys_nowait", "discover_plugins", "get_plugin_manager"):
+ monkeypatch.setattr(f"hermes_cli.plugins.{name}", lambda *_a: pytest.fail("probed plugins"))
+ stub._init_toolsets(["terminal", "voice_stack", "voice_stak"])
assert printed == []
- # The configured list is kept verbatim; only the false warning is silenced.
- assert stub.enabled_toolsets == ["terminal", "voice_stack"]
-
- def test_real_typo_still_warns(self, monkeypatch):
- _, printed = self._init_toolsets(
- monkeypatch,
- ["terminal", "voice_stak"],
- registry={"terminal"},
- plugin_keys={"voice_stack"},
- )
- assert len(printed) == 1
- assert "voice_stak" in printed[0]
- assert "voice_stack" not in printed[0]
+ assert stub.enabled_toolsets == ["terminal", "voice_stack", "voice_stak"]
diff --git a/tests/hermes_cli/test_cli_profile_toolsets.py b/tests/hermes_cli/test_cli_profile_toolsets.py
index 7c38cc1ce2d..07a3c166f36 100644
--- a/tests/hermes_cli/test_cli_profile_toolsets.py
+++ b/tests/hermes_cli/test_cli_profile_toolsets.py
@@ -54,14 +54,29 @@ def _created(client):
def test_stale_profile_toolset_warns_and_the_session_is_created(store, monkeypatch):
- from gateway.session_local_inventory import _policy_tools
+ from gateway.session_local_inventory import _policy_tools, _unknown_toolsets
from gateway.session_policy import build_policy
+ from tests.hermes_cli import test_gateway_session_store as fake
db, client = store
+ # The gateway judges the profile list against its own plugins and reports the stale name with the
+ # session (``unknown_toolsets``); the CLI prints main's "Unknown toolsets" line from it (PLG-7).
+ params_seen = {}
+ real_rpc = client.rpc
+
+ async def rpc(method, *, _timeout=None, **params):
+ reply = await real_rpc(method, **params)
+ if method == "session.create":
+ policy = params_seen["policy"] = build_policy(params, CONFIG)
+ reply["info"]["unknown_toolsets"] = _unknown_toolsets(list(policy.current_toolsets(CONFIG)), CONFIG)
+ return reply
+ monkeypatch.setattr(client, "rpc", rpc)
+ monkeypatch.setitem(fake.INFO, "enabled_toolsets", ["terminal"])
host, printed = _launch(monkeypatch, db)
- assert len(printed) == 1 and "gone_plugin" in printed[0] # main's "Unknown toolsets" startup warning
+ assert len(printed) == 1 and "gone_plugin" in printed[0] and "terminal" not in printed[0], printed
+ assert host.enabled_toolsets == ["terminal"] # the gateway's resolved list, for display
params = _created(client)
assert "toolsets" not in params
- policy = build_policy(params, CONFIG)
+ policy = params_seen["policy"]
assert "terminal" in policy.toolsets
_enabled, tools = _policy_tools(policy, CONFIG)
assert "terminal" in {tool["function"]["name"] for tool in tools}
diff --git a/tests/hermes_cli/test_cli_startup_trim.py b/tests/hermes_cli/test_cli_startup_trim.py
index ce5a3466a96..16e6b406335 100644
--- a/tests/hermes_cli/test_cli_startup_trim.py
+++ b/tests/hermes_cli/test_cli_startup_trim.py
@@ -56,21 +56,30 @@ def test_non_chat_agent_command_still_registers_hooks(monkeypatch):
assert calls == ["hooks", "webhooks"]
-def test_deferred_startup_spawns_no_mcp_and_registers_no_hooks(monkeypatch):
+def test_deferred_first_turn_discovers_no_plugins_spawns_no_mcp_and_registers_no_hooks(monkeypatch):
+ # Termux's deferred startup ran plugin discovery before the first turn; the gateway runs the turn
+ # and loads the plugins (PLG-7).
import cli as cli_mod
+ from hermes_cli import gateway_agent
+ from hermes_cli import mcp_startup
calls = []
monkeypatch.setenv("HERMES_DEFER_AGENT_STARTUP", "1")
- monkeypatch.setattr(cli_mod, "_deferred_agent_startup_done", False)
- monkeypatch.setitem(sys.modules, "hermes_cli.plugins", types.SimpleNamespace(
- discover_plugins=lambda: calls.append("plugins")))
- from hermes_cli import mcp_startup
+ cli = cli_mod.HermesCLI(compact=True)
+ import hermes_cli.plugins as plugins_mod
+ monkeypatch.setattr(plugins_mod, "discover_plugins", lambda *a, **k: calls.append("plugins"))
monkeypatch.setattr(mcp_startup, "start_background_mcp_discovery", lambda **k: calls.append("mcp"))
+ monkeypatch.setattr(mcp_startup, "ensure_mcp_discovery_before_agent_build", lambda **k: calls.append("mcp"))
monkeypatch.setitem(sys.modules, "agent.shell_hooks", types.SimpleNamespace(
register_from_config=lambda *a, **k: calls.append("hooks")))
monkeypatch.setitem(sys.modules, "agent.outbound_webhooks", types.SimpleNamespace(
register_from_config=lambda *a, **k: calls.append("webhooks")))
- cli_mod._prepare_deferred_agent_startup()
- assert calls == ["plugins"]
+ monkeypatch.setattr(gateway_agent, "GatewayAgent", lambda *_a, **_k: types.SimpleNamespace())
+ cli._session_db, cli._resumed, cli.conversation_history = object(), False, []
+ cli._install_tool_callbacks = lambda: None
+ cli._ensure_runtime_credentials = lambda: True
+ cli._ensure_gateway_session = lambda: None
+ assert cli._init_agent() is True
+ assert calls == []
def test_init_agent_runs_no_mcp_discovery(monkeypatch):
diff --git a/tests/hermes_cli/test_gateway_cli_commands.py b/tests/hermes_cli/test_gateway_cli_commands.py
index fdd2c070f47..edbf2557824 100644
--- a/tests/hermes_cli/test_gateway_cli_commands.py
+++ b/tests/hermes_cli/test_gateway_cli_commands.py
@@ -21,6 +21,11 @@ class _Conn:
return self.replies.get(method, {})
+def _observed(name, arg):
+ """The ``command.observe`` notice a command the CLI runs itself sends first (``pre_command``)."""
+ return ("command.observe", {"session_id": "local-s", "name": name, "arg": arg})
+
+
@pytest.fixture
def gateway_cli(monkeypatch):
def make(**replies):
@@ -41,7 +46,7 @@ def test_diff_session_renders_the_gateway_sessions_checkpoint_diff(gateway_cli,
cli, conn = gateway_cli(**{"rollback.session_diff": {
"enabled": True, "success": True, "stat": " a.py | 450 +", "diff": body, "diff_lines": 450}})
assert cli.process_command("/diff session") is True
- assert conn.calls == [("rollback.session_diff", {"session_id": "local-s"})]
+ assert conn.calls == [_observed("diff", "session"), ("rollback.session_diff", {"session_id": "local-s"})]
out = capsys.readouterr().out
assert "a.py | 450 +" in out and "+edited 399" in out and "+edited 400" not in out
assert "50 more lines" in out and "```" not in out
@@ -62,14 +67,14 @@ def test_diff_of_the_working_tree_stays_a_local_git_read(gateway_cli, monkeypatc
monkeypatch.setattr("tools.working_diff.collect_working_diff",
lambda cwd, mode, paths=None: seen.append(mode) or {"success": True, "empty": True})
cli.process_command("/diff staged")
- assert seen == ["staged"] and conn.calls == []
+ assert seen == ["staged"] and conn.calls == [_observed("diff", "staged")]
def test_reload_rereads_env_in_the_gateway_and_reports_its_count(gateway_cli, monkeypatch, capsys):
cli, conn = gateway_cli(**{"reload.env": {"updated": 3}})
monkeypatch.setattr("hermes_cli.config.reload_env", lambda: 0)
assert cli.process_command("/reload") is True
- assert conn.calls == [("reload.env", {"session_id": "local-s"})]
+ assert conn.calls == [_observed("reload", ""), ("reload.env", {"session_id": "local-s"})]
assert "3" in capsys.readouterr().out
@@ -77,4 +82,4 @@ def test_handoff_is_refused_with_a_message_on_the_gateway(gateway_cli, capsys):
cli, conn = gateway_cli()
assert cli.process_command("/handoff telegram") is True # the session stays
assert "/handoff is not available on the shared gateway yet" in capsys.readouterr().out
- assert conn.calls == []
+ assert conn.calls == [] # a named refusal runs nothing: no command.observe (pre_command) either
diff --git a/tests/hermes_cli/test_gateway_plugin_commands.py b/tests/hermes_cli/test_gateway_plugin_commands.py
index 56a5624267d..f1a98eb331e 100644
--- a/tests/hermes_cli/test_gateway_plugin_commands.py
+++ b/tests/hermes_cli/test_gateway_plugin_commands.py
@@ -241,10 +241,35 @@ def test_a_hung_up_connection_rereads_the_catalog_before_a_cached_name_runs(monk
conn.closed, conn._plugins = True, {} # the gateway restarted without the plugin
ran = _colliding_skill_and_bundle(monkeypatch, "gone-plugin")
assert c._process_unregistered_slash("/gone-plugin", "/gone-plugin") is True
+ # The name's miss re-reads the catalog (redialing) and the session's skills come from that same
+ # read: one refreshed snapshot, no stale cache answers.
assert _execs(conn) == ["gone-plugin"] and _catalog_reads(conn) == 2
assert ran == ["_run_skill_bundle_command"] and local_plugin_reads == []
+def test_a_hung_up_connection_rereads_the_sessions_skills(monkeypatch):
+ """/help and completion: the old gateway life's skills are not served after it hung up."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({})
+ conn.extra = {"skills": ["/old-skill"]}
+ c = _cli(monkeypatch, conn)
+ assert set(gateway_plugin_commands.skills(c) or ()) == {"/old-skill"}
+ conn.closed, conn.extra = True, {"skills": ["/new-skill"]} # same epoch until the next call redials
+ assert set(gateway_plugin_commands.skills(c) or ()) == {"/new-skill"}
+ assert _catalog_reads(conn) == 2
+
+
+def test_a_hung_up_connection_rereads_the_plugin_toolsets(monkeypatch):
+ """/tools validation: the old gateway life's plugin toolsets are not served after it hung up."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({}, reply={"toolsets": [{"key": "old-ts"}]})
+ c = _cli(monkeypatch, conn)
+ assert gateway_plugin_commands.toolsets(c) == ([("old-ts", "old-ts", "")], set())
+ conn.closed, conn._reply = True, {"toolsets": [{"key": "new-ts"}]}
+ assert gateway_plugin_commands.toolsets(c) == ([("new-ts", "new-ts", "")], set())
+ assert [m for m, _ in conn.calls].count("plugins.list") == 2
+
+
def test_a_reply_that_is_no_plugin_run_is_reported(monkeypatch, capsys):
"""The gateway lost the plugin between lookup and ``slash.exec`` and answered for a same-named
skill (``type: skill``): nothing ran, and the input must not vanish without a word."""
@@ -377,3 +402,27 @@ def test_a_skill_reply_for_an_unloaded_plugin_command_runs_the_skill_here(monkey
monkeypatch.setattr(HermesCLI, "_run_skill_slash_command", lambda self, *a: ran.append(a[0]))
assert c._process_unregistered_slash("/pptwin", "/pptwin") is True
assert ran == ["/pptwin"] and "nothing was run" not in capsys.readouterr().out
+
+
+def test_the_open_sessions_catalog_is_read_and_an_older_gateway_is_asked_without_it(monkeypatch, local_plugin_reads):
+ """On its open gateway session the CLI reads that session's catalog (skills from the session's folder);
+ a gateway older than this CLI refuses ``session_id`` and is asked again without it."""
+ from hermes_cli import gateway_plugin_commands
+ from hermes_cli.gateway_client import GatewayRPCError
+ conn = _Conn({"mcp-status": "Ask the MCP server"})
+ c = _cli(monkeypatch, conn)
+ c._gateway_session_open = True
+ assert gateway_plugin_commands.lookup(c, "mcp-status") is True
+ assert conn.calls[-1] == ("commands.catalog", {"session_id": "local-s"})
+ newer = conn.call_tagged
+
+ def older(method, **params):
+ if method == "commands.catalog" and params:
+ conn.calls.append((method, params))
+ raise GatewayRPCError("invalid_params", code=-32602)
+ return newer(method, **params)
+ monkeypatch.setattr(conn, "call_tagged", older)
+ c.session_id = "local-t" # another session: its catalog is read again
+ assert gateway_plugin_commands.lookup(c, "mcp-status") is True
+ assert [p for m, p in conn.calls if m == "commands.catalog"][-2:] == [{"session_id": "local-t"}, {}]
+ assert local_plugin_reads == []
diff --git a/tests/hermes_cli/test_single_query_plugin_cli_ref.py b/tests/hermes_cli/test_single_query_plugin_cli_ref.py
index e3e74f8edca..0d4ef419dbe 100644
--- a/tests/hermes_cli/test_single_query_plugin_cli_ref.py
+++ b/tests/hermes_cli/test_single_query_plugin_cli_ref.py
@@ -1,7 +1,8 @@
-"""``hermes chat -q``/``-Q`` runs give plugins the CLI reference like the interactive loop does.
+"""``hermes chat -q``/``-Q`` runs leave this process's plugin manager alone.
-Only ``HermesCLI.run()`` set ``PluginManager._cli_ref``, so a plugin tool dispatched from a one-shot
-turn saw ``_cli_ref is None`` and ``PluginContext.dispatch_tool`` injected no ``parent_agent`` (#67597).
+On main they set ``PluginManager._cli_ref`` so a plugin tool dispatched from a one-shot turn got a
+``parent_agent`` (#67597). The turn and its plugin tools now run in the gateway, and the CLI loads
+no plugins (PLG-7), so there is nothing here to bind.
"""
from __future__ import annotations
@@ -33,16 +34,16 @@ def _stub(**extra):
)
-def test_one_shot_turn_binds_the_cli_for_plugins():
+def test_one_shot_turn_binds_nothing_on_the_local_plugin_manager():
stub = _stub()
with pytest.raises(SystemExit):
cli._run_single_query_mode(stub, "do the thing", None, False, True)
- assert get_plugin_manager()._cli_ref is stub
+ assert get_plugin_manager()._cli_ref is None
-def test_quiet_turn_binds_the_cli_for_plugins():
+def test_quiet_turn_binds_nothing_on_the_local_plugin_manager():
stub = _stub(_ensure_runtime_credentials=lambda: False, _credentials_rate_limited=False,
session_id="s1", model="m")
with pytest.raises(SystemExit):
cli._run_single_query_mode(stub, "do the thing", None, True, True)
- assert get_plugin_manager()._cli_ref is stub
+ assert get_plugin_manager()._cli_ref is None
diff --git a/tests/hermes_cli/test_tui_launcher_skips_plugin_discovery.py b/tests/hermes_cli/test_tui_launcher_skips_plugin_discovery.py
index 935c10811dc..c01608b85e0 100644
--- a/tests/hermes_cli/test_tui_launcher_skips_plugin_discovery.py
+++ b/tests/hermes_cli/test_tui_launcher_skips_plugin_discovery.py
@@ -68,7 +68,14 @@ def test_plugin_discovery_skipped_for_tui_launch(monkeypatch):
)
-def test_plugin_discovery_runs_for_plain_chat(monkeypatch):
+def test_plain_chat_leaves_plugin_discovery_to_the_gateway(monkeypatch):
+ # Its turns, plugin commands and pre_command run in the gateway, which loads the plugins (PLG-7).
calls = _install_discover_spy(monkeypatch)
main_mod._prepare_agent_startup(_args(tui=False, command="chat"))
+ assert calls == []
+
+
+def test_plugin_discovery_runs_for_acp(monkeypatch):
+ calls = _install_discover_spy(monkeypatch)
+ main_mod._prepare_agent_startup(_args(tui=False, command="acp"))
assert calls == ["discover"]
diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.py
index 9448f707f8e..eefe6973a0d 100644
--- a/tui_gateway/contracts/canonical.py
+++ b/tui_gateway/contracts/canonical.py
@@ -126,6 +126,22 @@ canonical_method("session.prune", params=SessionPruneParams, result=SessionPrune
"selected, skipping busy sessions and retained reset owners.")
+class CommandObserveParams(Params):
+ session_id: str
+ name: str
+ arg: str | None = None
+ profile: str | None = None
+
+
+class CommandObserveResult(Result):
+ queued: bool
+
+
+canonical_method("command.observe", params=CommandObserveParams, result=CommandObserveResult,
+ doc="Fire-only: a recognized command the classic CLI runs in its own process; the gateway fires "
+ "`pre_command` for it in the session's profile after replying (`queued` false: not fired).")
+
+
class CanonicalSessionInfoParams(Params):
session_id: str
@@ -152,6 +168,7 @@ class SessionInventoryFields(Result):
# Classic CLI surface (``source: cli``) only: main's startup lines under the banner (Rich markup).
tool_availability_warnings: list[str] | None = None
browser_backend_notice: str | None = None
+ unknown_toolsets: list[str] | None = None # main's "Unknown toolsets" warning, judged by the gateway
class CanonicalSessionInfo(SessionInventoryFields, OpenModel):
diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.py
index 2e5c0dc27d6..75f61b11007 100644
--- a/tui_gateway/contracts/tools_mcp_plugins.py
+++ b/tui_gateway/contracts/tools_mcp_plugins.py
@@ -587,10 +587,25 @@ class LegacyPluginRow(Result):
name: str
version: str
enabled: bool
+ # The canonical gateway's rows also carry the load details the classic CLI's /plugins prints.
+ key: str | None = None
+ tools: int | None = None
+ hooks: int | None = None
+ commands: int | None = None
+ error: str | None = None
+
+
+class PluginToolsetRow(Result):
+ key: str
+ label: str
+ description: str
class PluginsListResult(Result):
plugins: list[LegacyPluginRow]
+ # The canonical gateway's plugin toolsets and portable MCP servers (the classic CLI's /tools reads them).
+ toolsets: list[PluginToolsetRow] | None = None
+ portable_mcp_servers: list[str] | None = None
method("plugins.list", params=PluginsListParams, result=PluginsListResult,
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index 906ac3e004f..066092b9b7f 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -478,7 +478,7 @@ Payload fields below are the exact event-specific fields supplied by each call s
| `pre_gateway_dispatch` | Directive/control | Once per incoming non-internal message, at ingress: platform-adapter messages before auth/pairing/dispatch; webhook and relay deliveries after their authorization, before the admission commits; never for local CLI/TUI/Desktop or API turns, a retry of a committed delivery, or a queued admission when it executes. First valid `skip`, `rewrite`, or `allow` controls flow. | `event`, `gateway`, `session_store` | Extremely privileged in-process objects expose inbound user/routing data and host handles. |
| `post_gateway_admission` | Directive/control (fail-open) | Admitted non-internal message after auth, pause/drain, pending-reply, running-session and slash-command lanes, inside the claimed session slot and the routed profile's scope; first `handled` result skips the agent turn, anything else (including a raise or timeout) runs it. | `session_key`, `platform`, `source` (dict snapshot), `message_id`, `text` | Inbound text is untrusted user data; no runner or session-store handles are passed. |
| `gateway_platform_event` | Observer | After the gateway's profile-scoped authorization succeeds, when a supported platform-native event is normalized at the gateway boundary (Telegram: reactions, message edits; Discord: message edits/deletes, thread created/renamed); return ignored. | `platform`, `event_type`, `payload` (event-type-specific dict — see the per-event contracts below) | Normalized plain-dict envelope only; raw SDK objects, adapter handles, and bot clients are never exposed. |
-| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. |
+| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). A command the classic CLI, TUI or Desktop sends to the gateway fires it once, in the gateway, with `surface` and `platform` both `"cli"` as before (Ink and Desktop fired it through the CLI slash worker) and `session_key` the session id; a command the classic CLI runs itself is reported to the gateway (`command.observe`), which fires it there after replying, so the CLI never loads plugin code. A gateway older than the CLI gets a one-time notice and no hook for those commands. During a local session's turn every command that still runs fires it except `/stop`, `/approve` and `/deny`; a command that is refused (rejected while busy, or named as unavailable on the gateway) fires nothing. Each callback is timeout-bounded (`plugins.hook_callback_timeout`) and runs on the gateway's own observer workers; one session's commands reach it in order, and a callback still running for that session (hung) is skipped for its later commands instead of running out of order, without holding up other sessions. Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. |
| `pre_approval_request` | Observer | Before prompted or smart approval; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id` | Command may contain secrets; smart observer preparation force-redacts, but surfaces do not all have identical redaction. |
| `post_approval_response` | Observer | After a decision, timeout, or gateway notification failure; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id`, `choice`; smart path may add `decided_by` | Same command sensitivity plus decision metadata. |
| `on_human_input_request` | Observer | The agent is about to block on a person — sudo password prompt, `clarify` question, or dangerous-command approval — on CLI, Ink TUI/Desktop, ACP and gateway platforms; return ignored. | `kind` (`"sudo"` \| `"clarify"` \| `"approval"`), `request_id`, `session_id`, `session_key`, `platform`, `prompt` | `prompt` is always force-redacted; the typed password or answer is never passed. |