Skip to content

The agent that grows with you

fix(plugins): send a key-less inject_message to the session the plugin is working for

unsupportedpastelsf7322744fc1c
diff --git a/gateway/plugin_keyless_inject.py b/gateway/plugin_keyless_inject.py
new file mode 100644
index 00000000000..c8ed3322c09
--- /dev/null
+++ b/gateway/plugin_keyless_inject.py
@@ -0,0 +1,104 @@
+"""Where a key-less ``PluginContext.inject_message(text)`` goes when plugin code runs for the gateway.
+
+Before the one-gateway runtime each classic CLI loaded its own plugins, so a key-less inject meant that
+CLI's own chat. The gateway's copy of a plugin (or its plugin host's) serves every session of its
+profile, so the target is picked here, in order:
+
+1. The local session the call is working for: the session bound in the calling context (its slash
+ command, a hook fired for it, a tool or hook in its turn). Never a guess, however many are open.
+2. No session in the calling context (a timer, the plugin's own thread): the one local session of the
+ plugin's profile launched by the classic CLI (frozen policy source ``cli``) with a viewer attached.
+3. Otherwise refused by name: nothing is injected anywhere.
+
+A calling context that is not a local session of the plugin's profile (a messaging chat) keeps main's
+refusal. A resolved target is committed like a keyed plugin inject under the session authority: a
+queued producer admission in that session's FIFO, run once, in order.
+"""
+from __future__ import annotations
+
+import contextlib
+import logging
+from pathlib import Path
+import time
+
+from gateway.config import Platform
+
+logger = logging.getLogger("gateway.run")
+
+# One refusal warning per (plugin, kind) per window: a plugin retrying on a timer must not flood the log.
+_WARN_WINDOW_S = 300.0
+_warned: dict[tuple[str, str], float] = {}
+
+
+def _refuse(plugin_id: str, kind: str, detail: str) -> None:
+ now = time.monotonic()
+ if now - _warned.get((plugin_id, kind), -_WARN_WINDOW_S) < _WARN_WINDOW_S:
+ logger.debug("inject_message from plugin %s refused again: %s", plugin_id, detail)
+ return
+ _warned[(plugin_id, kind)] = now
+ logger.warning("inject_message from plugin %s has no session key and %s; nothing was injected. Pass "
+ "session_key= (or origin=) to choose the chat.", plugin_id, detail)
+
+
+def _local(runner, live) -> bool:
+ from gateway.session_local import authorize_local_source
+ source = live.source
+ return source is not None and source.platform == Platform.LOCAL and authorize_local_source(runner, source) is True
+
+
+def _launched_by_classic_cli(runner, live) -> bool:
+ from gateway.session_policy import policy_for_source
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ policy = policy_for_source(runner, live.source)
+ except RuntimeStoreError:
+ return False
+ return policy is not None and policy.source == "cli"
+
+
+def resolve(runner, *, plugin_home, calling_session_key: str, plugin_id: str):
+ """``(authority, live session)`` the key-less inject goes to, or ``None`` (logged). Runs on the
+ plugin's calling thread so a refusal is the plugin's own ``False``; it only reads the authority's
+ live map, never the store."""
+ from gateway.session_authorities import authority_for_home
+ authority = authority_for_home(runner, plugin_home) if plugin_home is not None else None
+ if authority is None:
+ _refuse(plugin_id, "unserved", f"its profile home {plugin_home} is not served by this gateway")
+ return None
+ sessions = list(authority.sessions.values())
+ if calling_session_key:
+ live = next((s for s in sessions if s.route == calling_session_key and _local(runner, s)), None)
+ if live is None:
+ # Main's answer for a key-less inject from a messaging chat's command, hook or tool.
+ logger.warning("inject_message: gateway mode requires an existing session_key or an origin")
+ return None
+ return authority, live
+ attached = [s for s in sessions if s.subscribers and _local(runner, s) and _launched_by_classic_cli(runner, s)]
+ if len(attached) == 1:
+ return authority, attached[0]
+ if not attached:
+ _refuse(plugin_id, "none", "no classic CLI session is attached in its profile")
+ return None
+ _refuse(plugin_id, "several", f"{len(attached)} classic CLI sessions are attached in its profile")
+ return None
+
+
+async def admit(runner, authority, live, *, content: str, plugin_id: str) -> bool:
+ """Commit the text to *live*'s durable FIFO through the keyed path's producer admission, under the
+ plugin's profile (whose authority resolved it)."""
+ from gateway.session_authorities import active_authority
+ if not runner._plugin_injection_accepting():
+ return False
+ entry = await runner.async_session_store.lookup_by_session_key(live.route)
+ if entry is None or not runner._plugin_injection_accepting():
+ return False
+ scope = contextlib.nullcontext()
+ if getattr(getattr(runner, "config", None), "multiplex_profiles", False) is True:
+ from gateway.run import _async_profile_runtime_scope
+ scope = _async_profile_runtime_scope(Path(authority.profile_id))
+ async with scope:
+ if active_authority(runner) is not authority:
+ return False
+ return bool(await runner._admit_plugin_injection(
+ runner._adapter_for_source(live.source), live.source, session_key=live.route,
+ session_id=entry.session_id, content=content, plugin_id=plugin_id))
diff --git a/gateway/run_plugin_injection.py b/gateway/run_plugin_injection.py
index 9cad626c581..cc3e3d381d6 100644
--- a/gateway/run_plugin_injection.py
+++ b/gateway/run_plugin_injection.py
@@ -39,17 +39,27 @@ class GatewayPluginInjectionMixin:
def _schedule_plugin_message_injection(
self, *, content: str, plugin_id: str, session_key: Optional[str] = None,
origin: Optional[Mapping[str, Any]] = None, plugin_home: Optional[Path] = None,
+ keyless: bool = False, calling_session_key: str = "",
) -> bool:
"""Schedule a plugin-triggered turn on the live gateway loop (thread-safe).
With ``origin`` the profile, origin and adapter checks run here, synchronously, so the plugin
- gets ``False`` for a chat it may not start; authorization is rechecked at dispatch."""
+ gets ``False`` for a chat it may not start; authorization is rechecked at dispatch. ``keyless``
+ (neither given) picks the target here too (``gateway/plugin_keyless_inject.py``)."""
from gateway.run import safe_schedule_threadsafe
loop = getattr(self, "_gateway_loop", None)
if not getattr(self, "_running", False) or loop is None or loop.is_closed():
return False
- if origin is not None:
+ if keyless:
+ from gateway import plugin_keyless_inject
+ resolved = plugin_keyless_inject.resolve(self, plugin_home=plugin_home, plugin_id=plugin_id,
+ calling_session_key=calling_session_key)
+ if resolved is None:
+ return False
+ target = f"session={resolved[1].route} (no key given)"
+ coro = plugin_keyless_inject.admit(self, *resolved, content=content, plugin_id=plugin_id)
+ elif origin is not None:
source = self._plugin_origin_source(origin, plugin_home=plugin_home, plugin_id=plugin_id)
if source is None or not self._plugin_origin_admissible(source, plugin_home=plugin_home,
plugin_id=plugin_id):
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index 9416328b23c..67f84f69b02 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -279,9 +279,10 @@ def _pre_command(authority, ref, canonical, alias, arg):
logger.warning('pre_command for /%s dropped: %d deliveries already queued for this session', canonical, pending)
return None
- def fire():
+ def fire(): # bound to the session it fires for: a key-less inject_message from the hook lands there
+ from gateway.session_context import scoped_session_key
from hermes_cli.plugins import fire_pre_command_hook
- with _profile_runtime_scope(home):
+ with _profile_runtime_scope(home), scoped_session_key(live.route):
fire_pre_command_hook(surface='cli', command=canonical, alias_used=alias, args_raw=arg,
session_key=ref.session_id, platform='cli')
diff --git a/gateway/session_context.py b/gateway/session_context.py
index 036ceb60969..8bfc49a920c 100644
--- a/gateway/session_context.py
+++ b/gateway/session_context.py
@@ -105,6 +105,24 @@ def scoped_current_session_id(session_id: str | None = None) -> Iterator[None]:
_SESSION_ID.set(previous)
+@contextmanager
+def scoped_session_key(session_key: str) -> Iterator[None]:
+ """Bind only the route key of the session a call works for (a hook fired for it outside its
+ turn) and restore the prior value on exit; never touches ``os.environ``."""
+ token = _SESSION_KEY.set(session_key)
+ try:
+ yield
+ finally:
+ _SESSION_KEY.reset(token)
+
+
+def bound_session_key() -> str:
+ """The route key bound in THIS context, ``""`` when none is: no ``os.environ`` fallback, so a
+ thread that inherited no context never borrows another session's key."""
+ value = _SESSION_KEY.get()
+ return "" if value is _UNSET else value
+
+
def source_route_metadata(source: Any, metadata: dict | None) -> dict | None:
"""Keep inbound route anchors for durable deliveries after the source is gone."""
anchors = {key: str(value) for key in ("scope_id", "parent_chat_id")
diff --git a/hermes_cli/gateway_chat_inject.py b/hermes_cli/gateway_chat_inject.py
deleted file mode 100644
index eb04f4009be..00000000000
--- a/hermes_cli/gateway_chat_inject.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""The attached classic view as the plugin manager's CLI slot.
-
-Main's classic REPL registered itself as ``PluginManager._cli_ref``, so ``ctx.inject_message(text)``
-with no ``session_key``/``origin`` (the documented "Active CLI conversation" form) queued into the
-REPL. The classic chat is now a gateway client: the same call submits into the attached session at
-the gateway (same FIFO as a typed line) from whatever thread the plugin calls on."""
-from __future__ import annotations
-
-import asyncio
-from contextlib import contextmanager
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class _InjectSlot:
- _agent_running = False # one queue: the gateway FIFO orders it behind a running turn
-
- def __init__(self, view, loop):
- self._view, self._loop = view, loop
- self._pending_input = self._interrupt_queue = self
-
- def put(self, message):
- asyncio.run_coroutine_threadsafe(self._submit(message), self._loop)
-
- async def _submit(self, message):
- print(f"\n{'─' * 40}\n● {message}", flush=True)
- try:
- await self._view.submit(message)
- except Exception:
- logger.warning("plugin inject_message: submit to %s failed", self._view.session_id, exc_info=True)
-
-
-@contextmanager
-def plugin_inject_slot(view):
- from hermes_cli.plugins import get_plugin_manager
- manager = get_plugin_manager()
- slot = manager._cli_ref = _InjectSlot(view, asyncio.get_running_loop())
- try:
- yield
- finally:
- if manager._cli_ref is slot:
- manager._cli_ref = None
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 9deb250f62a..95ed7ee5ef5 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -475,8 +475,7 @@ class GatewayChatView:
bottom_toolbar=lambda: f" \u2624 {self.model} \u2502 {self.session_id} ")
prompt_symbol = get_active_prompt_symbol("❯ ")
self._composer = prompt if sys.stdin.isatty() else None
- from hermes_cli.gateway_chat_inject import plugin_inject_slot
- with patch_stdout(), plugin_inject_slot(self):
+ with patch_stdout():
while not self.failure:
try:
# Empty when the stream failed first: the loop guard then raises it.
diff --git a/hermes_cli/plugins_injection.py b/hermes_cli/plugins_injection.py
index 1c059d639cd..ed6378f5020 100644
--- a/hermes_cli/plugins_injection.py
+++ b/hermes_cli/plugins_injection.py
@@ -21,16 +21,13 @@ def inject_plugin_message(
queue_ = cli._interrupt_queue if getattr(cli, "_agent_running", False) else cli._pending_input
queue_.put(msg)
return True
- if not session_key and origin is None:
- # Main queued key-less text into the classic CLI REPL. That session's turns now run in the
- # gateway, so a hook or tool running for it targets the session itself.
- from hermes_cli.plugin_session import session_key as calling_session_key, session_surface
- if session_surface() == "cli":
- session_key = calling_session_key() or None
if session_key and origin is not None:
logger.warning("inject_message: pass session_key or origin, not both")
return False
- if not session_key and origin is None:
+ # Neither: the live gateway picks the chat (gateway/plugin_keyless_inject.py) from the session this
+ # call works for, read here on the caller's own context; no gateway keeps main's refusal.
+ keyless = not session_key and origin is None
+ if keyless and not manager.has_gateway_message_injector:
logger.warning("inject_message: gateway mode requires an existing session_key or an origin")
return False
if origin is not None and not isinstance(origin, Mapping):
@@ -58,8 +55,12 @@ def inject_plugin_message(
# The manager's immutable home is the plugin's profile: the gateway creates an origin's session
# there or nowhere, and a keyed local session must belong to it (never the ambient HERMES_HOME
# of whatever thread called us).
- if origin is None:
- target: dict[str, Any] = {"session_key": session_key, "plugin_home": manager.home_path}
+ if keyless:
+ from gateway.session_context import bound_session_key
+ target: dict[str, Any] = {"keyless": True, "calling_session_key": bound_session_key(),
+ "plugin_home": manager.home_path}
+ elif origin is None:
+ target = {"session_key": session_key, "plugin_home": manager.home_path}
else:
target = {"origin": dict(origin), "plugin_home": manager.home_path}
try:
diff --git a/tests/gateway/test_plugin_keyless_inject.py b/tests/gateway/test_plugin_keyless_inject.py
new file mode 100644
index 00000000000..eaba957052d
--- /dev/null
+++ b/tests/gateway/test_plugin_keyless_inject.py
@@ -0,0 +1,208 @@
+"""A key-less ``ctx.inject_message(text)`` from plugin code the gateway runs (#134889 PLG-7, B2-11).
+
+Before the one-gateway runtime each classic CLI loaded its own plugins, so a key-less inject meant that
+CLI's own chat. The gateway's plugin copy serves every session of its profile, so the gateway picks the
+target: the local session the plugin is working for (its command, a hook fired for it, a hook in its
+turn); with no session in the calling context (the plugin's own thread), the one attached classic CLI
+session of the plugin's profile; otherwise a named refusal and nothing injected.
+
+A real daemon (``gateway.run``) loads a probe plugin that notes each ``inject_message`` result; a landed
+inject is a queued admission in the profile's ``state.db`` that runs once.
+"""
+from contextlib import contextmanager
+import json
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+import signal
+import sqlite3
+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.gateway.test_pre_command_in_gateway import _ProfileWire
+from tests.waiting import wait_until
+
+_PLUGIN = '''import json
+import threading
+
+
+def register(ctx):
+ def inject(where, text, **kw):
+ ok = ctx.inject_message(text, **kw)
+ with open(%r, "a") as log:
+ log.write(json.dumps({"where": where, "text": text, "ok": ok}) + "\\n")
+
+ def keyed(arg):
+ key, _, text = arg.partition(" ")
+ inject("keyed", text, session_key=key)
+
+ def own_thread(arg):
+ threading.Thread(target=inject, args=("thread", arg), daemon=True).start()
+ return "started"
+
+ def pre_command(command="", args_raw="", **_kw):
+ if command == "help" and args_raw.startswith("inject "):
+ inject("hook", args_raw[len("inject "):])
+
+ def pre_llm_call(user_message="", **_kw):
+ if str(user_message).startswith("TURN_INJECT "):
+ inject("turn", str(user_message)[len("TURN_INJECT "):])
+
+ ctx.register_command("inj", lambda arg: inject("command", arg), description="Probe inject")
+ ctx.register_command("inj-key", keyed, description="Probe keyed inject")
+ ctx.register_command("inj-thread", own_thread, description="Probe inject from a thread")
+ ctx.register_hook("pre_command", pre_command)
+ ctx.register_hook("pre_llm_call", pre_llm_call)
+'''
+
+
+def _probe_plugin(home, log):
+ plugin = home / 'plugins' / 'probe-inj'
+ plugin.mkdir(parents=True)
+ (plugin / 'plugin.yaml').write_text("name: probe-inj\nversion: '1.0'\n")
+ (plugin / '__init__.py').write_text(_PLUGIN % str(log))
+
+
+@contextmanager
+def keyless_gateway(tmp_path, *, isolation=None, beta=False):
+ """A real daemon whose profile loads the probe plugin (``allow_gateway_injection`` granted):
+ ``(desc, home, work, log, peer)``. ``beta`` also serves profile ``beta`` (multiplexed) with its own
+ copy of the plugin, noting to ``beta.jsonl``."""
+ 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 / 'inject.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'
+ plugins = {'enabled': ['probe-inj'], 'entries': {'probe-inj': {'allow_gateway_injection': True}},
+ **({'isolation': isolation} if isolation else {})}
+ profile = {'model': {'provider': 'custom', 'default': 'plugin-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'plugins': plugins}
+ (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 desc, home, work, log, peer
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ finally:
+ peer.release.set()
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+
+
+def noted(log, where, text):
+ """The plugin's ``inject_message`` result for ``text`` (its note lands after the call returns)."""
+ def note():
+ lines = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
+ return next(([r['ok']] for r in lines if (r['where'], r['text']) == (where, text)), None)
+ return wait_until(note, timeout=20, what=f'the {where} note for {text!r}')[0]
+
+
+def admissions(home, text):
+ """``(session id, status)`` of every admission in ``home``'s ledger whose text is ``text``."""
+ with sqlite3.connect(home / 'state.db') as db:
+ rows = db.execute('SELECT target_session_id, status, payload_json FROM session_admissions ORDER BY seq').fetchall()
+ return [(sid, status) for sid, status, payload in rows if json.loads(payload).get('text') == text]
+
+
+def landed_once(home, peer, text):
+ """The one session ``text`` was queued into, once its turn ran; the model saw it exactly once."""
+ def ran():
+ rows = admissions(home, text)
+ return rows if rows and all(status == 'terminal' for _, status in rows) else None
+ rows = wait_until(ran, timeout=30, what=f'the turn for {text!r}')
+ asked = [r for r in peer.requests
+ if next((m.get('content') for m in reversed(r['messages']) if m['role'] == 'user'), None) == text]
+ assert len(rows) == 1 and len(asked) == 1, (rows, len(asked))
+ return rows[0][0]
+
+
+def gateway_log(home):
+ return (home / 'restart.log').read_text()
+
+
[email protected]('isolation', [None, 'host'])
+def test_a_key_less_inject_goes_to_the_session_the_plugin_is_working_for(tmp_path, isolation):
+ """Rule 1, with two classic CLI sessions (and a TUI one) attached: a plugin command, a ``pre_command``
+ hook fired for a session and a hook in a session's turn each land in that session only, once, as a
+ queued input; in the plugin host too (the forwarded call keeps its caller). A keyed inject is
+ unchanged: accepted for the gateway's keyed path, which never falls back to the calling session."""
+ with keyless_gateway(tmp_path, isolation=isolation) as (_desc, home, work, log, peer):
+ wire = _Wire(home, _desc)
+ try:
+ cli1, cli2, tui = (wire.call('session.create', request_id=f'r1-{source}-{n}', source=source, toolsets=[],
+ cwd=str(work))['session_id'] for n, source in enumerate(('cli', 'cli', 'tui')))
+ wire.call('slash.exec', session_id=cli2, command='/inj CMD_TEXT')
+ wire.call('slash.exec', session_id=tui, command='/inj TUI_TEXT')
+ wire.call('slash.exec', session_id=cli1, command='/help inject HOOK_TEXT')
+ wire.call('prompt.submit', session_id=cli1, input_id='turn', text='TURN_INJECT TURN_TEXT')
+ wire.call('slash.exec', session_id=cli1, command='/inj-key agent:main:telegram:dm:nobody KEYED_TEXT')
+ results = {text: noted(log, where, text) for where, text in (
+ ('command', 'CMD_TEXT'), ('command', 'TUI_TEXT'), ('hook', 'HOOK_TEXT'), ('turn', 'TURN_TEXT'),
+ ('keyed', 'KEYED_TEXT'))}
+ targets = {text: landed_once(home, peer, text) for text in ('CMD_TEXT', 'TUI_TEXT', 'HOOK_TEXT', 'TURN_TEXT')}
+ wait_until(lambda: 'plugin=probe-inj session=agent:main:telegram:dm:nobody' in gateway_log(home),
+ timeout=20, what='the keyed inject reaching the keyed path')
+ keyed = admissions(home, 'KEYED_TEXT')
+ finally:
+ wire.close()
+ assert results == dict.fromkeys(results, True), results
+ assert targets == {'CMD_TEXT': cli2, 'TUI_TEXT': tui, 'HOOK_TEXT': cli1, 'TURN_TEXT': cli1}, targets
+ assert keyed == []
+
+
+def test_with_no_calling_session_only_the_one_attached_classic_cli_session_is_picked(tmp_path):
+ """Rules 2 and 3 from the plugin's own thread (started by a command, it inherits no session): with
+ only TUI, Desktop and another profile's classic CLI session attached it is refused by name and
+ nothing lands anywhere; with one classic CLI session of its profile it lands there once; with two it
+ is refused again (one warning per kind, not one per call)."""
+ with keyless_gateway(tmp_path, beta=True) as (desc, home, work, log, peer):
+ beta_home = (home / 'profiles' / 'beta').resolve()
+ root, beta = _Wire(home, desc), _ProfileWire(home, desc, beta_home)
+ try:
+ beta.call('session.create', request_id='beta-cli', source='cli', toolsets=[], cwd=str(work))
+ tui, _gui = (root.call('session.create', request_id=f'r2-{source}', source=source, toolsets=[],
+ cwd=str(work))['session_id'] for source in ('tui', 'gui'))
+ root.call('slash.exec', session_id=tui, command='/inj-thread ZERO_TEXT')
+ zero = noted(log, 'thread', 'ZERO_TEXT')
+ zero_rows = admissions(home, 'ZERO_TEXT') + admissions(beta_home, 'ZERO_TEXT')
+ cli1 = root.call('session.create', request_id='r2-cli1', source='cli', toolsets=[], cwd=str(work))['session_id']
+ root.call('slash.exec', session_id=tui, command='/inj-thread ONE_TEXT')
+ one = noted(log, 'thread', 'ONE_TEXT')
+ one_target = landed_once(home, peer, 'ONE_TEXT')
+ root.call('session.create', request_id='r2-cli2', source='cli', toolsets=[], cwd=str(work))
+ for text in ('TWO_TEXT_A', 'TWO_TEXT_B'):
+ root.call('slash.exec', session_id=tui, command=f'/inj-thread {text}')
+ two = [noted(log, 'thread', text) for text in ('TWO_TEXT_A', 'TWO_TEXT_B')]
+ two_rows = [row for text in ('TWO_TEXT_A', 'TWO_TEXT_B')
+ for row in admissions(home, text) + admissions(beta_home, text)]
+ log_text = gateway_log(home)
+ finally:
+ root.close()
+ beta.close()
+ assert (zero, zero_rows) == (False, [])
+ assert (one, one_target) == (True, cli1)
+ assert (two, two_rows) == ([False, False], [])
+ refusals = [line for line in log_text.splitlines()
+ if 'WARNING' in line and 'plugin probe-inj has no session key' in line and 'Pass session_key=' in line]
+ assert len(refusals) == 2, refusals
+ assert 'no classic CLI session' in refusals[0] and '2 classic CLI sessions' in refusals[1], refusals
diff --git a/tests/gateway/test_pre_command_in_gateway.py b/tests/gateway/test_pre_command_in_gateway.py
index 13c78c52cb5..a368026bd87 100644
--- a/tests/gateway/test_pre_command_in_gateway.py
+++ b/tests/gateway/test_pre_command_in_gateway.py
@@ -432,7 +432,7 @@ def test_commands_the_cli_refuses_on_the_gateway_fire_nothing(monkeypatch, capsy
def _authority(state):
from types import SimpleNamespace
- live = SimpleNamespace(source=object())
+ live = SimpleNamespace(source=object(), route='agent:main:local:dm:s1')
return SimpleNamespace(sessions={'s1': live}, runner=object(), profile_id='/tmp/home',
_handle=lambda _ref: SimpleNamespace(execution_state=state))
@@ -482,7 +482,7 @@ def test_a_hung_pre_command_callback_is_bounded_and_each_session_keeps_its_order
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())
+ live = SimpleNamespace(source=object(), route='agent:main:local:dm:s1')
authority = SimpleNamespace(sessions=dict.fromkeys('ABC', live), runner=object(), profile_id='/tmp/home',
_handle=lambda _ref: SimpleNamespace(execution_state='idle'))
@@ -540,7 +540,7 @@ def test_callbacks_waiting_out_their_bound_hold_no_worker_another_session_needs(
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())
+ live = SimpleNamespace(source=object(), route='agent:main:local:dm:s1')
authority = SimpleNamespace(sessions=dict.fromkeys([*slow, 'fresh'], live), runner=object(),
profile_id='/tmp/home', _handle=lambda _ref: SimpleNamespace(execution_state='idle'))
diff --git a/tests/hermes_cli/test_gateway_chat_plugin_inject.py b/tests/hermes_cli/test_gateway_chat_plugin_inject.py
index a75f011d728..89b102bc304 100644
--- a/tests/hermes_cli/test_gateway_chat_plugin_inject.py
+++ b/tests/hermes_cli/test_gateway_chat_plugin_inject.py
@@ -1,44 +1,47 @@
"""`ctx.inject_message(text)` with no session_key/origin (plugins.md "Active CLI conversation") reaches
-the attached classic `hermes chat` session as a prompt.submit, from a plugin's own thread (B2-11)."""
-import asyncio
-import threading
+the attached classic `hermes chat` session as a queued prompt, from a plugin's own thread (B2-11).
+The classic CLI loads no plugin code on a gateway session (PLG-7): the plugin runs in the gateway, which
+picks the one attached classic CLI session of the plugin's profile."""
import pytest
+from tests.gateway.test_cli_plugin_command_in_gateway import _Wire
+from tests.gateway.test_plugin_keyless_inject import keyless_gateway, landed_once, noted
+
+
+def test_no_key_inject_submits_into_the_attached_classic_session(tmp_path):
+ with keyless_gateway(tmp_path) as (desc, home, work, log, peer):
+ wire = _Wire(home, desc)
+ try:
+ sid = wire.call('session.create', request_id='b2-11', source='cli', toolsets=[], cwd=str(work))['session_id']
+ wire.call('slash.exec', session_id=sid, command='/inj-thread New data arrived')
+ accepted = noted(log, 'thread', 'New data arrived')
+ target = landed_once(home, peer, 'New data arrived')
+ finally:
+ wire.close()
+ assert accepted is True
+ assert target == sid
+
@pytest.mark.asyncio
-async def test_no_key_inject_submits_into_the_attached_classic_session(capsys):
+async def test_the_classic_chat_view_reads_no_plugin_manager(monkeypatch):
+ """No plugin code runs in the classic CLI process on a gateway session, so its chat view has no
+ plugin inject slot to install."""
+ import asyncio
+ import hermes_cli.plugins as plugins_mod
from hermes_cli.gateway_chat_view import GatewayChatView
- from hermes_cli.plugins import PluginContext, get_plugin_manager
- from hermes_cli.plugins_manifest import PluginManifest
- submitted = asyncio.Event()
+ monkeypatch.setattr(plugins_mod, 'get_plugin_manager', lambda: pytest.fail('the chat view read the plugin manager'))
class Peer:
events = asyncio.Queue()
- calls = []
async def rpc(self, method, **params):
- self.calls.append((method, params))
- if method == "prompt.submit":
- submitted.set()
- return {"admission_id": "adm"}
-
- view = GatewayChatView(Peer(), {"stored_session_id": "sid"})
- ctx = PluginContext(PluginManifest(name="watcher"), get_plugin_manager())
- accepted = []
+ return {}
async def read_line(prompt, symbol):
- if accepted:
- return "/quit"
- thread = threading.Thread(target=lambda: accepted.append(ctx.inject_message("New data arrived")))
- thread.start()
- thread.join()
- await asyncio.wait_for(submitted.wait(), 5)
- return ""
+ return '/quit'
+ view = GatewayChatView(Peer(), {'stored_session_id': 'sid'})
view._read_line = read_line
assert await view.run() == 0
- assert accepted == [True]
- assert [(m, p["session_id"], p["text"]) for m, p in Peer.calls] == [("prompt.submit", "sid", "New data arrived")]
- assert get_plugin_manager()._cli_ref is None # detached: the slot is released
- assert "● New data arrived" in capsys.readouterr().out
diff --git a/tests/hermes_cli/test_plugin_message_injection.py b/tests/hermes_cli/test_plugin_message_injection.py
index ee797ad1b57..d4ff2275f6c 100644
--- a/tests/hermes_cli/test_plugin_message_injection.py
+++ b/tests/hermes_cli/test_plugin_message_injection.py
@@ -55,13 +55,38 @@ def test_cli_running_injection_keeps_existing_interrupt_behaviour():
assert cli._pending_input.empty()
-def test_gateway_injection_requires_session_key(tmp_path, monkeypatch):
+def test_key_less_gateway_injection_lets_the_gateway_pick_the_chat(tmp_path, monkeypatch):
+ """No key and no origin: the live gateway picks the chat (gateway/plugin_keyless_inject.py) from
+ the session bound in the caller's own context, read here; none bound is passed as ``""``."""
+ from gateway.session_context import scoped_session_key
_write_plugin_config(
tmp_path,
monkeypatch,
{"allow_gateway_injection": True},
)
context, manager = _context()
+ injector = MagicMock(return_value=False)
+ manager.set_gateway_message_injector(object(), injector)
+
+ assert context.inject_message("wake up") is False
+ with scoped_session_key("agent:main:local:dm:local-1"):
+ context.inject_message("for me")
+ calls = [c.kwargs for c in injector.call_args_list]
+ assert [(c["keyless"], c["calling_session_key"], c["content"]) for c in calls] == [
+ (True, "", "wake up"), (True, "agent:main:local:dm:local-1", "for me")]
+ assert all("session_key" not in c and c["plugin_home"] == manager.home_path for c in calls)
+
+
+def test_key_less_injection_without_a_gateway_is_refused(tmp_path, monkeypatch):
+ _write_plugin_config(tmp_path, monkeypatch, {"allow_gateway_injection": True})
+ context, _manager = _context()
+
+ assert context.inject_message("wake up") is False
+
+
+def test_key_less_gateway_injection_requires_explicit_permission(tmp_path, monkeypatch):
+ _write_plugin_config(tmp_path, monkeypatch, {})
+ context, manager = _context()
injector = MagicMock(return_value=True)
manager.set_gateway_message_injector(object(), injector)
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index 1a9bfd8cf6f..7f7d7e9317f 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -930,7 +930,7 @@ In a running session, `/plugins` shows which plugins are currently loaded.
Plugins can inject messages into a CLI conversation, a known gateway session, or a new gateway session in a given chat using `ctx.inject_message()`:
```python
-# Active CLI conversation
+# The chat the plugin is working for (see "Without a session key" below; prefer passing session_key)
ctx.inject_message("New data arrived from the webhook", role="user")
# Existing gateway conversation
@@ -956,17 +956,24 @@ ctx.inject_message(
**Signature:** `ctx.inject_message(content: str, role: str = "user", *, session_key: str | None = None, origin: Mapping[str, Any] | None = None) -> bool`
-In CLI mode:
+When the classic CLI runs plugins in its own process (no gateway session):
- If the agent is **idle** (waiting for user input), the message is queued as the next input and starts a new turn.
- If the agent is **mid-turn** (actively running), the message interrupts the current operation — the same as a user typing a new message and pressing Enter.
- For non-`"user"` roles, the content is prefixed with `[role]` (e.g. `[system] ...`).
- Returns `True` if the message was queued successfully.
-In gateway mode:
+Without a session key (`session_key` and `origin` both omitted), when the plugin runs in the gateway (or its plugin host) — which is where plugins run for classic CLI, TUI and Desktop sessions — the gateway picks the chat:
-- `session_key` is required and must identify an existing gateway session. It is the stable routing key, not the CLI session ID.
-- Exception: a hook or tool running for a classic CLI session (`hermes chat`, whose turns run in the gateway) may omit both `session_key` and `origin`, as it could in the CLI. The text is committed to that session's queue and runs as its next turn; it no longer interrupts a running one. The turn and its reply are in the session's transcript, but the attached classic CLI does not display them. `allow_gateway_injection` is still required.
+1. If the plugin is handling a local session's own call (its slash command, a hook fired for that session, or a tool or hook in its turn), the message goes to that session. This never guesses, however many sessions are open.
+2. With no session in the calling context (a timer, a background thread — a thread the plugin starts does not inherit the call's context), it goes to the one local session of the plugin's profile that was started by the classic CLI (`hermes chat`) and has a viewer attached. TUI and Desktop sessions, messaging chats and other profiles' sessions are never picked this way.
+3. Otherwise (no such session, or several) it is refused: `False`, nothing is injected anywhere, and the gateway log names the plugin and says to pass a session key.
+
+The chosen session receives the text as a queued input, the same way as a keyed injection; it needs the `allow_gateway_injection` permission below. When that is a classic CLI session, the turn and its reply are in the session's transcript, but the attached classic CLI does not display them. A call made for a messaging chat without a key is refused, as before. Prefer passing `session_key`: a key-less call can be refused when the chat is ambiguous, and key-less injection may be retired later.
+
+In gateway mode with a key:
+
+- `session_key` must identify an existing gateway session. It is the stable routing key, not the CLI session ID.
- Hermes reuses that session's stored platform, chat, thread, profile, and conversation history. Plugins cannot change that route through `session_key`.
- The session must belong to the plugin's own profile: the key of another profile's chat or local session gets `False` right away, with the reason in the gateway log.
- Hermes rechecks the stored route against the gateway's current authorisation rules before dispatch.
@@ -975,7 +982,7 @@ In gateway mode:
- The route and conversation are pinned while dispatch is pending. Hermes drops the request if topic recovery changes the route or the session rotates before handling starts.
- The request enters the platform adapter's normal message path. Active sessions use the existing busy-session queue rather than starting a competing turn.
- Returns `True` when the live gateway accepts the request for asynchronous dispatch. This does not confirm that the agent turn or platform delivery has completed.
-- Returns `False` when neither `session_key` nor `origin` is given (or both are), the permission is not granted, or no live host can accept the request. Unknown or unroutable session keys discovered after asynchronous acceptance are written to the gateway log.
+- Returns `False` when both `session_key` and `origin` are given, neither is given and no chat is chosen (above), the permission is not granted, or no live host can accept the request. Unknown or unroutable session keys discovered after asynchronous acceptance are written to the gateway log.
Starting a session with `origin` (gateway mode only):