Skip to content

The agent that grows with you

fix(gateway): parse named-profile namespaces in session keys

Konstantin Khlopkovbdb38e3fc640
diff --git a/gateway/run.py b/gateway/run.py
index 47285b88734..64eb47ebbc0 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2906,13 +2906,27 @@ def _resolve_hermes_bin() -> Optional[list[str]]:
return None
+_PROFILE_ID_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
+
+
def _parse_session_key(session_key: str) -> "dict | None":
- """Parse a session key (``agent:main:{platform}:{chat_type}:{chat_id}[:{extra}...]``).
- For group/channel sessions the suffix may be a user_id, not a thread_id, so ``thread_id`` is omitted.
+ """Parse a session key (``agent:{ns}:{platform}:{chat_type}:{chat_id}[:{extra}...]``).
+
+ ``{ns}`` is ``main`` for the default profile or a named-profile id (profile ids match
+ ``[a-z0-9][a-z0-9_-]{0,63}`` — never contain ``:`` — so a plain split stays unambiguous).
+ For group/channel sessions the suffix may be a user_id, not a thread_id, so ``thread_id``
+ is omitted. Named profiles are reported as ``profile``; ``main`` keys keep their historical
+ shape exactly (no ``profile`` key) so equality assertions on parsed dicts stay stable.
"""
parts = session_key.split(":")
- if len(parts) >= 5 and parts[0] == "agent" and parts[1] == "main":
+ if (
+ len(parts) >= 5
+ and parts[0] == "agent"
+ and (parts[1] == "main" or _PROFILE_ID_KEY_RE.match(parts[1]))
+ ):
result = {"platform": parts[2], "chat_type": parts[3], "chat_id": parts[4]}
+ if parts[1] != "main":
+ result["profile"] = parts[1]
if len(parts) > 5 and parts[3] in {"dm", "thread"}:
result["thread_id"] = parts[5]
return result
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index f6a8139e34c..5557c1f4659 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -19,7 +19,7 @@ from agent.session_activity import format_iteration_progress
from gateway.config import Platform
from gateway.platforms.base import EphemeralReply
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.session import SessionSource
+from gateway.session import SessionSource, _session_key_namespace
from typing import Any, Dict, Optional, Union
if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
@@ -1001,8 +1001,15 @@ class GatewayBusySessionMixin:
platform = source.platform.value
chat_type = getattr(source, "chat_type", None) or ""
# Match the exact key or prefix + ":" so a thread id that merely starts with this one
- # is not matched.
- prefix = ":".join(["agent:main", platform, chat_type, str(chat_id), str(thread_id)])
+ # is not matched. The namespace follows the source's profile so a named-profile run
+ # under multiplexing still matches its own keys.
+ prefix = ":".join([
+ _session_key_namespace(getattr(source, "profile", None)),
+ platform,
+ chat_type,
+ str(chat_id),
+ str(thread_id),
+ ])
return [
key
for key, agent in self._running_agent_items()
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 2af9cb78a5a..91b19eac78f 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -885,8 +885,6 @@ class GatewayNotificationsMixin:
from gateway.run import _parse_session_key
session_key = str(evt.get("session_key") or "").strip()
derived = {}
- parts = session_key.split(":")
- profile = parts[1] if len(parts) >= 5 and parts[0] == "agent" and parts[1] != "main" else None
if session_key:
try:
self.session_store._ensure_loaded()
@@ -898,8 +896,8 @@ class GatewayNotificationsMixin:
cached_source = self._get_cached_session_source(session_key)
if cached_source is not None:
return cached_source
- parse_key = ":".join(["agent", "main", *parts[2:]]) if profile else session_key
- derived = _parse_session_key(parse_key) or {}
+ derived = _parse_session_key(session_key) or {}
+ profile = derived.get("profile")
platform_name = str(evt.get("platform") or derived.get("platform") or "").strip().lower()
chat_type = str(evt.get("chat_type") or derived.get("chat_type") or "").strip().lower()
chat_id = str(evt.get("chat_id") or derived.get("chat_id") or "").strip()
diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.py
index 031b4af2d34..a2adca47fab 100644
--- a/tests/gateway/test_background_process_notifications.py
+++ b/tests/gateway/test_background_process_notifications.py
@@ -520,6 +520,73 @@ def test_parse_session_key_with_extra_parts():
assert result == {"platform": "discord", "chat_type": "group", "chat_id": "chan123"}
+def test_parse_session_key_named_profile():
+ """A named-profile namespace parses and is reported as ``profile``."""
+ result = _parse_session_key("agent:work:telegram:dm:123")
+ assert result == {
+ "profile": "work",
+ "platform": "telegram",
+ "chat_type": "dm",
+ "chat_id": "123",
+ }
+
+
+def test_parse_session_key_named_profile_thread_id():
+ """Thread-slot handling is identical for named-profile keys."""
+ result = _parse_session_key("agent:work:telegram:thread:100:42")
+ assert result == {
+ "profile": "work",
+ "platform": "telegram",
+ "chat_type": "thread",
+ "chat_id": "100",
+ "thread_id": "42",
+ }
+
+
+def test_parse_session_key_named_profile_group_suffix_omitted():
+ """Group-suffix (user_id) stays omitted for named-profile keys too."""
+ result = _parse_session_key("agent:work:discord:group:chan1:user9")
+ assert result == {
+ "profile": "work",
+ "platform": "discord",
+ "chat_type": "group",
+ "chat_id": "chan1",
+ }
+
+
+def test_parse_session_key_main_shape_unchanged():
+ """``main`` keys keep their historical dict shape exactly (no ``profile`` key)."""
+ result = _parse_session_key("agent:main:telegram:dm:123:42")
+ assert result == {
+ "platform": "telegram",
+ "chat_type": "dm",
+ "chat_id": "123",
+ "thread_id": "42",
+ }
+
+
+def test_parse_session_key_rejects_invalid_namespace():
+ """A namespace slot that cannot be a profile id still parses to None."""
+ assert _parse_session_key("agent:Bad_NS:telegram:dm:123") is None
+ assert _parse_session_key("agent:main:telegram:dm") is None
+ assert _parse_session_key("raw-session-id") is None
+
+
+def test_build_process_event_source_named_profile_key(monkeypatch, tmp_path):
+ """A synthetic event keyed by a named-profile session resolves platform/chat and keeps
+ the profile, instead of being unresolvable and dropped with a warning."""
+ runner = _build_runner(monkeypatch, tmp_path, "all")
+ source = runner._build_process_event_source({
+ "session_id": "proc_watch",
+ "session_key": "agent:work:telegram:dm:123",
+ })
+ assert source is not None
+ assert source.platform is Platform.TELEGRAM
+ assert source.chat_id == "123"
+ assert source.chat_type == "dm"
+ assert source.profile == "work"
+
+
# ---------------------------------------------------------------------------
# api_server (stateless) wake routing — gateway/wake.py self-post path
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_stop_thread_sibling.py b/tests/gateway/test_stop_thread_sibling.py
index 63fe48708ef..234931393f3 100644
--- a/tests/gateway/test_stop_thread_sibling.py
+++ b/tests/gateway/test_stop_thread_sibling.py
@@ -57,6 +57,36 @@ def test_sibling_returns_empty_for_non_thread_source():
assert runner._sibling_thread_run_keys(nonthread, "agent:main:discord:group:chan1:userA") == []
+def test_sibling_matches_named_profile_runs():
+ # Under multiplexing the sibling prefix must follow the source's profile namespace,
+ # so /stop finds another participant's run under the SAME named profile...
+ runner = object.__new__(GatewayRunner)
+ source = _thread_source("userA")
+ source.profile = "work"
+ key_b = build_session_key(
+ _thread_source("userB"), thread_sessions_per_user=True, profile="work"
+ )
+ runner._running_agents = {key_b: _FakeAgent()}
+ assert runner._sibling_thread_run_keys(
+ source, "agent:work:discord:forum:chan1:thr1:userA"
+ ) == [key_b]
+
+
+def test_sibling_does_not_cross_profiles():
+ # ...and never reaches a DIFFERENT profile's run in the same chat/thread.
+ runner = object.__new__(GatewayRunner)
+ source = _thread_source("userA")
+ source.profile = "work"
+ main_key = build_session_key(_thread_source("userB"), thread_sessions_per_user=True)
+ runner._running_agents = {main_key: _FakeAgent()}
+ assert (
+ runner._sibling_thread_run_keys(
+ source, "agent:work:discord:forum:chan1:thr1:userA"
+ )
+ == []
+ )
+
+
# ---------------------------------------------------------------------------
# _handle_stop_command fallback path
# ---------------------------------------------------------------------------