Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion gateway/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1193,13 +1193,19 @@ class MessageEvent:
# trigger message alone, then prepend this context afterward.
channel_context: Optional[str] = None

# Target Hermes profile override — set by the gateway when profile_routing
# config maps this user to a specific profile. When set, the gateway
# switches to this profile for the duration of the message processing,
# then restores the original profile afterward.
target_profile: Optional[str] = None

# Internal flag — set for synthetic events (e.g. background process
# completion notifications) that must bypass user authorization checks.
internal: bool = False

# Timestamps
timestamp: datetime = field(default_factory=datetime.now)

def is_command(self) -> bool:
"""Check if this is a command message (e.g., /new, /reset)."""
return self.text.startswith("/")
Expand Down
59 changes: 58 additions & 1 deletion gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1695,6 +1695,7 @@ def __init__(self, config: Optional[GatewayConfig] = None):
self._busy_text_mode = self._load_busy_text_mode()
self._restart_drain_timeout = self._load_restart_drain_timeout()
self._provider_routing = self._load_provider_routing()
self._profile_routing = self._load_profile_routing()
self._fallback_model = self._load_fallback_model()

# Wire process registry into session store for reset protection
Expand Down Expand Up @@ -3015,6 +3016,45 @@ def _load_provider_routing() -> dict:
pass
return {}

@staticmethod
def _load_profile_routing() -> dict:
"""Load per-user profile routing from config.yaml.

``profile_routing`` is a dict mapping user identity strings
(Telegram UID, Discord snowflake, etc.) to Hermes profile names.

Example config.yaml snippet::

profile_routing:
"7165055445": palantir # Telegram UID → palantir profile
"123456789": arien # Discord ID → arien profile

Returns an empty dict when the key is absent or unreadable.
"""
try:
import yaml as _y
cfg_path = _hermes_home / "config.yaml"
if cfg_path.exists():
with open(cfg_path, encoding="utf-8") as _f:
cfg = _y.safe_load(_f) or {}
return cfg.get("profile_routing", {}) or {}
except Exception:
pass
return {}

@staticmethod
def _resolve_profile_for_user(user_id: str | None, profile_routing: dict) -> str | None:
"""Resolve the Hermes profile for a given user.

Looks up *user_id* in the *profile_routing* mapping. Returns the
target profile name when found, or None to fall through to the
current profile. Unknown/unmapped users keep whatever profile
is active — routing only overrides when explicitly configured.
"""
if not user_id or not profile_routing:
return None
return profile_routing.get(str(user_id))

@staticmethod
def _load_fallback_model() -> list | None:
"""Load fallback provider chain from config.yaml.
Expand Down Expand Up @@ -6858,7 +6898,24 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]:
# Record rate limit so subsequent messages are silently ignored
self.pairing_store._record_rate_limit(platform_name, source.user_id)
return None


# --- Per-user profile routing ---------------------------------------
# If profile_routing is configured, check whether this user's ID maps
# to a specific Hermes profile. When matched, attach the target profile
# to the MessageEvent so downstream agent initialization picks it up.
if self._profile_routing and source.user_id:
_routed_profile = self._resolve_profile_for_user(
str(source.user_id), self._profile_routing
)
if _routed_profile and _routed_profile != self._active_profile_name():
logger.info(
"Profile routing: user %s → profile '%s' (was '%s')",
source.user_id,
_routed_profile,
self._active_profile_name(),
)
event.target_profile = _routed_profile

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

target_profile is not consumed by the gateway execution path. Current main scopes the turn from source.profile (gateway/run.py:16977-16987) and resolves the response adapter from that same field (gateway/authz_mixin.py:61-70), so this assignment does not route the message. Apply the resolved profile at the source/profile ingress seam before authorization and session-key creation.


# Intercept messages that are responses to a pending /update prompt.
# The update process (detached) wrote .update_prompt.json; the watcher
# forwarded it to the user; now the user's reply goes back via
Expand Down