The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): compact slash_commands_session/model — fold calls, inline single-use helpers, tighten docs
Teknium559714fb18f4
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex 212090853b1..cfee6563884 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -19,8 +19,7 @@ from gateway.platforms.base import MessageEventfrom hermes_cli.config import atomic_config_write, clear_model_endpoint_credentialsfrom utils import base_url_host_matches-# Log-record parity with gateway/run.py and the origin module.-logger = logging.getLogger("gateway.run")+logger = logging.getLogger("gateway.run") # log-record parity with gateway/run.py# /fast argument -> (service tier, persisted value, i18n label key; None = value.upper())._FAST_SELECTIONS = {@@ -37,12 +36,8 @@ _REASONING_DISPLAY_TOGGLES = {"show": True, "on": True, "hide": False, "off": Fadef _model_switch_skew_guard() -> Optional[str]:- """Refuse a model switch when the gateway is running stale code.-- A long-lived gateway keeps boot-time modules in memory; if the checkout changed underneath it,- a first-time lazy import on a new code path can crash on a stale cached dependency. Scoped to- model switching only (the highest-risk trigger).- """+ """Refuse a model switch when the gateway is running stale code: a first-time lazy import on+ a new code path can crash on a stale cached dependency. Scoped to the highest-risk trigger."""from gateway.code_skew import detect_code_skewskew = detect_code_skew()@@ -62,10 +57,9 @@ def _model_switch_skew_guard() -> Optional[str]:async def _persist_model_switch_to_config(result, config_path) -> None:"""Write-through a resolved /model switch to ``config_path`` (model.default/provider/base_url).- Raw read is correct (merged defaults must not be persisted back). A scalar/None ``model:`` is- coerced into a dict first or the assignments below raise ``TypeError``. Named providers- re-resolve base_url/api_mode fresh, so leftovers are cleared; custom providers have no registry- entry to re-derive from, so they need an explicit set-or-clear.+ Raw read: merged defaults must not be persisted back. A scalar/None ``model:`` is coerced to a+ dict first. Named providers re-resolve base_url/api_mode, so leftovers are cleared; custom+ providers have no registry entry to re-derive from and need an explicit set-or-clear."""from hermes_cli.config import read_user_config_raw, save_config@@ -79,17 +73,13 @@ async def _persist_model_switch_to_config(result, config_path) -> None:model_cfg = cfg["model"] = {}try:from hermes_cli.route_identity import should_clear_context_pin_async-- if await should_clear_context_pin_async(- model_cfg.get("default") or model_cfg.get("model"),- result.new_model,- model_cfg.get("base_url"),- result.base_url,- model_cfg.get("provider"),- result.target_provider,- ):- model_cfg.pop("context_length", None)+ clear_pin = await should_clear_context_pin_async(+ model_cfg.get("default") or model_cfg.get("model"), result.new_model,+ model_cfg.get("base_url"), result.base_url, model_cfg.get("provider"), result.target_provider,+ )except Exception:+ clear_pin = True+ if clear_pin:model_cfg.pop("context_length", None)model_cfg["default"] = result.new_modelmodel_cfg["provider"] = result.target_provider@@ -128,7 +118,6 @@ class _ModelSwitchContext:def read_config(self) -> None:"""Fill the current route from ``config_path``; fail-open to the defaults."""from gateway.run import _load_gateway_config-try:cfg = _load_gateway_config(config_path=self.config_path)if not cfg:@@ -158,15 +147,6 @@ class _ModelSwitchContext:self.current_base_url = override.get("base_url", self.current_base_url)self.current_api_key = override.get("api_key", self.current_api_key)- def listing_kwargs(self) -> dict:- return dict(- current_provider=self.current_provider,- current_base_url=self.current_base_url,- current_model=self.current_model,- user_providers=self.user_provs,- custom_providers=self.custom_provs,- excluded_providers=self.excluded_provs,- )def _model_provider_listing_lines(providers) -> list[str]:@@ -186,23 +166,6 @@ def _model_provider_listing_lines(providers) -> list[str]:return lines-async def _configured_display_context() -> tuple[dict, Optional[int]]:- """(model config section, its ``context_length`` as int) for the switch confirmation; fail-open."""- from gateway.run import _load_gateway_config-- model_cfg: dict = {}- config_ctx = None- with contextlib.suppress(Exception):- model_cfg = _load_gateway_config().get("model", {})- if isinstance(model_cfg, dict):- raw = model_cfg.get("context_length")- if raw is not None:- config_ctx = int(raw)- if not isinstance(model_cfg, dict):- model_cfg = {}- return model_cfg, config_ctx--class GatewayModelCommandsMixin:"""Model-route slash commands (/model, /codex-runtime, /reasoning, /fast, /personality)."""@@ -218,33 +181,22 @@ class GatewayModelCommandsMixin:skew_error = _model_switch_skew_guard()if skew_error:return None, skew_error- # Off the event loop: switch_model() can fall through to a synchronous models.dev HTTP- # fetch (15s timeout) on a cold/expired cache, which would freeze the gateway.+ # Off-loop: switch_model() can hit a synchronous models.dev fetch (15s) on a cold cache.result = await asyncio.to_thread(- switch_model,- raw_input=raw_input,- current_provider=ctx.current_provider,- current_model=ctx.current_model,- current_base_url=ctx.current_base_url,- current_api_key=ctx.current_api_key,- is_global=ctx.persist_global,- explicit_provider=explicit_provider,- user_providers=ctx.user_provs,+ switch_model, raw_input=raw_input, current_provider=ctx.current_provider,+ current_model=ctx.current_model, current_base_url=ctx.current_base_url,+ current_api_key=ctx.current_api_key, is_global=ctx.persist_global,+ explicit_provider=explicit_provider, user_providers=ctx.user_provs,custom_providers=ctx.custom_provs,)if not result.success:return None, t("gateway.model.error_prefix", error=result.error_message)try:from hermes_cli.context_switch_guard import enrich_model_switch_warnings_for_gateway-# Off-loop: merge_preflight_compression_warning() runs the sync provider probe ladder.await asyncio.to_thread(- enrich_model_switch_warnings_for_gateway,- result,- self,- session_key=ctx.session_key,- source=source,- custom_providers=ctx.custom_provs,+ enrich_model_switch_warnings_for_gateway, result, self, session_key=ctx.session_key,+ source=source, custom_providers=ctx.custom_provs,load_gateway_config=_load_gateway_config,)except Exception as exc:@@ -254,20 +206,16 @@ class GatewayModelCommandsMixin:def _switch_cached_agent_model(self, result, ctx: _ModelSwitchContext, picker: bool) -> Optional[str]:"""In-place swap on the cached agent; returns the error reply when it failed.- The agent rolls back to the OLD working model/client and re-raises. Abort the commit (DB- persist, session override, cache eviction, config write) so a failed switch is a no-op —- otherwise the next message rebuilds a broken agent from the override.+ The agent rolls back to the OLD model/client and re-raises; the commit (DB, override,+ eviction, config) is aborted so the next message doesn't rebuild a broken agent."""cached_agent = self._cached_agent_for(ctx.session_key)if cached_agent is None:return Nonetry:cached_agent.switch_model(- new_model=result.new_model,- new_provider=result.target_provider,- api_key=result.api_key,- base_url=result.base_url,- api_mode=result.api_mode,+ new_model=result.new_model, new_provider=result.target_provider,+ api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode,capabilities=getattr(result, "runtime_capabilities", None),)except Exception as exc:@@ -286,13 +234,12 @@ class GatewayModelCommandsMixin:"""Persist a committed switch: session DB, next-turn note, override map, config write-through."""from hermes_cli.model_switch import format_model_for_display- # Session DB so the dashboard shows the updated model._sess_db = getattr(self, "_session_db", None)- if _sess_db is not None:+ if _sess_db is not None: # so the dashboard shows the updated modeltry:_sess_entry = await self.async_session_store.get_or_create_session(source)- # Typed path: consume an auto-reset flag so the next regular message's cleanup does- # not wipe the override stored below.+ # Typed path: consume the auto-reset flag so the next message's cleanup does not+ # wipe the override stored below.if not picker and getattr(_sess_entry, "was_auto_reset", False):_sess_entry.was_auto_reset = Falseawait _sess_db.update_session_model(@@ -300,9 +247,8 @@ class GatewayModelCommandsMixin:)except Exception as exc:logger.debug("Failed to persist model switch to DB: %s", exc)-- # Note prepended to the next user message (avoids system messages mid-history). Display- # form strips opaque Palantir RID prefixes; the override map keeps the full ID for the wire.+ # Prepended to the next user message (no system messages mid-history). Display form strips+ # opaque Palantir RID prefixes; the override map keeps the full ID for the wire.if not hasattr(self, "_pending_model_notes"):self._pending_model_notes = {}self._pending_model_notes[ctx.session_key] = (@@ -329,10 +275,8 @@ class GatewayModelCommandsMixin:)elif not picker and hasattr(self, "_pending_one_turn_model_restores"):self._pending_one_turn_model_restores.pop(ctx.session_key, None)-# Non-secret write-through so the override survives a restart (api_key/api_mode are- # re-resolved on rehydration). /model --once is EXCLUDED: a one-turn override must not- # outlive a restart.+ # re-resolved on rehydration); a --once override must NOT outlive a restart.if not one_turn:try:await self.async_session_store.set_model_override(@@ -340,10 +284,7 @@ class GatewayModelCommandsMixin:)except Exception:logger.debug("Failed to persist session model override", exc_info=True)-- # Evict so the next turn builds a fresh agent from the override.- self._evict_cached_agent(ctx.session_key)-+ self._evict_cached_agent(ctx.session_key) # next turn builds fresh from the overrideif ctx.persist_global:try:await _persist_model_switch_to_config(result, ctx.config_path)@@ -354,24 +295,28 @@ class GatewayModelCommandsMixin:self, result, ctx: _ModelSwitchContext, *, one_turn: bool, picker: bool) -> str:"""Confirmation text with full metadata (display form shortens opaque Palantir IDs)."""+ from gateway.run import _load_gateway_configfrom hermes_cli.model_switch import format_model_for_display, resolve_display_context_length_asynclines = [t("gateway.model.switched", model=format_model_for_display(result.new_model)),t("gateway.model.provider_label", provider=result.provider_label or result.target_provider),]- # Context: the provider-aware chain so Codex OAuth, Copilot and Nous-enforced caps win over- # the raw models.dev entry.+ # Provider-aware chain: Codex OAuth, Copilot and Nous caps win over the raw models.dev entry.mi = result.model_info- model_cfg, config_ctx = await _configured_display_context()+ model_cfg: dict = {}+ config_ctx = None+ with contextlib.suppress(Exception): # fail-open on config read errors+ model_cfg = _load_gateway_config().get("model", {})+ if isinstance(model_cfg, dict) and model_cfg.get("context_length") is not None:+ config_ctx = int(model_cfg["context_length"])+ if not isinstance(model_cfg, dict):+ model_cfg = {}ctx_len = await resolve_display_context_length_async(- result.new_model,- result.target_provider,+ result.new_model, result.target_provider,base_url=result.base_url or ctx.current_base_url or "",- api_key=result.api_key or ctx.current_api_key or "",- model_info=mi,- custom_providers=ctx.custom_provs,- config_context_length=config_ctx,+ api_key=result.api_key or ctx.current_api_key or "", model_info=mi,+ custom_providers=ctx.custom_provs, config_context_length=config_ctx,configured_model=model_cfg.get("default") or model_cfg.get("model"),configured_provider=model_cfg.get("provider"),configured_base_url=model_cfg.get("base_url"),@@ -400,11 +345,8 @@ class GatewayModelCommandsMixin:async def _commit_model_switch(self, result, ctx: _ModelSwitchContext, *, source, picker: bool = False) -> str:- """Apply a resolved switch (cached agent, session, config) and build the confirmation.-- Shared by the typed ``/model <name>`` path and the picker callback (``picker=True``, which- never carries a one-turn override).- """+ """Apply a resolved switch (cached agent, session, config) and build the confirmation; shared+ by the typed path and the picker callback (``picker=True`` never carries --once)."""one_turn = False if picker else ctx.one_turnerror = self._switch_cached_agent_model(result, ctx, picker)if error is not None:@@ -412,24 +354,11 @@ class GatewayModelCommandsMixin:await self._record_model_switch(result, ctx, source=source, one_turn=one_turn, picker=picker)return await self._model_switch_confirmation(result, ctx, one_turn=one_turn, picker=picker)- async def _switch_and_commit(- self, ctx: _ModelSwitchContext, model_id: str, provider_slug, *, source, picker: bool = False- ) -> str:- result, error = await self._perform_model_switch(ctx, model_id, provider_slug, source)- if error is not None:- return error- return await self._commit_model_switch(result, ctx, source=source, picker=picker)-async def _send_model_picker(self, event: MessageEvent, source, adapter, session_key: str, listing_kwargs: dict, on_model_selected) -> bool:- """Send the interactive /model picker; False when nothing was sent (text fallback).-- *source* is the session-key-normalized source (Telegram topic recovery), so the picker's- thread metadata lands where the next turn reads.- """+ """Send the interactive /model picker; False when nothing was sent (text fallback). *source*+ is session-key-normalized so the picker's thread metadata lands where the next turn reads."""from hermes_cli.model_switch import list_picker_providers-- try:- # Off-loop: provider listing can fall through to a synchronous HTTP fetch on a stale cache.+ try: # off-loop: listing can hit a synchronous HTTP fetch on a stale cacheproviders = await asyncio.to_thread(list_picker_providers, max_models=50, include_moa=True, **listing_kwargs)@@ -438,11 +367,9 @@ class GatewayModelCommandsMixin:if not providers:return Falseresult = await adapter.send_model_picker(- chat_id=source.chat_id,- providers=providers,+ chat_id=source.chat_id, providers=providers,current_model=listing_kwargs["current_model"],- current_provider=listing_kwargs["current_provider"],- session_key=session_key,+ current_provider=listing_kwargs["current_provider"], session_key=session_key,on_model_selected=on_model_selected,metadata=self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)),)@@ -455,25 +382,32 @@ class GatewayModelCommandsMixin:from hermes_cli.model_switch import list_authenticated_providersfrom hermes_cli.providers import get_label- listing_kwargs = ctx.listing_kwargs()+ listing_kwargs = dict(+ current_provider=ctx.current_provider, current_base_url=ctx.current_base_url,+ current_model=ctx.current_model, user_providers=ctx.user_provs,+ custom_providers=ctx.custom_provs, excluded_providers=ctx.excluded_provs,+ )adapter = self._adapter_for_source(ctx.source)if adapter is not None and getattr(type(adapter), "send_model_picker", None) is not None:- async def _on_model_selected(_chat_id: str, model_id: str, provider_slug: str) -> str:- """Perform the model switch and return confirmation text."""+ async def _picker_switch(model_id: str, provider_slug: str) -> str:# The picker callback binds the raw event source (pre-normalization).+ result, error = await self._perform_model_switch(ctx, model_id, provider_slug, event.source)+ if error is not None:+ return error+ return await self._commit_model_switch(result, ctx, source=event.source, picker=True)++ async def _on_model_selected(_chat_id: str, model_id: str, provider_slug: str) -> str:if profile_home is None:- return await self._switch_and_commit(ctx, model_id, provider_slug, source=event.source, picker=True)+ return await _picker_switch(model_id, provider_slug)from gateway.run import _profile_runtime_scope-with _profile_runtime_scope(profile_home):- return await self._switch_and_commit(ctx, model_id, provider_slug, source=event.source, picker=True)+ return await _picker_switch(model_id, provider_slug)if await self._send_model_picker(event, ctx.source, adapter, ctx.session_key, listing_kwargs, _on_model_selected):return None # Picker sent — adapter handles the responselines = [t("gateway.model.current_label", model=ctx.current_model or "unknown", provider=get_label(ctx.current_provider)), ""]- try:- # Off-loop: provider listing can fall through to a stale-cache HTTP fetch.+ try: # off-loop: listing can hit a stale-cache HTTP fetchproviders = await asyncio.to_thread(list_authenticated_providers, max_models=5, **listing_kwargs)lines.extend(_model_provider_listing_lines(providers))except Exception:@@ -488,20 +422,16 @@ class GatewayModelCommandsMixin:) -> tuple[bool, Optional[str]]:"""Selection-guard confirmation for the typed path (pickers confirm via their own UI).- Runs the unified registry (cost + data-policy guards) off the event loop — pricing lookups- may hit models.dev or a /models endpoint on a cache miss. Returns ``(fired, reply)``; the- reply may be None when the platform rendered confirm buttons itself.+ The unified registry (cost + data-policy guards) runs off-loop — pricing lookups may hit+ models.dev on a cache miss. Returns ``(fired, reply)``; the reply is None when the platform+ rendered confirm buttons itself."""try:from hermes_cli.model_selection_guards import combined_selection_warning-warning = await asyncio.to_thread(- combined_selection_warning,- result.new_model,- provider=result.target_provider,+ combined_selection_warning, result.new_model, provider=result.target_provider,base_url=result.base_url or ctx.current_base_url or "",- api_key=result.api_key or ctx.current_api_key or "",- model_info=result.model_info,+ api_key=result.api_key or ctx.current_api_key or "", model_info=result.model_info,)except Exception:warning = None@@ -538,20 +468,15 @@ class GatewayModelCommandsMixin:profile_home = Noneif getattr(getattr(self, "config", None), "multiplex_profiles", False):profile_home = self._resolve_profile_home_for_source(event.source)-- # --provider/--global/--session/--once/--refresh via the single-owner parser.- request = parse_model_switch_args(event.get_command_args().strip())+ request = parse_model_switch_args(event.get_command_args().strip()) # single-owner parserif request.errors:- # Gateway decoration: "❌ " prefix over the canonical error copy.- return f"❌ {request.error_messages()[0]}"- if request.force_refresh:- # Bust the disk cache so the picker shows live data.+ return f"❌ {request.error_messages()[0]}" # gateway decoration over canonical copy+ if request.force_refresh: # bust the disk cache so the picker shows live datawith contextlib.suppress(Exception):from hermes_cli.models import clear_provider_models_cacheclear_provider_models_cache()-- # Normalize the source the same way a message turn does (Telegram DM topic recovery) before- # deriving the override key, so the override is stored under the key the next turn reads.+ # Normalize like a message turn (Telegram DM topic recovery) before deriving the override+ # key, so the override lands under the key the next turn reads.source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)session_key = self._session_key_for_source(source)ctx = _ModelSwitchContext(@@ -559,9 +484,7 @@ class GatewayModelCommandsMixin:source=source,config_path=(profile_home or _hermes_home) / "config.yaml",persist_global=resolve_persist_behavior(- request.is_global,- request.is_session,- is_once=request.is_once,+ request.is_global, request.is_session, is_once=request.is_once,explicit_provider=request.explicit_provider,),one_turn=request.is_once,@@ -569,10 +492,8 @@ class GatewayModelCommandsMixin:)ctx.read_config()ctx.apply_override(self._session_model_overrides.get(session_key, {}))-if not request.target and not request.explicit_provider:return await self._model_listing_reply(event, ctx, profile_home)-result, error = await self._perform_model_switch(ctx, request.target, request.explicit_provider, source)if error is not None:return error@@ -588,8 +509,7 @@ class GatewayModelCommandsMixin:on the next message (avoids prompt-cache invalidation mid-session)."""from hermes_cli import codex_runtime_switch as crs- raw_args = event.get_command_args().strip() if event else ""- new_value, errors = crs.parse_args(raw_args)+ new_value, errors = crs.parse_args(event.get_command_args().strip() if event else "")if errors:return "❌ " + "\n❌ ".join(errors)try:@@ -603,10 +523,8 @@ class GatewayModelCommandsMixin:try:self._evict_cached_agent(self._session_key_for_source(event.source))except Exception:- logger.debug("could not evict cached agent after codex-runtime change",- exc_info=True)- prefix = "✓" if result.success else "✗"- return f"{prefix} {result.message}"+ logger.debug("could not evict cached agent after codex-runtime change", exc_info=True)+ return f"{'✓' if result.success else '✗'} {result.message}"async def _handle_personality_command(self, event: MessageEvent) -> str:"""Handle /personality — list or set a personality (hermes_cli.personality owns the state)."""@@ -625,7 +543,6 @@ class GatewayModelCommandsMixin:except Exception:config = {}personalities = available_personalities(config)-if not args:current = active_personality_name(config)lines = [t("gateway.personality.header"), t("gateway.personality.none_option")]@@ -636,15 +553,13 @@ class GatewayModelCommandsMixin:)lines.append(t("gateway.personality.usage"))return "\n".join(lines)-try:name, _new_prompt = resolve_personality(args, config)except ValueError:available = "`none`, " + ", ".join(f"`{n}`" for n in personalities)return t("gateway.personality.unknown", name=args.lower(), available=available)- # Persist the selection only — never agent.system_prompt (user-owned overlay). It lands in- # get_hermes_home()/config.yaml (the routed profile under multiplex) and the next turn- # re-resolves the prompt from it: no process-global state.+ # Persists the selection only (never agent.system_prompt, a user-owned overlay) into the+ # routed profile's config.yaml; the next turn re-resolves the prompt — no process-global state.if not persist_personality(name):return t("gateway.personality.save_failed", error="config write failed")if not name:@@ -660,8 +575,7 @@ class GatewayModelCommandsMixin:from hermes_cli.config import read_user_config_rawconfig_path = _gateway_config_home() / "config.yaml"try:- # Raw read: merged defaults must not be persisted back to the user's file.- user_config = read_user_config_raw(config_path)+ user_config = read_user_config_raw(config_path) # raw: never persist merged defaults*parents, leaf = key_path.split(".")_nested_dict(user_config, *parents)[leaf] = valueatomic_config_write(config_path, user_config)@@ -678,10 +592,7 @@ class GatewayModelCommandsMixin:def _apply_reasoning_selection(self, session_key: str, platform_key: str, value: str, persist_global: bool = False,) -> str:- """Apply a /reasoning argument (typed or picked) and return the reply.-- Single path shared by `/reasoning <arg>` and the choice picker so both match the parser.- """+ """Apply a /reasoning argument (typed or picked) and return the reply."""from hermes_constants import parse_reasoning_effortvalue = (value or "").strip().lower()@@ -712,37 +623,18 @@ class GatewayModelCommandsMixin:self._set_reasoning_override(session_key, parsed)return t("gateway.reasoning.set_session", effort=value)- def _reasoning_picker_choices(self, current_effort: str) -> list:- """Build the choice list for the interactive /reasoning picker."""- from hermes_constants import VALID_REASONING_EFFORTS-- choices = [{"value": "none", "label": t("gateway.reasoning.choice_none"), "is_current": current_effort == "none"}]- choices.extend({"value": level, "label": level, "is_current": level == current_effort} for level in VALID_REASONING_EFFORTS)- choices.extend(- {"value": v, "label": t(f"gateway.reasoning.choice_{v}"), "is_current": False}- for v in ("reset", "show", "hide")- )- return choices-async def _try_send_choice_picker(self, event: MessageEvent, session_key: str, title: str, choices: list, on_choice_selected,) -> bool:- """Send an interactive choice picker when the platform supports it.-- Mirrors the `/model` gate: capability is detected on the adapter *type*- (``send_choice_picker``); a failed send returns False (text fallback) instead of erroring.- """+ """Send an interactive choice picker when the adapter *type* supports it (the /model gate);+ a failed send returns False (text fallback) instead of erroring."""adapter = self._adapter_for_source(event.source)if adapter is None or getattr(type(adapter), "send_choice_picker", None) is None:return Falsetry:result = await adapter.send_choice_picker(- chat_id=event.source.chat_id,- title=title,- choices=choices,- session_key=session_key,- on_choice_selected=on_choice_selected,- metadata=self._reply_metadata(event),+ chat_id=event.source.chat_id, title=title, choices=choices, session_key=session_key,+ on_choice_selected=on_choice_selected, metadata=self._reply_metadata(event),)return bool(getattr(result, "success", False))except Exception as e:@@ -752,16 +644,15 @@ class GatewayModelCommandsMixin:async def _handle_reasoning_command(self, event: MessageEvent) -> Optional[str]:"""Handle /reasoning command — manage reasoning effort and display toggle."""from gateway.run import _platform_config_key+ from hermes_constants import VALID_REASONING_EFFORTSraw_args = event.get_command_args().strip()args, persist_global = self._parse_reasoning_command_args(raw_args)- # Normalize the source (Telegram DM topic recovery) before deriving the override key so- # storage matches the key the next message turn reads — same as /model.+ # Normalize (Telegram DM topic recovery) so the override key matches the next turn's._reasoning_source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)session_key = self._session_key_for_source(_reasoning_source)self._show_reasoning = self._load_show_reasoning()- # The session's effective model (session /model override wins over config default) so- # per-model reasoning_overrides display correctly.+ # Effective model (session /model override wins) so per-model reasoning_overrides display._session_model = str(((getattr(self, "_session_model_overrides", {}) or {}).get(session_key) or {}).get("model") or "")@@ -769,10 +660,8 @@ class GatewayModelCommandsMixin:source=event.source, session_key=session_key, model=_session_model,)platform_key = _platform_config_key(event.source.platform)- if raw_args:- # Typed argument path — same applier the picker uses.+ if raw_args: # typed path — same applier the picker usesreturn self._apply_reasoning_selection(session_key, platform_key, args, persist_global=persist_global)-rc = self._reasoning_configif rc is None:level, current_effort = t("gateway.reasoning.level_default"), "medium"@@ -787,12 +676,16 @@ class GatewayModelCommandsMixin:async def _on_reasoning_choice(_chat_id: str, value: str) -> str:return self._apply_reasoning_selection(session_key, platform_key, value)- # Interactive picker where supported (parity with /model); else the text status card.picker_sent = await self._try_send_choice_picker(event,session_key,title=t("gateway.reasoning.picker_title", level=level, scope=scope, display=display_state),- choices=self._reasoning_picker_choices(current_effort),+ choices=[+ {"value": "none", "label": t("gateway.reasoning.choice_none"), "is_current": current_effort == "none"},+ *({"value": lv, "label": lv, "is_current": lv == current_effort} for lv in VALID_REASONING_EFFORTS),+ *({"value": v, "label": t(f"gateway.reasoning.choice_{v}"), "is_current": False}+ for v in ("reset", "show", "hide")),+ ],on_choice_selected=_on_reasoning_choice,)if picker_sent:@@ -808,35 +701,28 @@ class GatewayModelCommandsMixin:label = t(label_key) if label_key else value.upper()self._service_tier = tierif persist and self._save_gateway_config_key("agent.service_tier", saved_value):- # Global write supersedes any session override.- self._set_session_service_tier_override(session_key, None, clear=True)+ self._set_session_service_tier_override(session_key, None, clear=True) # global winsself._evict_cached_agent(session_key)return t("gateway.fast.saved", label=label)- # Session override; also the fallback when the config write failed so the user's choice- # still applies (mirrors /reasoning --global).+ # Session override — also the fallback after a failed config write (as /reasoning --global).self._set_session_service_tier_override(session_key, tier)self._evict_cached_agent(session_key)return t("gateway.fast.session_only", label=label)async def _handle_fast_command(self, event: MessageEvent) -> Optional[str]:- """Handle /fast — mirror the CLI Priority Processing toggle in gateway chats.-- Session-scoped by default; ``--global`` persists agent.service_tier (parity with /model).- """+ """Handle /fast — the CLI Priority Processing toggle; session-scoped unless ``--global``+ (persists agent.service_tier, parity with /model)."""from gateway.run import _load_gateway_config, _resolve_gateway_modelfrom hermes_cli.models import model_supports_fast_mode- raw_args = event.get_command_args().strip().lower()- # The /reasoning arg parser strips --global (any position) and normalizes unicode dashes.- args, persist_global = self._parse_reasoning_command_args(raw_args)+ # The /reasoning parser strips --global (any position) and normalizes unicode dashes.+ args, persist_global = self._parse_reasoning_command_args(event.get_command_args().strip().lower())session_key = self._session_key_for_source(event.source)self._service_tier = self._resolve_session_service_tier(session_key=session_key)-if not model_supports_fast_mode(_resolve_gateway_model(_load_gateway_config())):return t("gateway.fast.not_supported")if args and args != "status":return self._apply_fast_selection(session_key, args, persist=persist_global)-mode = "fast" if self._service_tier == "priority" else (self._service_tier or "normal")status = {"fast": t("gateway.fast.status_fast"), "normal": t("gateway.fast.status_normal")}.get(mode, mode)diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex 81028372d2d..f4690503cc3 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -22,14 +22,11 @@ from gateway.config import Platformfrom gateway.platforms.base import EphemeralReply, MessageEvent, MessageTypefrom gateway.session import SessionSource, build_session_key, is_shared_multi_user_session-# Log-record parity with gateway/run.py and the origin module.-logger = logging.getLogger("gateway.run")+logger = logging.getLogger("gateway.run") # log-record parity with gateway/run.py-# Upper bound on the off-loop agent-resource cleanup during a /new or /reset. A stuck teardown must-# not block the event loop; past this the reset proceeds and the cleanup finishes (or leaks) in its-# worker thread.+# Bound on the off-loop agent cleanup during /new; past it the reset proceeds and the teardown+# finishes (or leaks) in its worker thread rather than blocking the event loop._RESET_CLEANUP_TIMEOUT_S = 30.0-# chat_type values whose session key is per-user (DM-like), incl. the unknown/blank case._DM_CHAT_TYPES = {"dm", "direct", "private", ""}@@ -45,11 +42,11 @@ def _sattr(obj, name: str) -> str:def _manual_compression_reply_lines(summary: dict, compressor, focus_topic) -> list[str]:- """Lines for the manual /compress confirmation, surfacing summariser/aux-model failures.+ """Manual /compress confirmation lines, surfacing summariser/aux-model failures.``_last_compress_aborted`` = no usable summary, messages unchanged. Provider exception text is- force-redacted at this UI boundary even when global redaction is off. A configured aux model- that failed and was recovered via main is an info note so the user can fix their config.+ force-redacted at this UI boundary even when global redaction is off; an aux model recovered+ via main is an info note so the user can fix their config."""lines = [f"🗜️ {summary['headline']}"]if focus_topic:@@ -103,8 +100,8 @@ def _reset_process_scoped_tool_state() -> None:def _branch_row(msg: dict) -> dict:- """Transcript row copied into a /branch child. Keeps the api_content sidecar so the branch's- first turn replays the parent's exact wire bytes (warm provider prompt cache), not a cold prefill."""+ """/branch child row; keeps the api_content sidecar so the branch's first turn replays the+ parent's exact wire bytes (warm provider prompt cache) instead of a cold prefill."""row = {k: msg.get(k) for k in _BRANCH_COPIED_FIELDS}row["role"] = msg.get("role", "user")row["tool_name"] = msg.get("tool_name") or msg.get("name")@@ -127,11 +124,11 @@ class GatewaySessionCommandsMixin:# ------------------------------------------------------------------ /new, /resetasync def _cleanup_old_agent_for_reset(self, session_key: str) -> None:- """Close the old agent's tool resources (sandboxes, browser daemons, subprocesses) before eviction.+ """Close the old agent's tool resources (sandboxes, browsers, subprocesses) before eviction.- _cleanup_agent_resources is blocking and this runs ON the event loop (confirm-button click),- so it is offloaded with a bounded timeout. wait_for cancels the await but not the worker- thread — a wedged teardown keeps running (or leaks); the reset proceeds either way.+ Blocking work on the event loop (confirm-button click) → offloaded with a bounded timeout.+ wait_for cancels the await, not the worker thread: a wedged teardown keeps running (or+ leaks); the reset proceeds either way."""_old_agent = self._cached_agent_for(session_key)if _old_agent is None:@@ -158,17 +155,13 @@ class GatewaySessionCommandsMixin:async def _fire_session_reset_hooks(self, source: SessionSource, session_key: str, old_sid, new_sid) -> None:- """Session-boundary hooks: plugin finalize (off-loop + bounded), session:end/reset, on_session_reset."""+ """Session-boundary hooks: plugin finalize (off-loop + bounded — trace exports can block+ arbitrarily), then session:end and session:reset."""platform_value = source.platform.value if source.platform else ""- # Finalize hooks can block arbitrarily (observability trace exports) and this handler runs- # on the gateway event loop (see GatewayRunner._finalize_session_off_loop).with contextlib.suppress(Exception):await self._finalize_session_off_loop(- session_id=old_sid,- platform=platform_value,- reason="new_session",- old_session_id=old_sid,- new_session_id=new_sid,+ session_id=old_sid, platform=platform_value, reason="new_session",+ old_session_id=old_sid, new_session_id=new_sid,)hook_payload = {"platform": platform_value, "user_id": source.user_id, "session_key": session_key}await self.hooks.emit("session:end", dict(hook_payload))@@ -179,12 +172,9 @@ class GatewaySessionCommandsMixin:try:from hermes_cli.lifecycle import invoke_hook as _invoke_hook_invoke_hook(- "on_session_reset",- session_id=new_sid,- platform=source.platform.value if source.platform else "",- reason="new_session",- old_session_id=old_sid,- new_session_id=new_sid,+ "on_session_reset", session_id=new_sid,+ platform=source.platform.value if source.platform else "", reason="new_session",+ old_session_id=old_sid, new_session_id=new_sid,)except Exception:pass@@ -198,22 +188,17 @@ class GatewaySessionCommandsMixin:# guarded release (old generation) returns False and would leave a zombie slot that silently# drops all later messages. Idempotent, so the run's finally calling it again is harmless.self._release_running_agent_state(session_key)-# Snapshot the old entry so on_session_finalize can report the expiring session id.old_entry = self.session_store._entries.get(session_key)await self._cleanup_old_agent_for_reset(session_key)self._evict_cached_agent(session_key)- # Conversation boundary: clear ALL conversation-scoped per-session state (model/reasoning- # overrides, one-turn restores, model notes, last-resolved cache, /queue overflow) +- # security state in one funnel call. See _CONVERSATION_SCOPED_STATE in gateway/run.py.+ # Conversation boundary: ALL conversation-scoped per-session state + security state in one+ # funnel call (see _CONVERSATION_SCOPED_STATE in gateway/run.py).self._clear_conversation_scope(session_key, reason="session_reset")-- # The old conversation's in-flight async delegations end WITH it: once the session id rotates- # their completions have no live owner (orphaned payload on the shared queue, wasted tokens).- # Interrupt by expiring durable session id (parent_session_id), routing key as legacy fallback.+ # In-flight async delegations end WITH the conversation: once the id rotates their+ # completions have no live owner. Expire by durable id, routing key as legacy fallback.try:from tools.async_delegation import interrupt_for_session-interrupt_for_session(session_key=session_key,parent_session_id=str(getattr(old_entry, "session_id", "") or ""),@@ -228,34 +213,28 @@ class GatewaySessionCommandsMixin:await self._fire_session_reset_hooks(source, session_key, _old_sid, new_entry.session_id if new_entry else None)-- # Session config info for the user, scoped to the profile serving this source so a- # multiplexed /new banner reports the profile's model, not the base config's.+ # Scoped to the profile serving this source so a multiplexed /new banner reports the+ # profile's model, not the base config's.try:session_info = await asyncio.to_thread(self._reset_notice_session_info, source)except Exception:session_info = ""-if new_entry:default_header = t("gateway.reset.header_default")- else:- # No existing session, just create one+ else: # no existing session: create onenew_entry = await self.async_session_store.get_or_create_session(source, force_new=True)default_header = t("gateway.reset.header_new")header = await asyncio.to_thread(self._telegram_topic_new_header, source) or default_header-_title_arg = event.get_command_args().strip()if _title_arg and self._session_db and new_entry:header = await self._reset_titled_header(header, new_entry.session_id, _title_arg)-- # Inside a Telegram DM topic lane, rewrite the (chat_id, thread_id) → session_id binding so- # the next message uses the fresh session instead of switching back to the old one.+ # Telegram DM topic lane: rebind (chat_id, thread_id) → session_id so the next message uses+ # the fresh session instead of switching back to the old one.if await asyncio.to_thread(self._is_telegram_topic_lane, source) and new_entry is not None:try:await asyncio.to_thread(self._record_telegram_topic_binding, source, new_entry)except Exception:logger.debug("Failed to rebind Telegram topic after /new", exc_info=True)-self._invoke_session_reset_lifecycle_hook(source, _old_sid, new_entry.session_id if new_entry else None)@@ -264,12 +243,11 @@ class GatewaySessionCommandsMixin:_tip_line = t("gateway.reset.tip", tip=get_random_tip())except Exception:_tip_line = ""- if session_info:- return EphemeralReply(f"{header}\n\n{session_info}{_tip_line}")- return EphemeralReply(f"{header}{_tip_line}")+ body = f"{header}\n\n{session_info}" if session_info else header+ return EphemeralReply(f"{body}{_tip_line}")async def _reset_titled_header(self, header: str, session_id: str, title_arg: str) -> str:- """Apply ``/new <title>``: titled header on success, else the header plus a rejection note."""+ """``/new <title>``: titled header on success, else the header plus a rejection note."""from hermes_state import SessionDBnote = ""try:@@ -285,8 +263,7 @@ class GatewaySessionCommandsMixin:note = t("gateway.reset.title_error_untitled", error=str(e))except Exception:pass- elif not note:- # sanitize_title returned empty (whitespace-only / unprintable)+ elif not note: # sanitize_title returned empty (whitespace-only / unprintable)note = t("gateway.reset.title_empty_untitled")return header + note@@ -298,19 +275,17 @@ class GatewaySessionCommandsMixin:if callable(lookup):entry = lookup(self.session_store, session_id)return getattr(entry, "origin", None) if entry is not None else None- # Test doubles and older stores may not expose the public lookup helper. Keep the Matrix- # resume guard fail-closed if no origin can be resolved.+ # Test doubles / older stores lack the public lookup; fail closed when nothing resolves.entries = getattr(self.session_store, "_entries", {}) or {}- for entry in entries.values():- if getattr(entry, "session_id", None) == session_id:- return getattr(entry, "origin", None)- return None+ return next(+ (getattr(e, "origin", None) for e in entries.values() if getattr(e, "session_id", None) == session_id),+ None,+ )@staticmethoddef _same_matrix_room(current: SessionSource, origin: Optional[SessionSource]) -> bool:- # thread_id is part of the session key and Matrix scopes a turn to the current room/thread,- # so a live session in another thread of the SAME room is a DIFFERENT session. Non-threaded- # rooms compare "" == "" unchanged.+ # thread_id is part of the session key, so another thread of the SAME room is a DIFFERENT+ # session; non-threaded rooms compare "" == "".return (origin is not Noneand origin.platform == Platform.MATRIX@@ -322,29 +297,27 @@ class GatewaySessionCommandsMixin:def _same_origin_chat(self, current: SessionSource, origin: Optional[SessionSource]) -> bool:"""Platform-agnostic counterpart to ``_same_matrix_room``.- Per-participant sessions (``build_session_key`` with the default ``group_sessions_per_user``)- must be participant-scoped here too, else a co-member could resume another member's live- session (IDOR). Only an explicitly shared group/thread (``is_shared_multi_user_session``) shares.+ Per-participant sessions must be participant-scoped here too, else a co-member could resume+ another member's live session (IDOR); only an explicitly shared group/thread shares."""if origin is None or current is None:return Falseif origin.platform != current.platform or origin.chat_id != current.chat_id:return False- # thread_id is part of the session key for every chat type, so threads of the same parent- # chat are DIFFERENT sessions; require thread equality before any sharing logic.+ # thread_id is part of every session key: threads of one chat are DIFFERENT sessions.if _sattr(current, "thread_id") != _sattr(origin, "thread_id"):return Falseif _sattr(current, "chat_type").lower() in _DM_CHAT_TYPES:- # DM: an equal non-empty chat_id IS the session key. build_session_key falls back to the- # participant (``user_id_alt or user_id`` — Signal/Feishu key on user_id_alt) only when- # there is NO chat_id; mirror that and fail closed on a missing/different participant.+ # An equal non-empty chat_id IS the DM key. build_session_key falls back to the+ # participant (``user_id_alt or user_id`` — Signal/Feishu key on alt) only without a+ # chat_id; mirror that and fail closed on a missing/different participant.if _sattr(current, "chat_id"):return Truecur_pid = str(current.user_id_alt or current.user_id or "")org_pid = str(origin.user_id_alt or origin.user_id or "")return bool(cur_pid) and cur_pid == org_pid- # Non-DM: a shared key is one session for every participant; a per-user key must compare the- # participant it is built from, failing closed when either side lacks one.+ # Non-DM: a shared key is one session for everyone; a per-user key compares the participant+ # it is built from, failing closed when either side lacks one.if self._is_shared_session_source(current):return Truecur_pid = current.user_id_alt or current.user_id@@ -352,22 +325,18 @@ class GatewaySessionCommandsMixin:return bool(cur_pid and org_pid) and cur_pid == org_piddef _is_shared_session_source(self, source: SessionSource) -> bool:- """Whether *source*'s session key is shared by every participant (not per-user).-- Mirrors build_session_key's isolation rules exactly, so the guards stay in lock-step with the key.- """+ """Whether *source*'s session key is shared by every participant (not per-user); mirrors+ build_session_key's isolation rules so the guards stay in lock-step with the key."""return is_shared_multi_user_session(- source,- group_sessions_per_user=getattr(self.config, "group_sessions_per_user", True),+ source, group_sessions_per_user=getattr(self.config, "group_sessions_per_user", True),thread_sessions_per_user=getattr(self.config, "thread_sessions_per_user", False),)def _resume_caller_is_admin(self, source: SessionSource) -> bool:- """Whether *source* is an EXPLICITLY-configured admin allowed cross-origin /resume or /sessions.+ """Whether *source* is an EXPLICITLY-configured admin (cross-origin /resume, /sessions).- Stricter than ``SlashAccessPolicy.is_admin()``, which returns True for every allowed caller- when slash gating is DISABLED; cross-origin DATA ACCESS needs a real configured admin, else- the default (no admin list) config would make every caller cross-origin-capable (IDOR).+ Stricter than ``SlashAccessPolicy.is_admin()``, which is True for every caller when slash+ gating is DISABLED — the default config would make everyone cross-origin-capable (IDOR)."""try:from gateway.slash_access import policy_for_source@@ -380,10 +349,9 @@ class GatewaySessionCommandsMixin:def _persisted_row_proves_owner(self, source: SessionSource, row: dict) -> bool:"""Whether a persisted (inactive) session *row* provably belongs to *source*'s session key.- Rows once stored only source + user_id, so a same-user row could belong to a DIFFERENT chat;- the persisted chat/thread origin closes that gap and legacy NULL rows fail closed. The table- has no user_id_alt column, so an alt-keyed (Signal/Feishu) caller can never be proven by- row_uid == caller_uid alone (CWE-639). Same platform alone is never ownership proof.+ Rows once stored only source + user_id, so the persisted chat/thread origin is compared too+ and legacy NULL rows fail closed. The table has no user_id_alt column, so an alt-keyed+ (Signal/Feishu) caller is never proven by user_id alone (CWE-639)."""caller_src = source.platform.value if source.platform else Nonerow_src = row.get("source")@@ -399,17 +367,15 @@ class GatewaySessionCommandsMixin:caller_chat = _sattr(source, "chat_id")caller_keys_on_alt = bool(_sattr(source, "user_id_alt"))if _sattr(source, "chat_type").lower() in _DM_CHAT_TYPES:- # DMs key on user_id; a no-chat_id DM is keyed PURELY on the participant (alt-keyed- # caller fails closed); with chat_id on both sides equality is the DM key.+ # A no-chat_id DM is keyed PURELY on the participant (alt-keyed caller fails closed).if caller_keys_on_alt and not (row_chat and caller_chat):return Falsereturn bool(row_uid) and row_uid == caller_uid and row_chat == caller_chat- # Non-DM: the key includes chat_id — both sides must carry it and match (a legacy NULL-chat- # row fails closed even when both normalize to "").+ # Non-DM: both sides must carry chat_id and match (legacy NULL-chat rows fail closed).if not (row_chat and caller_chat and row_chat == caller_chat):return False- # A SHARED group/thread is one session for every participant: same-chat proof suffices (a- # user-id check would block co-members). A per-user key still requires the same owner.+ # A SHARED group/thread is one session for everyone: same-chat proof suffices (a user-id+ # check would block co-members). A per-user key still requires the same owner.if self._is_shared_session_source(source):return Trueif caller_keys_on_alt:@@ -419,16 +385,14 @@ class GatewaySessionCommandsMixin:async def _resume_target_allowed(self, source: SessionSource, target_id: str, allow_override: bool = False) -> bool:- """Whether *source* may resume the persisted session *target_id*.+ """Whether *source* may resume session *target_id* (IDOR guard for every adapter).- Generalizes the Matrix-only room guard to every adapter so a caller cannot bind to another- user's/room's session (IDOR). Uses the live origin when the target is active, else the DB- row must PROVE ownership or fail closed. Admin ``--all`` bypasses.+ The live origin decides when the target is active; otherwise the DB row must PROVE+ ownership or fail closed. Admin ``--all`` bypasses."""if allow_override and self._resume_caller_is_admin(source):return True- # The live origin decides only when it resolves to a real SessionSource; a store that can't- # resolve it (or a lookup error) falls through to the deterministic DB scoping.+ # Only a real SessionSource origin decides; unresolvable/error falls through to DB scoping.try:origin = self._gateway_session_origin_for_id(target_id)except Exception:@@ -444,12 +408,8 @@ class GatewaySessionCommandsMixin:async def _resume_row_visible(self, source: SessionSource, row: dict, allow_all: bool) -> bool:- """Whether a titled-session listing *row* belongs to the caller's origin.-- Prevents cross-origin enumeration of session ids/previews via the numbered /resume list;- keeps Matrix room-scoping, scopes every other platform to the caller unless admin ``--all``.- Cross-room enumeration is cross-ORIGIN data access, so ``--all`` needs a configured admin.- """+ """Whether a listing *row* belongs to the caller's origin (blocks cross-origin enumeration of+ ids/previews); Matrix is room-scoped, ``--all`` needs a configured admin everywhere."""if allow_all and self._resume_caller_is_admin(source):return Truesid = str(row.get("id") or "")@@ -461,7 +421,7 @@ class GatewaySessionCommandsMixin:async def _handle_retry_command(self, event: MessageEvent) -> str:"""Handle /retry command - re-send the last user message."""- # The canonical projection excludes bookkeeping rows (role=user + display_kind) and pure+ # The canonical projection skips bookkeeping rows (role=user + display_kind) and pure# handoffs while still recognizing a real ask embedded in a compaction carrier.from agent.context_compressor import (history_before_user_originated_turn,@@ -479,9 +439,8 @@ class GatewaySessionCommandsMixin:)if last_user_idx is None:return t("gateway.retry.no_previous")-- # Resolve the live text and the scaffold-preserving prefix before any transcript write.- # Messaging retries cannot reconstruct attachments; reject media/unknown content untouched.+ # Resolve text + scaffold-preserving prefix BEFORE any write; messaging retries cannot+ # reconstruct attachments, so media/unknown content is rejected with the session untouched.try:truncated, live_view = history_before_user_originated_turn(history, last_user_idx)last_user_msg = retryable_user_text(live_view.get("content"))@@ -490,10 +449,9 @@ class GatewaySessionCommandsMixin:return f"Cannot retry that message safely: {exc}"if handoff is not None:- # A composite carrier is one physical row holding both the retained summary and the live- # ask: the carrier-aware rewind archives that row/tail and inserts its pure scaffold- # atomically, reselecting the latest carrier on the same snapshot so a concurrent newer- # turn can never be removed while stale text is resent.+ # Composite carrier (one row = retained summary + live ask): the carrier-aware rewind+ # archives it and inserts the pure scaffold atomically, reselecting the latest carrier+ # on the same snapshot so a concurrent newer turn is never removed for stale text.try:rewind_result = await self.async_session_store.rewind_session(session_entry.session_id, 1, require_retryable_composite=True,@@ -503,28 +461,22 @@ class GatewaySessionCommandsMixin:if rewind_result is None:return "Retry failed; transcript was not changed."last_user_msg = rewind_result["target_text"]- # After in-place compaction the pre-compaction transcript lives on as active=0/compacted=1- # rows under this id; active_only preserves that archive.+ # active_only preserves the active=0/compacted=1 archive left by in-place compaction.elif not await self.async_session_store.rewrite_transcript(session_entry.session_id, truncated, active_only=True, reject_active_turn_lease=True,):return "Retry failed; transcript was not changed."session_entry.last_prompt_tokens = 0 # transcript was truncated-retry_event = MessageEvent(- text=last_user_msg,- message_type=MessageType.TEXT,- source=source,- raw_message=event.raw_message,- channel_prompt=event.channel_prompt,+ text=last_user_msg, message_type=MessageType.TEXT, source=source,+ raw_message=event.raw_message, channel_prompt=event.channel_prompt,)return await self._handle_message(retry_event)async def _handle_undo_command(self, event: MessageEvent) -> str:"""Handle /undo [N] — back up N user turns (default 1), soft-deleting the truncated rows and- echoing the backed-up text. Evicts the cached agent so the next message rebuilds context- from the active-only transcript (gateway analogue of the CLI's history surgery).- """+ echoing the backed-up text; evicts the cached agent so the next turn rebuilds from the+ active-only transcript."""source = event.sourcen = 1raw_args = event.get_command_args().strip()@@ -533,7 +485,6 @@ class GatewaySessionCommandsMixin:n = max(1, int(raw_args.split()[0]))except (ValueError, IndexError):return t("gateway.undo.invalid_count", arg=raw_args.split()[0])-session_entry = await self.async_session_store.get_or_create_session(source)result = await self.async_session_store.rewind_session(session_entry.session_id, n)if result is None:@@ -543,64 +494,43 @@ class GatewaySessionCommandsMixin:self._evict_cached_agent(build_session_key(source))except Exception as e:logger.debug("undo: cached-agent eviction skipped: %s", e)-target_text = result["target_text"]preview = target_text[:200] + "..." if len(target_text) > 200 else target_textreturn t(- "gateway.undo.removed",- turns=result["turns_undone"],- count=result["rewound_count"],+ "gateway.undo.removed", turns=result["turns_undone"], count=result["rewound_count"],preview=preview,)# --------------------------------------------------------------------- /compressasync def _handle_compress_command(self, event: MessageEvent) -> str:- """Profile-scoping wrapper around manual /compress.-- Multiplexed gateways resolve credentials through the fail-closed per-profile secret scope;- slash dispatch (unlike ``_run_agent``) does not install it, so an unscoped /compress would- raise ``UnscopedSecretError``. Single-profile gateways skip this.- """+ """Profile-scoping wrapper around manual /compress: multiplexed gateways resolve credentials+ through the fail-closed per-profile secret scope, which slash dispatch (unlike ``_run_agent``)+ does not install — unscoped, /compress would raise ``UnscopedSecretError``."""if not getattr(getattr(self, "config", None), "multiplex_profiles", False):return await self._handle_compress_command_inner(event)-from gateway.run import _profile_runtime_scope-- profile_home = self._resolve_profile_home_for_source(event.source)- with _profile_runtime_scope(profile_home):+ with _profile_runtime_scope(self._resolve_profile_home_for_source(event.source)):return await self._handle_compress_command_inner(event)- async def _compress_codex_app_server_session(- self, session_key: str, session_id: str- ) -> str:- """Manual /compress for codex_app_server sessions.-- Compacts the LIVE cached agent's app-server thread (``thread/compact/start``, ``force=True``- bypasses the ``codex_app_server_auto`` gate) and keeps the agent cached. Never builds a- temporary agent or rewrites the mirror: neither can shrink the server-side thread.- """+ async def _compress_codex_app_server_session(self, session_key: str, session_id: str) -> str:+ """Manual /compress for codex_app_server sessions: compacts the LIVE cached agent's+ app-server thread (``force=True`` bypasses the ``codex_app_server_auto`` gate) and keeps it+ cached. A temporary agent or a mirror rewrite cannot shrink the server-side thread."""from gateway.run import _AGENT_PENDING_SENTINELagent = self._cached_agent_for(session_key)- if (- agent is None- or agent is _AGENT_PENDING_SENTINEL- or getattr(agent, "_codex_session", None) is None- ):+ if agent is None or agent is _AGENT_PENDING_SENTINEL or getattr(agent, "_codex_session", None) is None:return ("🗜️ Nothing to compact: this session runs on the Codex ""app-server runtime, whose context lives in a Codex-owned ""thread that only exists while the agent is active. Send a ""message first, then /compress — or /reset to start fresh.")-compressor = getattr(agent, "context_compressor", None)count_before = getattr(compressor, "compression_count", 0)try:- await self._run_in_executor_with_context(- lambda: agent._compress_context([], "", force=True)- )+ await self._run_in_executor_with_context(lambda: agent._compress_context([], "", force=True))except Exception as exc:return t("gateway.compress.failed", error=exc)if getattr(compressor, "compression_count", 0) > count_before:@@ -616,10 +546,8 @@ class GatewaySessionCommandsMixin:)async def _handle_compress_command_inner(self, event: MessageEvent) -> str:- """Handle /compress command -- manually compress conversation context.-- Optional ``/compress <focus>`` tells the summariser what to preserve, discarding the rest.- """+ """Handle /compress -- manually compress conversation context; ``/compress <focus>`` tells+ the summariser what to preserve."""from hermes_cli.partial_compress import extract_compress_flags, parse_partial_compress_argssource = event.source@@ -627,17 +555,14 @@ class GatewaySessionCommandsMixin:history = await self.async_session_store.load_transcript(session_entry.session_id)if not history or len(history) < 4:return t("gateway.compress.not_enough")-- # Strip --preview/--dry-run/--aggressive before positional parsing so the flags coexist with- # the boundary-aware "here [N]" (partial) and focus-topic (full) forms.- _raw_args = (event.get_command_args() or "").strip()- _raw_args, _preview, _aggressive = extract_compress_flags(_raw_args)+ # Flags are stripped before positional parsing so they coexist with the boundary-aware+ # "here [N]" (partial) and focus-topic (full) forms.+ _raw_args, _preview, _aggressive = extract_compress_flags((event.get_command_args() or "").strip())partial, keep_last, focus_topic = parse_partial_compress_args(_raw_args)-_agg_note = ""if _aggressive:- # LLM-free hard truncation is not supported on this surface — it would need its own- # transcript-persistence branch outside the guarded _compress_context rotation machinery.+ # LLM-free hard truncation would need its own persistence branch outside the guarded+ # _compress_context rotation machinery — unsupported on this surface._agg_note = t("gateway.compress.aggressive_unsupported")if not _preview:return _agg_note@@ -665,65 +590,54 @@ class GatewaySessionCommandsMixin:)session_key = self._session_key_for_source(source)- # Preserve the platform + stable gateway session identity of a normal turn so external- # context engines bind this agent to the original conversation, not a default "cli" host.+ # Platform + stable gateway session key bind this agent (for external context engines) to+ # the original conversation, not a default "cli" host.platform_key = _platform_config_key(source.platform) if source.platform else Nonemodel, runtime_kwargs = self._resolve_session_agent_runtime(source=source, session_key=session_key)if str(runtime_kwargs.get("api_mode") or "").lower() == "codex_app_server":- # The model's context is the server-side thread owned by the LIVE cached agent; a- # temporary agent has none (and finally-eviction would destroy the real context).+ # Context lives in the server-side thread of the LIVE cached agent; a temporary agent+ # has none (and finally-eviction would destroy the real context).return await self._compress_codex_app_server_session(session_key, session_entry.session_id)if not runtime_kwargs.get("api_key"):return t("gateway.compress.no_provider")-# FULL transcript (tool results included), like auto-compress: user/assistant-only starves# tool-result pruning and can trip the protect-first/last early-return.msgs = [m for m in history if m.get("role") in {"user", "assistant", "tool"}]- # Boundary-aware split: only the head is summarized; the most recent `keep_last` exchanges- # stay verbatim. The split snaps the tail to a user-turn start so role alternation holds.+ # Partial: only the head is summarized; the tail snaps to a user-turn start so role+ # alternation holds after rejoin.head, tail = msgs, []if partial:head, tail = split_history_for_partial_compress(msgs, keep_last)if not tail: # degenerate split — fall back to full compressionpartial, head = False, msgs-- # Assign directly (not setdefault: a resolver value would be a stale placeholder, and it- # avoids duplicate-kwarg TypeError); platform only when known so None -> "cli" holds.+ # Assign, not setdefault (a resolver value would be a stale placeholder); platform only when+ # known so None -> "cli" holds.if platform_key is not None:runtime_kwargs["platform"] = platform_keyruntime_kwargs["gateway_session_key"] = session_keytmp_agent = await self._build_manual_compression_agent(session_entry.session_id, model, runtime_kwargs)try:- # Estimate with system prompt + tool schemas so the figure reflects real request- # pressure; computed after tmp_agent is built so _cached_system_prompt/tools exist.+ # Estimate with system prompt + tool schemas (real request pressure); needs the built agent._sys_prompt = getattr(tmp_agent, "_cached_system_prompt", "") or ""_tools = getattr(tmp_agent, "tools", None) or Noneapprox_tokens = estimate_request_tokens_rough(msgs, system_prompt=_sys_prompt, tools=_tools)-compressor = tmp_agent.context_compressorif not compressor.has_content_to_compress(head):return t("gateway.compress.nothing_to_do")-- # Not a bare run_in_executor: the profile secret scope is a contextvar and the default-- # executor hop would drop it, failing the aux-client credential resolution closed.+ # Not a bare run_in_executor: the profile secret scope is a contextvar the default+ # executor hop would drop, failing aux-client credential resolution closed.compressed, _ = await self._run_in_executor_with_context(lambda: tmp_agent._compress_context(- head,- "",- approx_tokens=approx_tokens,- focus_topic=focus_topic,- force=True,+ head, "", approx_tokens=approx_tokens, focus_topic=focus_topic, force=True,defer_context_engine_notification=True,))- # Unchanged because a concurrent compression lock is held: say so instead of the- # misleading "No changes from compression" no-op text.+ # A held compression lock returns unchanged; say so instead of the misleading no-op text._lock_skipped = getattr(tmp_agent, "_compression_skipped_due_to_lock", None)if _lock_skipped is True or isinstance(_lock_skipped, str):from agent.manual_compression_feedback import describe_compression_lock_skipreturn describe_compression_lock_skip(_lock_skipped)-if partial and tail:compressed = rejoin_compressed_head_and_tail(compressed, tail)await self._persist_manual_compression(tmp_agent, session_entry, source, compressed)@@ -734,9 +648,8 @@ class GatewaySessionCommandsMixin:)finally:finalize_context_engine_compression_notification(tmp_agent, committed=False)- # Evict so the next turn rebuilds the system prompt from current files (SOUL.md, memory).- self._evict_cached_agent(session_key)- # Off-loop + bounded: temporary-agent teardown can block on subprocess/network/SQLite.+ self._evict_cached_agent(session_key) # next turn rebuilds the prompt from current files+ # Off-loop + bounded: teardown can block on subprocess/network/SQLite.await self._cleanup_agent_resources_off_loop(tmp_agent, context="manual compression")return "\n".join(_manual_compression_reply_lines(summary, compressor, focus_topic))@@ -747,9 +660,8 @@ class GatewaySessionCommandsMixin:from hermes_cli.config import load_config as _load_cfgfrom utils import is_truthy_value as _is_truthy- # This helper runs outside the live session's fully initialized prompt environment and- # _compress_context may persist its cached system prompt — restore the exact live-session- # prompt so provider blocks are retained.+ # _compress_context may persist its cached system prompt, and this agent runs outside the+ # live session's prompt environment — restore the exact live prompt so provider blocks stay.session_row = Noneget_session = getattr(self._session_db, "get_session", None)if callable(get_session):@@ -765,43 +677,33 @@ class GatewaySessionCommandsMixin:exc_info=True,)- # Lossy rewrite: when compression.checkpoint_required is on, the memory provider must be- # loaded so _compress_context() can write the pre-compression checkpoint; otherwise keep- # the historical fast path (no provider init).+ # compression.checkpoint_required needs the memory provider loaded so _compress_context()+ # can write the pre-compression checkpoint; otherwise keep the fast path (no provider init)._checkpoint_required = _is_truthy(((_load_cfg() or {}).get("compression") or {}).get("checkpoint_required"),default=False,)tmp_agent = AIAgent(- **runtime_kwargs,- model=model,- max_iterations=4,- quiet_mode=True,- skip_memory=not _checkpoint_required,- enabled_toolsets=["memory"],- session_id=session_id,- session_db=getattr(self._session_db, "_db", self._session_db),+ **runtime_kwargs, model=model, max_iterations=4, quiet_mode=True,+ skip_memory=not _checkpoint_required, enabled_toolsets=["memory"],+ session_id=session_id, session_db=getattr(self._session_db, "_db", self._session_db),)_seed_hygiene_system_prompt(tmp_agent, session_row)- # Keep the real source platform during construction so external context engines bind- # correctly; if compression has to rebuild the prompt, stamp that provider-less fallback as- # stale for the next real gateway turn.+ # Real platform during construction (context engines bind correctly); afterwards a prompt+ # rebuilt by compression is stamped as the provider-less fallback, stale for the next turn.tmp_agent.platform = _GATEWAY_HYGIENE_PLATFORMtmp_agent._print_fn = lambda *a, **kw: None- # close() must not end the newly rotated session — the gateway entry now points at the new- # id and must remain open for the next user turn.+ # close() must not end the rotated session the gateway entry now points at.tmp_agent._end_session_on_close = Falsereturn tmp_agentasync def _persist_manual_compression(self, tmp_agent, session_entry, source, compressed) -> None:"""Commit a manual /compress result to the session store.- _compress_context either rotated (new continuation id — write compressed messages into the- NEW session so the original stays searchable) or compacted in place (same id, transcript- replaced). Persist BEFORE repointing the live session: a failed write is fatal so old history- stays reachable. Only rewrite when rotation produced a NEW id: in-place compaction already- archived + inserted rows and rewrite_transcript() (active_only=False) would DELETE the- archived turns; an unchanged id without in-place means rotation FAILED.+ Rotation (new continuation id) writes the compressed messages into the NEW session so the+ original stays searchable; persist BEFORE repointing so a failed write is fatal and old+ history stays reachable. In-place compaction already archived + inserted rows, and a rewrite+ would DELETE the archive; an unchanged id without in-place means rotation FAILED."""new_session_id = tmp_agent.session_idif new_session_id != session_entry.session_id:@@ -812,8 +714,7 @@ class GatewaySessionCommandsMixin:session_entry.session_id = new_session_idawait self.async_session_store._save()await asyncio.to_thread(- self._sync_telegram_topic_binding,- source, session_entry, reason="compress-command",+ self._sync_telegram_topic_binding, source, session_entry, reason="compress-command",)elif not getattr(tmp_agent, "_last_compaction_in_place", False):logger.warning(@@ -822,7 +723,6 @@ class GatewaySessionCommandsMixin:"preserving original transcript instead of overwriting ""it (#44794).")- # Transcript changed — the stored token count is stale.await self.async_session_store.update_session(session_entry.session_key, last_prompt_tokens=0)# ------------------------------------------------------------------------ /topic@@ -835,15 +735,12 @@ class GatewaySessionCommandsMixin:if not self._session_db:return self._session_db_unavailable_reply()- # /topic activates multi-session mode and mutates SQLite side tables; routes already- # authorized the message, but defense in depth against unauthorized (non-allowlist) senders.- auth_fn = getattr(self, "_is_user_authorized", None)- if callable(auth_fn):- try:- if not auth_fn(source):- return t("gateway.topic.unauthorized")- except Exception:- logger.debug("Topic auth check failed", exc_info=True)+ # Defense in depth: /topic mutates SQLite side tables, so re-check the allowlist here.+ try:+ if not self._is_user_authorized(source):+ return t("gateway.topic.unauthorized")+ except Exception:+ logger.debug("Topic auth check failed", exc_info=True)args = event.get_command_args().strip()if args.lower() in {"help", "?", "-h", "--help"}:@@ -862,8 +759,7 @@ class GatewaySessionCommandsMixin:blocked_key = "gateway.topic.topics_disabled"elif capabilities.get("allows_users_to_create_topics") is False:blocked_key = "gateway.topic.topics_user_disallowed"- if blocked_key:- # Debounce the BotFather screenshot: don't re-send on every /topic while blocked.+ if blocked_key: # debounced BotFather screenshotif self._should_send_telegram_capability_hint(source):await self._send_telegram_topic_setup_image(source)return t(blocked_key)@@ -871,9 +767,7 @@ class GatewaySessionCommandsMixin:profile_name = self._telegram_topic_profile_name(source)try:await self._session_db.enable_telegram_topic_mode(- chat_id=str(source.chat_id),- user_id=str(source.user_id),- profile_name=profile_name,+ chat_id=str(source.chat_id), user_id=str(source.user_id), profile_name=profile_name,has_topics_enabled=capabilities.get("has_topics_enabled"),allows_users_to_create_topics=capabilities.get("allows_users_to_create_topics"),)@@ -886,8 +780,7 @@ class GatewaySessionCommandsMixin:return await self._telegram_topic_root_status_message(source)try:binding = await self._session_db.get_telegram_topic_binding(- chat_id=str(source.chat_id),- thread_id=str(source.thread_id),+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),profile_name=profile_name,)except Exception:@@ -901,8 +794,7 @@ class GatewaySessionCommandsMixin:except Exception:title = Nonereturn t(- "gateway.topic.bound_status",- label=title or t("gateway.topic.untitled_session"),+ "gateway.topic.bound_status", label=title or t("gateway.topic.untitled_session"),session_id=session_id,)@@ -934,23 +826,19 @@ class GatewaySessionCommandsMixin:session_id = session_entry.session_idif not self._session_db:return "Session database not available."- # The filename is echoed to the platform only — never trust path separators from chat input.+ # Never trust path separators from chat input; the filename is only echoed to the platform.filename = parts[1] if len(parts) > 1 else default_save_filename(session_id, fmt)filename = os.path.basename(filename) or default_save_filename(session_id, fmt)-- # self._session_db is an AsyncSessionDB — every forwarded call is awaited.export_data = await self._session_db.export_session(session_id)if not export_data:return f"No stored messages found for this session ({session_id})."if redact:from hermes_cli.session_export_md import redact_session_dataexport_data = redact_session_data(export_data)-temp_dir = tempfile.mkdtemp(prefix="hermes_save_")temp_path = os.path.join(temp_dir, filename)try:- # Off-loop: rendering a long session and writing it are CPU/disk-bound and scale with- # transcript size (multi-MB); inline they stall every other chat on the event loop.+ # Off-loop: render + write scale with transcript size (multi-MB) and would stall the loop.def _render_and_write() -> None:rendered = render_session_for_save(export_data, fmt)with open(temp_path, "w", encoding="utf-8") as f:@@ -961,9 +849,7 @@ class GatewaySessionCommandsMixin:if not adapter:return "Platform adapter not found to send the document."await adapter.send_document(- chat_id=source.chat_id,- file_path=temp_path,- caption=f"Session export: {filename}",+ chat_id=source.chat_id, file_path=temp_path, caption=f"Session export: {filename}",file_name=filename,)return "Export complete."@@ -984,21 +870,16 @@ class GatewaySessionCommandsMixin:return self._session_db_unavailable_reply()# The session may only exist in session_store so far (first command in a new session).+ # The messaging origin is persisted so a later /resume of this titled-but-inactive session+ # can prove it belongs to the caller's chat/thread (IDOR scoping).if await self._session_db.get_session_title(session_id) is None:- try:+ with contextlib.suppress(Exception): # may already existawait self._session_db.create_session(session_id=session_id,source=source.platform.value if source.platform else "unknown",- user_id=source.user_id,- # Persist the messaging origin so a later /resume of this titled-but-inactive- # session can prove it belongs to the caller's chat/thread (IDOR scoping).- chat_id=source.chat_id,- chat_type=source.chat_type,+ user_id=source.user_id, chat_id=source.chat_id, chat_type=source.chat_type,thread_id=source.thread_id,)- except Exception:- pass # Session might already exist, ignore errors-title_arg = event.get_command_args().strip()if not title_arg:title = await self._session_db.get_session_title(session_id)@@ -1017,14 +898,11 @@ class GatewaySessionCommandsMixin:return t("gateway.title.not_found")except ValueError as e:return t("gateway.shared.warn_passthrough", error=e)- # Propagate the user-chosen title to the visible Telegram forum topic name too (auto-- # generated titles already rename the topic).- schedule_rename = getattr(self, "_schedule_telegram_topic_title_rename", None)- if callable(schedule_rename):- try:- await asyncio.to_thread(schedule_rename, source, session_id, sanitized)- except Exception:- logger.debug("Failed to rename Telegram topic from /title", exc_info=True)+ # Mirror the title onto the Telegram forum topic name (auto titles already do this).+ try:+ await asyncio.to_thread(self._schedule_telegram_topic_title_rename, source, session_id, sanitized)+ except Exception:+ logger.debug("Failed to rename Telegram topic from /title", exc_info=True)return t("gateway.title.set_to", title=sanitized)# -------------------------------------------------------------- /resume, /sessions@@ -1034,14 +912,13 @@ class GatewaySessionCommandsMixin:widen = allow_all and self._resume_caller_is_admin(source)sessions = await self._session_db.list_sessions_rich(source=source.platform.value if source.platform else None,- session_key=None if widen else session_key,- limit=10,+ session_key=None if widen else session_key, limit=10,)titled = [s for s in sessions if s.get("title")][:10]return [s for s in titled if await self._resume_row_visible(source, s, allow_all)]async def _resolve_resume_target(self, source, session_key: str, name: str, allow_all: bool):- """``(target_id, display_name)`` for a numbered choice, session id or title; else an error reply."""+ """``(target_id, name)`` for a numbered choice, session id or title; else the error reply."""if name.isdigit():try:titled = await self._list_titled_sessions(source, session_key, allow_all)@@ -1053,14 +930,12 @@ class GatewaySessionCommandsMixin:return t("gateway.resume.out_of_range", index=index)target = titled[index - 1]target_id, name = target.get("id"), target.get("title") or name- else:- # Direct session ID lookup first so `/resume <session_id>` works, not just `<title>`.+ else: # session id first, then titlesession = await self._session_db.get_session(name)target_id = session["id"] if session else await self._session_db.resolve_session_by_title(name)if not target_id:return t("gateway.resume.not_found", name=name)- # Compression creates child continuations that hold the live transcript; follow the chain- # so gateway /resume matches CLI behavior.+ # Follow compression continuations to the live transcript (matches CLI /resume).try:target_id = await self._session_db.resolve_resume_session_id(target_id)except Exception as e:@@ -1070,8 +945,8 @@ class GatewaySessionCommandsMixin:async def _resume_access_denied_reply(self, source, target_id: str, name: str, allow_all: bool, allow_cross_room: bool) -> Optional[str]:- """IDOR guard: a session id/title is a routing handle, not authority. Bind /resume to the- caller's own room (Matrix) or platform/user/chat (every other adapter)."""+ """IDOR guard: a session id/title is a routing handle, not authority — bind /resume to the+ caller's own room (Matrix) or platform/user/chat (other adapters)."""if source.platform == Platform.MATRIX:target_origin = self._gateway_session_origin_for_id(target_id)if self._same_matrix_room(source, target_origin) or allow_cross_room:@@ -1080,8 +955,7 @@ class GatewaySessionCommandsMixin:return t("gateway.resume.matrix_blocked_no_origin", name=name)return t("gateway.resume.matrix_blocked_other_room",- room=target_origin.chat_name or target_origin.chat_id,- name=name,+ room=target_origin.chat_name or target_origin.chat_id, name=name,)if await self._resume_target_allowed(source, target_id, allow_override=(allow_all or allow_cross_room)):return None@@ -1091,7 +965,6 @@ class GatewaySessionCommandsMixin:"""Handle /resume command — list or switch to a previous session."""if not self._session_db:return self._session_db_unavailable_reply()-source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)session_key = self._session_key_for_source(source)try:@@ -1101,7 +974,6 @@ class GatewaySessionCommandsMixin:allow_all = "--all" in partsallow_cross_room = "--cross-room" in partsname = _strip_resume_name(parts)-if not name:try:titled = await self._list_titled_sessions(source, session_key, allow_all)@@ -1117,34 +989,26 @@ class GatewaySessionCommandsMixin:denied = await self._resume_access_denied_reply(source, target_id, name, allow_all, allow_cross_room)if denied is not None:return denied-current_entry = await self.async_session_store.get_or_create_session(source)if current_entry.session_id == target_id:return t("gateway.resume.already_on", name=name)-self._release_running_agent_state(session_key)new_entry = await self.async_session_store.switch_session(session_key, target_id)if not new_entry:return t("gateway.resume.switch_failed")- # Conversation boundary: clear ALL conversation-scoped per-session state (model/reasoning- # overrides, one-turn restores, model notes, last-resolved cache, /queue overflow) +- # security state in one funnel call.+ # Conversation boundary: all conversation-scoped state + security state in one funnel call.self._clear_conversation_scope(session_key, reason="resume")- # Evict so the next message rebuilds with the correct session_id end-to-end — otherwise the- # cached AIAgent (and its memory provider, which cached _session_id at initialize()) keeps- # writing to the wrong session. Mirrors /branch and /reset.+ # Evict so the next turn rebuilds with the right session_id — the cached AIAgent's memory+ # provider cached _session_id at initialize() and would keep writing to the wrong session.self._evict_cached_agent(session_key)-title = await self._session_db.get_session_title(target_id) or namehistory = await self.async_session_store.load_transcript(target_id)msg_count = len([m for m in history if m.get("role") == "user"]) if history else 0if source.platform == Platform.MATRIX and allow_cross_room:msg_part = f" ({msg_count} message{'s' if msg_count != 1 else ''})" if msg_count else ""return t(- "gateway.resume.matrix_cross_room_success",- title=title,- room=source.chat_name or source.chat_id,- msg_part=msg_part,+ "gateway.resume.matrix_cross_room_success", title=title,+ room=source.chat_name or source.chat_id, msg_part=msg_part,)if not msg_count:return t("gateway.resume.resumed_no_count", title=title)@@ -1153,13 +1017,11 @@ class GatewaySessionCommandsMixin:return t("gateway.resume.resumed_many", title=title, count=msg_count)def _resume_listing_reply(self, source, titled: list[dict], allow_all: bool) -> str:- """Numbered /resume list. A non-admin ``--all`` silently falls back to same-origin scoping;- say so instead of rendering an unexplained narrower list (sibling of the /sessions notice)."""- scope_note = (- t("gateway.resume.all_requires_admin")- if allow_all and not self._resume_caller_is_admin(source)- else None- )+ """Numbered /resume list; a non-admin ``--all`` falls back to same-origin scoping and says so+ (sibling of the /sessions notice)."""+ scope_note = None+ if allow_all and not self._resume_caller_is_admin(source):+ scope_note = t("gateway.resume.all_requires_admin")if not titled:if source.platform == Platform.MATRIX and not allow_all:return t("gateway.resume.matrix_no_named_sessions")@@ -1184,7 +1046,6 @@ class GatewaySessionCommandsMixin:"""Handle /sessions — list previous sessions for gateway chats."""if not self._session_db:return self._session_db_unavailable_reply()-from hermes_cli.session_listing import (format_gateway_session_listing,parse_session_listing_args,@@ -1192,23 +1053,19 @@ class GatewaySessionCommandsMixin:)try:- include_all, include_unnamed, target, search_query = (- parse_session_listing_args(event.get_command_args().strip())+ include_all, include_unnamed, target, search_query = parse_session_listing_args(+ event.get_command_args().strip())except ValueError as exc:return t("gateway.resume.parse_error", error=exc)if search_query == "":return "Usage: `/sessions search <query>`"if target:- resume_event = dataclasses.replace(event, text=f"/resume {target}")- return await self._handle_resume_command(resume_event)-+ return await self._handle_resume_command(dataclasses.replace(event, text=f"/resume {target}"))source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)session_key = self._session_key_for_source(source)- # A cross-origin listing (`/sessions all`) is honored only for an admin, mirroring- # `/resume --all`; ungated, any caller could enumerate other origins' session ids/titles/- # previews — the enumeration half of the IDOR. A non-admin `all` gets explicit feedback- # rather than a silently scoped list that reads as "my session vanished".+ # `/sessions all` is admin-only like `/resume --all` (else any caller could enumerate other+ # origins' ids/titles/previews); a non-admin gets explicit feedback, not a silent narrowing.cross_origin = include_all and self._resume_caller_is_admin(source)scope_notice = Noneif include_all and not cross_origin:@@ -1227,13 +1084,11 @@ class GatewaySessionCommandsMixin:include_all_sources=cross_origin,include_unnamed=include_unnamed,search_query=search_query,- # Search filters at SQL level, so over-fetch before the visibility cut: origin-invisible- # matches would otherwise consume the page.+ # Search filters in SQL: over-fetch so origin-invisible matches don't consume the page.limit=50 if search_query else 10,exclude_sources=["tool"],)if not cross_origin:- # Scope to the caller's own origin so other users'/rooms' ids/previews aren't enumerable.rows = [row for row in rows if await self._resume_row_visible(source, row, allow_all=False)]rows = rows[:10]if search_query:@@ -1247,44 +1102,33 @@ class GatewaySessionCommandsMixin:# ----------------------------------------------------------------------- /branchasync def _handle_branch_command(self, event: MessageEvent) -> str:- """Handle /branch [name] — fork the current session into a new independent copy so the- user can explore a different approach without losing the original.- """+ """Handle /branch [name] — fork the current session into an independent copy."""import json as _jsonimport uuid as _uuidfrom datetime import datetime as _dtif not self._session_db:return self._session_db_unavailable_reply()-source = event.sourcesession_key = self._session_key_for_source(source)current_entry = await self.async_session_store.get_or_create_session(source)history = await self.async_session_store.load_transcript(current_entry.session_id)if not history:return t("gateway.branch.no_conversation")-new_session_id = f"{_dt.now().strftime('%Y%m%d_%H%M%S')}_{_uuid.uuid4().hex[:6]}"branch_title = event.get_command_args().strip()if not branch_title:current_title = await self._session_db.get_session_title(current_entry.session_id)branch_title = await self._session_db.get_next_title_in_lineage(current_title or "branch")parent_session_id = current_entry.session_id-- # Serialize the parent's full origin (same shape as the reset path's db_create_kwargs in- # gateway/session.py) so the branch row carries complete identity from birth. Prefer the- # live entry's origin (it may hold richer metadata than the triggering event's source).- _branch_origin = current_entry.origin or source+ # Full parent origin (same shape as the reset path in gateway/session.py); the live entry's+ # origin may hold richer metadata than the triggering event's source._branch_origin_json = None- if _branch_origin is not None:- with contextlib.suppress(Exception):- _branch_origin_json = _json.dumps(_branch_origin.to_dict())-- # Persist a stable ``_branched_from`` marker in model_config so list_sessions_rich() keeps- # the branch visible in /resume and /sessions even after the parent is reopened and- # re-ended with a different end_reason. Forward ALL gateway routing columns at CREATE time:- # otherwise they're NULL until switch_session() records the peer, and a crash in between- # leaves the branch unroutable (by chat/thread lookup and by /resume's IDOR guard).+ with contextlib.suppress(Exception):+ _branch_origin_json = _json.dumps((current_entry.origin or source).to_dict())+ # ``_branched_from`` keeps the branch visible in /resume and /sessions after the parent is+ # reopened and re-ended. ALL routing columns go in at CREATE time: a crash before+ # switch_session() records the peer would otherwise leave the branch unroutable.try:await self._session_db.create_session(session_id=new_session_id,@@ -1304,21 +1148,18 @@ class GatewaySessionCommandsMixin:logger.error("Failed to create branch session: %s", e)return t("gateway.branch.create_failed", error=e)- # Bounded-chunk transactions (a history can be hundreds of rows). Best-effort: a failed- # copy still yields a usable (partial) branch.+ # Chunked transactions; best-effort — a failed copy still yields a usable (partial) branch.with contextlib.suppress(Exception):await self._session_db.append_messages_batch(new_session_id, [_branch_row(msg) for msg in history], chunk_rows=500,)with contextlib.suppress(Exception):await self._session_db.set_session_title(new_session_id, branch_title)-new_entry = await self.async_session_store.switch_session(session_key, new_session_id)if not new_entry:return t("gateway.branch.switch_failed")self._clear_session_boundary_security_state(session_key)self._evict_cached_agent(session_key)-msg_count = len([m for m in history if m.get("role") == "user"])key = "gateway.branch.branched_one" if msg_count == 1 else "gateway.branch.branched_many"return t(key, title=branch_title, count=msg_count, parent=parent_session_id, new=new_session_id)