The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): post_message review fixes — interim sends, full bound route, pending timeouts, raised-edit fallback
Teknium3e4f28ee8ae4
diff --git a/gateway/plugin_messages.py b/gateway/plugin_messages.pyindex b9a1d2daba7..5085419724f 100644--- a/gateway/plugin_messages.py+++ b/gateway/plugin_messages.py@@ -60,9 +60,11 @@ def _supports_edit(adapter: Any) -> bool: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"}+# Every source field the gateway binds for a call (``GatewayRunner._set_session_env``), so a rebuilt+# source keys exactly like the live one (Slack ``scope_id``, ``user_id_alt`` group keys, ...).+_ROUTE_VARS = {field: "HERMES_SESSION_" + field.upper() for field in (+ "platform", "chat_id", "chat_type", "chat_name", "thread_id", "user_id", "user_id_alt", "user_name",+ "scope_id", "parent_chat_id", "message_id", "profile")}def bound_route() -> dict:@@ -123,8 +125,10 @@ def _publish_local(target: PostTarget, text: str) -> dict:async def _send(target: PostTarget, text: str) -> dict:+ # Never the turn's answer: a relay stream open for the reply must not be sealed with it.+ metadata = {**(target.metadata or {}), "_interim_send": True}result = await target.adapter.send(target.chat_id, _fit(target.adapter, target.chat_id, text),- metadata=target.metadata)+ metadata=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}@@ -150,13 +154,18 @@ async def edit(target: PostTarget, message_id: Optional[str], text: str, *, plugif 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):+ try:+ sent = await target.adapter.edit_message(target.chat_id, message_id,+ _fit(target.adapter, target.chat_id, text))+ edit_error = "" if getattr(sent, "success", False) else str(getattr(sent, "error", "") or "")+ except Exception as exc: # a raised edit falls back like a refused one+ logger.debug("plugin_message plugin=%s edit_message raised", plugin_id, exc_info=True)+ sent, edit_error = None, str(exc) or type(exc).__name__+ if sent is not None and not edit_error: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]}+ "edit_error": edit_error[:256]}else:result = {**await _send(target, text), "edited": False, "fallback": True}except Exception as exc: # adapter boundary, as in post()diff --git a/hermes_cli/plugin_messages.py b/hermes_cli/plugin_messages.pyindex 9ba0ee4f1dc..02b95f630a3 100644--- a/hermes_cli/plugin_messages.py+++ b/hermes_cli/plugin_messages.py@@ -26,12 +26,15 @@ class PluginMessage:"""Handle for one posted message. ``ok`` / ``message_id`` / ``error`` describe the lastoperation; ``edit(text)`` replaces the text in place (or posts anew where the surface cannotedit, and the handle then follows the new message). A refused post returns a handle whose- edits are refused the same way."""+ edits are refused the same way. Operations stay ordered: one the gateway has not finished+ (``error == "timeout"``, ``pending`` set) is waited for before the next runs, and its outcome+ still lands on the handle, so a slow post never leaves an orphan message behind a dead handle."""def __init__(self, plugin_id: str, target: Any, result: dict[str, Any]):self._plugin_id, self._target = plugin_id, targetself.result = resultself.message_id: Optional[str] = result.get("message_id")+ self._pending: Optional[concurrent.futures.Future] = None@propertydef ok(self) -> bool:@@ -41,9 +44,16 @@ class PluginMessage:def error(self) -> Optional[str]:return self.result.get("error")+ @property+ def pending(self) -> bool:+ return self._pending is not None and not self._pending.done()+def __repr__(self) -> str:return f"<PluginMessage ok={self.ok} message_id={self.message_id!r} error={self.error!r}>"+ def _adopt(self, other: PluginMessage) -> None:+ self._target, self.result, self.message_id = other._target, other.result, other.message_id+def _refused(self) -> Optional[dict[str, Any]]:if self._target is None:return _err(self.error or "no_conversation", self.result.get("detail", ""))@@ -55,8 +65,7 @@ class PluginMessage: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)."""+ async def _edit(self, text: str) -> dict[str, Any]:refused = self._refused()if refused is not None:return refused@@ -64,12 +73,25 @@ class PluginMessage:return self._settle(await plugin_messages.edit(self._target, self.message_id, str(text),plugin_id=self._plugin_id))+ async def aedit(self, text: str) -> dict[str, Any]:+ """``edit`` for code already running on the gateway's event loop (async hooks/commands)."""+ if self.pending:+ await asyncio.wrap_future(self._pending)+ return await self._edit(text)+def edit(self, text: str) -> dict[str, Any]:"""Replace the message text: ``{"ok", "message_id", "edited", ["fallback"]}``. Thread-safe."""+ if self.pending:+ try:+ self._pending.result(_TIMEOUT_S)+ except concurrent.futures.TimeoutError:+ return _err("timeout", "the previous operation on this message has not finished")+ except Exception: # its own outcome is already on the handle+ logger.debug("plugin_message: previous operation failed", exc_info=True)refused = self._refused()if refused is not None:return refused- return _run_on_gateway_loop(self.aedit(text))+ return _run_on_gateway_loop(self._edit(text), self)def _gateway_loop():@@ -84,7 +106,9 @@ def _gateway_loop():return runner, loop-def _run_on_gateway_loop(coro) -> dict[str, Any]:+def _run_on_gateway_loop(coro, handle: PluginMessage) -> dict[str, Any]:+ """Run *coro* on the gateway loop and wait up to ``_TIMEOUT_S``; past that it keeps running as+ the handle's pending operation (its result still lands on the handle)."""_runner, loop = _gateway_loop()if loop is None:coro.close()@@ -96,10 +120,15 @@ def _run_on_gateway_loop(coro) -> dict[str, Any]:if running is loop:coro.close()return _err("on_event_loop", "called from the gateway event loop: use the async form (await ...)")+ future = asyncio.run_coroutine_threadsafe(coro, loop)+ handle._pending = futuretry:- return asyncio.run_coroutine_threadsafe(coro, loop).result(_TIMEOUT_S)+ return future.result(_TIMEOUT_S)except concurrent.futures.TimeoutError:- return _err("timeout", f"the gateway did not answer within {_TIMEOUT_S:.0f}s")+ result = _err("timeout", f"the gateway did not answer within {_TIMEOUT_S:.0f}s; the operation "+ "is still running and its result will land on this handle")+ handle.result = result+ return resultexcept Exception as exc: # the plugin gets a result, never the raiselogger.warning("plugin_message: gateway hand-off failed", exc_info=True)return _err("send_failed", str(exc)[:512])@@ -148,11 +177,13 @@ def post(ctx: Any, text: str) -> PluginMessage:return PluginMessage(ctx.plugin_id, None, _err("no_conversation", _NO_SESSION))from gateway.plugin_messages import bound_routeroute = bound_route()- holder: dict[str, PluginMessage] = {}+ handle = PluginMessage(ctx.plugin_id, None, _err("timeout"))async def _post() -> dict[str, Any]:- holder["message"] = await _post_for(ctx, text, session_key, route)- return holder["message"].result+ handle._adopt(await _post_for(ctx, text, session_key, route))+ return handle.result- result = _run_on_gateway_loop(_post())- return holder.get("message") or PluginMessage(ctx.plugin_id, None, result)+ result = _run_on_gateway_loop(_post(), handle)+ if handle._target is None and not handle.pending:+ handle.result = result+ return handlediff --git a/tests/gateway/test_plugin_post_message.py b/tests/gateway/test_plugin_post_message.pyindex def034670a5..ca744deb5d6 100644--- a/tests/gateway/test_plugin_post_message.py+++ b/tests/gateway/test_plugin_post_message.py@@ -26,6 +26,7 @@ class _Adapter(BasePlatformAdapter):return Noneasync def send(self, chat_id, content, reply_to=None, metadata=None):+ assert (metadata or {}).get("_interim_send") is True # never sealed as the turn's answerself.calls.append(("send", chat_id, content))return SendResult(success=True, message_id=f"m{len(self.calls)}")@@ -39,6 +40,11 @@ class _EditingAdapter(_Adapter):return SendResult(success=True, message_id=message_id)+class _RaisingEditAdapter(_Adapter):+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):+ raise ValueError("malformed edit response")++def _setup(tmp_path, adapter):store = SessionStore(sessions_dir=tmp_path / "sessions", config=GatewayConfig())entry = store.get_or_create_session(SessionSource(@@ -63,7 +69,8 @@ async def _in_session(session_key, fn):@pytest.mark.asyncio[email protected]("adapter_cls, edited", [(_EditingAdapter, True), (_Adapter, False)])[email protected]("adapter_cls, edited",+ [(_EditingAdapter, True), (_Adapter, False), (_RaisingEditAdapter, 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)@@ -75,7 +82,7 @@ async def test_post_then_edit_targets_the_calling_session(tmp_path, adapter_cls,assert result["ok"] is True and result["edited"] is editedif 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+ else: # no edit support, or the edit raised: a fresh message, and the handle follows itassert adapter.calls == [("send", "42", "step 1/2"), ("send", "42", "step 2/2")]assert result["fallback"] is True and handle.message_id == "m2"diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex f720602cd09..2adc9abb550 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -959,7 +959,10 @@ describe the last operation; `edit()` returns `{"ok", "message_id", "edited"}` pin 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 ...`.+branching. `timeout` means the gateway has not answered within 30 s: the operation keeps running and+its outcome still lands on the handle (`handle.pending` is true meanwhile), and the next `edit()` waits+for it first, so a slow post never leaves a message the handle cannot edit. An edit that the platform+refuses or that raises falls back to a fresh message the same way as a platform without edit support. Every post and edit is logged as `plugin_message plugin=<id> op=post|edit ...`.What each surface does: