The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway,cron): key Matrix handoff/cron thread seeds the way Matrix replies are keyed
teknium1f41ad3bc0acd
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex 600f03ea9f1..5f096340497 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -210,6 +210,12 @@ def _maybe_mirror_cron_delivery()+# chat_type slot a platform's adapter puts on a NON-DM in-thread reply. Discord (and the default)+# key the shared "thread" lane; Slack and Matrix keep the parent channel/room's "group" — a seed+# on the wrong slot is a row no reply ever resolves to (#111896, #112918).+_THREAD_REPLY_CHAT_TYPE = {"slack": "group", "matrix": "group"}++def _open_continuable_cron_thread(job: dict, adapter, chat_id: str, loop) -> Optional[str]:"""Open a thread for a continuable cron job via ``adapter.create_handoff_thread``. Returns thethread_id, or ``None`` (no thread primitive / failed) = caller falls back to the DM mirror."""@@ -282,14 +288,17 @@ def _seed_cron_thread_session("""Seed the freshly-opened cron thread's session with the brief (never raises), else theuser's in-thread reply resolves to a transcript without it. Threads are participant-shared(no real user_id); a DM thread must seed ``chat_type="dm"`` — DM-thread replies route through- the DM arm (``…:dm:<chat>:<thread>``), so a "thread"-typed seed is a row no DM reply hits."""+ the DM arm (``…:dm:<chat>:<thread>``), so a "thread"-typed seed is a row no DM reply hits.+ Non-DM threads seed the slot the platform's adapter puts on an in-thread reply+ (``_THREAD_REPLY_CHAT_TYPE``)."""text = (mirror_text or "").strip()if not text:returntry:ok = _seed_cron_session(job, adapter, platform_name, chat_id, text,- thread_id=str(thread_id), chat_type="dm" if is_dm else "thread",+ thread_id=str(thread_id),+ chat_type="dm" if is_dm else _THREAD_REPLY_CHAT_TYPE.get(platform_name.lower(), "thread"),user_id="system:cron", user_name="Cron", chat_name=chat_name, scope_id=scope_id,discord_keys_on_thread=True)if ok:diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 5445134a42a..cb7e0456901 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -1532,6 +1532,10 @@ class GatewayStartupMixin:chat_type = "dm" if home_chat_id.startswith("D") else "group"scope_for_chat = getattr(transport.adapter, "scope_id_for_chat", None)scope_id = home.scope_id or (scope_for_chat(home_chat_id) if callable(scope_for_chat) else None)+ if platform == Platform.MATRIX:+ # Matrix likewise keys an in-thread reply on the ROOM's type (#112918); the adapter's+ # get_chat_info reports "dm"/"group" for the home room.+ chat_type = "dm" if await self._handoff_home_is_dm(transport.adapter, home_chat_id) else "group"# Discord builds in-thread messages with ``chat_id == thread id``: key on the thread's OWN id.dest_source = SessionSource(platform=platform,@@ -1550,6 +1554,17 @@ class GatewayStartupMixin:handoff_config=handoff_config,)+ @staticmethod+ async def _handoff_home_is_dm(adapter, home_chat_id: str) -> bool:+ """Whether the home chat is a DM by the adapter's own ``get_chat_info`` (``type: "dm"``);+ unknown/failed → not a DM, the common handoff target."""+ try:+ info = await adapter.get_chat_info(home_chat_id)+ except Exception:+ logger.debug("Handoff: get_chat_info failed for %s", home_chat_id, exc_info=True)+ return False+ return isinstance(info, dict) and info.get("type") == "dm"+def _handoff_session_key(self, dest, profile_name: Optional[str]) -> str:"""Destination session_key by the adapters' own rules. Thread keys omit user_id so the nextmessage shares it. Namespaced to the queuing profile (else a multiplexed gateway buildsdiff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex b533c15c5e8..3917b788dc8 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -1413,38 +1413,21 @@ class MatrixAdapter(BasePlatformAdapter):self._client.send_message_event(RoomID(chat_id), EventType.ROOM_MESSAGE, msg_content), timeout=45)return str(event_id)- async def create_handoff_thread(- self,- parent_chat_id: str,- name: str,- ) -> Optional[str]:- """Create a Matrix thread anchor for a session handoff.-- Matrix has no channel-level "create thread" API — a thread is just- events whose ``m.relates_to``/``rel_type: m.thread`` reference a root- event's ``event_id`` (the same model Slack uses with ``thread_ts``).- So post a seed/root message into ``parent_chat_id`` and return its- ``event_id``: the handoff watcher / cron scheduler uses that as the- ``thread_id`` for subsequent sends, and ``_apply_relation_metadata``- already threads them off it.-- Returns the seed event id as a string, or ``None`` if the client is- unavailable or the seed send failed (callers fall back to- ``parent_chat_id`` directly).- """+ async def create_handoff_thread(self, parent_chat_id: str, name: str) -> Optional[str]:+ """Post a seed message and return its ``event_id`` as the handoff ``thread_id``. Matrix has+ no create-thread API: a thread is the events whose ``m.relates_to``/``rel_type: m.thread``+ point at a root event (Slack-style), and ``_apply_relation_metadata`` already threads later+ sends off a supplied ``thread_id``. ``None`` when disconnected or the seed send failed.++ In-thread replies keep the ROOM's chat_type (``dm``/``group``) in the session key — the+ handoff watcher and the cron seeder mirror that shape rather than the shared ``thread`` slot."""if self._client is None:return None- seed_text = (name or "").strip() or "Hermes session"- result = await self.send(parent_chat_id, seed_text)- root = result.message_id if (result and result.success) else None+ result = await self.send(parent_chat_id, (name or "").strip() or "Hermes session")+ root = result.message_id if result.success else Noneif not root:return None- try:- # Register the root so inbound replies in this thread are- # recognised as participated (mirrors inbound thread handling).- self._threads.mark(str(root))- except Exception: # pragma: no cover - defensive- pass+ self._threads.mark(str(root)) # replies in this thread bypass require_mention, like inbound rootsreturn str(root)async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:diff --git a/tests/cron/test_cron_thread_seed_dm_keying.py b/tests/cron/test_cron_thread_seed_dm_keying.pyindex 00839d9c437..4e470d75e1f 100644--- a/tests/cron/test_cron_thread_seed_dm_keying.py+++ b/tests/cron/test_cron_thread_seed_dm_keying.py@@ -5,9 +5,10 @@ cron thread seed created its session row with chat_type="thread", but aSlack DM thread reply arrives with chat_type="dm" — build_session_key putsthem in different rows (agent:main:slack:thread:D...:<ts> vsagent:main:slack:dm:D...:<ts>), so the user's reply hit a session that had-never seen the brief. Channels are unaffected (channel thread replies carry-chat_type="thread"); the DM lane is the unswept sibling of the flat-seed-is_dm fix (dcca9d8cfe).+never seen the brief. Slack channel and Matrix room thread replies key on the+PARENT chat's type (``group``), Discord on ``thread`` — the seed mirrors the+adapter (``_THREAD_REPLY_CHAT_TYPE``); the DM lane is the unswept sibling of+the flat-seed is_dm fix (dcca9d8cfe).Contract under test: the KEY of the seeded session equals the KEY theuser's in-thread reply will build. Asserting on build_session_key output —@@ -56,9 +57,9 @@ def test_dm_thread_seed_key_matches_dm_reply_key():def test_channel_thread_seed_key_matches_thread_reply_key():- """Channel behavior must NOT regress: a channel thread reply keys as- chat_type='thread' (participant-shared), and the seed must keep matching- it."""+ """A Slack channel thread reply keys on the parent channel's type+ (``group`` — the adapter's ``build_source`` shape, #111896), not on a+ ``thread`` slot; the seed must match it."""store = MagicMock()adapter = MagicMock()adapter._session_store = store@@ -73,7 +74,7 @@ def test_channel_thread_seed_key_matches_thread_reply_key():reply_source = SessionSource(platform=Platform.SLACK,chat_id="C0AAAAAAAA",- chat_type="thread",+ chat_type="group",user_id="U0B5F8EEYAD",thread_id="1787188000.000100",)@@ -82,6 +83,30 @@ def test_channel_thread_seed_key_matches_thread_reply_key():)+def test_matrix_room_thread_seed_key_matches_room_reply_key():+ """The Matrix adapter keys an in-thread reply on the ROOM's type (``group``), so a+ cron ``attach_to_session`` seed typed ``thread`` is a row no reply ever hits (#112918)."""+ store = MagicMock()+ adapter = MagicMock()+ adapter._session_store = store++ with patch("gateway.mirror.mirror_to_session", return_value=True):+ _seed_cron_thread_session(+ {"id": "j7", "name": "alert"}, adapter, "matrix",+ "!ops:example.org", "$seed_event", "Three bullets",+ chat_name="ops", is_dm=False,+ )++ reply_source = SessionSource(+ platform=Platform.MATRIX,+ chat_id="!ops:example.org",+ chat_type="group",+ user_id="@alice:example.org",+ thread_id="$seed_event",+ )+ assert build_session_key(_seeded_source(store)) == build_session_key(reply_source)++def test_dm_seed_default_is_backward_compatible():"""Callers that don't pass is_dm keep today's thread-keyed behavior —the new parameter must not silently rekey non-DM call sites."""@@ -145,7 +170,7 @@ def test_scoped_channel_thread_seed_key_matches_scoped_reply_key():reply_source = SessionSource(platform=Platform.SLACK,chat_id="C0AAAAAAAA",- chat_type="thread",+ chat_type="group",user_id="U0B5F8EEYAD",thread_id="1787188000.000100",scope_id="T0AAAA111",diff --git a/tests/gateway/test_handoff_thread_session_key.py b/tests/gateway/test_handoff_thread_session_key.pyindex f0a0f8e1fca..063d1dccac9 100644--- a/tests/gateway/test_handoff_thread_session_key.py+++ b/tests/gateway/test_handoff_thread_session_key.py@@ -25,6 +25,8 @@ import asynciofrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch+import pytest+from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfigfrom gateway.run import GatewayRunnerfrom gateway.session import SessionSource, build_session_key@@ -168,3 +170,45 @@ def test_telegram_forum_handoff_key_matches_the_topic_reply_key():platform=Platform.TELEGRAM, chat_id="-1001234567", chat_type="group", user_id="42",thread_id="77"), thread_sessions_per_user=False)assert handoff == "agent:main:telegram:group:-1001234567:77"+++def _matrix_adapter(room_id: str, *, is_dm: bool, monkeypatch):+ """A real MatrixAdapter with a fake client: the room's DM flag comes from the m.direct cache."""+ from plugins.platforms.matrix.adapter import MatrixAdapter++ monkeypatch.setenv("MATRIX_REQUIRE_MENTION", "false")+ monkeypatch.delenv("MATRIX_AUTO_THREAD", raising=False)+ adapter = MatrixAdapter(PlatformConfig(enabled=True, token="syt_test", extra={+ "homeserver": "https://matrix.example.org", "user_id": "@hermes:example.org"}))+ adapter._text_batch_delay_seconds = 0+ adapter._startup_ts = 0+ adapter._dm_rooms[room_id] = is_dm+ adapter._client = SimpleNamespace(send_message_event=AsyncMock(return_value="$seed"), crypto=None)+ adapter._get_display_name = AsyncMock(return_value="alice")+ adapter._background_read_receipt = lambda *_a: None+ adapter.handle_message = AsyncMock()+ return adapter+++def _organic_matrix_reply_key(adapter, room_id: str, thread_id: str) -> str:+ """Key the Matrix adapter builds for a human reply inside ``thread_id`` (real inbound path)."""+ import time++ event = SimpleNamespace(+ sender="@alice:example.org", event_id="$reply", room_id=room_id, timestamp=int(time.time() * 1000),+ content={"body": "what happened?", "msgtype": "m.text",+ "m.relates_to": {"rel_type": "m.thread", "event_id": thread_id}})+ asyncio.run(adapter._on_room_message(event))+ return build_session_key(adapter.handle_message.await_args.args[0].source, thread_sessions_per_user=False)++[email protected]("is_dm", [False, True], ids=["room", "dm"])+def test_matrix_handoff_key_matches_the_thread_reply_key(is_dm, monkeypatch):+ """A Matrix handoff (and cron ``attach_to_session``) seeds a thread rooted on the seed event; the+ adapter keys replies in it on the ROOM's type (``group``/``dm``), never a ``thread`` slot, so the+ destination must bind that key or the first reply opens an empty session (#112918)."""+ room_id = "!ops:example.org"+ adapter = _matrix_adapter(room_id, is_dm=is_dm, monkeypatch=monkeypatch)+ _dest, handoff = _handoff_destination(Platform.MATRIX, room_id, "$seed", None, adapter)+ assert handoff == _organic_matrix_reply_key(adapter, room_id, "$seed")+ assert handoff.split(":")[3] == ("dm" if is_dm else "group")diff --git a/tests/gateway/test_matrix_handoff_thread.py b/tests/gateway/test_matrix_handoff_thread.pyindex 6004209debb..d8f19119906 100644--- a/tests/gateway/test_matrix_handoff_thread.py+++ b/tests/gateway/test_matrix_handoff_thread.py@@ -4,8 +4,7 @@ Matrix has no channel-level "create thread" API, so the adapter seeds a rootmessage and returns its event_id as the thread handle (Slack-style — mirrors``tests/gateway/test_slack_sdk_response.py::TestHandoffThread``). These testscover: the seed event id becomes the thread id (and the root is registered as a-participated thread), a blank name falls back to a default seed, and ``None`` is-returned when the client is absent or the seed send fails.+participated thread), and ``None`` is returned when the seed send fails (#112918)."""import asyncio@@ -48,34 +47,9 @@ class TestHandoffThread:# Root registered so inbound replies in this thread are recognised.assert "$root_evt" in adapter._threads- def test_blank_name_falls_back_to_default_seed(self):- adapter = _make_adapter()- adapter._client = MagicMock()- adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="$root2"))-- thread_id = asyncio.run(adapter.create_handoff_thread("!room1:example.org", " "))-- assert thread_id == "$root2"- adapter.send.assert_awaited_once_with("!room1:example.org", "Hermes session")-- def test_no_client_yields_no_thread(self):- adapter = _make_adapter()- adapter._client = None- adapter.send = AsyncMock()-- assert asyncio.run(adapter.create_handoff_thread("!room1:example.org", "x")) is None- adapter.send.assert_not_awaited()-def test_failed_seed_send_yields_no_thread(self):adapter = _make_adapter()adapter._client = MagicMock()adapter.send = AsyncMock(return_value=SendResult(success=False, error="boom"))assert asyncio.run(adapter.create_handoff_thread("!room1:example.org", "x")) is None-- def test_seed_send_without_event_id_yields_no_thread(self):- adapter = _make_adapter()- adapter._client = MagicMock()- adapter.send = AsyncMock(return_value=SendResult(success=True, message_id=None))-- assert asyncio.run(adapter.create_handoff_thread("!room1:example.org", "x")) is Nonediff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.mdindex ddd8e0bf0cc..e54e6f43c9d 100644--- a/website/docs/reference/slash-commands.md+++ b/website/docs/reference/slash-commands.md@@ -69,7 +69,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in| `/btw <question>` | Ask a quick side question **about the current conversation** without interrupting it. A one-shot auxiliary LLM call answers from a read-only snapshot of the transcript — the live session's history and prompt cache are untouched, and the current turn keeps running. For independent work with a fresh context, use `/bg`. || `/branch [name]` (alias: `/fork`) | Branch the current session (explore a different path) || `/worktree [new [name]\|list]` | **CLI only.** Inspect or create isolated git worktrees mid-session (inspired by Copilot CLI's `/worktree new`). Bare `/worktree` shows the active worktree; `/worktree list` lists the repo's worktrees; `/worktree new [name]` creates a worktree under `.worktrees/` (branched from the freshly-fetched remote tip, honoring `worktree_sync`) and retargets the session's terminal and file tools into it. Named trees use your name (`hermes/<name>` branch); unnamed ones get a random `hermes-<id>`. On exit the tree is kept only if it has unpushed commits — same lifecycle as `hermes -w`. See [Git Worktrees](/user-guide/git-worktrees). |-| `/handoff <platform>` | **CLI only.** Hand the current session off to a messaging platform (Telegram, Discord, Slack, WhatsApp, Signal, Matrix). The gateway picks it up immediately, creates a fresh thread on platforms that support threads (Telegram topics, Discord text-channel threads, Slack message-anchored threads), re-binds the destination to your CLI session_id so the full role-aware transcript replays, and forges a synthetic user turn so the agent confirms it's working in the new place. Your CLI exits cleanly on success with a `/resume` hint; resume locally any time with `/resume <title>`. Refused mid-turn. Requires the gateway to be running and a home channel configured for the target platform (`/sethome` from the destination chat). See [Cross-Platform Handoff](/user-guide/sessions#cross-platform-handoff). |+| `/handoff <platform>` | **CLI only.** Hand the current session off to a messaging platform (Telegram, Discord, Slack, WhatsApp, Signal, Matrix). The gateway picks it up immediately, creates a fresh thread on platforms that support threads (Telegram topics, Discord text-channel threads, Slack and Matrix message-anchored threads), re-binds the destination to your CLI session_id so the full role-aware transcript replays, and forges a synthetic user turn so the agent confirms it's working in the new place. Your CLI exits cleanly on success with a `/resume` hint; resume locally any time with `/resume <title>`. Refused mid-turn. Requires the gateway to be running and a home channel configured for the target platform (`/sethome` from the destination chat). See [Cross-Platform Handoff](/user-guide/sessions#cross-platform-handoff). || `/journey [list\|delete <id>\|edit <id>]` (aliases: `/learning`, `/memory-graph`) | Open the learning journey timeline of learned skills + memories. Works in the classic CLI, as a TUI overlay, and in the desktop app (Star Map panel). Not available on messaging platforms. See [Learning Journey](/user-guide/features/memory#learning-journey-journey). |### Configurationdiff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 71c16a6060e..b6639dc7a69 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -649,7 +649,7 @@ cron:Behaviour is **thread-preferred**, scoped to the job's own conversation:-- **Thread-capable platforms** (Telegram topics, Discord/Slack threads): each+- **Thread-capable platforms** (Telegram topics, Discord/Slack/Matrix threads): eachdelivery opens its own dedicated thread and the brief is seeded into thatthread's session, so a reply in-thread continues with full context. Arecurring job (e.g. a daily brief) opens a fresh thread per run, keeping eachdiff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex ffedb37b2d0..7740c626cf4 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -231,7 +231,8 @@ What happens:- **Telegram** — opens a new forum topic (DM topics if Bot API 9.4+ Topics mode is enabled in the chat, or a forum supergroup topic).- **Discord** — creates a 1440-min auto-archive thread under the home text channel.- **Slack** — posts a seed message and uses its `ts` as the thread anchor.- - **WhatsApp / Signal / Matrix / SMS** — no native threads, falls back to the home channel directly.+ - **Matrix** — posts a seed message and uses its event id as the thread root (`m.thread` relation).+ - **WhatsApp / Signal / SMS** — no native threads, falls back to the home channel directly.4. The gateway re-binds the destination key to your existing CLI session id, then forges a synthetic user turn asking the agent to confirm and summarize. The reply lands in the new thread.5. When the gateway acknowledges success, the CLI prints a `/resume` hint and exits cleanly:@@ -251,7 +252,7 @@ What happens:- Thread creation fails (permissions, topics-mode off) → falls back to the home channel directly and still completes; no thread isolation but the handoff itself works.- `adapter.send` fails (rate limit, transient API error) → handoff marked failed with the reason; the row clears so you can retry.-**Limitation worth knowing:** for non-thread-capable platforms with multi-user group home channels, the synthetic turn keys as a DM-style session. This works for self-DM home channels (the typical setup) but isn't ideal for genuinely shared group chats. Threading covers Telegram / Discord / Slack — by far the common case — so most setups never hit this.+**Limitation worth knowing:** for non-thread-capable platforms with multi-user group home channels, the synthetic turn keys as a DM-style session. This works for self-DM home channels (the typical setup) but isn't ideal for genuinely shared group chats. Threading covers Telegram / Discord / Slack / Matrix — by far the common case — so most setups never hit this.## Session Naming