diff --git a/integrations/hermes-t3-gateway/COMPATIBILITY.md b/integrations/hermes-t3-gateway/COMPATIBILITY.md index 73072f749e..d0d13f2142 100644 --- a/integrations/hermes-t3-gateway/COMPATIBILITY.md +++ b/integrations/hermes-t3-gateway/COMPATIBILITY.md @@ -1,8 +1,22 @@ # Hermes event compatibility inventory The plugin deliberately uses only the public Hermes plugin and platform-adapter -surfaces audited at Hermes Agent commit -`3910ab28c0892fcf846fc61318d2fd15689eddf1`. +surfaces audited at Hermes Agent upstream commit `62e07223` (v0.19.0). + +Audited surfaces, all present at that commit: + +| Surface | Location at 62e07223 | +| ---------------------------------------- | ------------------------------------ | +| `save_env_value` / `get_env_path` | `hermes_cli/config.py:8137` / `:688` | +| `load_config_readonly` | `hermes_cli/config.py:7415` | +| `build_session_key` | `gateway/session.py:1029` | +| `resolve_gateway_approval` | `tools/approval.py:2073` | +| `resolve_gateway_clarify` | `tools/clarify_gateway.py:160` | +| `register_platform` (`**entry_kwargs`) | `hermes_cli/plugins.py:931` | +| `/steer` active-run handler | `gateway/run.py:11280` | +| Home-channel notice text | `gateway/run.py:13780` | +| Active-command inline dispatch | `gateway/platforms/base.py:4926` | +| User-plugin path `$HERMES_HOME/plugins/` | `hermes_cli/plugins.py:10`, `:1350` | This inventory describes gateway wire protocol v2. Protocol v2 adds active-turn recovery in `session.ready` and authoritative `content.snapshot` replacement; @@ -10,16 +24,17 @@ older server/plugin pairs are rejected during the handshake. ## Mapped in the initial scope -| Hermes surface | T3 gateway event | -| ----------------------------------------- | ---------------------------------------------- | -| Cumulative `send` / `edit_message` output | `content.delta` / `content.snapshot` | -| Final stream edit | `item.completed`, `turn.completed` | -| `pre_tool_call` / `post_tool_call` hooks | Typed `item.started` / `item.completed` | -| Live adapter status text | Generic `unknown` activity item | -| `send_exec_approval` | `request.opened` / `request.resolved` | -| `send_clarify` | `user-input.requested` / `user-input.resolved` | -| `/steer` gateway command | `turn.steer` | -| Adapter interrupt event | `turn.interrupt` | +| Hermes surface | T3 gateway event | +| -------------------------------------------- | ---------------------------------------------- | +| Cumulative `send` / `edit_message` output | `content.delta` / `content.snapshot` | +| Final stream edit | `item.completed`, `turn.completed` | +| `pre_tool_call` / `post_tool_call` hooks | Typed `item.started` / `item.completed` | +| Live adapter status text | `status_text` activity item | +| `load_config_readonly()["model"]["default"]` | Optional `model` on `connection.hello` | +| `send_exec_approval` | `request.opened` / `request.resolved` | +| `send_clarify` | `user-input.requested` / `user-input.resolved` | +| `/steer` gateway command | `turn.steer` | +| Adapter interrupt event | `turn.interrupt` | ## Known limitations @@ -31,12 +46,26 @@ older server/plugin pairs are rejected during the handshake. - Hermes' exact first-chat T3 home-channel notice is suppressed at the adapter output boundary. The plugin does not assign a home channel or redirect proactive delivery; other Hermes platform notices pass through unchanged. + This match is **exact string equality**, which is fragile: Hermes builds the + notice inline from an f-string (`gateway/run.py:13780`) rather than exporting + a constant, so any wording change upstream silently stops the suppression and + the notice reaches the transcript. Re-verified byte-for-byte at 62e07223 by + reconstructing the f-string with `platform_name="t3"` (`Platform("t3").value` + → `"t3"`, `.title()` → `"T3"`) and the non-Slack `/sethome` branch; it still + matches. A regression test pins the literal. - Hermes' documented tool hook surface exposes a `task_id`, tool name, - arguments, string result, and duration. The audited runtime additionally - supplies `session_id` and `tool_call_id`; the adapter uses them when present and falls - back to the documented IDs for older versions. It projects only canonical, - whitelisted fields (command/cwd, file path, search query, image path, or MCP - server/operation); arbitrary arguments and raw results never cross the wire. + arguments, string result, and duration. Verified at 62e07223: the runtime + additionally supplies `session_id`, `tool_call_id`, `turn_id`, + `api_request_id`, and `middleware_trace` on both hooks + (`hermes_cli/plugins.py:2146` for `pre_tool_call`, `model_tools.py:1050` for + `post_tool_call`), and `post_tool_call` also supplies `status`, `error_type`, + and `error_message`. The adapter consumes `session_id`, `tool_call_id`, and + `status` when present and falls back to the documented IDs for older + versions. It projects only canonical, whitelisted fields (command/cwd, file + path, search query, image path, or MCP server/operation); arbitrary arguments + and raw results never cross the wire. +- `post_tool_call` passes `result` as `Any`, not a guaranteed `str` — the + adapter never forwards it, so the looser type is inert here. - Approval resolution is session-FIFO in Hermes. T3 request IDs identify the UI prompt, then resolve the oldest matching Hermes approval for that session. - The public `clarify` hook is a single question. The wire protocol supports an @@ -45,10 +74,25 @@ older server/plugin pairs are rejected during the handshake. plugin uses the stream consumer's required `finalize=True` edit as the authoritative completion boundary. - Active `/steer` dispatch returns a textual Hermes control acknowledgement - through the normal platform `send(..., notify=True)` path. The plugin - captures that response in the originating steering request's async context, - suppresses it from the transcript, and acknowledges T3 only when the audited - Hermes success response begins with `⏩ Steer queued`. Unknown future response - shapes fail closed with `protocol.error` rather than completing the turn. + through the normal platform `send(..., notify=True)` path + (`gateway/platforms/base.py:4926`). The plugin captures that response in the + originating steering request's async context and suppresses it from the + transcript. Because a steer targets a _running_ turn, the capture is + correlated by the steering `requestId` — which the base adapter passes back + as `reply_to` via `_reply_anchor_for_event` — and not by `chat_id`. Genuine + assistant output emitted on the same thread during the steer window carries a + different correlation id and reaches the transcript untouched. +- The plugin acknowledges T3 only when the audited Hermes success response + begins with `⏩ Steer queued`. That prefix is likewise matched against an + inline f-string (`gateway/run.py:11280`) rather than an exported constant, so + it carries the same drift risk as the home-channel notice. Confirmed present + at 62e07223. Unknown future response shapes fail closed with `protocol.error` + rather than completing the turn. +- Hermes' configured default model is read once per handshake from the + documented read-only accessor `load_config_readonly()["model"]["default"]`. + That accessor returns the shared process-wide config cache and its docstring + forbids mutation, so the plugin copies out only a trimmed string. Any failure + — missing key, import error, older Hermes — omits the optional `model` field + from `connection.hello` rather than sending null or empty. - Attachments are not accepted. They are the first planned post-stability feature; the capability is reserved and fixed to `false` in protocol v2. diff --git a/integrations/hermes-t3-gateway/README.md b/integrations/hermes-t3-gateway/README.md index 213d67b669..8d9fa49cfe 100644 --- a/integrations/hermes-t3-gateway/README.md +++ b/integrations/hermes-t3-gateway/README.md @@ -14,15 +14,19 @@ not delete its transcript. ## Install from this repository -Copy or symlink this directory into the active Hermes profile: +Run the install script. It symlinks this directory into the active Hermes +profile's user-plugin directory and enables the plugin: ```bash -mkdir -p ~/.hermes/plugins -ln -s /path/to/t3code/integrations/hermes-t3-gateway \ - ~/.hermes/plugins/hermes-t3-gateway -hermes plugins enable hermes-t3-gateway +./integrations/hermes-t3-gateway/install.sh ``` +The script is safe to re-run: an existing correct symlink is left in place, and +enabling an already-enabled plugin is a no-op. It installs into +`$HERMES_HOME/plugins/` when `HERMES_HOME` is set, and `~/.hermes/plugins/` +otherwise. It fails with instructions if `hermes` is not on `PATH`, and refuses +to replace a real directory already sitting at the target path. + In T3 Code, open the Hermes instance settings, choose **Add Hermes**, enter a unique nickname, and copy the generated enrollment command. It has this shape: @@ -42,10 +46,14 @@ profile-aware `save_env_value` helper: - `HERMES_T3_GATEWAY_CREDENTIAL` - `HERMES_T3_GATEWAY_NICKNAME` -The long-lived credential is never printed. Restart `hermes gateway` after +The long-lived credential is never printed. Run `hermes gateway restart` after enrollment. `hermes t3 status` reports the local enrollment without revealing the credential. +The handshake also reports Hermes' configured default model so T3 can show a +truthful label in its picker. It is read-only — Hermes owns model selection — +and is omitted entirely if it cannot be read. + ## Initial scope - Text input and live assistant streaming diff --git a/integrations/hermes-t3-gateway/adapter.py b/integrations/hermes-t3-gateway/adapter.py index 2306ce1aa4..191391f4de 100644 --- a/integrations/hermes-t3-gateway/adapter.py +++ b/integrations/hermes-t3-gateway/adapter.py @@ -6,9 +6,9 @@ import asyncio import contextvars import logging import os -import threading import uuid import weakref +from collections.abc import Coroutine from dataclasses import dataclass, field from typing import Any @@ -42,6 +42,14 @@ _T3_HOME_CHANNEL_NOTICE = ( "Type /sethome to make this chat your home channel, or ignore to skip." ) +# T3's canonical item type for a free-form provider status line. Deliberately +# not `unknown`: that value is the "could not classify this" sentinel other +# adapters rely on being inert, so routing status text through it made stray +# activity rows appear in unrelated provider threads. T3 renders these rows +# preferring `detail` over `title`, so the live status string is sent as +# `detail`. +_STATUS_ITEM_TYPE = "status_text" + def _hermes_version() -> str: try: @@ -76,6 +84,16 @@ class _SteerControlResponse: request_id: str messages: list[str] = field(default_factory=list) + @property + def control_message_id(self) -> str: + """Synthetic id returned for captured control traffic. + + `edit_message` correlates against this so a later edit of the control + acknowledgement is captured too, while genuine assistant edits (which + carry the stream's own message id) pass straight through. + """ + return f"t3-steer-control-{self.request_id}" + _steer_control_response = contextvars.ContextVar[_SteerControlResponse | None]( "hermes_t3_steer_control_response", @@ -113,6 +131,10 @@ class T3PlatformAdapter(BasePlatformAdapter): self._active_turns: dict[str, _TurnState] = {} self._approval_requests: dict[str, tuple[str, str]] = {} self._user_input_requests: dict[str, tuple[str, str]] = {} + # Strong references to fire-and-forget tasks. asyncio only holds a weak + # reference to a running task, so without this the GC may collect one + # mid-flight and its exception surfaces as a bare warning. + self._scheduled_tasks: set[asyncio.Task[Any]] = set() type(self)._instances.add(self) @property @@ -166,8 +188,12 @@ class T3PlatformAdapter(BasePlatformAdapter): reply_to: str | None = None, metadata: dict[str, Any] | None = None, ) -> SendResult: - del reply_to - captured = self._capture_steer_control_response(chat_id, content) + # `reply_to` is the base adapter's reply anchor. For the inline + # slash-command path it is `_reply_anchor_for_event(event)`, which for + # this platform resolves to the dispatched MessageEvent's `message_id` + # — the steering requestId. That is the only correlation identifier + # `send` receives, so it is the capture discriminator here. + captured = self._capture_steer_control_response(chat_id, content, reply_to) if captured is not None: return captured turn = self._active_turns.get(str(chat_id)) @@ -195,7 +221,11 @@ class T3PlatformAdapter(BasePlatformAdapter): metadata: dict[str, Any] | None = None, ) -> SendResult: del metadata - captured = self._capture_steer_control_response(chat_id, content) + # `edit_message` never carries the reply anchor; its correlation + # identifier is the id of the message being edited. Only an edit of a + # message this adapter already reported as captured control traffic is + # control traffic itself. + captured = self._capture_steer_control_response(chat_id, content, message_id) if captured is not None: return captured turn = self._active_turns.get(str(chat_id)) @@ -518,15 +548,29 @@ class T3PlatformAdapter(BasePlatformAdapter): self, chat_id: str, content: str, + correlation_id: str | None, ) -> SendResult | None: + """Capture only the steering command's own acknowledgement. + + A steer targets a RUNNING turn, so Hermes can legitimately emit + assistant output on the same thread while the steering command is + still awaited. Matching on `chat_id` alone would swallow that output + and drop it from the transcript, so the capture is keyed on the + steering `requestId` the plugin stamped on the dispatched + `MessageEvent` (and, for follow-up edits, on the synthetic control + message id this method returns). Everything else falls through to the + normal assistant-content path. + """ control = _steer_control_response.get() if control is None or control.thread_id != str(chat_id): return None + if correlation_id is None: + return None + correlation = str(correlation_id) + if correlation not in {control.request_id, control.control_message_id}: + return None control.messages.append(str(content)) - return SendResult( - success=True, - message_id=f"t3-steer-control-{control.request_id}", - ) + return SendResult(success=True, message_id=control.control_message_id) async def _interrupt_turn(self, message: dict[str, Any]) -> None: thread_id = str(message["threadId"]) @@ -743,7 +787,7 @@ class T3PlatformAdapter(BasePlatformAdapter): sessionId=turn.session_id, turnId=turn.turn_id, itemId=turn.generic_activity_id, - itemType="unknown", + itemType=_STATUS_ITEM_TYPE, status="completed", title="Hermes activity", **( @@ -788,7 +832,7 @@ class T3PlatformAdapter(BasePlatformAdapter): sessionId=turn.session_id, turnId=turn.turn_id, itemId=activity_id, - itemType="unknown", + itemType=_STATUS_ITEM_TYPE, status="inProgress", title="Hermes activity", detail=normalized_detail, @@ -937,20 +981,42 @@ class T3PlatformAdapter(BasePlatformAdapter): if reason: logger.warning("T3 gateway offline: %s", reason) - def _schedule(self, coroutine) -> None: + def _schedule(self, coroutine: Coroutine[Any, Any, Any]) -> None: + """Run a coroutine on the adapter's bound loop from any thread. + + Hermes calls the tool hooks from the agent thread, so this is the + boundary back onto the gateway loop. `create_task` is only valid when + the *running* loop is the adapter's own loop — checking merely for "a + loop is running" would schedule onto whichever unrelated loop happens + to be current. Created tasks are held in a strong-reference set (asyncio + only holds a weak one) and their exceptions are logged rather than + surfacing as bare "task exception was never retrieved" warnings. + """ loop = self._event_loop if loop is None or loop.is_closed(): coroutine.close() return - if threading.current_thread() is threading.main_thread(): - try: - asyncio.get_running_loop() - except RuntimeError: - asyncio.run_coroutine_threadsafe(coroutine, loop) - else: - loop.create_task(coroutine) - else: + try: + running_loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop() + except RuntimeError: + running_loop = None + if running_loop is loop: + task = loop.create_task(coroutine) + self._scheduled_tasks.add(task) + task.add_done_callback(self._finish_scheduled_task) + return + try: asyncio.run_coroutine_threadsafe(coroutine, loop) + except RuntimeError: # loop closed between the check and the submit + coroutine.close() + + def _finish_scheduled_task(self, task: asyncio.Task[Any]) -> None: + self._scheduled_tasks.discard(task) + if task.cancelled(): + return + error = task.exception() + if error is not None: + logger.error("T3 gateway background task failed: %s", error, exc_info=error) def check_requirements() -> bool: diff --git a/integrations/hermes-t3-gateway/install.sh b/integrations/hermes-t3-gateway/install.sh new file mode 100755 index 0000000000..ac7f6cdabe --- /dev/null +++ b/integrations/hermes-t3-gateway/install.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# Install the T3 Code gateway plugin into the active Hermes profile. +# +# Symlinks this directory into "$HERMES_HOME/plugins/hermes-t3-gateway" (the +# documented user-plugin path, hermes_cli/plugins.py:10) and enables it. +# Safe to re-run: an existing correct symlink is left alone, and enabling an +# already-enabled plugin is a no-op in Hermes. + +set -eu + +PLUGIN_NAME="hermes-t3-gateway" +SOURCE_DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P) +HERMES_HOME_DIR=${HERMES_HOME:-"$HOME/.hermes"} +PLUGINS_DIR="$HERMES_HOME_DIR/plugins" +TARGET="$PLUGINS_DIR/$PLUGIN_NAME" + +if ! command -v hermes >/dev/null 2>&1; then + cat >&2 < $SOURCE_DIR" + else + echo "• Relinking $TARGET (was -> $CURRENT)" + rm -f "$TARGET" + ln -s "$SOURCE_DIR" "$TARGET" + fi +elif [ -e "$TARGET" ]; then + cat >&2 < $SOURCE_DIR" +fi + +echo "• Enabling $PLUGIN_NAME" +# --no-allow-tool-override: this plugin registers a platform adapter and two +# observer hooks. It never replaces a built-in tool, and passing the flag keeps +# the run non-interactive instead of stopping on the consent prompt. +hermes plugins enable "$PLUGIN_NAME" --no-allow-tool-override + +cat < --token + + 2. Restart the gateway so it picks up the new connection: + + hermes gateway restart + + Verify anytime with: hermes t3 status +EOF diff --git a/integrations/hermes-t3-gateway/protocol.py b/integrations/hermes-t3-gateway/protocol.py index a2a80b5430..f86d8583cf 100644 --- a/integrations/hermes-t3-gateway/protocol.py +++ b/integrations/hermes-t3-gateway/protocol.py @@ -55,13 +55,40 @@ def frame(frame_type: str, **payload: Any) -> dict[str, Any]: } +def configured_model() -> str | None: + """Return Hermes' configured default model, or None when unavailable. + + Reads `hermes_cli.config.load_config_readonly()`, the documented read-only + accessor. That function returns the *shared, process-wide cached* config + dict, so nothing here mutates it or hands a nested structure to a caller + that might: only a trimmed string copy of `model.default` leaves this + function. + + Every failure mode — no Hermes on the path, an older Hermes without the + accessor, a config with no model section — degrades to None so the field is + omitted from the handshake rather than sent as null or empty. + """ + try: + from hermes_cli.config import load_config_readonly + + model = load_config_readonly().get("model", {}).get("default") + except Exception: # noqa: BLE001 - model reporting must never break the handshake + return None + if not isinstance(model, str): + return None + trimmed = model.strip() + return trimmed or None + + def connection_hello( *, hermes_version: str, authentication: dict[str, str], hello_request_id: str | None = None, + model: str | None = None, ) -> dict[str, Any]: - return { + resolved_model = model if model is not None else configured_model() + hello: dict[str, Any] = { "type": "connection.hello", "requestId": hello_request_id or request_id(), "protocolVersion": PROTOCOL_VERSION, @@ -70,6 +97,11 @@ def connection_hello( "capabilities": dict(CAPABILITIES), "authentication": authentication, } + # Optional on the wire: omit entirely rather than send null/empty so a + # server that has the field still falls back to its generic label. + if resolved_model: + hello["model"] = resolved_model + return hello def protocol_error( diff --git a/integrations/hermes-t3-gateway/tests/test_adapter.py b/integrations/hermes-t3-gateway/tests/test_adapter.py index 9282e46731..c33f835329 100644 --- a/integrations/hermes-t3-gateway/tests/test_adapter.py +++ b/integrations/hermes-t3-gateway/tests/test_adapter.py @@ -8,6 +8,7 @@ import pathlib import sys import types import unittest +import unittest.mock ROOT = pathlib.Path(__file__).resolve().parents[1] PACKAGE = "hermes_t3_gateway_adapter_test" @@ -77,14 +78,18 @@ class BasePlatformAdapter: and event.text.startswith("/steer ") ): # Faithful model of Hermes BasePlatformAdapter's active-command - # path: the gateway handler returns a control acknowledgement, - # then BasePlatformAdapter sends it through the platform adapter - # with notify=True. + # bypass path (gateway/platforms/base.py ~4926 at upstream + # 62e07223): the gateway handler returns a control + # acknowledgement, then the base adapter sends it through the + # platform adapter with `reply_to=_reply_anchor_for_event(event)` + # — which, for a platform with no thread_id, is the dispatched + # event's own message_id — and notify=True metadata. response = await self._message_handler(event) if response: await self.send( event.source.chat_id, response, + reply_to=event.message_id, metadata={"notify": True}, ) @@ -398,6 +403,35 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(updated["itemId"], started["itemId"]) self.assertEqual(updated["detail"], "Running tests") + async def test_live_status_uses_status_text_not_the_unknown_sentinel(self): + await self._start_turn("thread-status-type", "turn-status-type") + turn = self.adapter._active_turns["thread-status-type"] + + await self.adapter._emit_generic_activity(turn, "Reading repository") + await self.adapter._emit_generic_activity(turn, "Running tests") + await self.adapter._complete_turn(turn) + + status_frames = [ + message + for message in self.connection.messages + if message.get("itemId") == turn.generic_activity_id + ] + self.assertEqual( + [message["type"] for message in status_frames], + ["item.started", "item.updated", "item.completed"], + ) + # `unknown` is the canonical "could not classify" sentinel other + # adapters rely on being inert; status lines get their own type. + self.assertEqual( + {message["itemType"] for message in status_frames}, + {"status_text"}, + ) + # T3 renders these rows preferring `detail`, so the real status string + # must ride there rather than only in `title`. + self.assertEqual(status_frames[0]["detail"], "Reading repository") + self.assertEqual(status_frames[1]["detail"], "Running tests") + self.assertEqual(status_frames[2]["detail"], "Running tests") + async def test_concurrent_generic_activity_updates_share_one_lifecycle(self): await self._start_turn("thread-activity-concurrent", "turn-activity-concurrent") turn = self.adapter._active_turns["thread-activity-concurrent"] @@ -482,6 +516,23 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): ) self.assertNotIn("thread-activity-complete", self.adapter._active_turns) + def test_home_channel_notice_literal_matches_hermes_construction(self): + # Hermes builds this notice inline from an f-string rather than + # exporting a constant (gateway/run.py:13780 at upstream 62e07223), and + # the adapter suppresses it by exact string equality. Reconstruct it the + # same way so upstream wording drift fails here loudly instead of + # leaking the notice into a T3 transcript. + platform_name = "t3" # Platform("t3").value + sethome_cmd = "/sethome" # non-Slack branch + expected = ( + f"📬 No home channel is set for {platform_name.title()}. " + f"A home channel is where Hermes delivers cron job results " + f"and cross-platform messages.\n\n" + f"Type {sethome_cmd} to make this chat your home channel, " + f"or ignore to skip." + ) + self.assertEqual(adapter_module._T3_HOME_CHANNEL_NOTICE, expected) + async def test_exact_t3_home_channel_notice_is_suppressed(self): await self._start_turn("thread-notice", "turn-notice") content_start = len(self.connection.messages) @@ -681,6 +732,90 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(deltas, ["Actual response after steering"]) self.assertNotIn("thread-2", self.adapter._active_turns) + async def test_assistant_output_during_a_steer_is_not_captured_as_control(self): + session_id = await self._start_turn("thread-steer-race", "turn-steer-race") + messages_before_steer = len(self.connection.messages) + + async def stream_while_steering(event): + # A steer targets a RUNNING turn, so Hermes can emit genuine + # assistant output on this same thread while the steering command + # is still being awaited. That output must reach the transcript. + await self.adapter.edit_message( + "thread-steer-race", + "hermes-stream-message", + "Mid-steer assistant output", + ) + del event + return "⏩ Steer queued — arrives after the next tool call: 'Focus'" + + self.adapter._message_handler = stream_while_steering + await self.adapter._handle_server_frame( + { + "type": "turn.steer", + "protocolVersion": 2, + "requestId": "steer-race", + "threadId": "thread-steer-race", + "sessionId": session_id, + "turnId": "turn-steer-race", + "text": "Focus", + } + ) + + steer_messages = self.connection.messages[messages_before_steer:] + self.assertEqual( + [message["type"] for message in steer_messages], + ["item.started", "content.delta", "turn.started"], + ) + self.assertEqual(steer_messages[1]["delta"], "Mid-steer assistant output") + # The acknowledgement itself is still captured and suppressed, so the + # steer is acknowledged rather than failing closed on the prefix check. + self.assertEqual(steer_messages[2]["requestId"], "steer-race") + self.assertIn("thread-steer-race", self.adapter._active_turns) + self.assertEqual( + self.adapter._active_turns["thread-steer-race"].visible_text, + "Mid-steer assistant output", + ) + + async def test_steer_control_acknowledgement_edits_stay_suppressed(self): + session_id = await self._start_turn("thread-steer-edit", "turn-steer-edit") + messages_before_steer = len(self.connection.messages) + acknowledgement = "⏩ Steer queued — arrives after the next tool call: 'Focus'" + + async def edit_own_acknowledgement(event): + sent = await self.adapter.send( + "thread-steer-edit", + acknowledgement, + reply_to=event.message_id, + metadata={"notify": True}, + ) + # A retry/finalize edit of the control message correlates by the + # synthetic control message id, so it stays out of the transcript. + await self.adapter.edit_message( + "thread-steer-edit", + sent.message_id, + acknowledgement, + finalize=True, + ) + + self.adapter._message_handler = edit_own_acknowledgement + await self.adapter._handle_server_frame( + { + "type": "turn.steer", + "protocolVersion": 2, + "requestId": "steer-edit", + "threadId": "thread-steer-edit", + "sessionId": session_id, + "turnId": "turn-steer-edit", + "text": "Focus", + } + ) + + steer_messages = self.connection.messages[messages_before_steer:] + self.assertEqual( + [message["type"] for message in steer_messages], ["turn.started"] + ) + self.assertIn("thread-steer-edit", self.adapter._active_turns) + async def test_rejected_steer_emits_error_without_completing_active_turn(self): await self.adapter._handle_server_frame( { @@ -784,6 +919,73 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(steer_messages[0]["code"], "internal-error") self.assertIn("thread-failed-steer", self.adapter._active_turns) + async def test_schedule_keeps_a_strong_reference_until_the_task_finishes(self): + self.adapter._event_loop = asyncio.get_running_loop() + released = asyncio.Event() + + async def work(): + await asyncio.sleep(0) + released.set() + + self.adapter._schedule(work()) + self.assertEqual(len(self.adapter._scheduled_tasks), 1) + await released.wait() + await asyncio.sleep(0) + self.assertEqual(self.adapter._scheduled_tasks, set()) + + async def test_schedule_logs_background_task_failures(self): + self.adapter._event_loop = asyncio.get_running_loop() + + async def boom(): + raise RuntimeError("background frame failed") + + with self.assertLogs(adapter_module.logger, level="ERROR") as captured: + self.adapter._schedule(boom()) + await asyncio.sleep(0) + await asyncio.sleep(0) + self.assertTrue( + any("background frame failed" in line for line in captured.output) + ) + self.assertEqual(self.adapter._scheduled_tasks, set()) + + async def test_schedule_does_not_create_tasks_on_a_foreign_loop(self): + other_loop = asyncio.new_event_loop() + self.adapter._event_loop = other_loop + + async def work(): + return None + + coroutine = work() + try: + with ( + unittest.mock.patch.object(other_loop, "create_task") as create_task, + unittest.mock.patch.object( + adapter_module.asyncio, "run_coroutine_threadsafe" + ) as threadsafe, + ): + # The running loop is this test's loop, not the adapter's, so + # create_task would schedule onto the wrong loop entirely. + self.adapter._schedule(coroutine) + create_task.assert_not_called() + threadsafe.assert_called_once_with(coroutine, other_loop) + self.assertEqual(self.adapter._scheduled_tasks, set()) + finally: + coroutine.close() + other_loop.close() + + async def test_schedule_closes_the_coroutine_when_the_loop_is_gone(self): + self.adapter._event_loop = None + started = False + + async def work(): + nonlocal started + started = True + + coroutine = work() + self.adapter._schedule(coroutine) + self.assertFalse(started) + self.assertEqual(self.adapter._scheduled_tasks, set()) + async def test_session_status_counts_ready_sessions_and_stop_decrements(self): await self.adapter._handle_server_frame( { diff --git a/integrations/hermes-t3-gateway/tests/test_protocol.py b/integrations/hermes-t3-gateway/tests/test_protocol.py index cacf8af3f4..ac02048491 100644 --- a/integrations/hermes-t3-gateway/tests/test_protocol.py +++ b/integrations/hermes-t3-gateway/tests/test_protocol.py @@ -2,7 +2,10 @@ from __future__ import annotations import importlib.util import pathlib +import sys +import types import unittest +from contextlib import contextmanager ROOT = pathlib.Path(__file__).resolve().parents[1] SPEC = importlib.util.spec_from_file_location( @@ -13,18 +16,87 @@ protocol = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(protocol) +@contextmanager +def fake_hermes_config(loader): + """Install a stand-in `hermes_cli.config` for the duration of a test.""" + saved = { + name: sys.modules.get(name) for name in ("hermes_cli", "hermes_cli.config") + } + package = types.ModuleType("hermes_cli") + package.__path__ = [] + config = types.ModuleType("hermes_cli.config") + if loader is not None: + config.load_config_readonly = loader + package.config = config + sys.modules["hermes_cli"] = package + sys.modules["hermes_cli.config"] = config + try: + yield + finally: + for name, module in saved.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + class ProtocolTests(unittest.TestCase): def test_hello_matches_v2_contract(self): hello = protocol.connection_hello( hermes_version="0.19.0", authentication={"type": "enrollment-token", "token": "once"}, hello_request_id="request-1", + model="gpt-5.6-terra", ) self.assertEqual(hello["type"], "connection.hello") self.assertEqual(hello["requestId"], "request-1") self.assertEqual(hello["protocolVersion"], 2) self.assertFalse(hello["capabilities"]["attachments"]) self.assertTrue(hello["capabilities"]["streaming"]) + self.assertEqual(hello["model"], "gpt-5.6-terra") + + def test_hello_reports_the_configured_hermes_model(self): + config = {"model": {"default": "gpt-5.6-terra"}} + + with fake_hermes_config(lambda: config): + hello = protocol.connection_hello( + hermes_version="0.19.0", + authentication={"type": "enrollment-token", "token": "once"}, + ) + + self.assertEqual(hello["model"], "gpt-5.6-terra") + # `load_config_readonly` returns the shared process-wide cache; the + # lookup must never mutate it. + self.assertEqual(config, {"model": {"default": "gpt-5.6-terra"}}) + + def test_hello_omits_model_when_hermes_cannot_report_one(self): + def missing_section(): + return {"agent": {}} + + def older_hermes(): + raise ImportError("load_config_readonly is unavailable") + + for loader in (missing_section, older_hermes, None): + with self.subTest(loader=getattr(loader, "__name__", "absent")): + with fake_hermes_config(loader): + hello = protocol.connection_hello( + hermes_version="0.19.0", + authentication={ + "type": "enrollment-token", + "token": "once", + }, + ) + # Omitted entirely — never null or empty. + self.assertNotIn("model", hello) + + def test_configured_model_ignores_blank_and_non_string_values(self): + for value in ("", " ", None, 5, {"default": "nested"}): + config = {"model": {"default": value}} + with ( + self.subTest(value=value), + fake_hermes_config(lambda config=config: config), + ): + self.assertIsNone(protocol.configured_model()) def test_server_frame_validation_is_closed(self): with self.assertRaisesRegex(ValueError, "unsupported"):