The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): ctx.post_message — post one message to the current conversation and edit it in place
Tekniuma2eab1f45c2e
diff --git a/gateway/plugin_messages.py b/gateway/plugin_messages.pynew file mode 100644index 00000000000..b9a1d2daba7--- /dev/null+++ b/gateway/plugin_messages.py@@ -0,0 +1,168 @@+"""Where ``PluginContext.post_message`` lands: the conversation the calling plugin code works for.++The route is never chosen by the plugin. It is the session whose key is bound in the calling context+(a tool or hook in its turn, its slash command, a hook fired for it), resolved here on the gateway loop:++* a messaging chat posts through the adapter that answers it (``adapter.send``) and edits through+ ``adapter.edit_message``; an adapter without edit support, or a refused edit, gets a fresh send and+ the handle follows the new message;+* a local CLI/TUI/Desktop session has no transport of its own (``LocalSessionAdapter.send`` is a no-op),+ so the text goes to its viewers as a keyed ``notification.show``; an edit re-publishes the same key,+ which Desktop and the Ink TUI replace in place (the classic CLI queues each as a line for its next+ turn end).+"""+from __future__ import annotations++import logging+import uuid+from dataclasses import dataclass+from typing import Any, Optional++from gateway.config import Platform++logger = logging.getLogger(__name__)+++@dataclass+class PostTarget:+ """A resolved conversation: a messaging ``adapter`` + ``chat_id``, or a local session's ``live``."""+ platform: str+ chat_id: str+ adapter: Any = None+ metadata: Optional[dict] = None+ live: Any = None+ notice_key: str = ""+++def _err(code: str, detail: str = "") -> dict:+ return {"ok": False, "error": code, **({"detail": detail} if detail else {})}+++def _fit(adapter: Any, chat_id: str, text: str) -> str:+ """Clamp *text* to the adapter's per-chat message limit (ellipsis), never split it."""+ try:+ limit = int(adapter.max_message_length_for_chat(chat_id))+ measure = adapter.message_len_fn_for_chat(chat_id)+ except (AttributeError, TypeError, ValueError): # an adapter not built on BasePlatformAdapter+ limit, measure = 4096, len+ if limit <= 0 or measure(text) <= limit:+ return text+ cut = text+ while cut and measure(cut + "…") > limit:+ cut = cut[: -max(1, measure(cut + "…") - limit)]+ return cut + "…"+++def _supports_edit(adapter: Any) -> bool:+ from gateway.platforms.base import BasePlatformAdapter+ if getattr(adapter, "SUPPORTS_MESSAGE_EDITING", True) is False:+ return False+ return getattr(type(adapter), "edit_message", None) is not BasePlatformAdapter.edit_message+++_ROUTE_VARS = {"platform": "HERMES_SESSION_PLATFORM", "chat_id": "HERMES_SESSION_CHAT_ID",+ "chat_type": "HERMES_SESSION_CHAT_TYPE", "thread_id": "HERMES_SESSION_THREAD_ID",+ "user_id": "HERMES_SESSION_USER_ID", "profile": "HERMES_SESSION_PROFILE"}+++def bound_route() -> dict:+ """The messaging route the gateway bound in THIS context (read on the caller's thread: the+ gateway loop runs the send in its own context)."""+ from gateway.session_context import get_session_env+ return {field: get_session_env(var, "") for field, var in _ROUTE_VARS.items()}+++def _bound_source(route: dict):+ """A source for a messaging chat whose session has no store entry yet (a plugin command that is+ the chat's first message): the route the gateway itself bound for this call."""+ from gateway.session import SessionSource+ if not route.get("platform") or not route.get("chat_id") or route["platform"] == Platform.LOCAL.value:+ return None+ try:+ return SessionSource.from_dict({k: v for k, v in route.items() if v})+ except (KeyError, TypeError, ValueError):+ return None+++def resolve(runner, *, session_key: str, route: dict, plugin_home, plugin_id: str):+ """``(PostTarget, None)`` for the session *session_key* names, or ``(None, error dict)``."""+ entry = runner.session_store.lookup_by_session_key(session_key)+ if entry is not None and entry.origin is not None:+ from gateway.session_identity import replace_source+ source = replace_source(runner._restored_source(entry))+ else:+ source = _bound_source(route)+ # The bound route must be the chat this key names (both are bound by the gateway together).+ if source is None or runner._session_key_for_source(source) != session_key:+ return None, _err("no_conversation", f"session {session_key!r} is not known to this gateway")+ if source.platform == Platform.LOCAL:+ live = runner._plugin_local_session(source, session_key, plugin_home=plugin_home, plugin_id=plugin_id)+ if live is None:+ return None, _err("no_conversation", "the local session is not live in this plugin's profile")+ key = f"plugin-message:{plugin_id}:{uuid.uuid4().hex[:12]}"+ return PostTarget(platform="local", chat_id=source.chat_id, live=live, notice_key=key), None+ if not runner._plugin_messaging_session_owned(session_key, plugin_home=plugin_home, plugin_id=plugin_id):+ return None, _err("no_conversation", "the session belongs to another profile")+ adapter = runner._delivery_adapter_for(source)+ if adapter is None:+ return None, _err("adapter_unavailable", f"no connected {source.platform.value} adapter answers this chat")+ try:+ metadata = runner._thread_metadata_for_source(source)+ except Exception: # thread routing is optional: post to the chat itself+ logger.debug("plugin_message: no thread metadata for %s", source.platform.value, exc_info=True)+ metadata = None+ return PostTarget(platform=source.platform.value, chat_id=str(source.chat_id), adapter=adapter,+ metadata=metadata), None+++def _publish_local(target: PostTarget, text: str) -> dict:+ delivered = target.live.event_stream.publish(target.chat_id, {+ "text": text, "level": "info", "kind": "sticky", "key": target.notice_key, "id": target.notice_key,+ }, event_type="notification.show")+ return {"ok": True, "message_id": target.notice_key, "delivered": bool(delivered)}+++async def _send(target: PostTarget, text: str) -> dict:+ result = await target.adapter.send(target.chat_id, _fit(target.adapter, target.chat_id, text),+ metadata=target.metadata)+ if not getattr(result, "success", False):+ return _err("send_failed", str(getattr(result, "error", "") or "")[:512])+ return {"ok": True, "message_id": str(result.message_id) if result.message_id is not None else None}+++async def post(target: PostTarget, text: str, *, plugin_id: str) -> dict:+ """First message of a handle."""+ try:+ result = _publish_local(target, text) if target.live is not None else await _send(target, text)+ except Exception as exc: # adapter boundary: the plugin gets a result, never the raise+ logger.warning("plugin_message plugin=%s op=post send raised", plugin_id, exc_info=True)+ result = _err("send_failed", str(exc)[:512])+ logger.info("plugin_message plugin=%s op=post platform=%s chat=%s ok=%s message_id=%s%s", plugin_id,+ target.platform, target.chat_id, result.get("ok"), result.get("message_id"),+ "" if result.get("ok") else f" error={result.get('error')}")+ return result+++async def edit(target: PostTarget, message_id: Optional[str], text: str, *, plugin_id: str) -> dict:+ """Edit *message_id* in place; a surface that cannot edit gets a fresh message (``fallback``)."""+ result: dict+ try:+ if target.live is not None:+ result = {**_publish_local(target, text), "edited": True}+ elif message_id and _supports_edit(target.adapter):+ sent = await target.adapter.edit_message(target.chat_id, message_id,+ _fit(target.adapter, target.chat_id, text))+ if getattr(sent, "success", False):+ result = {"ok": True, "message_id": str(sent.message_id or message_id), "edited": True}+ else:+ result = {**await _send(target, text), "edited": False, "fallback": True,+ "edit_error": str(getattr(sent, "error", "") or "")[:256]}+ else:+ result = {**await _send(target, text), "edited": False, "fallback": True}+ except Exception as exc: # adapter boundary, as in post()+ logger.warning("plugin_message plugin=%s op=edit raised", plugin_id, exc_info=True)+ result = _err("edit_failed", str(exc)[:512])+ logger.info("plugin_message plugin=%s op=edit platform=%s chat=%s ok=%s edited=%s message_id=%s%s",+ plugin_id, target.platform, target.chat_id, result.get("ok"), result.get("edited", False),+ result.get("message_id"), "" if result.get("ok") else f" error={result.get('error')}")+ return resultdiff --git a/hermes_cli/plugin_isolation.py b/hermes_cli/plugin_isolation.pyindex 7a4d1ef354a..2d1497e49f2 100644--- a/hermes_cli/plugin_isolation.py+++ b/hermes_cli/plugin_isolation.py@@ -39,6 +39,8 @@ HOST_UNSUPPORTED_CTX_METHODS: dict[str, str] = {"register_slack_action_handler": "the callback receives native slack_bolt ack/body objects","register_dashboard_auth_provider": "dashboard auth is owned by the launch process, not a profile","register_approval_transport": "approval transports hold the live approval request/response channel",+ "post_message": "the returned handle is bound to the gateway's event loop and live adapter",+ "apost_message": "the returned handle is bound to the gateway's event loop and live adapter",}# Registered in-process only; skipped (with a warning, the plugin still loads) inside the hostdiff --git a/hermes_cli/plugin_messages.py b/hermes_cli/plugin_messages.pynew file mode 100644index 00000000000..9ba0ee4f1dc--- /dev/null+++ b/hermes_cli/plugin_messages.py@@ -0,0 +1,158 @@+"""``PluginContext.post_message``: one message in the current conversation, editable in place.++The conversation is the session bound in the calling context (a tool or hook running in its turn,+its slash command, a hook fired for it): the plugin never names a chat, so it cannot reach another+one. Outside any session (a timer, a plugin thread, cron, a process with no live gateway) the call+is refused with a result, never an exception. Routing and the edit fallback live in+``gateway/plugin_messages.py``; this side only hands work to the gateway loop and back.+"""+from __future__ import annotations++import asyncio+import concurrent.futures+import logging+from typing import Any, Optional++logger = logging.getLogger("hermes_cli.plugins")++_TIMEOUT_S = 30.0+++def _err(code: str, detail: str = "") -> dict[str, Any]:+ return {"ok": False, "error": code, **({"detail": detail} if detail else {})}+++class PluginMessage:+ """Handle for one posted message. ``ok`` / ``message_id`` / ``error`` describe the last+ operation; ``edit(text)`` replaces the text in place (or posts anew where the surface cannot+ edit, and the handle then follows the new message). A refused post returns a handle whose+ edits are refused the same way."""++ def __init__(self, plugin_id: str, target: Any, result: dict[str, Any]):+ self._plugin_id, self._target = plugin_id, target+ self.result = result+ self.message_id: Optional[str] = result.get("message_id")++ @property+ def ok(self) -> bool:+ return bool(self.result.get("ok"))++ @property+ def error(self) -> Optional[str]:+ return self.result.get("error")++ def __repr__(self) -> str:+ return f"<PluginMessage ok={self.ok} message_id={self.message_id!r} error={self.error!r}>"++ def _refused(self) -> Optional[dict[str, Any]]:+ if self._target is None:+ return _err(self.error or "no_conversation", self.result.get("detail", ""))+ return None++ def _settle(self, result: dict[str, Any]) -> dict[str, Any]:+ self.result = result+ if result.get("ok") and result.get("message_id"):+ self.message_id = result["message_id"]+ return result++ async def aedit(self, text: str) -> dict[str, Any]:+ """``edit`` for code already running on the gateway's event loop (async hooks/commands)."""+ refused = self._refused()+ if refused is not None:+ return refused+ from gateway import plugin_messages+ return self._settle(await plugin_messages.edit(self._target, self.message_id, str(text),+ plugin_id=self._plugin_id))++ def edit(self, text: str) -> dict[str, Any]:+ """Replace the message text: ``{"ok", "message_id", "edited", ["fallback"]}``. Thread-safe."""+ refused = self._refused()+ if refused is not None:+ return refused+ return _run_on_gateway_loop(self.aedit(text))+++def _gateway_loop():+ try:+ from gateway.run import _gateway_runner_ref+ runner = _gateway_runner_ref()+ except ImportError:+ runner = None+ loop = getattr(runner, "_gateway_loop", None)+ if runner is None or not getattr(runner, "_running", False) or loop is None or loop.is_closed():+ return None, None+ return runner, loop+++def _run_on_gateway_loop(coro) -> dict[str, Any]:+ _runner, loop = _gateway_loop()+ if loop is None:+ coro.close()+ return _err("gateway_unavailable", "no live gateway is running in this process")+ try:+ running = asyncio.get_running_loop()+ except RuntimeError:+ running = None+ if running is loop:+ coro.close()+ return _err("on_event_loop", "called from the gateway event loop: use the async form (await ...)")+ try:+ return asyncio.run_coroutine_threadsafe(coro, loop).result(_TIMEOUT_S)+ except concurrent.futures.TimeoutError:+ return _err("timeout", f"the gateway did not answer within {_TIMEOUT_S:.0f}s")+ except Exception as exc: # the plugin gets a result, never the raise+ logger.warning("plugin_message: gateway hand-off failed", exc_info=True)+ return _err("send_failed", str(exc)[:512])+++_NO_SESSION = ("no session is bound in the calling context (a tool call, slash command or hook "+ "fired for a session)")+++async def _post_for(ctx: Any, text: str, session_key: str, route: dict) -> PluginMessage:+ plugin_id = ctx.plugin_id+ runner, _loop = _gateway_loop()+ result: dict[str, Any]+ if not session_key:+ result = _err("no_conversation", _NO_SESSION)+ elif runner is None:+ result = _err("gateway_unavailable", "no live gateway is running in this process")+ else:+ from gateway import plugin_messages+ # The session store read is disk-bound: keep it off the gateway loop.+ target, refusal = await asyncio.to_thread(plugin_messages.resolve, runner, session_key=session_key,+ route=route, plugin_home=ctx._manager.home_path, plugin_id=plugin_id)+ if target is None:+ result = refusal or _err("no_conversation")+ else:+ result = await plugin_messages.post(target, str(text), plugin_id=plugin_id)+ if result.get("ok"):+ return PluginMessage(plugin_id, target, result)+ logger.info("plugin_message plugin=%s op=post refused: %s", plugin_id, result.get("error"))+ return PluginMessage(plugin_id, None, result)+++async def apost(ctx: Any, text: str) -> PluginMessage:+ """``post`` for code already running on the gateway's event loop (async hooks/commands)."""+ from gateway.plugin_messages import bound_route+ from gateway.session_context import bound_session_key+ return await _post_for(ctx, text, bound_session_key(), bound_route())+++def post(ctx: Any, text: str) -> PluginMessage:+ """Post *text* to the calling session from a tool handler or hook on a worker thread. The session+ is read here, on the caller's own context, then the send runs on the gateway loop."""+ from gateway.session_context import bound_session_key+ session_key = bound_session_key()+ if not session_key:+ return PluginMessage(ctx.plugin_id, None, _err("no_conversation", _NO_SESSION))+ from gateway.plugin_messages import bound_route+ route = bound_route()+ holder: dict[str, PluginMessage] = {}++ async def _post() -> dict[str, Any]:+ holder["message"] = await _post_for(ctx, text, session_key, route)+ return holder["message"].result++ result = _run_on_gateway_loop(_post())+ return holder.get("message") or PluginMessage(ctx.plugin_id, None, result)diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 7e2a87b7b4f..0e5f3b1601f 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -459,12 +459,7 @@ class PluginContext:"""Register a tool in the global registry and track it as plugin-provided. ``override=True``replaces a same-named built-in (without it a name claimed by another toolset is rejected) andneeds operator opt-in via ``plugins.entries.<plugin_id>.allow_tool_override: true`` — otherwise- any enabled plugin could silently replace a privileged built-in like ``write_file``.-- ``override=True`` against a built-in tool requires the operator to opt in via- ``plugins.entries.<plugin_id>.allow_tool_override: true`` in config.yaml — mirrors the trust gate- pattern used for ``ctx.llm`` provider/model overrides (#23194).- """+ any enabled plugin could silently replace a privileged built-in like ``write_file`` (#23194)."""if override and not self._tool_override_allowed(name):raise PluginToolOverrideError(f"Plugin {self.manifest.name!r} cannot override built-in tool {name!r}. Set "@@ -573,16 +568,8 @@ class PluginContext:def _tool_override_allowed(self, tool_name: str) -> bool:"""Whether this plugin may override built-in tools: bundled plugins are trusted (a maintainerchoice, not privilege escalation); others need ``tools.override`` via- :func:`plugin_capability_granted` (granted_capabilities OR legacy ``allow_tool_override: true``).-- Bundled plugins (shipped with Hermes core) are trusted by default — an override there is a- deliberate maintainer choice, not a third-party plugin trying to elevate privilege. For every other- source, the canonical check is :func:`plugin_capability_granted` with the ``tools.override``- capability — satisfied by EITHER the consent-flow grant- (``plugins.entries.<plugin_id>.granted_capabilities``) OR the deprecated legacy key- ``allow_tool_override: true`` (still honored for backward compatibility; #64228 reference- migration).- """+ :func:`plugin_capability_granted` (granted_capabilities OR legacy ``allow_tool_override: true``,+ still honored for backward compatibility; #64228)."""if self.manifest.source == "bundled":return Truetry:@@ -617,6 +604,17 @@ class PluginContext:from hermes_cli.plugin_session import context_surfacereturn context_surface(self._manager)+ def post_message(self, text: str) -> Any:+ """Post *text* into the session bound to this call; the handle's ``edit(text)`` updates it in+ place. Never raises (``ok=False`` + ``error`` with no conversation): ``plugin_messages.py``."""+ from hermes_cli.plugin_messages import post+ return post(self, text)++ async def apost_message(self, text: str) -> Any:+ """``post_message`` for async code on the gateway loop (edit with ``await handle.aedit``)."""+ from hermes_cli.plugin_messages import apost+ return await apost(self, text)+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/tests/gateway/test_plugin_post_message.py b/tests/gateway/test_plugin_post_message.pynew file mode 100644index 00000000000..def034670a5--- /dev/null+++ b/tests/gateway/test_plugin_post_message.py@@ -0,0 +1,91 @@+"""``PluginContext.post_message``: one message in the calling session's chat, edited in place."""++import asyncio+import contextvars+from unittest.mock import MagicMock, patch++import pytest++from gateway.config import GatewayConfig, Platform+from gateway.platforms.base import BasePlatformAdapter, PlatformConfig, SendResult+from gateway.run import GatewayRunner+from gateway.session import SessionSource, SessionStore+from gateway.session_context import scoped_session_key+from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+++class _Adapter(BasePlatformAdapter):+ def __init__(self):+ super().__init__(PlatformConfig(enabled=True, token="t"), Platform.TELEGRAM)+ self.calls = []++ async def connect(self, *, is_reconnect=False):+ return True++ async def disconnect(self):+ return None++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.calls.append(("send", chat_id, content))+ return SendResult(success=True, message_id=f"m{len(self.calls)}")++ async def get_chat_info(self, chat_id):+ return {"id": chat_id, "type": "dm"}+++class _EditingAdapter(_Adapter):+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):+ self.calls.append(("edit", chat_id, message_id, content))+ return SendResult(success=True, message_id=message_id)+++def _setup(tmp_path, adapter):+ store = SessionStore(sessions_dir=tmp_path / "sessions", config=GatewayConfig())+ entry = store.get_or_create_session(SessionSource(+ platform=Platform.TELEGRAM, chat_id="42", chat_type="dm", user_id="42", user_name="u"))+ runner = object.__new__(GatewayRunner)+ runner.session_store = store+ runner.adapters = {Platform.TELEGRAM: adapter}+ runner._profile_adapters = {}+ runner._gateway_loop = asyncio.get_running_loop()+ runner._running = True+ runner._is_user_authorized = MagicMock(return_value=True)+ ctx = PluginContext(PluginManifest(name="progress", key="progress", source="user"), PluginManager())+ return runner, ctx, entry+++async def _in_session(session_key, fn):+ """Run *fn* on a worker thread with the session bound, as a tool handler is."""+ def bound():+ with scoped_session_key(session_key):+ return fn()+ return await asyncio.to_thread(contextvars.copy_context().run, bound)++[email protected]("adapter_cls, edited", [(_EditingAdapter, True), (_Adapter, False)])+async def test_post_then_edit_targets_the_calling_session(tmp_path, adapter_cls, edited):+ adapter = adapter_cls()+ runner, ctx, entry = _setup(tmp_path, adapter)+ with patch("gateway.run._gateway_runner_ref", lambda: runner), \+ patch.object(GatewayRunner, "_plugin_messaging_session_owned", return_value=True):+ handle = await _in_session(entry.session_key, lambda: ctx.post_message("step 1/2"))+ assert handle.ok and handle.message_id == "m1"+ result = await _in_session("", lambda: handle.edit("step 2/2")) # the handle carries its route+ assert result["ok"] is True and result["edited"] is edited+ if edited:+ assert adapter.calls == [("send", "42", "step 1/2"), ("edit", "42", "m1", "step 2/2")]+ else: # no edit support: a fresh message, and the handle follows it+ assert adapter.calls == [("send", "42", "step 1/2"), ("send", "42", "step 2/2")]+ assert result["fallback"] is True and handle.message_id == "m2"+++async def test_no_bound_session_is_refused_without_sending(tmp_path):+ adapter = _EditingAdapter()+ runner, ctx, _entry = _setup(tmp_path, adapter)+ with patch("gateway.run._gateway_runner_ref", lambda: runner):+ handle = await asyncio.to_thread(ctx.post_message, "from a timer")+ edit = await asyncio.to_thread(handle.edit, "still nothing")+ assert (handle.ok, handle.error, edit["ok"]) == (False, "no_conversation", False)+ assert adapter.calls == []diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex a1eb0fa23c0..f720602cd09 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -108,6 +108,7 @@ Every `ctx.*` API below is available inside a plugin's `register(ctx)` function.| Dispatch tools from commands | `ctx.dispatch_tool(name, args)` — invokes a registered tool with parent-agent context auto-wired || Add CLI commands | `ctx.register_cli_command(name, help, setup_fn, handler_fn)` — adds `hermes <plugin> <subcommand>` || Inject messages | `ctx.inject_message(content, role="user", session_key=... \| origin=...)` - see [Injecting Messages](#injecting-messages) |+| Post and edit a status message | `handle = ctx.post_message(text)`, then `handle.edit(text)` — see [Posting a live message](#posting-a-live-message) || Ship data files | `Path(__file__).parent / "data" / "file.yaml"` || Bundle skills | `ctx.register_skill(name, path)` — namespaced as `plugin:skill`, loaded via `skill_view("plugin:skill")` || Gate on env vars | `requires_env: [API_KEY]` in plugin.yaml — prompted during `hermes plugins install` |@@ -925,6 +926,56 @@ The default for a newly-installed or bundled plugin is `not enabled`. `hermes plIn a running session, `/plugins` shows which plugins are currently loaded.+## Posting a live message++A plugin can post one message into the conversation it is working for and update that same message+later, on any channel, with no per-platform code. Use it for live progress (a checklist while a long+tool runs, a plan card that changes as the plan is revised):++```python+def run_migration(args, **kwargs):+ status = ctx.post_message("Migrating: 0/3 tables")+ for i, table in enumerate(TABLES, 1):+ migrate(table)+ status.edit(f"Migrating: {i}/3 tables")+ status.edit("Migration done ✓")+ return tool_result({"migrated": len(TABLES)})+```++**Signatures:** `ctx.post_message(text: str) -> PluginMessage` and+`PluginMessage.edit(text: str) -> dict`. From `async` code that already runs on the gateway's event loop+(an async hook or slash-command handler) use `await ctx.apost_message(text)` and `await handle.aedit(text)`+instead; the sync forms refuse there with `error: "on_event_loop"` rather than deadlocking the loop.++**Which conversation.** The current conversation is the session bound to the calling code: a tool+handler or hook running in that session's turn, its slash command, or a hook fired for it. The plugin+never names a chat, so it cannot post anywhere else. A thread the plugin starts itself does not inherit+that binding (start it with `contextvars.copy_context().run(...)` if it should), and a timer, a cron+run or a process with no live gateway has no conversation at all.++**Never raises.** Every call returns a result. `handle.ok`, `handle.message_id` and `handle.error`+describe the last operation; `edit()` returns `{"ok", "message_id", "edited"}` plus+`"fallback": True` when it had to post a new message. Error codes: `no_conversation` (nothing is bound+in the calling context, the session is not live, or it belongs to another profile),+`gateway_unavailable`, `adapter_unavailable`, `send_failed`, `edit_failed`, `on_event_loop`, `timeout`.+A refused post returns a handle whose `edit()` is refused the same way, so the happy path needs no+branching. Every post and edit is logged as `plugin_message plugin=<id> op=post|edit ...`.++What each surface does:++| Surface | `post_message` | `edit` |+|---|---|---|+| Messaging platforms that can edit (Telegram, Discord, Slack, Matrix, ...) | the adapter's normal `send` into the chat/thread | edits the same message in place |+| Platforms without edit support (SMS, email, plugin adapters that do not implement `edit_message`) | `send` | sends a new message; the handle follows it (`edited: False, fallback: True`) |+| Desktop and the Ink TUI | a keyed notice to the session's viewers (Desktop toast, TUI status line) | replaces that notice in place |+| Classic CLI (`hermes chat`) | queued as a notice line, printed at the end of the next turn (the classic CLI has no live notice slot) | each edit queues another line |++Text is clamped to the platform's message limit with an ellipsis (never split). It is plain text: an+adapter may render its own formatting, but the plugin should not depend on it. No permission is needed,+because the message can only reach the conversation that already invoked the plugin.+`ctx.post_message` is not available to plugins running in the out-of-process plugin host+(`plugins.isolation: host`): the handle is bound to the gateway's event loop and live adapter.+## Injecting MessagesPlugins can inject messages into a CLI conversation, a known gateway session, or a new gateway session in a given chat using `ctx.inject_message()`: