The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): refuse inject_message(origin=...) up front when the FIFO cannot admit it
unsupportedpastels5018d437cc2e
diff --git a/gateway/run_plugin_injection.py b/gateway/run_plugin_injection.pyindex aceede24ba0..d88b7d89642 100644--- a/gateway/run_plugin_injection.py+++ b/gateway/run_plugin_injection.py@@ -50,7 +50,8 @@ class GatewayPluginInjectionMixin:if origin is not None:source = self._plugin_origin_source(origin, plugin_home=plugin_home, plugin_id=plugin_id)- if source is None:+ if source is None or not self._plugin_origin_admissible(source, plugin_home=plugin_home,+ plugin_id=plugin_id):return Falsetarget = f"origin={source.platform.value}/{source.chat_id}"coro = self._dispatch_plugin_origin_injection(source=source, content=content, plugin_id=plugin_id)@@ -220,6 +221,24 @@ class GatewayPluginInjectionMixin:where, identity.runtime_profile, profile)return source+ def _plugin_origin_admissible(self, source: SessionSource, *, plugin_home: Optional[Path], plugin_id: str) -> bool:+ """Under the session authority a plugin turn borrows the connector provenance of a human+ message already committed in that chat, and the gateway never mints it for a chat the+ platform did not deliver: refuse such an origin here, so the plugin gets ``False`` instead of+ a ``True`` for a turn the dispatch then drops. Dispatch rechecks."""+ from gateway.session_authorities import authority_for_home+ from gateway.session_automation import committed_route_envelope+ authority = authority_for_home(self, plugin_home) if plugin_home is not None else None+ if authority is None:+ return True # no authority: the adapter's normal session path creates the session+ entry = self.session_store.lookup_by_session_key(self._session_key_for_source(source))+ if entry is not None and committed_route_envelope(authority, entry) is not None:+ return True+ logger.warning("Plugin message injection refused: plugin=%s origin=%s/%s has no human message admitted "+ "yet; a plugin can continue a chat, not open one", plugin_id, source.platform.value,+ source.chat_id)+ return False+async def _dispatch_plugin_origin_injection(self, *, source: SessionSource, content: str, plugin_id: str) -> bool:diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 121b05afcdb..7973b13a7f4 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -110,6 +110,18 @@ def _route_identity(source):return {key: value for key, value in source.to_dict().items() if key != 'message_id'}+def committed_route_envelope(authority, entry):+ """The route's last committed native envelope with connector provenance (what a producer turn+ borrows), or ``None`` while no human message was admitted there."""+ from hermes_state_runtime import list_session_admissions+ # Admissions belong to the logical root; ``entry.session_id`` is only the transcript tip.+ prior = list_session_admissions(authority.db, session_id=authority.logical_owner(entry.session_id),+ pending_only=False)+ envelope = next((r['payload']['native_text_v1'] for r in reversed(prior)+ if 'native_text_v1' in r['payload']), None)+ return envelope if envelope is not None and 'provenance' in envelope else None++def snapshot_automation(authority, adapter, event, identity):runner = authority.runnerif (not event.internal or event.message_type != MessageType.TEXT or event.is_command()@@ -122,13 +134,9 @@ def snapshot_automation(authority, adapter, event, identity):if event.source.platform == Platform.LOCAL:return snapshot_local_automation(authority, adapter, event, identity, entry)from gateway.session_envelope import restore_native- from hermes_state_runtime import list_session_admissions- # Admissions belong to the logical root; ``entry.session_id`` is only the transcript tip.owner = authority.logical_owner(entry.session_id)- prior = list_session_admissions(authority.db, session_id=owner, pending_only=False)- envelope = next((r['payload']['native_text_v1'] for r in reversed(prior)- if 'native_text_v1' in r['payload']), None)- if envelope is None or 'provenance' not in envelope:+ envelope = committed_route_envelope(authority, entry)+ if envelope is None:raise RuntimeStoreError('not_found')# Persisted origins deliberately omit relay trust. Borrow only an exact# committed source's private proof, revalidated against the live connector.@@ -403,12 +411,8 @@ async def admit_route_wake(runner, adapter, source, text, producer, metadata=Nonawait authority.admit_automation(adapter, event, identity)return Truefrom gateway.session_envelope import restore_native- from hermes_state_runtime import list_session_admissions- prior = list_session_admissions(authority.db, session_id=authority.logical_owner(entry.session_id),- pending_only=False)- envelope = next((r['payload']['native_text_v1'] for r in reversed(prior)- if 'native_text_v1' in r['payload']), None)- if envelope is None or 'provenance' not in envelope:+ envelope = committed_route_envelope(authority, entry)+ if envelope is None:return False# The route's committed source, which ``snapshot_automation`` re-derives and compares.restored = restore_native({'text': text, 'native_text_v1': {diff --git a/tests/gateway/test_plugin_origin_injection_authority.py b/tests/gateway/test_plugin_origin_injection_authority.pynew file mode 100644index 00000000000..f155fef7fd9--- /dev/null+++ b/tests/gateway/test_plugin_origin_injection_authority.py@@ -0,0 +1,88 @@+"""``inject_message(origin=...)`` under the session authority answers ``False`` up front for a chat+the FIFO cannot admit it into (no human message admitted there yet), instead of ``True`` for a+message the dispatch then drops (PLG-6). Real GatewayRunner, DiscordAdapter and SessionAuthority.+"""+import asyncio++import pytest+import hermes_yaml as yaml++from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+from tests.waiting import async_wait_until++PLUGIN = "desk"+++def _context(home) -> tuple[PluginContext, PluginManager]:+ (home / "config.yaml").write_text(yaml.safe_dump({+ "plugins": {"entries": {PLUGIN: {"allow_gateway_injection": True}}},+ }), encoding="utf-8")+ manager = PluginManager(scope_key=str(home))+ return PluginContext(PluginManifest(name=PLUGIN, key=PLUGIN, source="user"), manager), manager+++def _publish(runner, manager) -> None:+ runner._gateway_loop = asyncio.get_running_loop()+ runner._running = True+ manager.set_gateway_message_injector(runner, runner._schedule_plugin_message_injection)+++def _plugin_rows(authority, session_id, text):+ from hermes_state_runtime import list_session_admissions+ return [row for row in list_session_admissions(authority.db, session_id=session_id, pending_only=False)+ if row["payload"].get("text") == text]+++async def test_origin_injection_is_refused_up_front_until_the_chat_holds_a_human_turn(monkeypatch):+ from gateway.config import GatewayConfig, Platform, PlatformConfig+ from gateway.platforms.base import SendResult+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_results import execution_result+ from hermes_constants import get_hermes_home+ from plugins.platforms.discord.adapter import DiscordAdapter++ monkeypatch.setenv("DISCORD_ALLOWED_USERS", "42")+ runner = GatewayRunner(GatewayConfig())+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fixture-token", typing_indicator=False))++ async def send(chat_id, content, reply_to=None, metadata=None):+ return SendResult(success=True, message_id="sent")+ monkeypatch.setattr(adapter, "send", send)+ adapter.gateway_runner = runner+ runner.adapters = {Platform.DISCORD: adapter}+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="owner")+ runner._wire_adapter_handlers(adapter)+ executed = []++ async def turn(event, source, quick_key, run_generation):+ executed.append(event.text)+ captured = execution_result.get()+ if captured is not None:+ captured["result"] = {"final_response": "reply", "messages": []}+ return "reply"+ monkeypatch.setattr(runner, "_handle_message_with_agent", turn)++ ctx, manager = _context(get_hermes_home())+ _publish(runner, manager)+ origin = {"platform": "discord", "chat_id": "42", "chat_type": "dm", "user_id": "42"}+ source = adapter.build_source(chat_id="42", chat_type="dm", user_id="42")+ key = runner.session_store._generate_session_key(source)++ # No session in that chat yet: the FIFO cannot admit a producer turn there.+ assert await asyncio.to_thread(ctx.inject_message, "reminder", origin=origin) is False+ assert runner.session_store.lookup_by_session_key(key) is None++ # A session row with no committed human turn has no connector provenance to borrow either.+ runner.session_store.get_or_create_session(source)+ assert await asyncio.to_thread(ctx.inject_message, "reminder", origin=origin) is False++ # Once a human message was admitted there, the plugin turn joins the chat's durable FIFO.+ await adapter.handle_message(MessageEvent(text="A", source=source, message_id="A"))+ await async_wait_until(lambda: "A" in executed, timeout=10, what="the human turn")+ assert await asyncio.to_thread(ctx.inject_message, "reminder", origin=origin) is True+ owner = authority.logical_owner(runner.session_store.lookup_by_session_key(key).session_id)+ await async_wait_until(lambda: _plugin_rows(authority, owner, "reminder"), timeout=10,+ what="the plugin admission")diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 0434973a0bb..ffeeb916f63 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -951,7 +951,7 @@ Starting a session with `origin` (gateway mode only):- `origin` uses the same shape as a stored session origin (`SessionSource.to_dict()`): `platform` and `chat_id` are required; `chat_type`, `thread_id`, `user_id`, `user_name`, `chat_name` and the other origin fields are optional. Use it when no session exists yet — for example, a bot-authored forum post, which platforms like Discord never deliver back to the bot as an inbound message.- The session is created in **the plugin's own profile** (the profile whose plugin manager loaded it) through the normal session path, with a fresh prompt and an empty history, and the reply is delivered to that chat/thread. If the chat already has a session in that profile, the text joins it exactly like a human message would (the busy-session queue applies), so a human follow-up in the same thread continues the same session.-- Under the gateway's session authority (every gateway-owned session), the plugin turn is committed to that session's durable FIFO and borrows the connector provenance of a human message already admitted there. An `origin` whose chat has **no session yet** is therefore refused (`False` at dispatch, logged as "has no session under the session authority yet"): Hermes never mints platform provenance for a chat the platform did not deliver. Have the first message in that chat come from the platform (or a human), then inject with `origin` or `session_key`.+- Under the gateway's session authority (every gateway-owned session), the plugin turn is committed to that session's durable FIFO and borrows the connector provenance of a human message already admitted there. An `origin` whose chat has **no human message admitted yet** (no session, or a session with no committed human turn) is therefore refused: `inject_message` returns `False` right away and the gateway log says "has no human message admitted yet". Hermes never mints platform provenance for a chat the platform did not deliver. Have the first message in that chat come from the platform (or a human), then inject with `origin` or `session_key`.- A plugin can never target another profile. `False` is returned (with the reason in the gateway log) when the origin names a different `profile`, when the gateway's own profile routing sends that chat to a different profile, when the plugin's profile is not served by this gateway, or when that profile has no connected adapter for `platform` — another profile's bot is never borrowed. On a multiplexed gateway the turn runs under the plugin's profile home and secrets.- Authorisation is not bypassed: the origin's user must pass the gateway's current allowlists, pairing, or allow-all configuration for that profile, the same check as the `session_key` path. Choose a `user_id` that is authorised, or the request is dropped at dispatch and logged.- The same text rules apply: no slash commands, approvals, or prompt resolution. The permission below is read from the plugin's own profile `config.yaml`.