The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): give gateway-run plugin code the calling session's key, surface and cwd
unsupportedpastels11ba615c3c5e
diff --git a/gateway/run_plugin_injection.py b/gateway/run_plugin_injection.pyindex d88b7d89642..47ebf147160 100644--- a/gateway/run_plugin_injection.py+++ b/gateway/run_plugin_injection.py@@ -16,6 +16,7 @@ import weakreffrom pathlib import Pathfrom typing import Any, Mapping, Optional+from gateway.config import Platformfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.session import SessionSource@@ -56,9 +57,11 @@ class GatewayPluginInjectionMixin:target = f"origin={source.platform.value}/{source.chat_id}"coro = self._dispatch_plugin_origin_injection(source=source, content=content, plugin_id=plugin_id)else:+ if not self._plugin_session_key_admissible(session_key, plugin_home=plugin_home, plugin_id=plugin_id):+ return Falsetarget = f"session={session_key}"coro = self._dispatch_plugin_message_injection(- session_key=session_key, content=content, plugin_id=plugin_id,+ session_key=session_key, content=content, plugin_id=plugin_id, plugin_home=plugin_home,)try:current_loop = asyncio.get_running_loop()@@ -99,15 +102,15 @@ class GatewayPluginInjectionMixin:def _plugin_injection_accepting(self) -> bool:return getattr(self, "_running", False) and not getattr(self, "_draining", False)- def _plugin_injection_scope(self, source: SessionSource):- """Multiplex: enter the source's profile runtime scope around ``handle_message`` so the- background task it spawns — the turn AND the reply send after the handler returns — inherits- that profile's home and secrets (this coroutine runs from the default loop context, not from- the profile adapter's own intake task)."""+ def _plugin_injection_scope(self, source: SessionSource, home: Optional[Path] = None):+ """Multiplex: enter the source's profile runtime scope (or *home*'s, when the owner is known)+ around ``handle_message`` so the background task it spawns — the turn AND the reply send after+ the handler returns — inherits that profile's home and secrets (this coroutine runs from the+ default loop context, not from the profile adapter's own intake task)."""if getattr(getattr(self, "config", None), "multiplex_profiles", False) is not True:return contextlib.nullcontext()from gateway.run import _async_profile_runtime_scope- return _async_profile_runtime_scope(self._resolve_profile_home_for_source(source))+ return _async_profile_runtime_scope(home or self._resolve_profile_home_for_source(source))def _plugin_injection_authorized(self, source: SessionSource, *, plugin_id: str, target: str) -> bool:"""Current gateway authorization for the route the injected turn will run as. Host-side@@ -124,8 +127,35 @@ class GatewayPluginInjectionMixin:plugin_id, target)return authorized+ def _plugin_session_key_admissible(self, session_key: str, *, plugin_home: Optional[Path], plugin_id: str) -> bool:+ """Synchronous refusal of a keyed injection into another profile's local session, so the+ plugin gets ``False``; any other key is decided at dispatch, as before. Dispatch rechecks."""+ entry = self.session_store.lookup_by_session_key(session_key)+ if entry is None or entry.origin is None:+ return True+ from gateway.session_identity import replace_source+ source = replace_source(self._restored_source(entry))+ return source.platform != Platform.LOCAL or self._plugin_local_session(+ source, session_key, plugin_home=plugin_home, plugin_id=plugin_id) is not None++ def _plugin_local_session(self, source: SessionSource, session_key: str, *, plugin_home: Optional[Path],+ plugin_id: str):+ """A local session's own source passes no chat allowlist, so the plugin's profile boundary is+ the only check: the session authority registered for the plugin's immutable home must hold+ the live session under this key. Its ``LiveSession``, or ``None`` (logged). Never resolved+ through the source's profile, whose fallback is the ambient scope (a default-profile local+ source carries none, so under beta's scope it would read as beta's)."""+ from gateway.session_authorities import authority_for_home+ authority = authority_for_home(self, plugin_home) if plugin_home is not None else None+ live = authority.sessions.get(source.chat_id) if authority is not None else None+ if live is not None and live.route == session_key:+ return live+ logger.warning("Plugin message injection refused: plugin=%s session=%s is not a live local session of the "+ "plugin's profile home %s", plugin_id, session_key, plugin_home)+ return None+async def _dispatch_plugin_message_injection(- self, *, session_key: str, content: str, plugin_id: str+ self, *, session_key: str, content: str, plugin_id: str, plugin_home: Optional[Path] = None,) -> bool:"""Route a plugin-triggered turn through the session's live adapter."""if not self._plugin_injection_accepting():@@ -136,6 +166,9 @@ class GatewayPluginInjectionMixin:from gateway.session_identity import replace_sourcesource = replace_source(self._restored_source(entry))+ if source.platform == Platform.LOCAL:+ return await self._dispatch_plugin_local_injection(source, entry, content=content, plugin_id=plugin_id,+ plugin_home=plugin_home)if not self._plugin_injection_authorized(source, plugin_id=plugin_id, target=f"session={session_key}"):return False@@ -164,6 +197,20 @@ class GatewayPluginInjectionMixin:)return True+ async def _dispatch_plugin_local_injection(self, source: SessionSource, entry, *, content: str,+ plugin_id: str, plugin_home: Optional[Path]) -> bool:+ """A local (CLI/TUI/Desktop) session has no messaging adapter or chat allowlist: the plugin+ turn is committed to its FIFO on the live session's own source and adapter, as a bot delivery+ is, only when the plugin's own profile's authority holds the session (checked before entering+ that scope). Main queued key-less CLI injections into the REPL; this is where they land now."""+ live = self._plugin_local_session(source, entry.session_key, plugin_home=plugin_home, plugin_id=plugin_id)+ if live is None:+ return False+ async with self._plugin_injection_scope(source, plugin_home):+ return bool(await self._admit_plugin_injection(+ self._adapter_for_source(live.source), live.source, session_key=entry.session_key,+ session_id=entry.session_id, content=content, plugin_id=plugin_id))+def _served_profile_for_home(self, home: Optional[Path]) -> Optional[str]:"""Name of the profile this gateway serves at *home* (a plugin manager's immutable home), or``None`` when this gateway does not serve it."""diff --git a/hermes_cli/plugin_session.py b/hermes_cli/plugin_session.pynew file mode 100644index 00000000000..50f86d46feb--- /dev/null+++ b/hermes_cli/plugin_session.py@@ -0,0 +1,48 @@+"""The session a plugin hook or tool is running for, read from the turn's task-local context.++Plugin hooks and tools run in the gateway process, whose own cwd is the install root and is shared+by every session (it is never ``os.chdir``-ed). These read the calling session's key, client surface+and recorded working directory instead.+"""+from __future__ import annotations++import os+++def _active_policy():+ from gateway.session_policy import active_policy+ return active_policy()+++def session_key() -> str:+ """Route key of the session whose turn is running in this context, ``""`` outside one."""+ from gateway.session_context import get_session_env+ return get_session_env("HERMES_SESSION_KEY", "")+++def session_surface() -> str:+ """``cli``/``tui``/``desktop``/``acp`` for a local session's turn, the messaging platform+ (``telegram``, ``discord``, ...) for a chat's turn, ``""`` outside any session."""+ policy = _active_policy()+ if policy is not None:+ return policy.platform+ from gateway.session_context import get_session_env+ return get_session_env("HERMES_SESSION_PLATFORM", "")+++def session_cwd() -> str:+ """The calling session's recorded working directory (a local session's workspace, else the+ profile's terminal cwd), ``""`` when it has none. Never the gateway process's own cwd."""+ from agent.runtime_cwd import scope_terminal_cwd, scoped_session_cwd+ policy = _active_policy()+ return scoped_session_cwd() or (policy.cwd if policy is not None else "") or scope_terminal_cwd().strip()+++def context_surface(manager) -> str:+ """``session_surface()`` for a plugin context: the classic CLI process itself is ``cli``."""+ return "cli" if manager._cli_ref is not None else session_surface()+++def context_cwd(manager) -> str:+ """``session_cwd()`` for a plugin context: the classic CLI process keeps its launch directory."""+ return os.getcwd() if manager._cli_ref is not None else session_cwd()diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex c68e50f606d..a97bc1ef686 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -602,21 +602,21 @@ class PluginContext:self, content: str, role: str = "user", *, session_key: str | None = None,origin: Mapping[str, Any] | None = None,) -> bool:- """Inject a message into a CLI, Ink TUI/desktop, or messaging-gateway conversation.-- CLI uses the attached REPL queues. Ink TUI and desktop use a separate injector- from the messaging gateway and queue onto the live session named by ``session_key``- (the durable key, not the ephemeral UI session id). ``origin`` (a- ``SessionSource.to_dict()``-shaped mapping: platform, chat_id, chat_type, thread_id,- user_id, ...) instead names a messaging chat: the gateway starts (or continues) that- chat's session in THIS plugin's own profile and runs a turn there; the plugin cannot- target another profile. Non-CLI injection needs ``session_key`` or ``origin`` plus- ``plugins.entries.<plugin_id>.allow_gateway_injection`` in the plugin's profile config.- ``True`` means a host accepted the request, not that the turn completed.- """+ """Queue *content* for a session (``session_key``) or a chat in this plugin's own profile+ (``origin``); ``True`` means a host accepted it. Contract: plugins_injection.py, plugin docs."""from hermes_cli.plugins_injection import inject_plugin_messagereturn inject_plugin_message(self, content, role, session_key=session_key, origin=origin)+ def session_cwd(self) -> str:+ """The calling session's recorded cwd, never the gateway's own (``plugin_session``)."""+ from hermes_cli.plugin_session import context_cwd+ return context_cwd(self._manager)++ def session_surface(self) -> str:+ """The calling session's client (``cli``/``tui``/``desktop``/``acp``) or messaging platform."""+ from hermes_cli.plugin_session import context_surface+ return context_surface(self._manager)+def _gateway_injection_allowed(self) -> bool:"""Return whether this plugin may trigger gateway session turns (read from the plugin'sown profile config, never the calling thread's ambient home)."""diff --git a/hermes_cli/plugins_injection.py b/hermes_cli/plugins_injection.pyindex 52659d8fae4..1c059d639cd 100644--- a/hermes_cli/plugins_injection.py+++ b/hermes_cli/plugins_injection.py@@ -21,6 +21,12 @@ def inject_plugin_message(queue_ = cli._interrupt_queue if getattr(cli, "_agent_running", False) else cli._pending_inputqueue_.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 Noneif session_key and origin is not None:logger.warning("inject_message: pass session_key or origin, not both")return False@@ -49,11 +55,12 @@ def inject_plugin_message(if not manager.has_gateway_message_injector:logger.warning("inject_message: no live gateway is available")return False+ # 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}+ target: dict[str, Any] = {"session_key": session_key, "plugin_home": manager.home_path}else:- # The manager's immutable home is the plugin's profile: the gateway creates the session- # there or nowhere (never the ambient HERMES_HOME of whatever thread called us).target = {"origin": dict(origin), "plugin_home": manager.home_path}try:return bool(manager.inject_gateway_message(**target, content=msg, plugin_id=ctx.plugin_id))diff --git a/tests/gateway/test_plugin_gateway_session_parity.py b/tests/gateway/test_plugin_gateway_session_parity.pynew file mode 100644index 00000000000..34ce22c2a18--- /dev/null+++ b/tests/gateway/test_plugin_gateway_session_parity.py@@ -0,0 +1,226 @@+"""Plugin code running inside the gateway sees the session it runs for (LC-5).++* A key-less ``inject_message`` from a classic CLI session's turn lands in that session, as main+ queued it into the CLI REPL.+* Approval hooks report a CLI session's ``surface='cli'`` (as on main);+ ``ctx.session_cwd()`` / ``ctx.session_surface()`` read the session, never the daemon's cwd.+"""+import asyncio+import contextvars+import os+from types import SimpleNamespace++import pytest++from tests.gateway.test_plugin_origin_injection_authority import _context, _plugin_rows, _publish+from tests.waiting import async_wait_until+++async def test_keyless_injection_from_a_cli_session_turn_lands_in_that_session(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner+ from gateway.session_authority import SessionAuthority, initialize_session_authority+ from gateway.session_context import set_session_vars+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from gateway.session_policy import _ACTIVE_POLICY+ from hermes_state import SessionDB++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: None)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ db = SessionDB(tmp_path / "state.db")+ runner.session_store._db = db+ runner._session_db = db+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="owner", db=db)+ try:+ actor = Principal("test-owner", "default", frozenset({"session:create", "session:submit", "session:read"}),+ "fixture")+ ref = create_local_session(authority, actor, dict(request_id="cli", source="cli", model="fixture",+ toolsets=[]))+ live = authority.sessions[ref.session_id]+ ctx, manager = _context(tmp_path)+ _publish(runner, manager)++ def hook_in_the_cli_turn():+ # What a plugin hook or tool sees while the gateway runs this CLI session's turn.+ set_session_vars(platform="local", session_key=live.route, session_id=ref.session_id)+ _ACTIVE_POLICY.set(SimpleNamespace(platform="cli", cwd=str(tmp_path)))+ return ctx.inject_message("plugin note")++ accepted = await asyncio.to_thread(contextvars.copy_context().run, hook_in_the_cli_turn)+ assert accepted is True+ await async_wait_until(lambda: _plugin_rows(authority, ref.session_id, "plugin note"), timeout=10,+ what="the plugin admission in the CLI session")+ finally:+ db.close()+++async def test_keyed_local_injection_stays_inside_the_plugins_own_profile(tmp_path, monkeypatch):+ """Multiplexed gateway: a plugin of profile A may inject into A's live local sessions (key-less+ from the turn, or by key), never into profile B's by naming B's session key; that is refused+ up front (``False``, reason in gateway.log) and admits nothing."""+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner, _profile_runtime_scope+ from gateway.session_authorities import SessionAuthorities+ from gateway.session_authority import SessionAuthority+ from gateway.session_context import set_session_vars+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from gateway.session_policy import _ACTIVE_POLICY+ from hermes_state import SessionDB+ from hermes_state_runtime import begin_runtime_epoch++ launch = tmp_path / ".hermes"+ beta = launch / "profiles" / "beta"+ beta.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(launch))+ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: None)+ runner = GatewayRunner(GatewayConfig(sessions_dir=launch / "sessions"))+ runner.config.multiplex_profiles = True+ runner.config._runtime_profile_homes = [("default", launch), ("beta", beta)]+ runner.session_authorities = SessionAuthorities(launch, multiplexed=True)+ authorities, sessions, contexts = {}, {}, {}+ for name, home in (("default", launch), ("beta", beta)):+ contexts[name] = _context(home)+ db = SessionDB(home / "state.db")+ authorities[name] = SessionAuthority(runner, profile_id=str(home), instance_id="owner", db=db,+ epoch=begin_runtime_epoch(db, instance_id="owner"))+ runner.session_authorities.add(home, authorities[name], name=name)+ runner.session_authority = authorities["default"]+ runner.session_store._db = runner._session_db = authorities["default"].db+ try:+ for name, home in (("default", launch), ("beta", beta)):+ authority = authorities[name]+ actor = Principal("test-owner", authority.profile_id,+ frozenset({"session:create", "session:submit", "session:read"}), "fixture")+ with _profile_runtime_scope(home, hydrate_secrets=False):+ ref = create_local_session(authority, actor, dict(request_id="cli", source="cli", model="fixture",+ toolsets=[]))+ sessions[name] = (ref.session_id, authority.sessions[ref.session_id].route)+ for _ctx, manager in contexts.values():+ _publish(runner, manager)+ alpha_ctx, beta_ctx = contexts["default"][0], contexts["beta"][0]+ alpha_sid, alpha_key = sessions["default"]+ beta_sid, beta_key = sessions["beta"]++ def keyless_in_alphas_cli_turn():+ set_session_vars(platform="local", session_key=alpha_key, session_id=alpha_sid)+ _ACTIVE_POLICY.set(SimpleNamespace(platform="cli", cwd=str(tmp_path)))+ return alpha_ctx.inject_message("alpha keyless")++ assert await asyncio.to_thread(contextvars.copy_context().run, keyless_in_alphas_cli_turn) is True+ assert await asyncio.to_thread(alpha_ctx.inject_message, "alpha keyed", session_key=alpha_key) is True+ assert await asyncio.to_thread(beta_ctx.inject_message, "beta keyed", session_key=beta_key) is True+ for name, text in (("default", "alpha keyless"), ("default", "alpha keyed"), ("beta", "beta keyed")):+ await async_wait_until(lambda: _plugin_rows(authorities[name], sessions[name][0], text), timeout=10,+ what=f"the same-profile plugin admission {text!r}")++ with caplog_at("gateway.run") as records:+ assert await asyncio.to_thread(alpha_ctx.inject_message, "cross", session_key=beta_key) is False+ # Dispatch rechecks before entering the target profile's scope.+ assert await runner._dispatch_plugin_message_injection(+ session_key=beta_key, content="cross", plugin_id="desk", plugin_home=launch) is False++ def in_betas_scope(call):+ # Where beta's plugin code runs: the ambient home is beta's, which must not make a+ # default-profile session (its source carries no profile) look like beta's.+ with _profile_runtime_scope(beta, hydrate_secrets=False):+ return call()++ def keyless_in_beta_scope_for_alphas_turn():+ set_session_vars(platform="local", session_key=alpha_key, session_id=alpha_sid)+ _ACTIVE_POLICY.set(SimpleNamespace(platform="cli", cwd=str(tmp_path)))+ return in_betas_scope(lambda: beta_ctx.inject_message("cross"))++ with caplog_at("gateway.run") as beta_records:+ assert await asyncio.to_thread(+ in_betas_scope, lambda: beta_ctx.inject_message("cross", session_key=alpha_key)) is False+ assert await asyncio.to_thread(contextvars.copy_context().run, keyless_in_beta_scope_for_alphas_turn) is False+ assert await asyncio.to_thread(+ in_betas_scope, lambda: beta_ctx.inject_message("beta again", session_key=beta_key)) is True+ await async_wait_until(lambda: _plugin_rows(authorities["beta"], beta_sid, "beta again"), timeout=10,+ what="the same-profile plugin admission from beta's scope")+ assert not _plugin_rows(authorities["beta"], beta_sid, "cross")+ assert not _plugin_rows(authorities["default"], alpha_sid, "cross")+ assert all("not a live local session of the plugin's profile" in record.getMessage()+ for record in (*records, *beta_records) if "refused" in record.getMessage())+ assert sum("refused" in record.getMessage() for record in beta_records) == 2+ finally:+ for authority in authorities.values():+ authority.db.close()+++class caplog_at:+ """Collect one logger's records without depending on the caplog fixture's propagation."""++ def __init__(self, name):+ import logging+ self.logger, self.records = logging.getLogger(name), []+ self.handler = logging.Handler()+ self.handler.emit = self.records.append++ def __enter__(self):+ self.logger.addHandler(self.handler)+ return self.records++ def __exit__(self, *_exc):+ self.logger.removeHandler(self.handler)+++def test_gateway_approval_hooks_report_a_cli_sessions_surface(tmp_path, monkeypatch):+ from gateway.session_policy import _ACTIVE_POLICY+ from tools.approval_gateway_wait import _await_gateway_decision++ seen = []+ approval_hooks = {"pre_approval_request", "post_approval_response"}+ monkeypatch.setattr("hermes_cli.lifecycle.invoke_hook",+ lambda name, **kw: seen.append((name, kw)) if name in approval_hooks else None)++ def boom(_data):+ raise RuntimeError("no client")++ def decide(policy):+ if policy is not None:+ _ACTIVE_POLICY.set(policy)+ return _await_gateway_decision("k", boom, {"command": "rm -rf x", "description": "d", "pattern_key": "rm"})++ workspace = tmp_path / "ws"+ workspace.mkdir()+ result = contextvars.copy_context().run(decide, SimpleNamespace(platform="cli", cwd=str(workspace)))+ assert result["notify_failed"] is True+ assert [(name, kw["surface"]) for name, kw in seen] == [+ ("pre_approval_request", "cli"), ("post_approval_response", "cli")]++ # TUI/Desktop and messaging sessions keep the documented gateway surface.+ seen.clear()+ contextvars.copy_context().run(decide, SimpleNamespace(platform="tui", cwd=str(workspace)))+ contextvars.copy_context().run(decide, None)+ assert {kw["surface"] for _name, kw in seen} == {"gateway"}+++def test_plugin_context_reads_the_calling_sessions_cwd_and_surface(tmp_path):+ from agent.runtime_cwd import set_session_cwd+ from gateway.session_context import set_session_vars+ from gateway.session_policy import _ACTIVE_POLICY++ ctx, manager = _context(tmp_path)+ workspace = tmp_path / "ws"+ workspace.mkdir()++ def in_local_turn():+ _ACTIVE_POLICY.set(SimpleNamespace(platform="tui", cwd=str(workspace)))+ set_session_cwd(str(workspace))+ return ctx.session_cwd(), ctx.session_surface()++ def in_messaging_turn():+ set_session_vars(platform="telegram", session_key="agent:main:telegram:dm:1")+ return ctx.session_surface()++ assert contextvars.copy_context().run(in_local_turn) == (str(workspace), "tui")+ assert contextvars.copy_context().run(in_messaging_turn) == "telegram"+ # The classic CLI process itself still runs in the user's launch directory.+ manager._cli_ref = SimpleNamespace()+ assert (ctx.session_cwd(), ctx.session_surface()) == (os.getcwd(), "cli")diff --git a/tests/gateway/test_plugin_message_injection.py b/tests/gateway/test_plugin_message_injection.pyindex 89ccbc83edd..0cd477ed7b8 100644--- a/tests/gateway/test_plugin_message_injection.py+++ b/tests/gateway/test_plugin_message_injection.py@@ -42,7 +42,8 @@ def _entry(*, origin=True) -> SessionEntry:def _runner(entry: SessionEntry | None, adapter=None) -> GatewayRunner:runner = object.__new__(GatewayRunner)- runner.session_store = SimpleNamespace()+ # The scheduler's synchronous profile check reads the store; dispatch reads the async facade.+ runner.session_store = SimpleNamespace(lookup_by_session_key=lambda _key: None)runner._async_session_store = SimpleNamespace(_store=runner.session_store, lookup_by_session_key=AsyncMock(return_value=entry))diff --git a/tests/hermes_cli/test_plugin_message_injection.py b/tests/hermes_cli/test_plugin_message_injection.pyindex e7453b32922..ee797ad1b57 100644--- a/tests/hermes_cli/test_plugin_message_injection.py+++ b/tests/hermes_cli/test_plugin_message_injection.py@@ -162,6 +162,7 @@ def test_gateway_injection_passes_host_owned_plugin_identity(tmp_path, monkeypatassert result is Trueinjector.assert_called_once_with(session_key="agent:main:telegram:dm:42",+ plugin_home=manager.home_path,content="[system] wake up",plugin_id="notify-plugin",)@@ -238,8 +239,10 @@ def test_published_gateway_host_reaches_existing_and_future_profile_managers(tmpfinally:reset_hermes_home_override(token)+ # The calling manager's immutable home, not the launch home, rides with the key.injector.assert_called_once_with(session_key="agent:secondary:telegram:dm:42",+ plugin_home=secondary_manager.home_path,content="continue",plugin_id="notify-plugin",)diff --git a/tests/tui_gateway/test_plugin_inject_host.py b/tests/tui_gateway/test_plugin_inject_host.pyindex 65bddbb98fe..6444224b1c6 100644--- a/tests/tui_gateway/test_plugin_inject_host.py+++ b/tests/tui_gateway/test_plugin_inject_host.py@@ -114,6 +114,7 @@ def test_unknown_session_key_falls_through_to_the_gateway_slot(tmp_path, monkeypgateway.assert_called_once_with(session_key="agent:main:telegram:dm:42",+ plugin_home=manager.home_path,content="wake telegram",plugin_id="notify-plugin",)diff --git a/tools/approval.py b/tools/approval.pyindex 3c1ff3ff4dc..0ff6526a42c 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -835,8 +835,8 @@ def _human_decision(spec: _GateSpec, *, command: str, description: str,if spec.transport:attempt = _present_with_selected_transport(command=command, description=description, pattern_key=pattern_key, pattern_keys=pattern_keys,- session_key=session_key, surface="gateway" if (is_gateway or is_ask) else "cli",- allow_session=not smart_denied, allow_permanent=allow_permanent,+ session_key=session_key, allow_session=not smart_denied, allow_permanent=allow_permanent,+ surface=approval_context.gateway_approval_surface() if (is_gateway or is_ask) else "cli",)choice, denied = _transport_choice(attempt, pattern_key=pattern_key, description=description)if denied is not None:diff --git a/tools/approval_context.py b/tools/approval_context.pyindex 7b693516e97..a0084b83bed 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -73,6 +73,13 @@ def _fire_approval_hook(hook_name: str, **kwargs) -> None:logger.debug("Approval hook %s dispatch failed: %s", hook_name, exc)+def gateway_approval_surface() -> str:+ """Surface a gateway-rendered approval reports: ``cli`` for a classic CLI session's turn (main+ prompted those in the CLI process), else ``gateway``."""+ from hermes_cli.plugin_session import session_surface+ return "cli" if session_surface() == "cli" else "gateway"++def set_current_session_key(session_key: str) -> contextvars.Token[str]:"""Bind the active approval session key to the current context."""return _approval_session_key.set(session_key or "")diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.pyindex 1bbb59e5d07..45b73abdabf 100644--- a/tools/approval_gateway_wait.py+++ b/tools/approval_gateway_wait.py@@ -151,6 +151,8 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,from agent.terminal_approval_batch import approval_published, preparing_terminal_approval, register_prepared_approvalprimary_key = approval_data.get("pattern_key", "")+ if surface == "gateway":+ surface = _ctx.gateway_approval_surface()payload = {"command": approval_data.get("command", ""),"description": approval_data.get("description", ""),diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 317be17ed0d..906ac3e004f 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -1392,7 +1392,7 @@ def my_callback(| `pattern_key` | `str` | Primary pattern key that triggered the approval (e.g. `"rm_rf"`, `"sudo"`) || `pattern_keys` | `list[str]` | All pattern keys that matched || `session_key` | `str` | Session identifier, useful for scoping notifications per-chat |-| `surface` | `str` | `"cli"` for classic interactive-CLI prompts (dangerous commands, protected agent-instruction writes, consent prompts), `"gateway"` for async platform approvals (the Ink TUI and Desktop app also report `"gateway"` today), `"smart"` for auxiliary-LLM auto approve/deny decisions, or the caller's consent surface for MCP/vault prompts (`"mcp-elicitation/<server>"`, `"mcp-trust/<server>"`, `"vault-payment"`) |+| `surface` | `str` | `"cli"` for classic CLI sessions (dangerous commands, protected agent-instruction writes, consent prompts; also when the gateway renders the prompt for that session), `"gateway"` for async platform approvals (the Ink TUI and Desktop app also report `"gateway"` today), `"smart"` for auxiliary-LLM auto approve/deny decisions, or the caller's consent surface for MCP/vault prompts (`"mcp-elicitation/<server>"`, `"mcp-trust/<server>"`, `"vault-payment"`) |**Return value:** ignored. Hooks here are observer-only; they cannot veto or pre-answer the approval. Use [`pre_tool_call`](#pre_tool_call) to block a tool before it reaches the approval system.diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex ffeeb916f63..a1619df85b7 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -938,6 +938,7 @@ In CLI mode:In gateway mode:- `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 starts the next turn; it no longer interrupts a running one. `allow_gateway_injection` is still required.- Hermes reuses that session's stored platform, chat, thread, profile, and conversation history. Plugins cannot change that route through `session_key`.- Hermes rechecks the stored route against the gateway's current authorisation rules before dispatch.- Routes that relied only on an adapter-time or upstream authorisation decision are rejected unless Hermes can revalidate them from current core allowlists, pairing, or explicit allow-all configuration.@@ -977,6 +978,17 @@ Only grant gateway injection to plugins you trust. Hermes checks this host API pThis plugin API does not expose a public HTTP endpoint or CLI command for external processes. The plugin must already know the target gateway `session_key`, for example from its own trusted configuration or previously retained session state.:::+## Plugin code inside the gateway++Hooks, tools and injected turns of every chat and every local session (CLI, TUI, Desktop) run in the one gateway process, not in the client you launched. Some process-level habits from the classic CLI do not carry over:++- `os.getcwd()` is the gateway's own directory, shared by every session; Hermes never changes it. Use `ctx.session_cwd()` for the working directory of the session the hook or tool runs for: the workspace a CLI/TUI/Desktop session was started in, or the profile's terminal cwd for a chat (`""` when there is none). Pass it as `cwd=` to subprocesses. It reads the session from the running turn, so it works in code that runs for a session: turn hooks, tool handlers and approval hooks. Ingress hooks such as `pre_gateway_dispatch` run before the message is admitted to any session; there it returns the profile's terminal cwd, or `""` when none is configured.+- `ctx.session_surface()` names the calling session's client: `"cli"`, `"tui"`, `"desktop"`, `"acp"`, or the messaging platform (`"telegram"`, …); `""` outside a session.+- `print()` output goes to the gateway's `gateway-stdio.log`, not to your terminal. Use `logging` instead.+- `input()` gets end-of-file: the gateway has no terminal. Ask through a tool result or a slash command.++In the classic CLI process itself (for example a plugin slash command), `ctx.session_cwd()` is the launch directory and `ctx.session_surface()` is `"cli"`.+## Calling MCP servers from plugins`ctx.call_mcp()` lets a plugin call a tool on one of the user's configured MCP servers — synchronously, from any hook or tool handler — routing through Hermes' existing native MCP client (same connections, trust-tier gates, circuit breaker, and reconnect logic as model-invoked MCP tools; never a parallel client).