Skip to content

The agent that grows with you

refactor(gateway): extract run_sync onto TurnRunner (completes the TurnContext seam; AST-identical body)

teknium11a3a9de630a8
diff --git a/gateway/run.py b/gateway/run.py
index 4097139688d..57cf1755ad0 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3962,19547 +3962,19606 @@ class TurnRunner:
logger.error("Progress message error: %s", e)
await asyncio.sleep(1)
+ def voice_ack_callback(self, call_id, tool_name, args):
+ """tool_start_callback: speak a one-time ack in the voice channel."""
+ ctx = self._ctx
+ if ctx._voice_ack_fired[0] or ctx._voice_ack_guild[0] is None:
+ return
+ if not ctx._run_still_current():
+ return
+ ctx._voice_ack_fired[0] = True
+ _adapter = self._runner.adapters.get(Platform.DISCORD)
+ if _adapter is None or not hasattr(_adapter, "play_ack_in_voice"):
+ return
+ try:
+ safe_schedule_threadsafe(
+ _adapter.play_ack_in_voice(ctx._voice_ack_guild[0]),
+ ctx._voice_ack_loop,
+ logger=logger,
+ log_message="voice ack scheduling error",
+ )
+ except Exception as _ack_err:
+ logger.debug("voice ack schedule failed: %s", _ack_err)
+ def _step_callback_sync(self, iteration: int, prev_tools: list) -> None:
+ ctx = self._ctx
+ if not ctx._run_still_current():
+ return
+ # prev_tools may be list[str] or list[dict] with "name"/"result"
+ # keys. Normalise to keep "tool_names" backward-compatible for
+ # user-authored hooks that do ', '.join(tool_names)'.
+ _names: list[str] = []
+ for _t in (prev_tools or []):
+ if isinstance(_t, dict):
+ _names.append(_t.get("name") or "")
+ else:
+ _names.append(str(_t))
+ safe_schedule_threadsafe(
+ ctx._hooks_ref.emit("agent:step", {
+ "platform": ctx.source.platform.value if ctx.source.platform else "",
+ "user_id": ctx.source.user_id,
+ "session_id": ctx.session_id,
+ "iteration": iteration,
+ "tool_names": _names,
+ "tools": prev_tools,
+ }),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="agent:step hook scheduling error",
+ )
-class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, GatewaySlashCommandsMixin):
- """
- Main gateway controller.
+ def _event_callback_sync(self, event_type: str, context: dict) -> None:
+ ctx = self._ctx
+ try:
+ asyncio.run_coroutine_threadsafe(
+ ctx._hooks_ref.emit(event_type, context),
+ ctx._loop_for_step,
+ )
+ except Exception as _e:
+ logger.debug("event_callback hook error: %s", _e)
- Manages the lifecycle of all platform adapters and routes
- messages to/from the agent.
- """
+ def _status_callback_sync(self, event_type: str, message: str) -> None:
+ ctx = self._ctx
+ if not ctx._status_adapter or not ctx._run_still_current():
+ return
+ prepared_message = _prepare_gateway_status_message(
+ ctx.source.platform,
+ event_type,
+ message,
+ )
+ if prepared_message is None:
+ logger.debug(
+ "status_callback suppressed for %s/%s: %s",
+ ctx.source.platform.value if ctx.source.platform else "unknown",
+ event_type,
+ _redact_gateway_user_facing_secrets(str(message or ""))[:160],
+ )
+ return
+ _fut = safe_schedule_threadsafe(
+ _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared_message, ctx._status_thread_metadata),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message=f"status_callback ({event_type}) scheduling error",
+ )
+ if _fut is None:
+ return
+ if ctx._cleanup_progress:
+ def _track_status_id(fut) -> None:
+ try:
+ res = fut.result()
+ except Exception:
+ return
+ mid = getattr(res, "message_id", None)
+ if getattr(res, "success", False) and mid:
+ ctx._cleanup_msg_ids.append(str(mid))
+ _fut.add_done_callback(_track_status_id)
- # Class-level defaults so partial construction in tests doesn't
- # blow up on attribute access.
- _busy_input_mode: str = "interrupt"
- _busy_text_mode: str = "interrupt"
- _restart_drain_timeout: float = DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT
- _exit_code: Optional[int] = None
- _draining: bool = False
- _external_drain_active: bool = False
- _restart_requested: bool = False
- _restart_task_started: bool = False
- _restart_detached: bool = False
- _restart_via_service: bool = False
- _detached_restart_helper_started: bool = False
- _restart_command_source: Optional[SessionSource] = None
- _stop_task: Optional[asyncio.Task] = None
- _restart_task: Optional[asyncio.Task] = None
- _profile_failed_platforms: Optional[Dict[str, Dict[Platform, asyncio.Task]]] = None
- _systemd_watchdog: Optional[Any] = None
- _startup_restore_in_progress: bool = False
+ def run_sync(self):
+ ctx = self._ctx
+ # Historical note: as a nested closure this body declared
+ # `nonlocal message` because the conditional re-assignments below
+ # (prepending model-switch / resume-recovery notes) would otherwise
+ # make `message` function-local and break the earlier read at
+ # `_resolve_turn_agent_config(message, …)`. As a method the turn
+ # message lives on the shared TurnContext instead: every rebind
+ # writes `ctx.message`, so the outer `_run_agent_inner` body observes
+ # the updated value exactly as it did through the closure cell.
+
+ # session_key is propagated via contextvars in _set_session_env()
+ # (_SESSION_KEY) and via set_current_session_key() (_approval_session_key)
+ # below — both concurrency-safe and inherited by tool worker threads.
+ # We deliberately do NOT write os.environ["HERMES_SESSION_KEY"] here:
+ # os.environ is process-global, so concurrent gateway sessions (e.g.
+ # two Discord threads) would clobber each other's value, and a tool
+ # thread whose contextvar is unset would fall back to os.environ and
+ # read the wrong session key — misrouting command-approval prompts to
+ # the wrong thread (#24100). The non-gateway surfaces don't depend on
+ # this write: CLI and cron bind the session via contextvars
+ # (set_current_session_key / session context), and only the TUI
+ # slash-worker *subprocess* exports HERMES_SESSION_KEY (from its own
+ # --session-key argv, a separate process) — so removing this in-process
+ # gateway write does not affect any of them.
+
+ # Map platform enum to the platform hint key the agent understands.
+ # Platform.LOCAL ("local") maps to "cli"; others pass through as-is.
+ platform_key = "cli" if ctx.source.platform == Platform.LOCAL else ctx.source.platform.value
+
+ # Combine platform context, YAML channel_prompts hint for this chat,
+ # channel_overrides system_prompt (or global ephemeral), and gateway
+ # ephemeral prompt from _get_system_prompt_for_channel.
+ combined_ephemeral = ctx.context_prompt or ""
+ event_channel_prompt = (ctx.channel_prompt or "").strip()
+ if event_channel_prompt:
+ combined_ephemeral = (combined_ephemeral + "\n\n" + event_channel_prompt).strip()
+ cfg_channel_prompt = self._runner._get_system_prompt_for_channel(
+ ctx.source.platform,
+ ctx.source.chat_id or "",
+ thread_id=getattr(ctx.source, "thread_id", None),
+ parent_id=getattr(ctx.source, "parent_chat_id", None),
+ )
+ if cfg_channel_prompt:
+ combined_ephemeral = (combined_ephemeral + "\n\n" + cfg_channel_prompt).strip()
- # ------------------------------------------------------------------
- # Legacy per-session dict adapters. All per-session state lives in
- # ``self._sessions`` (Dict[str, SessionState]); these properties expose
- # the pre-consolidation dict attributes as LIVE MutableMapping views so
- # the extensive test surface (and a few mixin/adapter call sites) that
- # read/write ``runner._running_agents`` etc. keeps working unchanged.
- # New production code should use ``self._session_state(key)`` directly.
- # ------------------------------------------------------------------
- _running_agents = legacy_dict_property("_running_agents")
- _running_agents_ts = legacy_dict_property("_running_agents_ts")
- _active_session_leases = legacy_dict_property("_active_session_leases")
- _busy_ack_ts = legacy_dict_property("_busy_ack_ts")
- _turn_lease_tokens = legacy_lease_token_property()
- _session_run_generation = legacy_dict_property("_session_run_generation")
- _session_model_overrides = legacy_dict_property("_session_model_overrides")
- _pending_one_turn_model_restores = legacy_dict_property(
- "_pending_one_turn_model_restores"
- )
- _session_reasoning_overrides = legacy_dict_property("_session_reasoning_overrides")
- _session_service_tier_overrides = legacy_dict_property(
- "_session_service_tier_overrides"
- )
- _last_resolved_model = legacy_dict_property("_last_resolved_model")
- _queued_events = legacy_dict_property("_queued_events")
- _pending_turn_sidecar_notes = legacy_dict_property("_pending_turn_sidecar_notes")
- _pending_messages = legacy_dict_property("_pending_messages")
- _pending_native_image_paths_by_session = legacy_dict_property(
- "_pending_native_image_paths_by_session"
- )
- _session_ephemeral_pin = legacy_dict_property("_session_ephemeral_pin")
- _session_vc_last = legacy_dict_property("_session_vc_last")
- _pending_approvals = legacy_dict_property("_pending_approvals")
- _update_prompt_pending = legacy_dict_property("_update_prompt_pending")
+ max_iterations = _current_max_iterations()
- # -- SessionState accessors -----------------------------------------
- def _sessions_map(self) -> Dict[str, "SessionState"]:
- """The per-session state map; lazily created so bare test runners
- built via ``object.__new__`` work without ``__init__``."""
- sessions = self.__dict__.get("_sessions")
- if sessions is None:
- sessions = {}
- self.__dict__["_sessions"] = sessions
- return sessions
+ try:
+ model, runtime_kwargs = self._runner._resolve_session_agent_runtime(
+ source=ctx.source,
+ session_key=ctx.session_key,
+ user_config=ctx.user_config,
+ )
+ logger.debug(
+ "run_agent resolved: model=%s provider=%s session=%s",
+ model, runtime_kwargs.get("provider"), ctx.session_key or "",
+ )
+ except Exception as exc:
+ return {
+ "final_response": f"⚠️ Provider authentication failed: {exc}",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ }
- def _session_state(self, session_key: str) -> "SessionState":
- """Get-or-create the :class:`SessionState` for ``session_key``."""
- sessions = self._sessions_map()
- state = sessions.get(session_key)
- if state is None:
- state = SessionState()
- sessions[session_key] = state
- return state
+ pr = self._runner._provider_routing
+ reasoning_config = self._runner._resolve_session_reasoning_config(
+ source=ctx.source,
+ session_key=ctx.session_key,
+ model=model,
+ )
+ self._runner._reasoning_config = reasoning_config
+ self._runner._service_tier = self._runner._resolve_session_service_tier(
+ source=ctx.source, session_key=ctx.session_key
+ )
+ # Set up stream consumer for token streaming or interim commentary.
+ _stream_consumer = None
+ _stream_delta_cb = None
+ # #60671 — streaming TTS consumer is created on the outer
+ # event-loop thread before run_sync launches. run_sync only
+ # reads it via ``streaming_tts_consumer_holder[0]`` for delta
+ # callback wiring.
+ _stts_consumer_ref = ctx.streaming_tts_consumer_holder[0]
+ _scfg = getattr(getattr(self._runner, 'config', None), 'streaming', None)
+ if _scfg is None:
+ from gateway.config import StreamingConfig
+ _scfg = StreamingConfig()
- def _peek_session_state(self, session_key: str) -> Optional["SessionState"]:
- """Return the SessionState for ``session_key`` without creating one."""
- sessions = self.__dict__.get("_sessions")
- if not sessions:
- return None
- return sessions.get(session_key)
+ # Per-platform streaming gate: display.platforms.<plat>.streaming
+ # can disable streaming for specific platforms even when the global
+ # streaming config is enabled.
+ _plat_streaming = ctx.resolve_display_setting(
+ ctx.user_config, platform_key, "streaming"
+ )
+ # None = no per-platform override → follow global config
+ _streaming_enabled = (
+ _scfg.enabled and _scfg.transport != "off"
+ if _plat_streaming is None
+ else bool(_plat_streaming)
+ )
+ _want_stream_deltas = _streaming_enabled
+ _want_interim_messages = ctx.interim_assistant_messages_enabled
+ _want_interim_consumer = _want_interim_messages
+ if _want_stream_deltas or _want_interim_consumer:
+ try:
+ from gateway.stream_consumer import GatewayStreamConsumer
+ _adapter = self._runner._adapter_for_source(ctx.source)
+ if _adapter:
+ _consumer_cfg, _pause_typing_before_finalize = (
+ self._runner._build_stream_consumer_config(
+ ctx.source, _scfg, _adapter,
+ on_missing_cursor="raise",
+ )
+ )
+ _stream_consumer = GatewayStreamConsumer(
+ adapter=_adapter,
+ chat_id=ctx.source.chat_id,
+ config=_consumer_cfg,
+ metadata=ctx._status_thread_metadata,
+ on_new_message=(
+ (lambda: ctx.progress_queue.put(("__reset__",)))
+ if ctx.progress_queue is not None
+ else None
+ ),
+ on_before_finalize=_pause_typing_before_finalize,
+ initial_reply_to_id=ctx.event_message_id,
+ run_still_current=ctx._run_still_current,
+ )
+ if _want_stream_deltas:
+ def _stream_delta_cb(text: str) -> None:
+ if ctx._run_still_current():
+ _stream_consumer.on_delta(text)
+ # Tee to the streaming-TTS consumer (#60671).
+ if _stts_consumer_ref is not None:
+ _stts_consumer_ref.on_delta(text)
+ ctx.stream_consumer_holder[0] = _stream_consumer
+ except Exception as _sc_err:
+ logger.debug("Could not set up stream consumer: %s", _sc_err)
- def _is_session_running(self, session_key: str) -> bool:
- """True when the session holds a running-turn slot (agent or sentinel)."""
- state = self._peek_session_state(session_key)
- return state is not None and state.turn.agent is not None
+ # When text streaming is off but streaming TTS is active,
+ # install a TTS-only delta callback so the consumer still
+ # receives LLM deltas for audio synthesis (#60671).
+ if _stream_delta_cb is None and _stts_consumer_ref is not None:
+ def _stream_delta_cb(text: str) -> None:
+ if ctx._run_still_current():
+ _stts_consumer_ref.on_delta(text)
- def _running_agent_items(self) -> List[tuple]:
- """(session_key, agent) pairs for sessions with a running turn
- (including pending sentinels), matching the old ``_running_agents``
- dict contents."""
- return [
- (key, state.turn.agent)
- for key, state in self._sessions_map().items()
- if state.turn.agent is not None
- ]
- # Loop-liveness heartbeat / watchdog handles (#66892, #69089). Class-level
- # defaults so partial construction in tests doesn't blow up on access; the
- # real values are set in __init__ / start() / stop().
- _loop_heartbeat_task: Optional["asyncio.Task"] = None
- _loop_floor_timer_handle: Optional[Any] = None
- _loop_liveness_watchdog: Optional[Any] = None
- _gateway_started_at: float = 0.0
- _shutdown_watchdog_done: Optional["threading.Event"] = None
- _platform_lock_takeover_on_start: bool = False
- _reconnect_watcher_task: Optional["asyncio.Task"] = None
+ def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
+ if not ctx._run_still_current():
+ return
+ display_text = text
+ if _stream_consumer is not None:
+ if already_streamed:
+ _stream_consumer.on_segment_break()
+ else:
+ _stream_consumer.on_commentary(display_text)
+ return
+ if already_streamed or not ctx._status_adapter or not str(display_text or "").strip():
+ return
+ safe_schedule_threadsafe(
+ ctx._status_adapter.send(
+ ctx._status_chat_id,
+ display_text,
+ metadata=ctx._status_thread_metadata,
+ ),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="interim_assistant_callback scheduling error",
+ )
- def __init__(self, config: Optional[GatewayConfig] = None):
- global _gateway_runner_ref
- # When multiplex_profiles is on, load under the default profile secret
- # scope so bot tokens in that profile's .env resolve the same way
- # secondary profiles do (#64674). Explicit config= injection (tests)
- # is left untouched.
- self.config = config if config is not None else load_gateway_config_for_runner()
- # Mark the process as a profile multiplexer when configured. This flips
- # agent.secret_scope.get_secret() to fail-closed on any unscoped
- # credential read, so a missed migration crashes loudly instead of
- # leaking a cross-profile value (Workstream A). Inert when off.
- try:
- from agent.secret_scope import set_multiplex_active
- set_multiplex_active(bool(getattr(self.config, "multiplex_profiles", False)))
- except Exception:
- logger.debug("could not set multiplex-active flag", exc_info=True)
- self.adapters: Dict[Platform, BasePlatformAdapter] = {}
- # Multi-profile multiplexing: adapters for NON-default profiles live
- # here, keyed by profile name then Platform. self.adapters stays the
- # default/active profile's map so the ~93 existing self.adapters[...]
- # sites are untouched when multiplexing is off (this dict is empty).
- # Populated by _start_secondary_profile_adapters().
- self._profile_adapters: Dict[str, Dict[Platform, BasePlatformAdapter]] = {}
- self._warn_if_docker_media_delivery_is_risky()
- _gateway_runner_ref = _weakref.ref(self)
+ turn_route = self._runner._resolve_turn_agent_config(ctx.message, model, runtime_kwargs)
+
+ # Check agent cache — reuse the AIAgent from the previous message
+ # in this session to preserve the frozen system prompt and tool
+ # schemas for prompt cache hits.
+ _sig = self._runner._agent_config_signature(
+ turn_route["model"],
+ turn_route["runtime"],
+ ctx.enabled_toolsets,
+ combined_ephemeral,
+ cache_keys=self._runner._extract_cache_busting_config(ctx.user_config),
+ user_id=getattr(ctx.source, "user_id", None),
+ user_id_alt=getattr(ctx.source, "user_id_alt", None),
+ )
+ agent = None
+ reused_cached_agent = False
+ _cache_lock = getattr(self._runner, "_agent_cache_lock", None)
+ _cache = getattr(self._runner, "_agent_cache", None)
+
+ # Peek at the cached entry's snapshot session_id (if any) so we can
+ # check, OUTSIDE the cache lock, whether THAT session_id is a DEAD
+ # session in state.db. This closes a gap in the #54947 fix: that
+ # fix treats "cached session_id != current session_id" as an
+ # intentional /resume-style switch and reuses the agent unchanged.
+ # But the #54878 self-heal produces the exact same tuple shape
+ # when it recovers a routing key away from a session that was
+ # already ended — the cached AIAgent still belongs to the DEAD
+ # session, not a valid sibling conversation. Reusing it lets that
+ # turn's post-run "session split" sync write the routing key
+ # straight back onto the dead session_id, undoing the self-heal
+ # and looping every message until an interrupt happens to race in
+ # first (the #54878 x #54947 interaction — no existing upstream
+ # issue tracks this combination as of 2026-07-12).
+ _peek_cached_sid = None
+ if _cache_lock and _cache is not None:
+ with _cache_lock:
+ _peek_entry = _cache.get(ctx.session_key)
+ if _peek_entry and len(_peek_entry) > 3:
+ _peek_cached_sid = _peek_entry[3]
+ _cached_sid_is_dead = False
+ if (
+ _peek_cached_sid is not None
+ and ctx.session_id is not None
+ and _peek_cached_sid != ctx.session_id
+ ):
+ try:
+ _cached_sid_is_dead = self._runner.session_store._is_session_ended_in_db(
+ _peek_cached_sid
+ )
+ except Exception:
+ _cached_sid_is_dead = False
+
+ # Detect cross-process writes: when another process (e.g. hermes
+ # dashboard) appends to the same session in the shared SessionDB,
+ # the cached agent's in-memory transcript becomes stale. Compare
+ # the session's current message_count against the count recorded
+ # when the agent was cached; on mismatch, invalidate the cache
+ # so a fresh agent re-reads from disk. (#45966)
+ _current_msg_count = None
+ if self._runner._session_db is not None and ctx.session_id:
+ try:
+ # run_sync is off-loop (executor); sync DB is fine.
+ _sess_row = self._runner._session_db._db.get_session(ctx.session_id)
+ if _sess_row:
+ _current_msg_count = _sess_row.get("message_count", 0)
+ except Exception:
+ pass
- # Load ephemeral config from config.yaml / env vars.
- # Both are injected at API-call time only and never persisted.
- self._prefill_messages = self._load_prefill_messages()
- self._ephemeral_system_prompt = self._load_ephemeral_system_prompt()
- self._reasoning_config = self._load_reasoning_config()
- self._service_tier = self._load_service_tier()
- self._show_reasoning = self._load_show_reasoning()
- self._busy_input_mode = self._load_busy_input_mode()
- 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._fallback_model = self._load_fallback_model()
+ _xproc_evicted_agent = None
+ if _cache_lock and _cache is not None:
+ with _cache_lock:
+ cached = _cache.get(ctx.session_key)
+ if cached and cached[1] == _sig:
+ # cached[2] is the message_count at cache time;
+ # stale when a second process appended rows.
+ # cached[3] (when present) is the session_id the
+ # snapshot was taken for — used to skip the guard
+ # when the active session_id differs (#54947).
+ _cached_mc = cached[2] if len(cached) > 2 else None
+ _cached_sid = cached[3] if len(cached) > 3 else None
+ # If the snapshot belongs to a different session_id
+ # (same session_key, different conversation), the
+ # message_count comparison is meaningless — the
+ # counts track DIFFERENT DB rows. REUSE the cached
+ # agent rather than rebuild and bust the prompt cache
+ # on every session switch (#54947).
+ _session_id_mismatch = (
+ _cached_sid is not None
+ and ctx.session_id is not None
+ and _cached_sid != ctx.session_id
+ )
+ # Re-validate the OUTSIDE-lock dead-session peek
+ # against the tuple actually read under THIS lock —
+ # the cache entry could have been replaced between
+ # the peek and this lock acquisition, and a stale
+ # "dead" verdict must never be applied to a
+ # different (possibly live) cached agent.
+ _stale_dead_sid_reuse = (
+ _session_id_mismatch
+ and _cached_sid_is_dead
+ and _cached_sid == _peek_cached_sid
+ )
+ if _stale_dead_sid_reuse:
+ # #54878 x #54947 interaction: the routing key
+ # was just self-healed away from a session that
+ # state.db already marked ended, but the cached
+ # AIAgent here still belongs to that DEAD
+ # session_id. The #54947 "different session_id
+ # under the same key = intentional switch, reuse
+ # freely" rule does not hold here — this isn't a
+ # sibling conversation, it's a stale agent left
+ # over from before the self-heal. Reusing it lets
+ # this turn's post-run "session split" sync write
+ # the routing key straight back onto the dead
+ # session_id, undoing the self-heal and looping
+ # every message until an interrupt happens to
+ # race in first. Discard and rebuild fresh
+ # instead, same as a genuine cross-process write.
+ logger.info(
+ "Agent cache invalidated for session %s: "
+ "cached agent's session_id %s is ended in "
+ "state.db (stale self-heal artifact, "
+ "#54878 x #54947) — discarding instead of "
+ "reusing across the routing recovery",
+ ctx.session_key, _cached_sid,
+ )
+ evicted = self._runner._agent_cache.pop(ctx.session_key, None)
+ _ev_agent = evicted[0] if isinstance(evicted, tuple) and evicted else None
+ if _ev_agent and _ev_agent is not _AGENT_PENDING_SENTINEL:
+ # Same deferred-cleanup rationale as the
+ # cross-process branch below (#52197): don't
+ # block the event loop / cache lock on
+ # memory-provider shutdown or socket teardown.
+ _xproc_evicted_agent = _ev_agent
+ elif (
+ not _session_id_mismatch
+ and _cached_mc is not None
+ and _current_msg_count is not None
+ and _current_msg_count != _cached_mc
+ ):
+ # Cross-process write detected — discard stale
+ # agent so it rebuilds from fresh DB transcript.
+ logger.info(
+ "Agent cache invalidated for session %s: "
+ "message_count changed (%s -> %s), "
+ "possible cross-process write",
+ ctx.session_key, _cached_mc, _current_msg_count,
+ )
+ evicted = self._runner._agent_cache.pop(ctx.session_key, None)
+ _ev_agent = evicted[0] if isinstance(evicted, tuple) and evicted else None
+ if _ev_agent and _ev_agent is not _AGENT_PENDING_SENTINEL:
+ # Defer cleanup until AFTER the lock is
+ # released — _cleanup_agent_resources /
+ # release_clients can block on memory-provider
+ # shutdown and socket teardown, and running it
+ # here would stall the gateway event loop while
+ # _sweep_idle_cached_agents (session-expiry
+ # watcher) waits on the same lock, blocking
+ # Discord heartbeats (#52197). The same session
+ # rebuilds a fresh agent immediately below, so
+ # use the SOFT release that preserves the
+ # session's terminal sandbox / browser / bg
+ # processes for the rebuilt agent to inherit —
+ # mirrors _evict_cached_agent / idle-sweep.
+ _xproc_evicted_agent = _ev_agent
+ else:
+ agent = cached[0]
+ # Refresh LRU order so the cap enforcement evicts
+ # truly-oldest entries, not the one we just used.
+ if hasattr(_cache, "move_to_end"):
+ try:
+ _cache.move_to_end(ctx.session_key)
+ except KeyError:
+ pass
+ self._runner._init_cached_agent_for_turn(agent, ctx._interrupt_depth)
+ # Refresh agent max_iterations from current config
+ # (cached agent may have been created with old config)
+ agent.max_iterations = max_iterations
+ logger.debug("Reusing cached agent for session %s", ctx.session_key)
+ reused_cached_agent = True
+
+ # Lock released — refresh the fallback chain from disk for the
+ # reused agent OUTSIDE the cache lock (config.yaml read is disk
+ # I/O; the idle-sweep watcher contends on this lock and stalls
+ # Discord heartbeats — same reasoning as #52197). A chain
+ # configured after this agent was cached (or after gateway start)
+ # must reach the next turn (#60955). Per-session turn
+ # serialization (_running_agents) keeps this safe post-lock.
+ if reused_cached_agent and agent is not None:
+ self._runner._apply_fallback_chain_to_agent(
+ agent, self._runner._refresh_fallback_model(),
+ )
- # Wire process registry into session store for reset protection.
- # A background process older than the configured threshold (default 24h,
- # session_reset.bg_process_max_age_hours) is treated as stale and no
- # longer blocks session idle / daily reset — see #29177. The process is
- # NOT killed, only ignored by the reset guard.
- from tools.process_registry import process_registry
- _bg_max_age_hours = getattr(
- self.config.default_reset_policy, "bg_process_max_age_hours", 24
- )
- _bg_max_age_seconds = (
- _bg_max_age_hours * 3600 if _bg_max_age_hours and _bg_max_age_hours > 0 else None
- )
- self.session_store = SessionStore(
- self.config.sessions_dir, self.config,
- has_active_processes_fn=lambda key: process_registry.has_active_for_session(
- key, max_active_age=_bg_max_age_seconds,
- ),
+ # Lock released — now schedule cleanup of any cross-process-evicted
+ # agent on a daemon thread so memory-provider shutdown / socket
+ # teardown never blocks the gateway event loop or the cache lock
+ # the session-expiry watcher needs (#52197).
+ if _xproc_evicted_agent is not None:
+ try:
+ threading.Thread(
+ target=self._runner._release_evicted_agent_soft,
+ args=(_xproc_evicted_agent,),
+ daemon=True,
+ name=f"agent-xproc-evict-{str(ctx.session_key)[:24]}",
+ ).start()
+ except Exception:
+ # Interpreter shutdown or thread-spawn failure — release
+ # inline as a best-effort fallback.
+ try:
+ self._runner._release_evicted_agent_soft(_xproc_evicted_agent)
+ except Exception:
+ pass
+
+ if agent is None:
+ # Config changed or first message — create fresh agent
+ agent = ctx.AIAgent(
+ model=turn_route["model"],
+ **turn_route["runtime"],
+ **_checkpoint_agent_kwargs(ctx.user_config),
+ max_iterations=max_iterations,
+ quiet_mode=True,
+ verbose_logging=False,
+ enabled_toolsets=ctx.enabled_toolsets,
+ disabled_toolsets=ctx.disabled_toolsets,
+ ephemeral_system_prompt=combined_ephemeral or None,
+ prefill_messages=self._runner._prefill_messages or None,
+ reasoning_config=reasoning_config,
+ service_tier=self._runner._service_tier,
+ request_overrides=turn_route.get("request_overrides"),
+ providers_allowed=pr.get("only"),
+ providers_ignored=pr.get("ignore"),
+ providers_order=pr.get("order"),
+ provider_sort=pr.get("sort"),
+ provider_require_parameters=pr.get("require_parameters", False),
+ provider_data_collection=pr.get("data_collection"),
+ session_id=ctx.session_id,
+ platform=platform_key,
+ user_id=ctx.source.user_id,
+ user_id_alt=ctx.source.user_id_alt,
+ user_name=ctx.source.user_name,
+ chat_id=ctx.source.chat_id,
+ chat_name=ctx.source.chat_name,
+ chat_type=ctx.source.chat_type,
+ thread_id=ctx.source.thread_id,
+ gateway_session_key=ctx.session_key,
+ session_db=getattr(self._runner._session_db, "_db", self._runner._session_db),
+ # Reload from disk — do not reuse the startup snapshot (#60955).
+ fallback_model=self._runner._refresh_fallback_model(),
+ )
+ if _cache_lock and _cache is not None:
+ with _cache_lock:
+ # Record the session_id the snapshot was taken for
+ # alongside the message_count, so the cross-process
+ # guard can skip the (meaningless) count comparison
+ # when the active session_id later switches under
+ # the same session_key (#54947).
+ _cache[ctx.session_key] = (
+ agent, _sig, _current_msg_count, ctx.session_id,
+ )
+ self._runner._enforce_agent_cache_cap()
+ logger.debug("Created new agent for session %s (sig=%s)", ctx.session_key, _sig)
+
+ # Per-message state — callbacks and reasoning config change every
+ # turn and must not be baked into the cached agent constructor.
+ # Gate on needs_progress_queue (tool_progress OR thinking_progress)
+ # rather than tool_progress alone: the progress_callback also relays
+ # _thinking assistant scratch text, which is gated on
+ # thinking_progress and is intentionally independent of tool
+ # progress. With the old `tool_progress_enabled`-only gate, a user
+ # who set thinking_progress:true but kept tool_progress:off got a
+ # None callback — so _thinking scratch bubbles never relayed even
+ # though the progress queue was created for them.
+ agent.tool_progress_callback = (
+ ctx.progress_callback
+ if (
+ ctx.needs_progress_queue
+ or ctx.log_mode_enabled
+ or ctx._live_status_adapter is not None
+ )
+ else None
)
- # One enforced loop-side boundary for the synchronous SessionStore.
- # Sync helpers keep using ``session_store`` directly; async gateway
- # handlers call this facade and await every operation.
- self._async_session_store = AsyncSessionStore(self.session_store)
- self.delivery_router = DeliveryRouter(self.config)
- self._running = False
- self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None
- self._shutdown_event = asyncio.Event()
- self._exit_cleanly = False
- self._exit_with_failure = False
- self._exit_reason: Optional[str] = None
- self._exit_code: Optional[int] = None
- self._draining = False
- self._profile_failed_platforms: Dict[str, Dict[Platform, asyncio.Task]] = {}
- self._systemd_watchdog = None
- # External (NAS-driven) drain state — distinct from the shutdown
- # ``_draining`` flag above. Set by ``_drain_control_watcher`` when the
- # ``.drain_request.json`` marker is present: the gateway flips
- # ``gateway_state -> draining`` and refuses NEW turns, but the process
- # does NOT exit (the whole point — quiesce-without-restart, D4a). It is
- # fully reversible: removing the marker reverts to ``running`` and
- # re-accepts turns. ``_draining`` (shutdown) is one-way and ends in
- # process exit; this one is a steady state NAS polls during its
- # request -> poll -> proceed loop.
- self._external_drain_active = False
- self._restart_requested = False
- # Set by shutdown_signal_handler when a SIGTERM/SIGINT arrived
- # WITHOUT a planned-stop / takeover marker — i.e. an unexpected
- # external signal (container/s6 SIGTERM on `docker restart` or
- # image upgrade, OOM-killer, bare `kill`). Distinct from an
- # operator-requested stop, which writes a marker first. Used by
- # _stop_impl to decide whether to persist gateway_state=stopped
- # (see issue #42675): an unexpected signal must NOT persist
- # "stopped", or container_boot refuses to auto-start the gateway
- # on the next boot.
- self._signal_initiated_shutdown = False
- self._restart_task_started = False
- self._restart_detached = False
- self._restart_via_service = False
- self._detached_restart_helper_started = False
- self._restart_command_source: Optional[SessionSource] = None
- # Monotonic-ish wall clock of when this GatewayRunner was constructed.
- # Used by the /restart redelivery guard to bound the window in which a
- # missing dedup marker is treated as a stale redelivery.
- self._startup_time: float = time.time()
- # Set True at startup when this process booted as the result of a
- # chat-originated /restart (i.e. .restart_notify.json existed on boot).
- # A one-shot signal consumed by _is_stale_restart_redelivery so the
- # marker-missing fallback only suppresses a /restart when we KNOW we
- # just came out of a restart cycle — never on a genuine fresh boot.
- self._booted_from_restart: bool = False
- self._stop_task: Optional[asyncio.Task] = None
- self._restart_task: Optional[asyncio.Task] = None
- self._executor_lock = threading.Lock()
- self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
- # Set on gateway stop so the recreate-on-shutdown path can't resurrect
- # the pool during a real shutdown.
- self._executor_closing = False
- # ALL per-session state (turn / conversation / persistent scopes)
- # lives in one container — see gateway/session_state.py. Access via
- # self._session_state(key) (get-or-create) or
- # self._peek_session_state(key) (read-only).
- self._sessions: Dict[str, SessionState] = {}
- # Per-SESSION_ID turn lease (#64934): serializes the
- # [load history → run → flush] region when two ROUTING KEYS resolve
- # to one session_id (switch_session's many-to-one mapping). The
- # routing-key guards above cannot see that overlap. Acquired in
- # _handle_message_with_agent after session resolution is final,
- # released via _release_turn_lease in the same method's finally.
- self._turn_leases = SessionTurnLeaseRegistry()
- # Tokens for held turn leases, keyed by (routing key, run generation)
- # so release is granted per-turn and a stale unwind can never free a
- # newer turn's lease (#28686 ownership lesson).
- # Held turn-lease tokens live on SessionState.turn.lease_token /
- # .lease_generation (the old dict was keyed (routing key, generation)
- # so a stale unwind could never free a newer turn's lease — the
- # generation field preserves that ownership check, #28686).
- # Runner-level queued interrupt text lives on
- # SessionState.persistent.pending_command_text (NOTE: distinct from
- # the adapter-level _pending_messages Dict[str, MessageEvent] in
- # gateway/platforms/base.py, which shares the legacy name).
- # Last successfully-resolved (non-empty) model, keyed by session. Used
- # as a fallback when a fresh config read transiently returns an empty
- # model (e.g. an mtime-keyed config-cache miss during a post-interrupt
- # recovery turn). Without this, the agent is built with model="" and
- # every API call fails HTTP 400 "No models provided" — the session goes
- # silent until the user manually re-sends. See #35314. The ``"*"``
- # session entry holds a process-wide last-known-good for sessions
- # seen for the first time. Lives on
- # SessionState.conversation.last_resolved_model.
- # Overflow buffer for explicit /queue commands. The adapter-level
- # _pending_messages dict is a single slot per session (designed for
- # "next-turn" follow-ups where repeated sends collapse into one
- # event). /queue has different semantics: each invocation must
- # produce its own full agent turn, in FIFO order, with no merging.
- # When the slot is occupied, additional /queue items land here and
- # are promoted one-at-a-time after each run's drain. Cleared on
- # /new and /reset. /model and other mid-session operations
- # preserve the queue. Lives on SessionState.conversation.queued_events;
- # native image paths, busy-ack debounce timestamps and the monotonic
- # run-generation counter (#28686, NEVER reset) live on SessionState too.
- # Startup restore gate: while restart-interrupted sessions are being
- # auto-resumed, real inbound messages are queued instead of competing
- # with the synthetic resume turns for the same session. The queued
- # events drain only after all startup resume tasks have finished.
- self._startup_restore_in_progress = False
- # Set by start_gateway() only for an explicit ``--replace`` launch.
- # _connect_initial_adapter_with_timeout scopes it to each adapter's
- # cold-start connect and removes it before any reconnect can run.
- self._platform_lock_takeover_on_start = False
- self._startup_restore_queue: List[MessageEvent] = []
- self._startup_restore_tasks: List[asyncio.Task] = []
- # LRU cache of live SessionSources keyed by session_key. Used by
- # fallback routing paths (shutdown notifications, synthetic
- # background-process events) when the persisted origin is missing
- # and _parse_session_key can't recover thread_id. Capped so it
- # cannot grow unbounded over a long-running gateway lifetime.
- self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()
- self._session_sources_max = 512
- # Completion delivery is intentionally lifecycle-scoped. This closes
- # duplicate queue/watcher races inside one gateway without pretending
- # the adapter call and a persistence write can be exactly-once across
- # a process crash. Any durable async-delegation replay state remains
- # owned by tools.async_delegation, not a parallel gateway ledger.
- self._completion_delivery_lock = threading.Lock()
- self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()
- self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()
- self._completion_delivery_retention = 2048
+ # Discord voice verbal-ack hook (fires once per turn on first tool
+ # call; armed only when in a voice channel with the mixer running).
+ agent.tool_start_callback = (
+ ctx.voice_ack_callback if ctx._voice_ack_guild[0] is not None else None
+ )
+ agent.step_callback = ctx._step_callback_sync if ctx._hooks_ref.loaded_hooks else None
+ agent.stream_delta_callback = _stream_delta_cb
+ agent.interim_assistant_callback = _interim_assistant_cb if _want_interim_messages else None
+ agent.status_callback = ctx._status_callback_sync
+ # Credits / out-of-band notices (usage bands, depletion, restored).
+ # Messaging has no persistent status bar, so each notice is a
+ # standalone push: render to a single plaintext line and deliver via
+ # the shared _deliver_platform_notice rail (honors private/public +
+ # thread metadata). Fires from the agent's sync worker thread, so we
+ # hop onto the gateway loop with safe_schedule_threadsafe - same
+ # pattern as _status_callback_sync. The fired-once latch lives on the
+ # cached agent and persists across turns, so a band crosses -> one
+ # push (no per-turn re-nag). Recovery ("✓ Credit access restored")
+ # rides the same show path (it's emitted as a success notice, not a
+ # clear). The clear callback is a no-op: a sent platform message
+ # can't be cleanly retracted, and the band already fired once.
+ def _notice_callback_sync(notice) -> None:
+ if not ctx._status_adapter or not ctx._run_still_current():
+ return
+ try:
+ line = render_notice_line(notice)
+ except Exception:
+ logger.debug("render_notice_line failed", exc_info=True)
+ return
+ if not line:
+ return
+ safe_schedule_threadsafe(
+ self._runner._deliver_platform_notice(ctx.source, line),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="notice_callback delivery scheduling error",
+ )
- # Cache AIAgent instances per session to preserve prompt caching.
- # Without this, a new AIAgent is created per message, rebuilding the
- # system prompt (including memory) every turn — breaking prefix cache
- # and costing ~10x more on providers with prompt caching (Anthropic).
- # Key: session_key, Value: (AIAgent, config_signature_str)
+ agent.notice_callback = _notice_callback_sync
+ agent.notice_clear_callback = None
+ agent.event_callback = ctx._event_callback_sync
+ agent.reasoning_config = reasoning_config
+ agent.service_tier = self._runner._service_tier
+ agent.request_overrides = turn_route.get("request_overrides") or {}
+ # Must-deliver notes for THIS turn ride the current user message
+ # (api_content sidecar), never the system prompt: staged by
+ # _handle_message_with_agent (auto-reset note, first-contact
+ # intro, voice-channel change). Assigned unconditionally so a
+ # reused cached agent never replays a stale note.
+ agent._gateway_turn_context_notes = "\n\n".join(
+ self._runner._consume_pending_turn_sidecar_notes(ctx.session_key)
+ )
+
+ _bg_review_release = threading.Event()
+ _bg_review_pending: list[str] = []
+ _bg_review_pending_lock = threading.Lock()
+
+ def _deliver_bg_review_message(message: str) -> None:
+ if not ctx._status_adapter or not ctx._run_still_current():
+ return
+ safe_schedule_threadsafe(
+ ctx._status_adapter.send(
+ ctx._status_chat_id,
+ message,
+ metadata=_non_conversational_metadata(ctx._status_thread_metadata, platform=ctx.source.platform),
+ ),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="background_review_callback scheduling error",
+ )
+
+ def _release_bg_review_messages() -> None:
+ _bg_review_release.set()
+ with _bg_review_pending_lock:
+ pending = list(_bg_review_pending)
+ _bg_review_pending.clear()
+ for queued in pending:
+ _deliver_bg_review_message(queued)
+
+ # Background review delivery — send "💾 Memory updated" etc. to user
+ def _bg_review_send(message: str) -> None:
+ if not ctx._status_adapter or not ctx._run_still_current():
+ return
+ if not _bg_review_release.is_set():
+ with _bg_review_pending_lock:
+ if not _bg_review_release.is_set():
+ _bg_review_pending.append(message)
+ return
+ _deliver_bg_review_message(message)
+
+ agent.background_review_callback = _bg_review_send
+ # Register the release hook on the adapter so base.py's finally
+ # block can fire it after delivering the main response.
+ if ctx._status_adapter and ctx.session_key:
+ if getattr(type(ctx._status_adapter), "register_post_delivery_callback", None) is not None:
+ ctx._status_adapter.register_post_delivery_callback(
+ ctx.session_key,
+ _release_bg_review_messages,
+ generation=ctx.run_generation,
+ )
+ else:
+ _pdc = getattr(ctx._status_adapter, "_post_delivery_callbacks", None)
+ if _pdc is not None:
+ _pdc[ctx.session_key] = _release_bg_review_messages
+ # Memory update notifications in chat. Config: display.memory_notifications
+ # off — no chat notification (still logged to stdout)
+ # on — generic "💾 Memory updated" (default)
+ # verbose — content preview: "💾 Memory ➕ Hermes Repo..."
+ _mem_notif = ctx.user_config.get("display", {}).get("memory_notifications")
+ if isinstance(_mem_notif, bool):
+ _mem_notif = "on" if _mem_notif else "off"
+ agent.memory_notifications = str(_mem_notif).lower() if _mem_notif else "on"
+
+ # ------------------------------------------------------------------
+ # Clarify callback: present a clarify prompt and block on a response.
#
- # OrderedDict so _enforce_agent_cache_cap() can pop the least-recently-
- # used entry (move_to_end() on cache hits, popitem(last=False) for
- # eviction). Hard cap via _AGENT_CACHE_MAX_SIZE, idle TTL enforced
- # from _session_expiry_watcher().
- import threading as _threading
- self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()
- self._agent_cache_lock = _threading.Lock()
+ # Runs on the agent's worker thread (see clarify_tool's synchronous
+ # callback contract). Bridges sync→async by scheduling the
+ # adapter's send_clarify on the gateway event loop, then blocks on
+ # the clarify primitive's threading.Event with a configurable
+ # timeout. Returns the user's response string, or a sentinel
+ # explaining that no response arrived (so the agent can adapt
+ # rather than hang forever).
+ # ------------------------------------------------------------------
+ def _clarify_callback_sync(question: str, choices, multi_select: bool = False) -> str:
+ from tools import clarify_gateway as _clarify_mod
+ import uuid as _uuid
- # Conversation-scoped per-session state (/model, /model --once,
- # /reasoning, /fast overrides; per-turn sidecar notes; ephemeral
- # context pin; last-delivered voice-channel context) lives on
- # SessionState.conversation — see gateway/session_state.py.
- self._kanban_notifier_profile = self._active_profile_name()
- # Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
- self._teams_pipeline_runtime = None
- self._teams_pipeline_runtime_error: Optional[str] = None
- # Pending exec approvals live on SessionState.persistent.approvals.
+ if not ctx._status_adapter:
+ return ""
- # Track platforms that failed to connect for background reconnection.
- # Key: Platform enum, Value: {"config": platform_config, "attempts": int, "next_retry": float}
- self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}
+ clarify_id = _uuid.uuid4().hex[:10]
+ _clarify_mod.register(
+ clarify_id=clarify_id,
+ session_key=ctx.session_key or "",
+ question=question,
+ choices=list(choices) if choices else None,
+ multi_select=bool(multi_select),
+ )
- # Strong refs to detached fatal-error handler tasks (see
- # _handle_adapter_fatal_error) so the event loop can't GC them mid-run.
- self._fatal_handler_tasks: set = set()
+ # Pause typing — like approval, we don't want a "thinking..."
+ # status to obscure the prompt or block the user from typing
+ # an "Other" response on platforms that disable input while
+ # typing is active (Slack Assistant API).
+ try:
+ ctx._status_adapter.pause_typing_for_chat(ctx._status_chat_id)
+ except Exception:
+ pass
- # Pending /update prompt flags live on
- # SessionState.persistent.update_prompt_pending.
+ # Ordering barrier (#clarify-ordering): flush any buffered
+ # assistant prose (interim commentary / streamed deltas) to the
+ # platform BEFORE sending the poll. The poll is delivered on a
+ # separate, agent-thread-blocking path; without this barrier it
+ # races ahead of prose still sitting in the stream consumer's
+ # queue, so the question renders ABOVE its own explanation.
+ # Best-effort + short timeout: never hang the agent thread if
+ # the consumer task isn't running.
+ try:
+ _sc = ctx.stream_consumer_holder[0] if ctx.stream_consumer_holder else None
+ _flush = getattr(_sc, "flush_pending_sync", None)
+ if callable(_flush):
+ _flush(timeout=3.0)
+ except Exception:
+ logger.debug(
+ "Stream-consumer flush before clarify prompt failed",
+ exc_info=True,
+ )
- # Slash-confirm state lives in tools.slash_confirm (module-level),
- # so platform adapters can resolve callbacks without a backref to
- # this runner. Keep a local counter for confirm_id generation so
- # IDs stay compact (button callback_data has a 64-byte cap on
- # some platforms).
- import itertools as _itertools
- self._slash_confirm_counter = _itertools.count(1)
+ send_ok = False
+ fut = safe_schedule_threadsafe(
+ ctx._status_adapter.send_clarify(
+ chat_id=ctx._status_chat_id,
+ question=question,
+ choices=list(choices) if choices else None,
+ clarify_id=clarify_id,
+ session_key=ctx.session_key or "",
+ metadata=ctx._status_thread_metadata,
+ ),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="Clarify send failed to schedule",
+ )
+ if fut is None:
+ send_ok = False
+ else:
+ try:
+ result = fut.result(timeout=15)
+ send_ok = bool(getattr(result, "success", False))
+ except Exception as exc:
+ logger.warning("Clarify send failed: %s", exc)
+ send_ok = False
- # Persistent Honcho managers keyed by gateway session key.
- # This preserves write_frequency="session" semantics across short-lived
- # per-message AIAgent instances.
+ if not send_ok:
+ # Couldn't deliver the prompt — clean up and return
+ # sentinel so the agent can fall back to a sensible
+ # default rather than hanging.
+ _clarify_mod.clear_session(ctx.session_key or "")
+ return "[clarify prompt could not be delivered]"
+
+ timeout = _clarify_mod.get_clarify_timeout()
+ response = _clarify_mod.wait_for_response(clarify_id, timeout=float(timeout))
+ if response is None or response == "":
+ # Timeout or session-boundary cancellation
+ return f"[user did not respond within {int(timeout / 60)}m]"
+ return response
+ agent.clarify_callback = _clarify_callback_sync
+ # Show assistant thinking between tool calls — independent of
+ # tool_progress mode. Mattermost needs an explicit per-platform
+ # opt-in so global scratch-text display does not leak into threads.
+ agent.thinking_progress = ctx._thinking_enabled
+ # Store agent reference for interrupt support
+ ctx.agent_holder[0] = agent
+ # Capture the full tool definitions for transcript logging
+ ctx.tools_holder[0] = agent.tools if hasattr(agent, 'tools') else None
+
+ # Convert history to agent format.
+ # Two cases:
+ # 1. Normal path (from transcript): simple {role, content, timestamp} dicts
+ # - Strip timestamps, keep role+content
+ # 2. Interrupt path (from agent result["messages"]): full agent messages
+ # that may include tool_calls, tool_call_id, reasoning, etc.
+ # - These must be passed through intact so the API sees valid
+ # assistant→tool sequences (dropping tool_calls causes 500 errors)
+ #
+ # Telegram observed group context is handled structurally here:
+ # observed=True transcript rows are withheld from replayable
+ # history and attached to the current addressed message as
+ # API-only context, so persisted history stores only the real
+ # addressed user turn.
+ agent_history, observed_group_context = _build_gateway_agent_history(
+ ctx.history,
+ channel_prompt=ctx.channel_prompt,
+ inject_timestamps=_message_timestamps_enabled(_load_gateway_config()),
+ )
- # Ensure tirith security scanner is available (downloads if needed)
- try:
- from tools.tirith_security import ensure_installed
- ensure_installed(log_failures=False)
- except Exception:
- pass # Non-fatal — fail-open at scan time if unavailable
+ # FTS write-corruption guard (#50502): when message persistence
+ # fails silently through corrupt FTS triggers, the reloaded
+ # transcript above is stale/empty even though the SAME cached agent
+ # still holds the full live conversation in `_session_messages`.
+ # Replacing the live transcript with that shorter copy causes
+ # immediate same-session amnesia. Only applies when we reused a
+ # cached agent bound to this exact session_id.
+ if reused_cached_agent and getattr(agent, "session_id", None) == ctx.session_id:
+ _selected = _select_cached_agent_history(
+ agent_history, getattr(agent, "_session_messages", None)
+ )
+ if _selected is not agent_history:
+ logger.warning(
+ "Persisted transcript lagged live cached history for "
+ "session %s (disk=%d, memory=%d); preserving live "
+ "conversation context (possible FTS write corruption)",
+ ctx.session_key, len(agent_history), len(_selected),
+ )
+ # The live in-memory history bypassed the
+ # _build_gateway_agent_history cleanup pipeline above —
+ # re-apply the stale-confirmation expiry (#59607) so a
+ # dangerous confirmation can't slip through this path
+ # either. Idempotent; messages without timestamps are
+ # untouched.
+ agent_history = _strip_stale_dangerous_confirmations(
+ _selected, now=time.time()
+ )
+
+ # Collect MEDIA paths already in history so we can exclude them
+ # from the current turn's extraction. This is compression-safe:
+ # even if the message list shrinks, we know which paths are old.
+ _history_media_paths: set = _collect_history_media_paths(agent_history)
+
+ # Register per-session gateway approval callback so dangerous
+ # command approval blocks the agent thread (mirrors CLI input()).
+ # The callback bridges sync→async to send the approval request
+ # to the user immediately.
+ from tools.approval import (
+ register_gateway_notify,
+ reset_current_session_key,
+ set_current_session_key,
+ unregister_gateway_notify,
+ )
- # Startup heads-up (#30882): a gateway in manual approval mode with no
- # automated risk assessor (tirith disabled AND no auxiliary.approval
- # model) can only gate dangerous commands / execute_code scripts via
- # live in-chat approval. With approval routing fixed, those actions now
- # fail closed (block) rather than silently auto-running — surface that
- # so operators knowingly enable tirith or configure auxiliary.approval
- # for unattended gateways.
- try:
- from hermes_cli.config import load_config as _load_full_config
- _appr_cfg = _load_full_config()
- _appr_mode = str(
- cfg_get(_appr_cfg, "approvals", "mode", default="manual") or "manual"
- ).strip().lower()
- _tirith_on = bool(cfg_get(_appr_cfg, "security", "tirith_enabled", default=True))
- _aux_approval = cfg_get(_appr_cfg, "auxiliary", "approval", default=None)
- if _appr_mode == "manual" and not _tirith_on and not _aux_approval:
- logger.warning(
- "Gateway approvals.mode=manual with no automated risk "
- "assessor (security.tirith_enabled is false and "
- "auxiliary.approval is unset): dangerous commands and "
- "execute_code scripts will BLOCK until a human approves "
- "them in chat. Enable security.tirith_enabled or configure "
- "auxiliary.approval for unattended operation."
- )
- except Exception:
- logger.debug("approvals.mode startup check skipped", exc_info=True)
-
- # Initialize session database for session_search tool support
- self._session_db = None
- try:
- from hermes_state import AsyncSessionDB, SessionDB
- self._session_db = AsyncSessionDB(SessionDB())
- except Exception as e:
- # WARNING (not DEBUG) so the failure appears in errors.log — matches
- # cli.py's handling of the same init path. Users hitting NFS-mounted
- # HERMES_HOME silently lost /resume, /title, /history, /branch, and
- # session search without this. The underlying cause (usually
- # "locking protocol" from NFS) is now also captured by
- # hermes_state.get_last_init_error() for slash-command error strings.
- logger.warning("SQLite session store not available: %s", e)
+ def _approval_notify_sync(approval_data: dict) -> None:
+ """Send the approval request to the user from the agent thread.
- # Opportunistic state.db maintenance: prune ended sessions inactive
- # for sessions.retention_days + optional VACUUM. Tracks last-run
- # in state_meta so it only actually executes once per
- # sessions.min_interval_hours. Gateway is long-lived so blocking
- # a few seconds once per day is acceptable; failures are logged
- # but never raised.
- if self._session_db is not None:
- try:
- from hermes_cli.config import load_config as _load_full_config
- _sess_cfg = (_load_full_config().get("sessions") or {})
- # Non-destructive stale-session archive, independent of prune.
- if _sess_cfg.get("auto_archive", False):
- self._session_db._db.maybe_auto_archive(
- idle_days=float(_sess_cfg.get("auto_archive_days", 3)),
- min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)),
+ If the adapter supports interactive button-based approvals
+ (e.g. Discord's ``send_exec_approval``), use that for a richer
+ UX. Otherwise fall back to a plain text message with
+ ``/approve`` instructions.
+ """
+ # Pause the typing indicator while the agent waits for
+ # user approval. Critical for Slack's Assistant API where
+ # assistant_threads_setStatus disables the compose box — the
+ # user literally cannot type /approve while "is thinking..."
+ # is active. The approval message send auto-clears the Slack
+ # status; pausing prevents _keep_typing from re-setting it.
+ # Typing resumes in _handle_approve_command/_handle_deny_command.
+ ctx._status_adapter.pause_typing_for_chat(ctx._status_chat_id)
+
+ cmd = approval_data.get("command", "")
+ desc = approval_data.get("description", "dangerous command")
+
+ # Redact credentials from the command before displaying it in
+ # the approval prompt — Tirith's findings are already redacted,
+ # but the raw command string still leaks secrets to the chat
+ # platform (#48456). Applied here so BOTH the button-based
+ # (send_exec_approval) and plain-text fallback paths below use
+ # the redacted value.
+ cmd = _redact_approval_command(cmd)
+
+ # Prefer button-based approval when the adapter supports it.
+ # Check the *class* for the method, not the instance — avoids
+ # false positives from MagicMock auto-attribute creation in tests.
+ if getattr(type(ctx._status_adapter), "send_exec_approval", None) is not None:
+ try:
+ _approval_fut = safe_schedule_threadsafe(
+ ctx._status_adapter.send_exec_approval(
+ chat_id=ctx._status_chat_id,
+ command=cmd,
+ session_key=_approval_session_key,
+ description=desc,
+ metadata=ctx._status_thread_metadata,
+ allow_permanent=approval_data.get("allow_permanent", True),
+ allow_session=approval_data.get("allow_session", True),
+ smart_denied=approval_data.get("smart_denied", False),
+ ),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="send_exec_approval scheduling error",
)
- if _sess_cfg.get("auto_prune", False):
- # Construction-time, before the loop serves traffic; sync DB is fine.
- self._session_db._db.maybe_auto_prune_and_vacuum(
- retention_days=int(_sess_cfg.get("retention_days", 90)),
- min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)),
- vacuum=bool(_sess_cfg.get("vacuum_after_prune", True)),
- sessions_dir=self.config.sessions_dir,
+ if _approval_fut is None:
+ raise RuntimeError("send_exec_approval: loop unavailable")
+ _approval_result = _approval_fut.result(timeout=15)
+ if _approval_result.success:
+ return
+ logger.warning(
+ "Button-based approval failed (send returned error), falling back to text: %s",
+ _approval_result.error,
+ )
+ except Exception as _e:
+ logger.warning(
+ "Button-based approval failed, falling back to text: %s", _e
)
- except Exception as exc:
- logger.debug("state.db auto-maintenance skipped: %s", exc)
- # Opportunistic shadow-repo cleanup — deletes stale checkpoint repos
- # under ~/.hermes/checkpoints/. Opt-in via checkpoints.auto_prune,
- # idempotent via .last_prune marker.
- try:
- from hermes_cli.config import load_config as _load_full_config
- _ckpt_cfg = (_load_full_config().get("checkpoints") or {})
- if _ckpt_cfg.get("auto_prune", False):
- from tools.checkpoint_manager import maybe_auto_prune_checkpoints
- # delete_orphans is intentionally never honoured here: a
- # missing workdir at startup is ambiguous (deleted project
- # vs. an unmounted external volume / network share / VPN
- # not yet up) and this sweep runs unattended. Orphan cleanup
- # is only ever done via the explicit `hermes checkpoints
- # prune` command, which the user has to invoke.
- maybe_auto_prune_checkpoints(
- retention_days=int(_ckpt_cfg.get("retention_days", 7)),
- min_interval_hours=int(_ckpt_cfg.get("min_interval_hours", 24)),
- delete_orphans=False,
- max_total_size_mb=int(_ckpt_cfg.get("max_total_size_mb", 500)),
+ # Fallback: plain text approval prompt. Use the adapter's
+ # typed prefix so Slack/Matrix users are told the form they
+ # can actually type (`!approve`) — typed "/" is blocked in
+ # Slack threads and reserved by Matrix clients.
+ _p = getattr(ctx._status_adapter, "typed_command_prefix", "/")
+ msg = _format_exec_approval_fallback(
+ cmd,
+ desc,
+ _p,
+ allow_permanent=approval_data.get("allow_permanent", True),
+ allow_session=approval_data.get("allow_session", True),
+ smart_denied=approval_data.get("smart_denied", False),
+ )
+ try:
+ _approval_send_fut = safe_schedule_threadsafe(
+ ctx._status_adapter.send(
+ ctx._status_chat_id,
+ msg,
+ metadata=ctx._status_thread_metadata,
+ ),
+ ctx._loop_for_step,
+ logger=logger,
+ log_message="Approval text-send scheduling error",
)
- except Exception as exc:
- logger.debug("checkpoint auto-maintenance skipped: %s", exc)
-
- # DM pairing store for code-based user authorization.
- # ``pairing_store`` stays as the global/default store for the
- # ``hermes pairing`` CLI and any caller without a profile context.
- # ``pairing_stores`` is the per-profile map used by
- # ``authz_mixin._is_user_authorized`` to route checks to the right
- # whitelist (one per profile in multiplex mode).
- from gateway.pairing import PairingStore
- self.pairing_store = PairingStore()
- self.pairing_stores: Dict[str, "PairingStore"] = {}
-
- # Event hook system
- from gateway.hooks import HookRegistry
- self.hooks = HookRegistry()
+ if _approval_send_fut is not None:
+ _approval_send_fut.result(timeout=15)
+ except Exception as _e:
+ logger.error("Failed to send approval request: %s", _e)
+
+ # Keep real user text separate from API-only recovery guidance. If
+ # an auto-continue note is prepended below, persist the original
+ # message so stale guidance never replays as user-authored text.
+ _persist_user_message_override: Optional[Any] = ctx.persist_user_message
+ _persist_user_timestamp_override: Optional[float] = ctx.persist_user_timestamp
+
+ # Prepend pending model switch note so the model knows about the switch
+ _pending_notes = getattr(self._runner, '_pending_model_notes', {})
+ _msn = _pending_notes.pop(ctx.session_key, None) if ctx.session_key else None
+ if _msn:
+ ctx.message = _msn + "\n\n" + ctx.message
+
+ # Auto-continue: if the loaded history ends with a tool result,
+ # the previous agent turn was interrupted mid-work (gateway
+ # restart, crash, SIGTERM). Prepend a system note so the model
+ # finishes processing the pending tool results before addressing
+ # the user's new message. (#4493)
+ #
+ # Session-level resume_pending (set on drain-timeout shutdown)
+ # escalates the wording — the transcript's last role may be
+ # anything (tool, assistant with unfinished work, etc.), so we
+ # give a stronger, reason-aware instruction that subsumes the
+ # tool-tail case.
+ #
+ # Freshness gate (#16802): both branches are gated on the age
+ # of the last persisted transcript row. That is the correct
+ # "when did we last do anything here" signal for both the
+ # resume_pending path (restart watchdog) and the tool-tail
+ # path (in-flight tool loop killed). We read ``history[-1]``
+ # here because ``agent_history`` has already stripped the
+ # ``timestamp`` field off tool/tool_call rows for API purity
+ # (see the `k != "timestamp"` filter above). Rows without a
+ # timestamp (legacy transcripts) are treated as fresh so the
+ # historical auto-continue behaviour is preserved.
+ _freshness_window = _auto_continue_freshness_window()
+ _interruption_is_fresh = _is_fresh_gateway_interruption(
+ _last_transcript_timestamp(ctx.history),
+ window_secs=_freshness_window,
+ )
- # Per-chat voice reply mode: "off" | "voice_only" | "all"
- self._voice_mode: Dict[str, str] = self._load_voice_modes()
- # Recent voice transcripts per (guild,user) for duplicate suppression.
- # Protects against the same utterance being emitted twice by the voice
- # capture / STT pipeline, which otherwise produces a second delayed reply.
- self._recent_voice_transcripts: Dict[tuple[int, int], List[tuple[float, str]]] = {}
+ _resume_entry = None
+ if ctx.session_key:
+ try:
+ _resume_entry = self._runner.session_store._entries.get(ctx.session_key)
+ except Exception:
+ _resume_entry = None
+
+ # resume_pending freshness uses a SECOND signal in addition to the
+ # transcript clock above. The restart watchdog stamps the session
+ # with ``last_resume_marked_at`` at interrupt time — that is the
+ # correct "when were we interrupted" signal. The transcript clock
+ # (_interruption_is_fresh) can be far older: an active thread you
+ # return to may have its last persisted row hours back, even though
+ # the interruption itself just happened. Gating resume_pending on
+ # the transcript clock alone makes the recovery note silently drop,
+ # and because the startup auto-resume turn carries empty text
+ # (_schedule_resume_pending_sessions), the model then receives a
+ # blank user message and replies with confused "the message came
+ # through blank" noise. Treat the marker as fresh when
+ # EITHER signal is fresh so the two freshness checks agree.
+ _resume_mark_is_fresh = False
+ if _resume_entry is not None and getattr(_resume_entry, "resume_pending", False):
+ _resume_mark_is_fresh = _is_fresh_gateway_interruption(
+ getattr(_resume_entry, "last_resume_marked_at", None),
+ window_secs=_freshness_window,
+ )
+ _is_resume_pending = bool(
+ _resume_entry is not None
+ and getattr(_resume_entry, "resume_pending", False)
+ and (_interruption_is_fresh or _resume_mark_is_fresh)
+ )
+ _has_fresh_tool_tail = bool(
+ agent_history
+ and agent_history[-1].get("role") == "tool"
+ and _interruption_is_fresh
+ )
- # Track background tasks to prevent garbage collection mid-execution
- self._background_tasks: set = set()
+ if _is_resume_pending:
+ _reason = getattr(_resume_entry, "resume_reason", None) or "restart_timeout"
+ _persist_user_message_override = ctx.message
+ # The empty-message case is the auto-resume startup turn
+ # synthesized by _schedule_resume_pending_sessions — there is
+ # no NEW user message to address. Guidance is adapter-aware:
+ # interactive platforms report the restore and ask what next;
+ # non-interactive event platforms (webhook, API server)
+ # continue the interrupted work instead, because nobody is
+ # present to answer and an acknowledgement would silently
+ # abandon the task (#57056).
+ _resume_adapter = self._runner._adapter_for_source(ctx.source)
+ _interactive_resume = bool(
+ getattr(_resume_adapter, "interactive_resume", True)
+ )
+ ctx.message = build_resume_recovery_note(
+ _reason, ctx.message, interactive=_interactive_resume,
+ )
+ elif _has_fresh_tool_tail:
+ _persist_user_message_override = ctx.message
+ ctx.message = (
+ "[System note: A new message has arrived. The conversation "
+ "history contains pending tool outputs from an interrupted turn. "
+ "IGNORE those pending results. Address the user's NEW message "
+ "below FIRST. Do NOT re-execute old tool calls from the history.]\n\n"
+ + ctx.message
+ )
- # Event-loop liveness heartbeat (#66892): rewritten every 30s while
- # the loop is dispatching. External supervisors use the file mtime /
- # updated_at to distinguish "process alive" from "loop frozen".
- self._gateway_started_at: float = time.time()
- self._loop_heartbeat_task: Optional[asyncio.Task] = None
- self._loop_floor_timer_handle = None
- self._loop_liveness_watchdog = None
+ # Consume one-shot /reload-skills note (if the user ran
+ # /reload-skills since their last turn in this session). Same
+ # queue pattern as CLI: prepend to the NEXT user message, then
+ # clear. Nothing was written to the transcript out-of-band, so
+ # message alternation stays intact.
+ _pending_notes = getattr(self._runner, "_pending_skills_reload_notes", None)
+ if _pending_notes and ctx.session_key and ctx.session_key in _pending_notes:
+ _srn = _pending_notes.pop(ctx.session_key, None)
+ if _srn:
+ ctx.message = _srn + "\n\n" + ctx.message
+
+ # Safety net: a startup auto-resume event carries empty
+ # text and relies on the resume_pending branch above to supply the
+ # recovery note. If that branch did not fire for any reason (e.g.
+ # both freshness signals disagreed, or the marker was cleared
+ # between scheduling and dispatch) we must NOT hand the model a
+ # blank user turn — it responds with confused "the message came
+ # through blank" noise. Restricted to resume_pending sessions so
+ # legitimately empty user turns (e.g. an image with no caption,
+ # wrapped as native content below) are untouched.
+ if (
+ isinstance(ctx.message, str)
+ and not ctx.message.strip()
+ and _resume_entry is not None
+ and getattr(_resume_entry, "resume_pending", False)
+ ):
+ _sn_reason = (
+ getattr(_resume_entry, "resume_reason", None) or "restart_timeout"
+ )
+ _sn_adapter = self._runner._adapter_for_source(ctx.source)
+ ctx.message = build_resume_recovery_note(
+ _sn_reason,
+ "",
+ interactive=bool(
+ getattr(_sn_adapter, "interactive_resume", True)
+ ),
+ )
- # scale-to-zero (Phase 0, F13): gateway-scoped "last inbound seen" clock.
- # There is no such clock today (only a per-agent _last_activity_ts), so the
- # idle predicate needs this. Stamped in _handle_message (the single inbound
- # chokepoint all adapters call); seeded to "now" so a fresh gateway isn't
- # considered idle from epoch. The scale-to-zero watcher (started only when
- # the instance is opted in + relay-only + has a wakeUrl) reads it.
- self._last_inbound_at: float = time.time()
- # Set after a wake (re-arm cooldown, 0.F) so we don't immediately re-go
- # dormant before the drained backlog has a chance to update the clock.
- self._scale_to_zero_cooldown_until: float = 0.0
+ _approval_session_key = ctx.session_key or ""
+ _approval_session_token = set_current_session_key(_approval_session_key)
+ register_gateway_notify(_approval_session_key, _approval_notify_sync)
+ try:
+ # If _prepare_inbound_message_text buffered image paths for native
+ # attachment, wrap the user turn as an OpenAI-style multimodal
+ # content list. Consume-and-clear so subsequent turns on the same
+ # runner instance don't re-attach stale images.
+ _native_imgs = self._runner._consume_pending_native_image_paths(ctx.session_key)
+ if _native_imgs:
+ try:
+ from agent.image_routing import build_native_content_parts
+ _parts, _skipped = build_native_content_parts(
+ ctx.message,
+ _native_imgs,
+ )
+ if _skipped:
+ logger.warning(
+ "Native image attachment: skipped %d unreadable path(s): %s",
+ len(_skipped), _skipped,
+ )
+ if any(p.get("type") == "image_url" for p in _parts):
+ _run_message: Any = _parts
+ else:
+ # All images failed to read — fall back to plain text.
+ _run_message = ctx.message
+ except Exception as _img_exc:
+ logger.warning(
+ "Native image attachment failed, falling back to text: %s",
+ _img_exc,
+ )
+ _run_message = ctx.message
+ else:
+ _run_message = ctx.message
+ _api_run_message = _wrap_current_message_with_observed_context(
+ _run_message,
+ observed_group_context,
+ )
+ _conversation_kwargs = {
+ "conversation_history": agent_history,
+ "task_id": ctx.session_id,
+ }
+ if _persist_user_message_override is not None:
+ _conversation_kwargs["persist_user_message"] = _persist_user_message_override
+ elif observed_group_context:
+ _conversation_kwargs["persist_user_message"] = ctx.message
+ if ctx.moa_config is not None:
+ _conversation_kwargs["moa_config"] = ctx.moa_config
+ if _persist_user_timestamp_override is not None:
+ _conversation_kwargs["persist_user_timestamp"] = _persist_user_timestamp_override
+ result = agent.run_conversation(_api_run_message, **_conversation_kwargs)
+ finally:
+ unregister_gateway_notify(_approval_session_key)
+ # Cancel any pending clarify entries so blocked agent
+ # threads don't hang past the end of the run (interrupt,
+ # completion, gateway shutdown). Idempotent.
+ try:
+ from tools.clarify_gateway import clear_session as _clear_clarify_session
+ _clear_clarify_session(_approval_session_key)
+ except Exception:
+ pass
+ reset_current_session_key(_approval_session_token)
+ ctx.result_holder[0] = result
- def _wire_teams_pipeline_runtime(self) -> None:
- """Bind the Teams meeting pipeline runtime to Graph webhook ingress.
+ # Signal the stream consumer that the agent is done
+ if _stream_consumer is not None:
+ _stream_consumer.finish()
- No-op when the msgraph_webhook adapter isn't running or the
- teams_pipeline plugin isn't enabled — lets the gateway start cleanly
- whether or not the user has opted into the pipeline.
- """
- if Platform.MSGRAPH_WEBHOOK not in self.adapters:
- return
- if not _teams_pipeline_plugin_enabled():
- logger.debug("Teams pipeline plugin is disabled; skipping runtime wiring")
- return
- try:
- from plugins.teams_pipeline.runtime import bind_gateway_runtime
- except Exception as exc:
- logger.warning("Teams pipeline runtime import failed: %s", exc)
- return
- try:
- bound = bind_gateway_runtime(self)
- except Exception as exc:
- logger.warning("Teams pipeline runtime wiring failed: %s", exc)
- return
- if bound:
- logger.info("Teams pipeline runtime bound to msgraph webhook ingress")
- elif self._teams_pipeline_runtime_error:
- logger.warning(
- "Teams pipeline runtime unavailable: %s",
- self._teams_pipeline_runtime_error,
+ # Signal the streaming-TTS consumer that the agent is done (#60671).
+ # finish() is called from the outer event-loop thread after the
+ # executor returns, so early returns from run_sync are also
+ # finalised. See the outer finally/completion section below.
+
+ # Return final response, or a message if something went wrong
+ final_response = result.get("final_response")
+
+ # Extract actual token counts from the agent instance used for this run
+ _last_prompt_toks = 0
+ _input_toks = 0
+ _output_toks = 0
+ _context_length = 0
+ _agent = ctx.agent_holder[0]
+ if _agent and hasattr(_agent, "context_compressor"):
+ _last_prompt_toks = getattr(_agent.context_compressor, "last_prompt_tokens", 0)
+ _input_toks = getattr(_agent, "session_prompt_tokens", 0)
+ _output_toks = getattr(_agent, "session_completion_tokens", 0)
+ _context_length = getattr(_agent.context_compressor, "context_length", 0) or 0
+ _resolved_model = getattr(_agent, "model", None) if _agent else None
+
+ # Sync session_id immediately after run_conversation(). Compression
+ # can rotate before a follow-up model call fails; the failure return
+ # below must still point the gateway at the compressed child.
+ agent = ctx.agent_holder[0]
+ _session_was_split = False
+ # In-place compaction (compression.in_place / #38763) compacts the
+ # transcript WITHOUT rotating the id, so the id-change diff below
+ # can't detect it. compress_context() sets this rotation-independent
+ # flag on the agent; the gateway uses it to re-baseline transcript
+ # handling (history_offset=0 + rewrite the JSONL transcript) the
+ # same way a split would, even though the session_id is unchanged.
+ _compacted_in_place = bool(getattr(agent, "_last_compaction_in_place", False)) if agent else False
+ agent_session_id = getattr(agent, 'session_id', ctx.session_id) if agent else ctx.session_id
+ if agent and ctx.session_key and agent_session_id != ctx.session_id:
+ _session_was_split = True
+ logger.info(
+ "Session split detected: %s → %s (compression)",
+ ctx.session_id, agent_session_id,
)
+ entry = self._runner.session_store._entries.get(ctx.session_key)
+ _session_split_entry_persisted = False
+ if entry:
+ entry_session_id = getattr(entry, "session_id", None)
+ if not ctx._run_still_current():
+ logger.info(
+ "Skipping session split sync for stale run %s — "
+ "generation %s is no longer current",
+ ctx.session_key or "?",
+ ctx.run_generation,
+ )
+ elif entry_session_id == agent_session_id:
+ _session_split_entry_persisted = True
+ elif entry_session_id != ctx.session_id:
+ logger.info(
+ "Skipping session split sync for %s because the "
+ "session binding moved from %s to %s before "
+ "compression finished",
+ ctx.session_key or "?",
+ ctx.session_id,
+ entry_session_id,
+ )
+ else:
+ entry.session_id = agent_session_id
+ self._runner.session_store._save()
+ self._runner.session_store._record_gateway_session_peer(
+ agent_session_id,
+ ctx.session_key,
+ ctx.source,
+ )
+ _session_split_entry_persisted = True
+
+ # If this is a Telegram DM and source.thread_id was lost during
+ # the session split (synthetic / recovered event), restore it
+ # from the binding so _thread_metadata_for_source produces the
+ # correct message_thread_id instead of routing to the General
+ # thread. Failure here is non-fatal — we log and continue;
+ # worst case the message lands in General, which is the
+ # pre-fix behaviour. Only do this after this run successfully
+ # published its session split; a stale /stop→/new predecessor
+ # must not mutate routing/binding state for the fresh session.
+ if _session_split_entry_persisted and (
+ getattr(ctx.source, "platform", None) == Platform.TELEGRAM
+ and getattr(ctx.source, "chat_type", None) == "dm"
+ and getattr(ctx.source, "thread_id", None) is None
+ and self._runner._session_db is not None
+ ):
+ try:
+ # run_sync is off-loop (executor); sync DB is fine.
+ _binding = self._runner._session_db._db.get_telegram_topic_binding_by_session(
+ session_id=agent_session_id,
+ )
+ if _binding and _binding.get("thread_id"):
+ ctx.source.thread_id = str(_binding["thread_id"])
+ logger.debug(
+ "Restored source.thread_id=%s from binding after session split %s → %s",
+ ctx.source.thread_id,
+ ctx.session_id,
+ agent_session_id,
+ )
+ except Exception:
+ logger.debug(
+ "Failed to restore thread_id from binding after session split",
+ exc_info=True,
+ )
+ if _session_split_entry_persisted:
+ self._runner._sync_telegram_topic_binding(
+ ctx.source, entry, reason="agent-run-compression",
+ )
+ effective_session_id = agent_session_id
+ self._runner._sync_session_model_from_agent(effective_session_id, agent)
+ # history_offset=0 whenever the agent's message list no longer has
+ # the original history prefix — i.e. on rotation (split) OR in-place
+ # compaction. In both cases the returned `messages` is the compacted
+ # set, so the gateway must persist all of it (offset 0), not slice
+ # past the pre-compaction length (which would drop everything).
+ _effective_history_offset = (
+ 0 if (_session_was_split or _compacted_in_place) else len(agent_history)
+ )
- def _warn_if_docker_media_delivery_is_risky(self) -> None:
- """Warn when Docker-backed gateways lack an explicit export mount.
-
- MEDIA delivery happens in the gateway process, so paths emitted by the model
- must be readable from the host. A plain container-local path like
- `/workspace/report.txt` or `/output/report.txt` often exists only inside
- Docker, so users commonly need a dedicated export mount such as
- `host-dir:/output`.
- """
- if os.getenv("TERMINAL_ENV", "").strip().lower() != "docker":
- return
+ if not final_response:
+ final_response = _normalize_empty_agent_response(
+ result, final_response or "", history_len=len(agent_history),
+ )
+ final_response = _sanitize_gateway_final_response(ctx.source.platform, final_response)
+ if not final_response:
+ final_response = f"⚠️ {result['error']}" if result.get("error") else ""
+ return {
+ "final_response": final_response,
+ "messages": result.get("messages", []),
+ "api_calls": result.get("api_calls", 0),
+ "failed": result.get("failed", False),
+ # Sibling of the non-empty-response return below (#64686):
+ # the classifier's failure_reason must survive the
+ # empty-response normalization path too, or downstream
+ # consumers (TUI billing surface, transient-failure
+ # persistence) lose the structured reason exactly when
+ # the run produced no text.
+ "failure_reason": result.get("failure_reason"),
+ "partial": result.get("partial", False),
+ "completed": result.get("completed"),
+ "interrupted": result.get("interrupted", False),
+ "interrupt_message": result.get("interrupt_message"),
+ "error": result.get("error"),
+ "compression_exhausted": result.get("compression_exhausted", False),
+ "compression_deferred": result.get("compression_deferred", False),
+ "tools": ctx.tools_holder[0] or [],
+ "history_offset": _effective_history_offset,
+ "compacted_in_place": _compacted_in_place,
+ "session_id": effective_session_id,
+ "last_prompt_tokens": _last_prompt_toks,
+ "input_tokens": _input_toks,
+ "output_tokens": _output_toks,
+ "model": _resolved_model,
+ "context_length": _context_length,
+ }
- connected = self.config.get_connected_platforms()
- messaging_platforms = [p for p in connected if p not in {Platform.LOCAL, Platform.API_SERVER, Platform.WEBHOOK}]
- if not messaging_platforms:
- return
+ # Scan tool results for MEDIA:<path> tags that need to be delivered
+ # as native audio/file attachments. The TTS tool embeds MEDIA: tags
+ # in its JSON response, but the model's final text reply usually
+ # doesn't include them. We collect unique tags from tool results and
+ # append any that aren't already present in the final response, so the
+ # adapter's extract_media() can find and deliver the files exactly once.
+ #
+ # Scope the scan to THIS turn's tool results only. ``agent_history``
+ # was passed into run_conversation as ``conversation_history``, so the
+ # agent's returned ``messages`` list is ``agent_history`` followed by
+ # the messages produced this turn. Slicing at ``len(agent_history)``
+ # isolates the current turn precisely, so a stale MEDIA: path emitted
+ # by a tool several turns earlier (still present in the full message
+ # list) can never leak onto a later text-only reply. (Fixes #34608)
+ #
+ # Path-based deduplication against _history_media_paths (collected
+ # before run_conversation) is retained as a secondary guard. It is
+ # also the sole guard on the fallback branch taken when mid-run
+ # context compression shrinks the message list below the original
+ # history length, preserving the compression-safe behaviour of #160.
+ if "MEDIA:" not in final_response:
+ media_tags, has_voice_directive = _collect_auto_append_media_tags(
+ result.get("messages", []),
+ history_offset=len(agent_history),
+ history_media_paths=_history_media_paths,
+ )
- raw_volumes = os.getenv("TERMINAL_DOCKER_VOLUMES", "").strip()
- volumes: List[str] = []
- if raw_volumes:
+ if media_tags:
+ seen = set()
+ unique_tags = []
+ for tag in media_tags:
+ if tag not in seen:
+ seen.add(tag)
+ unique_tags.append(tag)
+ if has_voice_directive:
+ unique_tags.insert(0, "[[audio_as_voice]]")
+ final_response = final_response + "\n" + "\n".join(unique_tags)
+
+ # Auto-generate session title after first exchange (non-blocking)
+ if final_response and self._runner._session_db:
try:
- parsed = json.loads(raw_volumes)
- if isinstance(parsed, list):
- volumes = [str(v) for v in parsed if isinstance(v, str)]
- except Exception:
- logger.debug("Could not parse TERMINAL_DOCKER_VOLUMES for gateway media warning", exc_info=True)
-
- has_explicit_output_mount = False
- for spec in volumes:
- match = _DOCKER_VOLUME_SPEC_RE.match(spec)
- if not match:
- continue
- container_path = match.group("container")
- if container_path in _DOCKER_MEDIA_OUTPUT_CONTAINER_PATHS:
- has_explicit_output_mount = True
- break
+ from agent.title_generator import maybe_auto_title
+ all_msgs = ctx.result_holder[0].get("messages", []) if ctx.result_holder[0] else []
+ # In Gateway mode, auto-title failures must NOT be
+ # surfaced as user-visible messages (fixes #23246).
+ # Log them at debug level only — they are not actionable
+ # to the end user. CLI mode keeps the existing behaviour
+ # via the agent's _emit_auxiliary_failure path.
+ def _title_failure_cb(task: str, exc: BaseException) -> None:
+ logger.debug(
+ "Gateway auto-title failure suppressed (not user-visible): %s: %s",
+ task, exc,
+ )
+ # Snapshot the runtime identity; the validator lets the
+ # background titler skip its LLM call if the session's
+ # model changed before it fires (a stale request would
+ # reload an unloaded Ollama model, #19027).
+ _title_model = getattr(agent, "model", None) if agent else None
+ _title_provider = getattr(agent, "provider", None) if agent else None
+ maybe_auto_title_kwargs = {
+ "failure_callback": _title_failure_cb,
+ "main_runtime": {
+ "model": getattr(agent, "model", None),
+ "provider": getattr(agent, "provider", None),
+ "base_url": getattr(agent, "base_url", None),
+ "api_key": getattr(agent, "api_key", None),
+ "api_mode": getattr(agent, "api_mode", None),
+ } if agent else None,
+ "runtime_validator": (lambda: (
+ getattr(agent, "model", None) == _title_model
+ and getattr(agent, "provider", None) == _title_provider
+ )) if agent else None,
+ }
+ if self._runner._is_telegram_topic_lane(ctx.source):
+ maybe_auto_title_kwargs["title_callback"] = lambda title: self._runner._schedule_telegram_topic_title_rename(
+ ctx.source,
+ effective_session_id,
+ title,
+ )
+ elif self._runner._is_discord_auto_thread_lane(ctx.source):
+ maybe_auto_title_kwargs["title_callback"] = lambda title: self._runner._schedule_discord_semantic_thread_rename(
+ ctx.source,
+ effective_session_id,
+ title,
+ )
+ maybe_auto_title(
+ getattr(self._runner._session_db, "_db", self._runner._session_db),
+ effective_session_id,
+ ctx.message,
+ final_response,
+ all_msgs,
+ **maybe_auto_title_kwargs,
+ )
+ except Exception:
+ pass
- if has_explicit_output_mount:
- return
+ return {
+ "final_response": final_response,
+ "last_reasoning": result.get("last_reasoning"),
+ "messages": ctx.result_holder[0].get("messages", []) if ctx.result_holder[0] else [],
+ "api_calls": ctx.result_holder[0].get("api_calls", 0) if ctx.result_holder[0] else 0,
+ "failed": ctx.result_holder[0].get("failed", False) if ctx.result_holder[0] else False,
+ "failure_reason": (
+ ctx.result_holder[0].get("failure_reason") if ctx.result_holder[0] else None
+ ),
+ "completed": ctx.result_holder[0].get("completed") if ctx.result_holder[0] else None,
+ "interrupted": ctx.result_holder[0].get("interrupted", False) if ctx.result_holder[0] else False,
+ "partial": ctx.result_holder[0].get("partial", False) if ctx.result_holder[0] else False,
+ "error": ctx.result_holder[0].get("error") if ctx.result_holder[0] else None,
+ "interrupt_message": ctx.result_holder[0].get("interrupt_message") if ctx.result_holder[0] else None,
+ # Soft lock-contention defer (#69870 consumer): distinct from
+ # compression_exhausted so the gateway never auto-resets a
+ # session that a concurrent compressor is about to shrink.
+ "compression_deferred": (
+ ctx.result_holder[0].get("compression_deferred", False)
+ if ctx.result_holder[0] else False
+ ),
+ "tools": ctx.tools_holder[0] or [],
+ "history_offset": _effective_history_offset,
+ "compacted_in_place": _compacted_in_place,
+ "last_prompt_tokens": _last_prompt_toks,
+ "input_tokens": _input_toks,
+ "output_tokens": _output_toks,
+ "model": _resolved_model,
+ "context_length": _context_length,
+ "session_id": effective_session_id,
+ "response_previewed": result.get("response_previewed", False),
+ "response_transformed": result.get("response_transformed", False),
+ # Pass through the agent_persisted flag so the persistence block
+ # above can correctly determine whether the codex app-server path
+ # self-persisted (it didn't — see codex_runtime.py). Default
+ # True preserves the skip-db behaviour for the standard runtime.
+ "agent_persisted": (ctx.result_holder[0].get("agent_persisted", True) if ctx.result_holder[0] else True),
+ }
- logger.warning(
- "Docker backend is enabled for the messaging gateway but no explicit host-visible "
- "output mount (for example '/home/user/.hermes/cache/documents:/output') is configured. "
- "This is fine if the model already emits host-visible paths, but MEDIA file delivery can fail "
- "for container-local paths like '/workspace/...' or '/output/...'."
- )
+class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, GatewaySlashCommandsMixin):
+ """
+ Main gateway controller.
- # -- Setup skill availability ----------------------------------------
+ Manages the lifecycle of all platform adapters and routes
+ messages to/from the agent.
+ """
- def _has_setup_skill(self) -> bool:
- """Check if the hermes-agent-setup skill is installed."""
- try:
- from tools.skill_manager_tool import _find_skill
- return _find_skill("hermes-agent-setup") is not None
- except Exception:
- return False
+ # Class-level defaults so partial construction in tests doesn't
+ # blow up on attribute access.
+ _busy_input_mode: str = "interrupt"
+ _busy_text_mode: str = "interrupt"
+ _restart_drain_timeout: float = DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT
+ _exit_code: Optional[int] = None
+ _draining: bool = False
+ _external_drain_active: bool = False
+ _restart_requested: bool = False
+ _restart_task_started: bool = False
+ _restart_detached: bool = False
+ _restart_via_service: bool = False
+ _detached_restart_helper_started: bool = False
+ _restart_command_source: Optional[SessionSource] = None
+ _stop_task: Optional[asyncio.Task] = None
+ _restart_task: Optional[asyncio.Task] = None
+ _profile_failed_platforms: Optional[Dict[str, Dict[Platform, asyncio.Task]]] = None
+ _systemd_watchdog: Optional[Any] = None
+ _startup_restore_in_progress: bool = False
- # -- Voice mode persistence ------------------------------------------
+ # ------------------------------------------------------------------
+ # Legacy per-session dict adapters. All per-session state lives in
+ # ``self._sessions`` (Dict[str, SessionState]); these properties expose
+ # the pre-consolidation dict attributes as LIVE MutableMapping views so
+ # the extensive test surface (and a few mixin/adapter call sites) that
+ # read/write ``runner._running_agents`` etc. keeps working unchanged.
+ # New production code should use ``self._session_state(key)`` directly.
+ # ------------------------------------------------------------------
+ _running_agents = legacy_dict_property("_running_agents")
+ _running_agents_ts = legacy_dict_property("_running_agents_ts")
+ _active_session_leases = legacy_dict_property("_active_session_leases")
+ _busy_ack_ts = legacy_dict_property("_busy_ack_ts")
+ _turn_lease_tokens = legacy_lease_token_property()
+ _session_run_generation = legacy_dict_property("_session_run_generation")
+ _session_model_overrides = legacy_dict_property("_session_model_overrides")
+ _pending_one_turn_model_restores = legacy_dict_property(
+ "_pending_one_turn_model_restores"
+ )
+ _session_reasoning_overrides = legacy_dict_property("_session_reasoning_overrides")
+ _session_service_tier_overrides = legacy_dict_property(
+ "_session_service_tier_overrides"
+ )
+ _last_resolved_model = legacy_dict_property("_last_resolved_model")
+ _queued_events = legacy_dict_property("_queued_events")
+ _pending_turn_sidecar_notes = legacy_dict_property("_pending_turn_sidecar_notes")
+ _pending_messages = legacy_dict_property("_pending_messages")
+ _pending_native_image_paths_by_session = legacy_dict_property(
+ "_pending_native_image_paths_by_session"
+ )
+ _session_ephemeral_pin = legacy_dict_property("_session_ephemeral_pin")
+ _session_vc_last = legacy_dict_property("_session_vc_last")
+ _pending_approvals = legacy_dict_property("_pending_approvals")
+ _update_prompt_pending = legacy_dict_property("_update_prompt_pending")
- _VOICE_MODE_PATH = _hermes_home / "gateway_voice_mode.json"
+ # -- SessionState accessors -----------------------------------------
+ def _sessions_map(self) -> Dict[str, "SessionState"]:
+ """The per-session state map; lazily created so bare test runners
+ built via ``object.__new__`` work without ``__init__``."""
+ sessions = self.__dict__.get("_sessions")
+ if sessions is None:
+ sessions = {}
+ self.__dict__["_sessions"] = sessions
+ return sessions
- def _voice_key(self, platform: Platform, chat_id: str) -> str:
- """Return a platform-namespaced key for voice mode state."""
- return f"{platform.value}:{chat_id}"
+ def _session_state(self, session_key: str) -> "SessionState":
+ """Get-or-create the :class:`SessionState` for ``session_key``."""
+ sessions = self._sessions_map()
+ state = sessions.get(session_key)
+ if state is None:
+ state = SessionState()
+ sessions[session_key] = state
+ return state
- def _load_voice_modes(self) -> Dict[str, str]:
- try:
- data = json.loads(self._VOICE_MODE_PATH.read_text(encoding="utf-8"))
- except (FileNotFoundError, json.JSONDecodeError, OSError):
- return {}
+ def _peek_session_state(self, session_key: str) -> Optional["SessionState"]:
+ """Return the SessionState for ``session_key`` without creating one."""
+ sessions = self.__dict__.get("_sessions")
+ if not sessions:
+ return None
+ return sessions.get(session_key)
- if not isinstance(data, dict):
- return {}
+ def _is_session_running(self, session_key: str) -> bool:
+ """True when the session holds a running-turn slot (agent or sentinel)."""
+ state = self._peek_session_state(session_key)
+ return state is not None and state.turn.agent is not None
- valid_modes = {"off", "voice_only", "all"}
- result = {}
- for chat_id, mode in data.items():
- if mode not in valid_modes:
- continue
- key = str(chat_id)
- # Skip legacy unprefixed keys (warn and skip)
- if ":" not in key:
- logger.warning(
- "Skipping legacy unprefixed voice mode key %r during migration. "
- "Re-enable voice mode on that chat to rebuild the prefixed key.",
- key,
- )
- continue
- result[key] = mode
- return result
+ def _running_agent_items(self) -> List[tuple]:
+ """(session_key, agent) pairs for sessions with a running turn
+ (including pending sentinels), matching the old ``_running_agents``
+ dict contents."""
+ return [
+ (key, state.turn.agent)
+ for key, state in self._sessions_map().items()
+ if state.turn.agent is not None
+ ]
+ # Loop-liveness heartbeat / watchdog handles (#66892, #69089). Class-level
+ # defaults so partial construction in tests doesn't blow up on access; the
+ # real values are set in __init__ / start() / stop().
+ _loop_heartbeat_task: Optional["asyncio.Task"] = None
+ _loop_floor_timer_handle: Optional[Any] = None
+ _loop_liveness_watchdog: Optional[Any] = None
+ _gateway_started_at: float = 0.0
+ _shutdown_watchdog_done: Optional["threading.Event"] = None
+ _platform_lock_takeover_on_start: bool = False
+ _reconnect_watcher_task: Optional["asyncio.Task"] = None
- def _save_voice_modes(self) -> None:
+ def __init__(self, config: Optional[GatewayConfig] = None):
+ global _gateway_runner_ref
+ # When multiplex_profiles is on, load under the default profile secret
+ # scope so bot tokens in that profile's .env resolve the same way
+ # secondary profiles do (#64674). Explicit config= injection (tests)
+ # is left untouched.
+ self.config = config if config is not None else load_gateway_config_for_runner()
+ # Mark the process as a profile multiplexer when configured. This flips
+ # agent.secret_scope.get_secret() to fail-closed on any unscoped
+ # credential read, so a missed migration crashes loudly instead of
+ # leaking a cross-profile value (Workstream A). Inert when off.
try:
- self._VOICE_MODE_PATH.parent.mkdir(parents=True, exist_ok=True)
- self._VOICE_MODE_PATH.write_text(
- json.dumps(self._voice_mode, indent=2), encoding="utf-8"
- )
- except OSError as e:
- logger.warning("Failed to save voice modes: %s", e)
-
- def _set_adapter_auto_tts_disabled(self, adapter, chat_id: str, disabled: bool) -> None:
- """Update an adapter's in-memory auto-TTS suppression set if present."""
- disabled_chats = getattr(adapter, "_auto_tts_disabled_chats", None)
- if not isinstance(disabled_chats, set):
- return
- if disabled:
- disabled_chats.add(chat_id)
- # ``/voice off`` also clears any explicit enable — it's a hard override.
- enabled_chats = getattr(adapter, "_auto_tts_enabled_chats", None)
- if isinstance(enabled_chats, set):
- enabled_chats.discard(chat_id)
- else:
- disabled_chats.discard(chat_id)
-
- def _set_adapter_auto_tts_enabled(self, adapter, chat_id: str, enabled: bool) -> None:
- """Update an adapter's per-chat auto-TTS opt-in set if present.
-
- Used for ``/voice on``/``/voice tts`` where the user explicitly wants
- auto-TTS even when ``voice.auto_tts`` is False globally.
- """
- enabled_chats = getattr(adapter, "_auto_tts_enabled_chats", None)
- if not isinstance(enabled_chats, set):
- return
- if enabled:
- enabled_chats.add(chat_id)
- # An explicit opt-in clears any stale /voice off for this chat.
- disabled_chats = getattr(adapter, "_auto_tts_disabled_chats", None)
- if isinstance(disabled_chats, set):
- disabled_chats.discard(chat_id)
- else:
- enabled_chats.discard(chat_id)
+ from agent.secret_scope import set_multiplex_active
+ set_multiplex_active(bool(getattr(self.config, "multiplex_profiles", False)))
+ except Exception:
+ logger.debug("could not set multiplex-active flag", exc_info=True)
+ self.adapters: Dict[Platform, BasePlatformAdapter] = {}
+ # Multi-profile multiplexing: adapters for NON-default profiles live
+ # here, keyed by profile name then Platform. self.adapters stays the
+ # default/active profile's map so the ~93 existing self.adapters[...]
+ # sites are untouched when multiplexing is off (this dict is empty).
+ # Populated by _start_secondary_profile_adapters().
+ self._profile_adapters: Dict[str, Dict[Platform, BasePlatformAdapter]] = {}
+ self._warn_if_docker_media_delivery_is_risky()
+ _gateway_runner_ref = _weakref.ref(self)
- def _sync_voice_mode_state_to_adapter(self, adapter) -> None:
- """Restore persisted /voice state into a live platform adapter.
+ # Load ephemeral config from config.yaml / env vars.
+ # Both are injected at API-call time only and never persisted.
+ self._prefill_messages = self._load_prefill_messages()
+ self._ephemeral_system_prompt = self._load_ephemeral_system_prompt()
+ self._reasoning_config = self._load_reasoning_config()
+ self._service_tier = self._load_service_tier()
+ self._show_reasoning = self._load_show_reasoning()
+ self._busy_input_mode = self._load_busy_input_mode()
+ 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._fallback_model = self._load_fallback_model()
- Populates three fields from config + ``self._voice_mode``:
- - ``_auto_tts_default``: global default from ``voice.auto_tts``
- - ``_auto_tts_enabled_chats``: chats with mode ``voice_only``/``all``
- - ``_auto_tts_disabled_chats``: chats with mode ``off``
- """
- platform = getattr(adapter, "platform", None)
- if not isinstance(platform, Platform):
- return
+ # Wire process registry into session store for reset protection.
+ # A background process older than the configured threshold (default 24h,
+ # session_reset.bg_process_max_age_hours) is treated as stale and no
+ # longer blocks session idle / daily reset — see #29177. The process is
+ # NOT killed, only ignored by the reset guard.
+ from tools.process_registry import process_registry
+ _bg_max_age_hours = getattr(
+ self.config.default_reset_policy, "bg_process_max_age_hours", 24
+ )
+ _bg_max_age_seconds = (
+ _bg_max_age_hours * 3600 if _bg_max_age_hours and _bg_max_age_hours > 0 else None
+ )
+ self.session_store = SessionStore(
+ self.config.sessions_dir, self.config,
+ has_active_processes_fn=lambda key: process_registry.has_active_for_session(
+ key, max_active_age=_bg_max_age_seconds,
+ ),
+ )
+ # One enforced loop-side boundary for the synchronous SessionStore.
+ # Sync helpers keep using ``session_store`` directly; async gateway
+ # handlers call this facade and await every operation.
+ self._async_session_store = AsyncSessionStore(self.session_store)
+ self.delivery_router = DeliveryRouter(self.config)
+ self._running = False
+ self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._shutdown_event = asyncio.Event()
+ self._exit_cleanly = False
+ self._exit_with_failure = False
+ self._exit_reason: Optional[str] = None
+ self._exit_code: Optional[int] = None
+ self._draining = False
+ self._profile_failed_platforms: Dict[str, Dict[Platform, asyncio.Task]] = {}
+ self._systemd_watchdog = None
+ # External (NAS-driven) drain state — distinct from the shutdown
+ # ``_draining`` flag above. Set by ``_drain_control_watcher`` when the
+ # ``.drain_request.json`` marker is present: the gateway flips
+ # ``gateway_state -> draining`` and refuses NEW turns, but the process
+ # does NOT exit (the whole point — quiesce-without-restart, D4a). It is
+ # fully reversible: removing the marker reverts to ``running`` and
+ # re-accepts turns. ``_draining`` (shutdown) is one-way and ends in
+ # process exit; this one is a steady state NAS polls during its
+ # request -> poll -> proceed loop.
+ self._external_drain_active = False
+ self._restart_requested = False
+ # Set by shutdown_signal_handler when a SIGTERM/SIGINT arrived
+ # WITHOUT a planned-stop / takeover marker — i.e. an unexpected
+ # external signal (container/s6 SIGTERM on `docker restart` or
+ # image upgrade, OOM-killer, bare `kill`). Distinct from an
+ # operator-requested stop, which writes a marker first. Used by
+ # _stop_impl to decide whether to persist gateway_state=stopped
+ # (see issue #42675): an unexpected signal must NOT persist
+ # "stopped", or container_boot refuses to auto-start the gateway
+ # on the next boot.
+ self._signal_initiated_shutdown = False
+ self._restart_task_started = False
+ self._restart_detached = False
+ self._restart_via_service = False
+ self._detached_restart_helper_started = False
+ self._restart_command_source: Optional[SessionSource] = None
+ # Monotonic-ish wall clock of when this GatewayRunner was constructed.
+ # Used by the /restart redelivery guard to bound the window in which a
+ # missing dedup marker is treated as a stale redelivery.
+ self._startup_time: float = time.time()
+ # Set True at startup when this process booted as the result of a
+ # chat-originated /restart (i.e. .restart_notify.json existed on boot).
+ # A one-shot signal consumed by _is_stale_restart_redelivery so the
+ # marker-missing fallback only suppresses a /restart when we KNOW we
+ # just came out of a restart cycle — never on a genuine fresh boot.
+ self._booted_from_restart: bool = False
+ self._stop_task: Optional[asyncio.Task] = None
+ self._restart_task: Optional[asyncio.Task] = None
+ self._executor_lock = threading.Lock()
+ self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Set on gateway stop so the recreate-on-shutdown path can't resurrect
+ # the pool during a real shutdown.
+ self._executor_closing = False
+ # ALL per-session state (turn / conversation / persistent scopes)
+ # lives in one container — see gateway/session_state.py. Access via
+ # self._session_state(key) (get-or-create) or
+ # self._peek_session_state(key) (read-only).
+ self._sessions: Dict[str, SessionState] = {}
+ # Per-SESSION_ID turn lease (#64934): serializes the
+ # [load history → run → flush] region when two ROUTING KEYS resolve
+ # to one session_id (switch_session's many-to-one mapping). The
+ # routing-key guards above cannot see that overlap. Acquired in
+ # _handle_message_with_agent after session resolution is final,
+ # released via _release_turn_lease in the same method's finally.
+ self._turn_leases = SessionTurnLeaseRegistry()
+ # Tokens for held turn leases, keyed by (routing key, run generation)
+ # so release is granted per-turn and a stale unwind can never free a
+ # newer turn's lease (#28686 ownership lesson).
+ # Held turn-lease tokens live on SessionState.turn.lease_token /
+ # .lease_generation (the old dict was keyed (routing key, generation)
+ # so a stale unwind could never free a newer turn's lease — the
+ # generation field preserves that ownership check, #28686).
+ # Runner-level queued interrupt text lives on
+ # SessionState.persistent.pending_command_text (NOTE: distinct from
+ # the adapter-level _pending_messages Dict[str, MessageEvent] in
+ # gateway/platforms/base.py, which shares the legacy name).
+ # Last successfully-resolved (non-empty) model, keyed by session. Used
+ # as a fallback when a fresh config read transiently returns an empty
+ # model (e.g. an mtime-keyed config-cache miss during a post-interrupt
+ # recovery turn). Without this, the agent is built with model="" and
+ # every API call fails HTTP 400 "No models provided" — the session goes
+ # silent until the user manually re-sends. See #35314. The ``"*"``
+ # session entry holds a process-wide last-known-good for sessions
+ # seen for the first time. Lives on
+ # SessionState.conversation.last_resolved_model.
+ # Overflow buffer for explicit /queue commands. The adapter-level
+ # _pending_messages dict is a single slot per session (designed for
+ # "next-turn" follow-ups where repeated sends collapse into one
+ # event). /queue has different semantics: each invocation must
+ # produce its own full agent turn, in FIFO order, with no merging.
+ # When the slot is occupied, additional /queue items land here and
+ # are promoted one-at-a-time after each run's drain. Cleared on
+ # /new and /reset. /model and other mid-session operations
+ # preserve the queue. Lives on SessionState.conversation.queued_events;
+ # native image paths, busy-ack debounce timestamps and the monotonic
+ # run-generation counter (#28686, NEVER reset) live on SessionState too.
+ # Startup restore gate: while restart-interrupted sessions are being
+ # auto-resumed, real inbound messages are queued instead of competing
+ # with the synthetic resume turns for the same session. The queued
+ # events drain only after all startup resume tasks have finished.
+ self._startup_restore_in_progress = False
+ # Set by start_gateway() only for an explicit ``--replace`` launch.
+ # _connect_initial_adapter_with_timeout scopes it to each adapter's
+ # cold-start connect and removes it before any reconnect can run.
+ self._platform_lock_takeover_on_start = False
+ self._startup_restore_queue: List[MessageEvent] = []
+ self._startup_restore_tasks: List[asyncio.Task] = []
+ # LRU cache of live SessionSources keyed by session_key. Used by
+ # fallback routing paths (shutdown notifications, synthetic
+ # background-process events) when the persisted origin is missing
+ # and _parse_session_key can't recover thread_id. Capped so it
+ # cannot grow unbounded over a long-running gateway lifetime.
+ self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()
+ self._session_sources_max = 512
+ # Completion delivery is intentionally lifecycle-scoped. This closes
+ # duplicate queue/watcher races inside one gateway without pretending
+ # the adapter call and a persistence write can be exactly-once across
+ # a process crash. Any durable async-delegation replay state remains
+ # owned by tools.async_delegation, not a parallel gateway ledger.
+ self._completion_delivery_lock = threading.Lock()
+ self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()
+ self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()
+ self._completion_delivery_retention = 2048
- disabled_chats = getattr(adapter, "_auto_tts_disabled_chats", None)
- enabled_chats = getattr(adapter, "_auto_tts_enabled_chats", None)
- if not isinstance(disabled_chats, set) and not isinstance(enabled_chats, set):
- return
+ # Cache AIAgent instances per session to preserve prompt caching.
+ # Without this, a new AIAgent is created per message, rebuilding the
+ # system prompt (including memory) every turn — breaking prefix cache
+ # and costing ~10x more on providers with prompt caching (Anthropic).
+ # Key: session_key, Value: (AIAgent, config_signature_str)
+ #
+ # OrderedDict so _enforce_agent_cache_cap() can pop the least-recently-
+ # used entry (move_to_end() on cache hits, popitem(last=False) for
+ # eviction). Hard cap via _AGENT_CACHE_MAX_SIZE, idle TTL enforced
+ # from _session_expiry_watcher().
+ import threading as _threading
+ self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()
+ self._agent_cache_lock = _threading.Lock()
- # Push the global voice.auto_tts default (config.yaml) onto the adapter.
- # Lazy import to avoid adding a module-level dep from gateway → hermes_cli.
- try:
- from hermes_cli.config import load_config as _load_full_config
- _full_cfg = _load_full_config()
- _auto_tts_default = bool(
- (_full_cfg.get("voice") or {}).get("auto_tts", False)
- )
- except Exception:
- _auto_tts_default = False
- if hasattr(adapter, "_auto_tts_default"):
- adapter._auto_tts_default = _auto_tts_default
+ # Conversation-scoped per-session state (/model, /model --once,
+ # /reasoning, /fast overrides; per-turn sidecar notes; ephemeral
+ # context pin; last-delivered voice-channel context) lives on
+ # SessionState.conversation — see gateway/session_state.py.
+ self._kanban_notifier_profile = self._active_profile_name()
+ # Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
+ self._teams_pipeline_runtime = None
+ self._teams_pipeline_runtime_error: Optional[str] = None
+ # Pending exec approvals live on SessionState.persistent.approvals.
- prefix = f"{platform.value}:"
- if isinstance(disabled_chats, set):
- disabled_chats.clear()
- disabled_chats.update(
- key[len(prefix):] for key, mode in self._voice_mode.items()
- if mode == "off" and key.startswith(prefix)
- )
- if isinstance(enabled_chats, set):
- enabled_chats.clear()
- enabled_chats.update(
- key[len(prefix):] for key, mode in self._voice_mode.items()
- if mode in {"voice_only", "all"} and key.startswith(prefix)
- )
+ # Track platforms that failed to connect for background reconnection.
+ # Key: Platform enum, Value: {"config": platform_config, "attempts": int, "next_retry": float}
+ self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}
- async def _await_adapter_cleanup_with_timeout(
- self, awaitable: Awaitable[Any], timeout: float
- ) -> bool:
- """Wait for adapter cleanup without letting cancellation swallowing hang us.
+ # Strong refs to detached fatal-error handler tasks (see
+ # _handle_adapter_fatal_error) so the event loop can't GC them mid-run.
+ self._fatal_handler_tasks: set = set()
- ``asyncio.wait_for`` cancels an overdue child but then waits for it to
- exit. An adapter close path that catches ``CancelledError`` can therefore
- block recovery forever. Keep ownership of the old task through its done
- callback, but release the runner at the deadline.
- """
- if timeout <= 0:
- await awaitable
- return True
+ # Pending /update prompt flags live on
+ # SessionState.persistent.update_prompt_pending.
- task = asyncio.ensure_future(awaitable)
- try:
- done, _pending = await asyncio.wait({task}, timeout=timeout)
- except asyncio.CancelledError:
- task.cancel()
- task.add_done_callback(consume_detached_task_result)
- raise
- if task in done:
- await task
- return True
+ # Slash-confirm state lives in tools.slash_confirm (module-level),
+ # so platform adapters can resolve callbacks without a backref to
+ # this runner. Keep a local counter for confirm_id generation so
+ # IDs stay compact (button callback_data has a 64-byte cap on
+ # some platforms).
+ import itertools as _itertools
+ self._slash_confirm_counter = _itertools.count(1)
- task.cancel()
- task.add_done_callback(consume_detached_task_result)
- return False
+ # Persistent Honcho managers keyed by gateway session key.
+ # This preserves write_frequency="session" semantics across short-lived
+ # per-message AIAgent instances.
- async def _safe_adapter_disconnect(self, adapter, platform) -> None:
- """Call adapter.disconnect() defensively, swallowing any error.
- Used when adapter.connect() failed or raised — the adapter may
- have allocated partial resources (aiohttp.ClientSession, poll
- tasks, child subprocesses) that would otherwise leak and surface
- as "Unclosed client session" warnings at process exit.
- Must tolerate partial-init state and never raise, since callers
- use it inside error-handling blocks.
- """
- timeout = self._adapter_disconnect_timeout_secs()
+ # Ensure tirith security scanner is available (downloads if needed)
try:
- completed = await self._await_adapter_cleanup_with_timeout(
- adapter.disconnect(), timeout
- )
- if not completed:
- logger.warning(
- "Timed out after %.1fs while disconnecting %s adapter; continuing shutdown",
- timeout,
- platform.value if platform is not None else "adapter",
- )
- except Exception as e:
- logger.debug(
- "Defensive %s disconnect after failed connect raised: %s",
- platform.value if platform is not None else "adapter",
- e,
- )
-
- async def _bounded_adapter_teardown(
- self, adapter, platform, *, profile: Optional[str] = None
- ) -> None:
- """Tear down one adapter on the shutdown path with bounded awaits.
-
- Both ``cancel_background_tasks()`` and ``disconnect()`` can block
- indefinitely when a platform's network state is half-dead (e.g. a
- wedged Feishu/Lark WebSocket thread waiting on I/O). An unbounded
- await here stalls the entire shutdown sequence past systemd's
- ``TimeoutStopSec``; the resulting SIGKILL skips ``atexit`` PID-file
- cleanup, so the next start dies with "PID file race lost" (#14128).
+ from tools.tirith_security import ensure_installed
+ ensure_installed(log_failures=False)
+ except Exception:
+ pass # Non-fatal — fail-open at scan time if unavailable
- Each await uses the existing per-adapter timeout budget
- (``HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT``). On timeout the old
- task is cancelled and detached, then teardown forces forward progress;
- the loop never hangs even if an adapter swallows cancellation. Never
- raises.
- """
- timeout = self._adapter_disconnect_timeout_secs()
- suffix = f" (profile: {profile})" if profile else ""
- started_at = time.monotonic()
+ # Startup heads-up (#30882): a gateway in manual approval mode with no
+ # automated risk assessor (tirith disabled AND no auxiliary.approval
+ # model) can only gate dangerous commands / execute_code scripts via
+ # live in-chat approval. With approval routing fixed, those actions now
+ # fail closed (block) rather than silently auto-running — surface that
+ # so operators knowingly enable tirith or configure auxiliary.approval
+ # for unattended gateways.
try:
- cancelled = await self._await_adapter_cleanup_with_timeout(
- adapter.cancel_background_tasks(), timeout
- )
- if not cancelled:
+ from hermes_cli.config import load_config as _load_full_config
+ _appr_cfg = _load_full_config()
+ _appr_mode = str(
+ cfg_get(_appr_cfg, "approvals", "mode", default="manual") or "manual"
+ ).strip().lower()
+ _tirith_on = bool(cfg_get(_appr_cfg, "security", "tirith_enabled", default=True))
+ _aux_approval = cfg_get(_appr_cfg, "auxiliary", "approval", default=None)
+ if _appr_mode == "manual" and not _tirith_on and not _aux_approval:
logger.warning(
- "✗ %s background-task cancel timed out after %.1fs - forcing continue%s",
- platform.value, timeout, suffix,
+ "Gateway approvals.mode=manual with no automated risk "
+ "assessor (security.tirith_enabled is false and "
+ "auxiliary.approval is unset): dangerous commands and "
+ "execute_code scripts will BLOCK until a human approves "
+ "them in chat. Enable security.tirith_enabled or configure "
+ "auxiliary.approval for unattended operation."
)
- except Exception as e:
- logger.debug("✗ %s background-task cancel error%s: %s", platform.value, suffix, e)
+ except Exception:
+ logger.debug("approvals.mode startup check skipped", exc_info=True)
+
+ # Initialize session database for session_search tool support
+ self._session_db = None
try:
- disconnected = await self._await_adapter_cleanup_with_timeout(
- adapter.disconnect(), timeout
- )
- if disconnected:
- logger.info(
- "✓ %s disconnected (%.2fs)%s",
- platform.value, time.monotonic() - started_at, suffix,
- )
- else:
- logger.warning(
- "✗ %s disconnect timed out after %.1fs - forcing continue%s",
- platform.value, timeout, suffix,
- )
+ from hermes_state import AsyncSessionDB, SessionDB
+ self._session_db = AsyncSessionDB(SessionDB())
except Exception as e:
- logger.error(
- "✗ %s disconnect error after %.2fs%s: %s",
- platform.value, time.monotonic() - started_at, suffix, e,
- )
-
- def _adapter_disconnect_timeout_secs(self) -> float:
- """Return the per-adapter disconnect timeout used during shutdown."""
- raw = os.getenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "").strip()
- if raw:
- try:
- timeout = float(raw)
- except ValueError:
- logger.warning(
- "Ignoring invalid HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT=%r",
- raw,
- )
- else:
- return max(0.0, timeout)
- return _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT
+ # WARNING (not DEBUG) so the failure appears in errors.log — matches
+ # cli.py's handling of the same init path. Users hitting NFS-mounted
+ # HERMES_HOME silently lost /resume, /title, /history, /branch, and
+ # session search without this. The underlying cause (usually
+ # "locking protocol" from NFS) is now also captured by
+ # hermes_state.get_last_init_error() for slash-command error strings.
+ logger.warning("SQLite session store not available: %s", e)
- def _platform_connect_timeout_secs(self, platform=None) -> float:
- """Return the per-platform connect timeout used during startup/retry."""
- raw = os.getenv("HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT", "").strip()
- if raw:
+ # Opportunistic state.db maintenance: prune ended sessions inactive
+ # for sessions.retention_days + optional VACUUM. Tracks last-run
+ # in state_meta so it only actually executes once per
+ # sessions.min_interval_hours. Gateway is long-lived so blocking
+ # a few seconds once per day is acceptable; failures are logged
+ # but never raised.
+ if self._session_db is not None:
try:
- timeout = float(raw)
- except ValueError:
- logger.warning(
- "Ignoring invalid HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT=%r",
- raw,
- )
- else:
- return max(0.0, timeout)
- if platform == Platform.TELEGRAM:
- return _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT
- return _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT
-
- async def _connect_adapter_with_timeout(
- self, adapter, platform, *, is_reconnect: bool = False
- ) -> bool:
- """Connect an adapter without allowing one platform to block others.
+ from hermes_cli.config import load_config as _load_full_config
+ _sess_cfg = (_load_full_config().get("sessions") or {})
+ # Non-destructive stale-session archive, independent of prune.
+ if _sess_cfg.get("auto_archive", False):
+ self._session_db._db.maybe_auto_archive(
+ idle_days=float(_sess_cfg.get("auto_archive_days", 3)),
+ min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)),
+ )
+ if _sess_cfg.get("auto_prune", False):
+ # Construction-time, before the loop serves traffic; sync DB is fine.
+ self._session_db._db.maybe_auto_prune_and_vacuum(
+ retention_days=int(_sess_cfg.get("retention_days", 90)),
+ min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)),
+ vacuum=bool(_sess_cfg.get("vacuum_after_prune", True)),
+ sessions_dir=self.config.sessions_dir,
+ )
+ except Exception as exc:
+ logger.debug("state.db auto-maintenance skipped: %s", exc)
- ``is_reconnect`` is forwarded to ``adapter.connect()`` so platform
- adapters can distinguish a cold first boot (drop any stale
- server-side queue) from a watcher reconnect after a prolonged outage
- (preserve the queue so messages sent during the outage are delivered
- rather than silently dropped — #46621).
- """
- timeout = self._platform_connect_timeout_secs(platform)
- if timeout <= 0:
- return await adapter.connect(is_reconnect=is_reconnect)
- # Use the detach-on-timeout pattern instead of plain asyncio.wait_for:
- # asyncio.wait_for cancels the overdue task but then waits for it to
- # exit. An adapter connect() that catches CancelledError can therefore
- # block recovery forever (the watcher never reaches the next retry).
- # Keep ownership of the old task through its done callback, but
- # release the runner at the deadline (#70344).
- task = asyncio.ensure_future(
- adapter.connect(is_reconnect=is_reconnect)
- )
+ # Opportunistic shadow-repo cleanup — deletes stale checkpoint repos
+ # under ~/.hermes/checkpoints/. Opt-in via checkpoints.auto_prune,
+ # idempotent via .last_prune marker.
try:
- done, _pending = await asyncio.wait({task}, timeout=timeout)
- except asyncio.CancelledError:
- task.cancel()
- task.add_done_callback(consume_detached_task_result)
- raise
- if task in done:
- result = await task
- return bool(result)
- task.cancel()
- task.add_done_callback(consume_detached_task_result)
- raise TimeoutError(
- f"{platform.value} connect timed out after {timeout:g}s"
- )
+ from hermes_cli.config import load_config as _load_full_config
+ _ckpt_cfg = (_load_full_config().get("checkpoints") or {})
+ if _ckpt_cfg.get("auto_prune", False):
+ from tools.checkpoint_manager import maybe_auto_prune_checkpoints
+ # delete_orphans is intentionally never honoured here: a
+ # missing workdir at startup is ambiguous (deleted project
+ # vs. an unmounted external volume / network share / VPN
+ # not yet up) and this sweep runs unattended. Orphan cleanup
+ # is only ever done via the explicit `hermes checkpoints
+ # prune` command, which the user has to invoke.
+ maybe_auto_prune_checkpoints(
+ retention_days=int(_ckpt_cfg.get("retention_days", 7)),
+ min_interval_hours=int(_ckpt_cfg.get("min_interval_hours", 24)),
+ delete_orphans=False,
+ max_total_size_mb=int(_ckpt_cfg.get("max_total_size_mb", 500)),
+ )
+ except Exception as exc:
+ logger.debug("checkpoint auto-maintenance skipped: %s", exc)
- async def _connect_initial_adapter_with_timeout(self, adapter, platform) -> bool:
- """Connect one cold-start adapter with tightly scoped replace intent.
+ # DM pairing store for code-based user authorization.
+ # ``pairing_store`` stays as the global/default store for the
+ # ``hermes pairing`` CLI and any caller without a profile context.
+ # ``pairing_stores`` is the per-profile map used by
+ # ``authz_mixin._is_user_authorized`` to route checks to the right
+ # whitelist (one per profile in multiplex mode).
+ from gateway.pairing import PairingStore
+ self.pairing_store = PairingStore()
+ self.pairing_stores: Dict[str, "PairingStore"] = {}
+
+ # Event hook system
+ from gateway.hooks import HookRegistry
+ self.hooks = HookRegistry()
- The capability is visible only while this initial connect is awaited.
- Reconnects call ``_connect_adapter_with_timeout`` directly and adapters
- also default to deny, so a later network recovery can never evict a
- healthy token holder.
- """
- adapter._platform_lock_takeover_allowed = bool(
- self._platform_lock_takeover_on_start
- )
- try:
- return await self._connect_adapter_with_timeout(adapter, platform)
- finally:
- adapter._platform_lock_takeover_allowed = False
+ # Per-chat voice reply mode: "off" | "voice_only" | "all"
+ self._voice_mode: Dict[str, str] = self._load_voice_modes()
+ # Recent voice transcripts per (guild,user) for duplicate suppression.
+ # Protects against the same utterance being emitted twice by the voice
+ # capture / STT pipeline, which otherwise produces a second delayed reply.
+ self._recent_voice_transcripts: Dict[tuple[int, int], List[tuple[float, str]]] = {}
- @property
- def should_exit_cleanly(self) -> bool:
- return self._exit_cleanly
+ # Track background tasks to prevent garbage collection mid-execution
+ self._background_tasks: set = set()
- @property
- def should_exit_with_failure(self) -> bool:
- return self._exit_with_failure
+ # Event-loop liveness heartbeat (#66892): rewritten every 30s while
+ # the loop is dispatching. External supervisors use the file mtime /
+ # updated_at to distinguish "process alive" from "loop frozen".
+ self._gateway_started_at: float = time.time()
+ self._loop_heartbeat_task: Optional[asyncio.Task] = None
+ self._loop_floor_timer_handle = None
+ self._loop_liveness_watchdog = None
- @property
- def exit_reason(self) -> Optional[str]:
- return self._exit_reason
+ # scale-to-zero (Phase 0, F13): gateway-scoped "last inbound seen" clock.
+ # There is no such clock today (only a per-agent _last_activity_ts), so the
+ # idle predicate needs this. Stamped in _handle_message (the single inbound
+ # chokepoint all adapters call); seeded to "now" so a fresh gateway isn't
+ # considered idle from epoch. The scale-to-zero watcher (started only when
+ # the instance is opted in + relay-only + has a wakeUrl) reads it.
+ self._last_inbound_at: float = time.time()
+ # Set after a wake (re-arm cooldown, 0.F) so we don't immediately re-go
+ # dormant before the drained backlog has a chance to update the clock.
+ self._scale_to_zero_cooldown_until: float = 0.0
- @property
- def exit_code(self) -> Optional[int]:
- return self._exit_code
- def _session_key_for_source(self, source: SessionSource) -> str:
- """Resolve the current session key for a source, honoring gateway config when available."""
- if hasattr(self, "session_store") and self.session_store is not None:
- try:
- session_key = self.session_store._generate_session_key(source)
- if isinstance(session_key, str) and session_key:
- return session_key
- except Exception:
- pass
- config = getattr(self, "config", None)
- # Mirror SessionStore._resolve_profile_for_key so this fallback path
- # produces the same namespace as the primary path: None (legacy
- # agent:main) unless multiplexing is on, then the active profile.
- _profile = None
- if getattr(config, "multiplex_profiles", False):
- if source.profile:
- _profile = source.profile
- else:
- try:
- from hermes_cli.profiles import get_active_profile_name
- _profile = get_active_profile_name() or "default"
- except Exception:
- _profile = None
- return build_session_key(
- source,
- group_sessions_per_user=getattr(config, "group_sessions_per_user", True),
- thread_sessions_per_user=getattr(config, "thread_sessions_per_user", False),
- profile=_profile,
- )
+ def _wire_teams_pipeline_runtime(self) -> None:
+ """Bind the Teams meeting pipeline runtime to Graph webhook ingress.
- def _telegram_topic_mode_enabled(self, source: SessionSource) -> bool:
- """Return whether Telegram DM topic mode is active for this chat."""
- if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
- return False
- session_db = getattr(self, "_session_db", None)
- if session_db is None:
- return False
- # Runs off-loop (always via asyncio.to_thread); use the sync handle.
- session_db = getattr(session_db, "_db", session_db)
+ No-op when the msgraph_webhook adapter isn't running or the
+ teams_pipeline plugin isn't enabled — lets the gateway start cleanly
+ whether or not the user has opted into the pipeline.
+ """
+ if Platform.MSGRAPH_WEBHOOK not in self.adapters:
+ return
+ if not _teams_pipeline_plugin_enabled():
+ logger.debug("Teams pipeline plugin is disabled; skipping runtime wiring")
+ return
try:
- raw = session_db.is_telegram_topic_mode_enabled(
- chat_id=str(source.chat_id),
- user_id=str(source.user_id),
+ from plugins.teams_pipeline.runtime import bind_gateway_runtime
+ except Exception as exc:
+ logger.warning("Teams pipeline runtime import failed: %s", exc)
+ return
+ try:
+ bound = bind_gateway_runtime(self)
+ except Exception as exc:
+ logger.warning("Teams pipeline runtime wiring failed: %s", exc)
+ return
+ if bound:
+ logger.info("Teams pipeline runtime bound to msgraph webhook ingress")
+ elif self._teams_pipeline_runtime_error:
+ logger.warning(
+ "Teams pipeline runtime unavailable: %s",
+ self._teams_pipeline_runtime_error,
)
- except Exception:
- logger.debug("Failed to read Telegram topic mode state", exc_info=True)
- return False
- # Only honor a real True from the SessionDB. Any other value
- # (including MagicMock instances from test fixtures that didn't
- # opt into topic mode) means topic mode is off for this chat.
- return raw is True
- # Telegram's General (pinned top) topic in forum-enabled private chats.
- # Bot API behavior varies: some clients omit message_thread_id for
- # General, others send "1". Treat both as "root" for lobby/lane purposes.
- _TELEGRAM_GENERAL_TOPIC_IDS = frozenset({"", "1"})
- def _is_telegram_topic_root_lobby(self, source: SessionSource) -> bool:
- """True for the main Telegram DM (or General topic) when topic mode has made it a lobby."""
- if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
- return False
- if not self._telegram_topic_mode_enabled(source):
- return False
- tid = str(source.thread_id or "")
- return tid in self._TELEGRAM_GENERAL_TOPIC_IDS
+ def _warn_if_docker_media_delivery_is_risky(self) -> None:
+ """Warn when Docker-backed gateways lack an explicit export mount.
- def _is_telegram_topic_lane(self, source: SessionSource) -> bool:
- """True for a user-created Telegram private-chat topic lane."""
- if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
- return False
- if not self._telegram_topic_mode_enabled(source):
- return False
- tid = str(source.thread_id or "")
- if not tid or tid in self._TELEGRAM_GENERAL_TOPIC_IDS:
- return False
- return True
+ MEDIA delivery happens in the gateway process, so paths emitted by the model
+ must be readable from the host. A plain container-local path like
+ `/workspace/report.txt` or `/output/report.txt` often exists only inside
+ Docker, so users commonly need a dedicated export mount such as
+ `host-dir:/output`.
+ """
+ if os.getenv("TERMINAL_ENV", "").strip().lower() != "docker":
+ return
- _TELEGRAM_LOBBY_REMINDER_COOLDOWN_S = 30.0
+ connected = self.config.get_connected_platforms()
+ messaging_platforms = [p for p in connected if p not in {Platform.LOCAL, Platform.API_SERVER, Platform.WEBHOOK}]
+ if not messaging_platforms:
+ return
- def _should_send_telegram_lobby_reminder(self, source: SessionSource) -> bool:
- """Rate-limit root-DM lobby reminders to one message per cooldown window.
+ raw_volumes = os.getenv("TERMINAL_DOCKER_VOLUMES", "").strip()
+ volumes: List[str] = []
+ if raw_volumes:
+ try:
+ parsed = json.loads(raw_volumes)
+ if isinstance(parsed, list):
+ volumes = [str(v) for v in parsed if isinstance(v, str)]
+ except Exception:
+ logger.debug("Could not parse TERMINAL_DOCKER_VOLUMES for gateway media warning", exc_info=True)
- A user who forgets multi-session mode is enabled and types several
- prompts in the root DM would otherwise get a reminder for every
- message. Cap it so the first one lands and the rest stay quiet.
- """
- if not hasattr(self, "_telegram_lobby_reminder_ts"):
- self._telegram_lobby_reminder_ts = {}
- chat_id = str(source.chat_id or "")
- if not chat_id:
- return True
- import time as _time
- now = _time.monotonic()
- last = self._telegram_lobby_reminder_ts.get(chat_id, 0.0)
- if now - last < self._TELEGRAM_LOBBY_REMINDER_COOLDOWN_S:
- return False
- self._telegram_lobby_reminder_ts[chat_id] = now
- return True
+ has_explicit_output_mount = False
+ for spec in volumes:
+ match = _DOCKER_VOLUME_SPEC_RE.match(spec)
+ if not match:
+ continue
+ container_path = match.group("container")
+ if container_path in _DOCKER_MEDIA_OUTPUT_CONTAINER_PATHS:
+ has_explicit_output_mount = True
+ break
- def _telegram_topic_root_lobby_message(self) -> str:
- return (
- "This main chat is reserved for system commands.\n\n"
- "To start a new Hermes chat, open the All Messages topic at the top "
- "of this bot interface and send any message there. Telegram will "
- "create a new topic for that message; each topic works as an "
- "independent Hermes session."
- )
+ if has_explicit_output_mount:
+ return
- def _telegram_topic_root_new_message(self) -> str:
- return (
- "To start a new parallel Hermes chat, open the All Messages topic "
- "at the top of this bot interface and send any message there. "
- "Telegram will create a new topic for it.\n\n"
- "Each topic is an independent Hermes session. Use /new inside an "
- "existing topic only if you want to replace that topic's current session."
+ logger.warning(
+ "Docker backend is enabled for the messaging gateway but no explicit host-visible "
+ "output mount (for example '/home/user/.hermes/cache/documents:/output') is configured. "
+ "This is fine if the model already emits host-visible paths, but MEDIA file delivery can fail "
+ "for container-local paths like '/workspace/...' or '/output/...'."
)
- def _telegram_topic_new_header(self, source: SessionSource) -> Optional[str]:
- if not self._is_telegram_topic_lane(source):
- return None
- return (
- "Started a new Hermes session in this topic.\n\n"
- "Tip: for parallel work, open All Messages and send a message there "
- "to create a separate topic instead of using /new here. /new replaces "
- "the session attached to the current topic."
- )
- def _record_telegram_topic_binding(
- self,
- source: SessionSource,
- session_entry,
- ) -> None:
- """Persist the Telegram topic -> Hermes session binding for topic lanes."""
- session_db = getattr(self, "_session_db", None)
- if session_db is None or not source.chat_id or not source.thread_id:
- return
- # Runs off-loop (always via asyncio.to_thread); use the sync handle.
- session_db = getattr(session_db, "_db", session_db)
- session_db.bind_telegram_topic(
- chat_id=str(source.chat_id),
- thread_id=str(source.thread_id),
- user_id=str(source.user_id or ""),
- session_key=session_entry.session_key,
- session_id=session_entry.session_id,
- )
- def _sync_telegram_topic_binding(
- self,
- source: SessionSource,
- session_entry,
- *,
- reason: str,
- ) -> None:
- """Update the topic binding to point at ``session_entry.session_id``.
+ # -- Setup skill availability ----------------------------------------
- Telegram topic lanes persist a (chat_id, thread_id) -> session_id row
- so reopening a topic in a fresh process resumes the right Hermes
- session. When compression rotates ``session_entry.session_id`` mid-turn,
- the binding goes stale and the next inbound message in that topic
- reloads the oversized parent transcript instead of the compressed
- child, retriggering preflight compression — sometimes in a loop
- (#20470, #29712, #33414).
- """
- if not self._is_telegram_topic_lane(source):
- return
+ def _has_setup_skill(self) -> bool:
+ """Check if the hermes-agent-setup skill is installed."""
try:
- self._record_telegram_topic_binding(source, session_entry)
+ from tools.skill_manager_tool import _find_skill
+ return _find_skill("hermes-agent-setup") is not None
except Exception:
- logger.debug(
- "telegram topic binding refresh failed (%s)", reason, exc_info=True,
- )
+ return False
- def _recover_telegram_topic_thread_id(
- self,
- source: SessionSource,
- ) -> Optional[str]:
- """Pin DM-topic routing to the user's last-active topic.
+ # -- Voice mode persistence ------------------------------------------
- Telegram can omit ``message_thread_id`` or surface General (``1``)
- for some topic-mode DM replies. In those lobby-shaped cases, keep the
- conversation attached to the user's most-recent bound topic.
+ _VOICE_MODE_PATH = _hermes_home / "gateway_voice_mode.json"
- Do not rewrite a non-lobby, previously-unbound thread id: a newly
- created Telegram DM topic is also "unknown" until the first inbound
- message is recorded, and rewriting it would send that brand-new topic's
- answer into an older lane. Returns None to leave the source alone.
- """
- if (
- source.platform != Platform.TELEGRAM
- or source.chat_type != "dm"
- or not source.chat_id
- or not source.user_id
- or not self._telegram_topic_mode_enabled(source)
- ):
- return None
- inbound = str(source.thread_id or "")
- is_lobby = not inbound or inbound in self._TELEGRAM_GENERAL_TOPIC_IDS
- if not is_lobby:
- # A non-lobby, unknown thread_id is most likely the first message in
- # a brand-new Telegram DM topic. Preserve it so it can be recorded
- # as a new independent lane below instead of hijacking the latest
- # existing topic binding.
- return None
- session_db = getattr(self, "_session_db", None)
- if session_db is None:
- return None
- # Runs off-loop (always via asyncio.to_thread); use the sync handle.
- session_db = getattr(session_db, "_db", session_db)
+ def _voice_key(self, platform: Platform, chat_id: str) -> str:
+ """Return a platform-namespaced key for voice mode state."""
+ return f"{platform.value}:{chat_id}"
+
+ def _load_voice_modes(self) -> Dict[str, str]:
try:
- bindings = session_db.list_telegram_topic_bindings_for_chat(
- chat_id=str(source.chat_id),
+ data = json.loads(self._VOICE_MODE_PATH.read_text(encoding="utf-8"))
+ except (FileNotFoundError, json.JSONDecodeError, OSError):
+ return {}
+
+ if not isinstance(data, dict):
+ return {}
+
+ valid_modes = {"off", "voice_only", "all"}
+ result = {}
+ for chat_id, mode in data.items():
+ if mode not in valid_modes:
+ continue
+ key = str(chat_id)
+ # Skip legacy unprefixed keys (warn and skip)
+ if ":" not in key:
+ logger.warning(
+ "Skipping legacy unprefixed voice mode key %r during migration. "
+ "Re-enable voice mode on that chat to rebuild the prefixed key.",
+ key,
+ )
+ continue
+ result[key] = mode
+ return result
+
+ def _save_voice_modes(self) -> None:
+ try:
+ self._VOICE_MODE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ self._VOICE_MODE_PATH.write_text(
+ json.dumps(self._voice_mode, indent=2), encoding="utf-8"
)
- except Exception:
- logger.debug("topic-recover: read failed", exc_info=True)
- return None
- if not bindings:
- return None
- user_id = str(source.user_id)
- for b in bindings: # newest-first
- if str(b.get("user_id") or "") == user_id:
- recovered = str(b.get("thread_id") or "")
- if recovered and recovered != inbound:
- return recovered
- return None
- return None
+ except OSError as e:
+ logger.warning("Failed to save voice modes: %s", e)
- def _normalize_source_for_session_key(
- self,
- source: SessionSource,
- ) -> SessionSource:
- """Apply Telegram DM topic recovery to a source for session-key purposes.
+ def _set_adapter_auto_tts_disabled(self, adapter, chat_id: str, disabled: bool) -> None:
+ """Update an adapter's in-memory auto-TTS suppression set if present."""
+ disabled_chats = getattr(adapter, "_auto_tts_disabled_chats", None)
+ if not isinstance(disabled_chats, set):
+ return
+ if disabled:
+ disabled_chats.add(chat_id)
+ # ``/voice off`` also clears any explicit enable — it's a hard override.
+ enabled_chats = getattr(adapter, "_auto_tts_enabled_chats", None)
+ if isinstance(enabled_chats, set):
+ enabled_chats.discard(chat_id)
+ else:
+ disabled_chats.discard(chat_id)
- ``_handle_message_with_agent`` rewrites ``source.thread_id`` via
- ``_recover_telegram_topic_thread_id`` *before* deriving the session
- key for a normal message turn (a lobby/stripped reply gets pinned to
- the user's last-active topic). Session-scoped command handlers like
- ``/model`` and ``/reasoning`` derive their override key from the raw
- inbound ``event.source``, which skips that recovery — so the override
- is stored under a different key than the next message turn reads,
- and the override is silently dropped on Telegram forum topics and
- after compression session splits (#30479).
+ def _set_adapter_auto_tts_enabled(self, adapter, chat_id: str, enabled: bool) -> None:
+ """Update an adapter's per-chat auto-TTS opt-in set if present.
- Returns a recovery-normalized copy when a rewrite applies, otherwise
- the original source unchanged. Always derive the override storage key
- from the result so storage and read use an identical key.
+ Used for ``/voice on``/``/voice tts`` where the user explicitly wants
+ auto-TTS even when ``voice.auto_tts`` is False globally.
"""
- try:
- recovered = self._recover_telegram_topic_thread_id(source)
- except Exception:
- return source
- if recovered is None:
- return source
- return dataclasses.replace(source, thread_id=recovered)
+ enabled_chats = getattr(adapter, "_auto_tts_enabled_chats", None)
+ if not isinstance(enabled_chats, set):
+ return
+ if enabled:
+ enabled_chats.add(chat_id)
+ # An explicit opt-in clears any stale /voice off for this chat.
+ disabled_chats = getattr(adapter, "_auto_tts_disabled_chats", None)
+ if isinstance(disabled_chats, set):
+ disabled_chats.discard(chat_id)
+ else:
+ enabled_chats.discard(chat_id)
- def _resolve_session_agent_runtime(
- self,
- *,
- source: Optional[SessionSource] = None,
- session_key: Optional[str] = None,
- user_config: Optional[dict] = None,
- ) -> tuple[str, dict]:
- """Resolve model/runtime for a session.
+ def _sync_voice_mode_state_to_adapter(self, adapter) -> None:
+ """Restore persisted /voice state into a live platform adapter.
- Priority (highest first): session ``/model`` → ``channel_overrides`` →
- global config/env (``_resolve_gateway_model(user_config)`` and default
- provider resolution).
+ Populates three fields from config + ``self._voice_mode``:
+ - ``_auto_tts_default``: global default from ``voice.auto_tts``
+ - ``_auto_tts_enabled_chats``: chats with mode ``voice_only``/``all``
+ - ``_auto_tts_disabled_chats``: chats with mode ``off``
"""
- resolved_session_key = session_key
- if not resolved_session_key and source is not None:
- try:
- resolved_session_key = self._session_key_for_source(source)
- except Exception:
- resolved_session_key = None
+ platform = getattr(adapter, "platform", None)
+ if not isinstance(platform, Platform):
+ return
- model = _resolve_gateway_model(user_config)
- if resolved_session_key:
- self._rehydrate_session_model_override(resolved_session_key)
- _override_state = (
- self._peek_session_state(resolved_session_key)
- if resolved_session_key
- else None
- )
- override = (
- _override_state.conversation.model_override if _override_state else None
- )
- if override:
- override_model = override.get("model", model)
- override_runtime = {
- "provider": override.get("provider"),
- "api_key": override.get("api_key"),
- "base_url": override.get("base_url"),
- "api_mode": override.get("api_mode"),
- "max_tokens": override.get("max_tokens"),
- "credential_pool": override.get("credential_pool"),
- }
- if override_runtime.get("api_key"):
- if override_runtime.get("credential_pool") is None:
- override_runtime["credential_pool"] = _credential_pool_for_provider(
- override.get("provider")
- )
- logger.debug(
- "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",
- resolved_session_key or "", model, override_model,
- override_runtime.get("provider"),
- )
- return override_model, override_runtime
- # Override exists but has no api_key — fall through to env-based
- # resolution and apply model/provider from the override on top.
- logger.debug(
- "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",
- resolved_session_key or "", model, override_model,
- )
- else:
- logger.debug(
- "No session model override: session=%s config_model=%s override_keys=%s",
- resolved_session_key or "", model,
- [
- _key
- for _key, _st in list(self._sessions_map().items())
- if _st.conversation.model_override is not None
- ][:5] or "[]",
- )
+ disabled_chats = getattr(adapter, "_auto_tts_disabled_chats", None)
+ enabled_chats = getattr(adapter, "_auto_tts_enabled_chats", None)
+ if not isinstance(disabled_chats, set) and not isinstance(enabled_chats, set):
+ return
- runtime_kwargs = _resolve_runtime_agent_kwargs()
- runtime_model = runtime_kwargs.pop("model", None)
- if runtime_model:
- logger.info(
- "Runtime provider supplied explicit model override: %s -> %s",
- model,
- runtime_model,
+ # Push the global voice.auto_tts default (config.yaml) onto the adapter.
+ # Lazy import to avoid adding a module-level dep from gateway → hermes_cli.
+ try:
+ from hermes_cli.config import load_config as _load_full_config
+ _full_cfg = _load_full_config()
+ _auto_tts_default = bool(
+ (_full_cfg.get("voice") or {}).get("auto_tts", False)
)
- model = runtime_model
+ except Exception:
+ _auto_tts_default = False
+ if hasattr(adapter, "_auto_tts_default"):
+ adapter._auto_tts_default = _auto_tts_default
- cfg = getattr(self, "config", None)
- if cfg and source is not None:
- chat_id = str(source.chat_id) if source.chat_id else ""
- thread_id = (
- str(source.thread_id) if getattr(source, "thread_id", None) else None
- )
- parent_id = (
- str(source.parent_chat_id)
- if getattr(source, "parent_chat_id", None)
- else None
+ prefix = f"{platform.value}:"
+ if isinstance(disabled_chats, set):
+ disabled_chats.clear()
+ disabled_chats.update(
+ key[len(prefix):] for key, mode in self._voice_mode.items()
+ if mode == "off" and key.startswith(prefix)
)
- ch = _get_channel_override(
- cfg,
- source.platform,
- chat_id,
- thread_id=thread_id,
- parent_id=parent_id,
+ if isinstance(enabled_chats, set):
+ enabled_chats.clear()
+ enabled_chats.update(
+ key[len(prefix):] for key, mode in self._voice_mode.items()
+ if mode in {"voice_only", "all"} and key.startswith(prefix)
)
- if ch:
- if ch.model:
- model = ch.model
- if ch.provider:
- runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(
- ch.provider
- )
- ch_runtime_model = runtime_kwargs.pop("model", None)
- # Only adopt the provider's bundled model when the override
- # did not specify an explicit model.
- if ch_runtime_model and not ch.model:
- model = ch_runtime_model
-
- if override and resolved_session_key:
- model, runtime_kwargs = self._apply_session_model_override(
- resolved_session_key, model, runtime_kwargs
- )
-
- # When the config has no model.default but a provider was resolved
- # (e.g. user ran `hermes auth add openai-codex` without `hermes model`),
- # fall back to the provider's first catalog model so the API call
- # doesn't fail with "model must be a non-empty string".
- if not model and runtime_kwargs.get("provider"):
- try:
- from hermes_cli.models import get_default_model_for_provider
- model = get_default_model_for_provider(runtime_kwargs["provider"])
- if model:
- logger.info(
- "No model configured — defaulting to %s for provider %s",
- model, runtime_kwargs["provider"],
- )
- except Exception:
- pass
-
- # Final safety net (#35314): if resolution still produced an empty
- # model — e.g. a transient config-cache miss during a post-interrupt
- # recovery turn returned an empty user_config — reuse the last model we
- # successfully resolved for this session (or, failing that, the most
- # recent one resolved process-wide). Building an agent with model=""
- # makes every API call fail HTTP 400 "No models provided" and the
- # session goes silent until the user manually re-sends. ``getattr``
- # guards against bare test runners built via ``object.__new__``.
- if not model:
- _lr_state = (
- self._peek_session_state(resolved_session_key)
- if resolved_session_key
- else None
- )
- _lr_star = self._peek_session_state("*")
- _recovered = (
- (_lr_state.conversation.last_resolved_model if _lr_state else "")
- or (_lr_star.conversation.last_resolved_model if _lr_star else "")
- )
- if _recovered:
- logger.warning(
- "Empty model resolved for session=%s — recovering "
- "last-known-good model %s (config read likely returned "
- "empty; see #35314)",
- resolved_session_key or "", _recovered,
- )
- model = _recovered
- elif model:
- # Cache the good resolution for future recovery turns.
- if resolved_session_key:
- self._session_state(
- resolved_session_key
- ).conversation.last_resolved_model = model
- self._session_state("*").conversation.last_resolved_model = model
-
- return model, runtime_kwargs
- def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:
- """Build the effective model/runtime config for a single turn.
+ async def _await_adapter_cleanup_with_timeout(
+ self, awaitable: Awaitable[Any], timeout: float
+ ) -> bool:
+ """Wait for adapter cleanup without letting cancellation swallowing hang us.
- Always uses the session's primary model/provider. If `/fast` is
- enabled and the model supports Priority Processing / Anthropic fast
- mode, attach `request_overrides` so the API call is marked
- accordingly.
+ ``asyncio.wait_for`` cancels an overdue child but then waits for it to
+ exit. An adapter close path that catches ``CancelledError`` can therefore
+ block recovery forever. Keep ownership of the old task through its done
+ callback, but release the runner at the deadline.
"""
- from hermes_cli.models import resolve_fast_mode_overrides
-
- runtime = {
- "api_key": runtime_kwargs.get("api_key"),
- "base_url": runtime_kwargs.get("base_url"),
- "provider": runtime_kwargs.get("provider"),
- "requested_provider": runtime_kwargs.get("requested_provider"),
- "api_mode": runtime_kwargs.get("api_mode"),
- "command": runtime_kwargs.get("command"),
- "args": list(runtime_kwargs.get("args") or []),
- "credential_pool": runtime_kwargs.get("credential_pool"),
- "max_tokens": runtime_kwargs.get("max_tokens"),
- }
- route = {
- "model": model,
- "runtime": runtime,
- "signature": (
- model,
- runtime["provider"],
- runtime["requested_provider"],
- runtime["base_url"],
- runtime["api_mode"],
- runtime["command"],
- tuple(runtime["args"]),
- ),
- }
-
- service_tier = getattr(self, "_service_tier", None)
- if not service_tier:
- route["request_overrides"] = {}
- return route
+ if timeout <= 0:
+ await awaitable
+ return True
+ task = asyncio.ensure_future(awaitable)
try:
- overrides = resolve_fast_mode_overrides(route["model"])
- except Exception:
- overrides = None
- route["request_overrides"] = overrides or {}
- return route
-
- def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:
- """Persist the runtime model/provider actually used by a gateway turn.
-
- Provider fallback can switch ``agent.model``/``agent.provider`` after the
- session row was created. Keep the session DB metadata in sync so session
- lists, desktop/dashboard details, and follow-up session tooling report the
- backend that actually answered the latest turn.
+ done, _pending = await asyncio.wait({task}, timeout=timeout)
+ except asyncio.CancelledError:
+ task.cancel()
+ task.add_done_callback(consume_detached_task_result)
+ raise
+ if task in done:
+ await task
+ return True
- Called from the ``run_sync`` closure, which executes off the event loop
- in the executor thread — so the synchronous ``SessionDB`` (``_db``) is
- used directly rather than awaiting the AsyncSessionDB forwarder.
- """
- if not session_id or agent is None or self._session_db is None:
- return
- model = getattr(agent, "model", None)
- if not model:
- return
- runtime = {
- "provider": getattr(agent, "provider", None),
- "base_url": getattr(agent, "base_url", None),
- "api_mode": getattr(agent, "api_mode", None),
- "fallback_active": bool(getattr(agent, "_fallback_activated", False)),
- }
- runtime = {k: v for k, v in runtime.items() if v not in (None, "")}
+ task.cancel()
+ task.add_done_callback(consume_detached_task_result)
+ return False
- try:
- db = self._session_db._db
- row = db.get_session(session_id)
- if not row:
- return
- current_model = row.get("model")
- raw_config = row.get("model_config")
- try:
- config = json.loads(raw_config) if raw_config else {}
- except Exception:
- config = {}
- if not isinstance(config, dict):
- config = {}
- gateway_runtime = dict(config.get("gateway_runtime") or {})
- if current_model == model and all(
- gateway_runtime.get(k) == v for k, v in runtime.items()
- ):
- return
- config["gateway_runtime"] = runtime
- db.update_session_meta(session_id, json.dumps(config), model=model)
- except Exception:
- logger.debug("Failed to sync gateway session model metadata", exc_info=True)
+ async def _safe_adapter_disconnect(self, adapter, platform) -> None:
+ """Call adapter.disconnect() defensively, swallowing any error.
- async def _handle_reaction_event(self, ctx: Dict[str, Any]) -> None:
- """Fan a normalised platform reaction event out to the HookRegistry.
+ Used when adapter.connect() failed or raised — the adapter may
+ have allocated partial resources (aiohttp.ClientSession, poll
+ tasks, child subprocesses) that would otherwise leak and surface
+ as "Unclosed client session" warnings at process exit.
- Adapters call this via ``set_reaction_handler`` for every
- platform-native reaction event they surface. The adapter-supplied
- ``event_name`` ("reaction:added" / "reaction:removed") becomes the
- hook event so user hooks subscribe with the same name scheme as the
- existing ``agent:*`` family. Errors never block the adapter's event
- loop — the hook contract is non-blocking.
+ Must tolerate partial-init state and never raise, since callers
+ use it inside error-handling blocks.
"""
- event_name = str(ctx.get("event_name") or "reaction:added")
+ timeout = self._adapter_disconnect_timeout_secs()
try:
- await self.hooks.emit(event_name, ctx)
- except Exception:
- logger.debug("[Gateway] reaction hook emit failed", exc_info=True)
+ completed = await self._await_adapter_cleanup_with_timeout(
+ adapter.disconnect(), timeout
+ )
+ if not completed:
+ logger.warning(
+ "Timed out after %.1fs while disconnecting %s adapter; continuing shutdown",
+ timeout,
+ platform.value if platform is not None else "adapter",
+ )
+ except Exception as e:
+ logger.debug(
+ "Defensive %s disconnect after failed connect raised: %s",
+ platform.value if platform is not None else "adapter",
+ e,
+ )
- async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> None:
- """React to an adapter failure after startup.
+ async def _bounded_adapter_teardown(
+ self, adapter, platform, *, profile: Optional[str] = None
+ ) -> None:
+ """Tear down one adapter on the shutdown path with bounded awaits.
- If the error is retryable (e.g. network blip, DNS failure), queue the
- platform for background reconnection instead of giving up permanently.
+ Both ``cancel_background_tasks()`` and ``disconnect()`` can block
+ indefinitely when a platform's network state is half-dead (e.g. a
+ wedged Feishu/Lark WebSocket thread waiting on I/O). An unbounded
+ await here stalls the entire shutdown sequence past systemd's
+ ``TimeoutStopSec``; the resulting SIGKILL skips ``atexit`` PID-file
+ cleanup, so the next start dies with "PID file race lost" (#14128).
- The notification arrives on the failing adapter's own polling task,
- and the disconnect inside the handler can cancel that task mid-flight:
- disconnect()'s current-task guard misses it because
- _safe_adapter_disconnect runs the close in a wrapper task. A cancelled
- handler dies between the fatal log and the reconnect queue, silently
- stranding the platform (observed 2026-07-21: telegram popped from
- adapters but never queued after a travel network outage). Run the real
- work in a detached task that adapter teardown cannot cancel.
+ Each await uses the existing per-adapter timeout budget
+ (``HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT``). On timeout the old
+ task is cancelled and detached, then teardown forces forward progress;
+ the loop never hangs even if an adapter swallows cancellation. Never
+ raises.
"""
- tasks = getattr(self, "_fatal_handler_tasks", None)
- if tasks is None:
- tasks = self._fatal_handler_tasks = set()
- task = asyncio.create_task(self._handle_adapter_fatal_error_detached(adapter))
- tasks.add(task)
- task.add_done_callback(tasks.discard)
- # Await so callers that expect completion still get it — but through
- # shield(): Task.cancel() on the caller also cancels the future it is
- # awaiting (_fut_waiter), so a plain `await task` would tunnel the
- # cancellation straight into the "detached" task. shield() absorbs
- # it: the caller sees CancelledError, the handler runs to completion.
- await asyncio.shield(task)
-
- async def _handle_adapter_fatal_error_detached(
- self, adapter: BasePlatformAdapter
- ) -> None:
- """Run the fatal handler; if the platform still ends up stranded
- (not reconnected, not queued, not intentionally disabled), exit the
- gateway with failure so the service manager restarts it instead of
- leaving a silent partial outage."""
- try:
- await self._handle_adapter_fatal_error_impl(adapter)
- except Exception:
- logger.exception(
- "Fatal-error handling for %s raised unexpectedly",
- adapter.platform.value,
+ timeout = self._adapter_disconnect_timeout_secs()
+ suffix = f" (profile: {profile})" if profile else ""
+ started_at = time.monotonic()
+ try:
+ cancelled = await self._await_adapter_cleanup_with_timeout(
+ adapter.cancel_background_tasks(), timeout
)
- finally:
- platform = adapter.platform
- shutdown_event = getattr(self, "_shutdown_event", None)
- stranded = (
- adapter.fatal_error_retryable
- and platform not in self.adapters
- and platform not in getattr(self, "_failed_platforms", {})
- and not (shutdown_event is not None and shutdown_event.is_set())
+ if not cancelled:
+ logger.warning(
+ "✗ %s background-task cancel timed out after %.1fs - forcing continue%s",
+ platform.value, timeout, suffix,
+ )
+ except Exception as e:
+ logger.debug("✗ %s background-task cancel error%s: %s", platform.value, suffix, e)
+ try:
+ disconnected = await self._await_adapter_cleanup_with_timeout(
+ adapter.disconnect(), timeout
)
- if stranded:
- logger.error(
- "%s adapter was lost without entering the reconnection "
- "queue; exiting gateway so the service manager restarts it.",
- platform.value,
+ if disconnected:
+ logger.info(
+ "✓ %s disconnected (%.2fs)%s",
+ platform.value, time.monotonic() - started_at, suffix,
)
- self._exit_reason = (
- f"{platform.value} adapter lost without reconnection queue"
+ else:
+ logger.warning(
+ "✗ %s disconnect timed out after %.1fs - forcing continue%s",
+ platform.value, timeout, suffix,
)
- self._exit_with_failure = True
- await self.stop()
-
- async def _handle_adapter_fatal_error_impl(self, adapter: BasePlatformAdapter) -> None:
- # Snapshot the current owner of this platform slot before doing
- # anything else. If it's neither this adapter nor empty, a different
- # adapter has already taken over (e.g. this is a delayed notification
- # from a background retry chain that raced with, and lost to, a
- # reconnect that already succeeded). Acting on a stale notification
- # would overwrite an already-healthy platform's runtime status and
- # incorrectly re-queue it for reconnection, so bail out before any of
- # that happens.
- existing = self.adapters.get(adapter.platform)
- if existing is not None and existing is not adapter:
- logger.debug(
- "Ignoring stale fatal error from a superseded %s adapter instance: %s",
- adapter.platform.value,
- adapter.fatal_error_code or "unknown",
+ except Exception as e:
+ logger.error(
+ "✗ %s disconnect error after %.2fs%s: %s",
+ platform.value, time.monotonic() - started_at, suffix, e,
)
- return
-
- logger.error(
- "Fatal %s adapter error (%s): %s",
- adapter.platform.value,
- adapter.fatal_error_code or "unknown",
- adapter.fatal_error_message or "unknown error",
- )
- # Phase 7 Unit 7d-B: a relay credential revoked by opt-out is not an
- # error to retry — render it as a clean "disabled" state, not red
- # "fatal"/"retrying". (The code is set non-retryable, so it also drops
- # out of the reconnect queue below.)
- if adapter.fatal_error_code == "relay_disabled":
- platform_state = "disabled"
- elif adapter.fatal_error_retryable:
- platform_state = "retrying"
- else:
- platform_state = "fatal"
- self._update_platform_runtime_status(
- adapter.platform.value,
- platform_state=platform_state,
- error_code=adapter.fatal_error_code,
- error_message=adapter.fatal_error_message,
- )
-
- if existing is adapter:
- # Claim this adapter for teardown before awaiting disconnect() —
- # a second fatal-error notification for the same adapter (e.g.
- # from a concurrent recovery path) would otherwise still see
- # itself as "existing" during the await below and disconnect()
- # the same object twice.
- self.adapters.pop(adapter.platform, None)
- self.delivery_router.adapters = self.adapters
- # A half-closed transport can wedge an adapter's native close()
- # indefinitely. Reuse the shutdown-path timeout so this runtime
- # fatal handler always reaches the reconnect queue.
- await self._safe_adapter_disconnect(adapter, adapter.platform)
- # Queue retryable failures for background reconnection
- if adapter.fatal_error_retryable:
- platform_config = self.config.platforms.get(adapter.platform)
- if platform_config and adapter.platform not in self._failed_platforms:
- self._failed_platforms[adapter.platform] = {
- "config": platform_config,
- "attempts": 0,
- "next_retry": time.monotonic(),
- }
- logger.info(
- "%s queued for background reconnection",
- adapter.platform.value,
+ def _adapter_disconnect_timeout_secs(self) -> float:
+ """Return the per-adapter disconnect timeout used during shutdown."""
+ raw = os.getenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "").strip()
+ if raw:
+ try:
+ timeout = float(raw)
+ except ValueError:
+ logger.warning(
+ "Ignoring invalid HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT=%r",
+ raw,
)
- # Ensure the reconnect watcher is alive — if it died (e.g. from
- # exhausting its restart budget), respawn it so queued platforms
- # are not permanently stranded (#70344).
- self._ensure_reconnect_watcher_running()
-
- if not self.adapters and not self._failed_platforms:
- self._exit_reason = adapter.fatal_error_message or "All messaging adapters disconnected"
- if adapter.fatal_error_retryable:
- self._exit_with_failure = True
- logger.error("No connected messaging platforms remain. Shutting down gateway for service restart.")
else:
- logger.error("No connected messaging platforms remain. Shutting down gateway cleanly.")
- await self.stop()
- elif not self.adapters and self._failed_platforms:
- # All platforms are down and queued for background reconnection.
- # Keep the gateway alive so:
- # • cron jobs still run
- # • the reconnect watcher can recover platforms when the
- # underlying problem clears (proxy comes back, user runs
- # `hermes whatsapp`, etc.)
- # We used to exit-with-failure here to trigger systemd restart,
- # but that converted a transient outage into a restart loop and
- # killed in-process state every time. The reconnect watcher
- # already handles long-running recovery — let it do its job.
- logger.warning(
- "No connected messaging platforms remain, but %d platform(s) "
- "queued for reconnection — gateway staying alive, watcher will "
- "retry in background.",
- len(self._failed_platforms),
- )
+ return max(0.0, timeout)
+ return _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT
- def _request_clean_exit(self, reason: str) -> None:
- self._exit_cleanly = True
- self._exit_reason = reason
- self._shutdown_event.set()
+ def _platform_connect_timeout_secs(self, platform=None) -> float:
+ """Return the per-platform connect timeout used during startup/retry."""
+ raw = os.getenv("HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT", "").strip()
+ if raw:
+ try:
+ timeout = float(raw)
+ except ValueError:
+ logger.warning(
+ "Ignoring invalid HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT=%r",
+ raw,
+ )
+ else:
+ return max(0.0, timeout)
+ if platform == Platform.TELEGRAM:
+ return _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT
+ return _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT
- def _running_agent_count(self) -> int:
- return len(self._running_agents)
+ async def _connect_adapter_with_timeout(
+ self, adapter, platform, *, is_reconnect: bool = False
+ ) -> bool:
+ """Connect an adapter without allowing one platform to block others.
- def _active_work_count(self) -> int:
- """All agent work the gateway must expose and drain as one total."""
- return (
- self._running_agent_count()
- + self._active_cron_job_count()
- + self._active_api_run_count()
+ ``is_reconnect`` is forwarded to ``adapter.connect()`` so platform
+ adapters can distinguish a cold first boot (drop any stale
+ server-side queue) from a watcher reconnect after a prolonged outage
+ (preserve the queue so messages sent during the outage are delivered
+ rather than silently dropped — #46621).
+ """
+ timeout = self._platform_connect_timeout_secs(platform)
+ if timeout <= 0:
+ return await adapter.connect(is_reconnect=is_reconnect)
+ # Use the detach-on-timeout pattern instead of plain asyncio.wait_for:
+ # asyncio.wait_for cancels the overdue task but then waits for it to
+ # exit. An adapter connect() that catches CancelledError can therefore
+ # block recovery forever (the watcher never reaches the next retry).
+ # Keep ownership of the old task through its done callback, but
+ # release the runner at the deadline (#70344).
+ task = asyncio.ensure_future(
+ adapter.connect(is_reconnect=is_reconnect)
+ )
+ try:
+ done, _pending = await asyncio.wait({task}, timeout=timeout)
+ except asyncio.CancelledError:
+ task.cancel()
+ task.add_done_callback(consume_detached_task_result)
+ raise
+ if task in done:
+ result = await task
+ return bool(result)
+ task.cancel()
+ task.add_done_callback(consume_detached_task_result)
+ raise TimeoutError(
+ f"{platform.value} connect timed out after {timeout:g}s"
)
- def _active_cron_job_count(self) -> int:
- """Count of cron jobs currently executing, from the cron scheduler's
- own in-flight tracking (``cron.scheduler._running_job_ids``).
+ async def _connect_initial_adapter_with_timeout(self, adapter, platform) -> bool:
+ """Connect one cold-start adapter with tightly scoped replace intent.
- Cron jobs run through a standalone ``AIAgent`` on the scheduler's own
- thread pool (``cron/scheduler.py::run_job``), entirely outside
- ``self._running_agents`` — the dict every OTHER active-work check on
- this class (``_running_agent_count``, ``_drain_active_agents``) reads.
- Without this, the shutdown drain is structurally blind to in-flight
- cron work: it can report ``active_at_start=0`` and proceed straight
- to killing tool subprocesses while a cron job's terminal command is
- still running (#60432). Best-effort: returns 0 if the cron module
- can't be imported (e.g. a minimal test double for this class).
+ The capability is visible only while this initial connect is awaited.
+ Reconnects call ``_connect_adapter_with_timeout`` directly and adapters
+ also default to deny, so a later network recovery can never evict a
+ healthy token holder.
"""
+ adapter._platform_lock_takeover_allowed = bool(
+ self._platform_lock_takeover_on_start
+ )
try:
- from cron.scheduler import get_running_job_ids
- return len(get_running_job_ids())
- except Exception:
- return 0
+ return await self._connect_adapter_with_timeout(adapter, platform)
+ finally:
+ adapter._platform_lock_takeover_allowed = False
- def _active_api_run_count(self) -> int:
- """Count API-server work that is outside ``_running_agents``.
+ @property
+ def should_exit_cleanly(self) -> bool:
+ return self._exit_cleanly
- The primary API server owns the sole HTTP listener. Secondary multiplex
- profiles cannot create an ``api_server`` adapter because it binds a port,
- so only the primary registry is a supported source of this work.
- """
- try:
- adapter = getattr(self, "adapters", {}).get(Platform.API_SERVER)
- helper = getattr(adapter, "active_agent_work_count", None)
- return max(0, int(helper())) if callable(helper) else 0
- except Exception:
- return 0
+ @property
+ def should_exit_with_failure(self) -> bool:
+ return self._exit_with_failure
- # ── scale-to-zero idle detection / dormant-quiesce (Phase 0) ──────────────
- # The gateway-side BEHAVIOUR that consumes the relay scale-to-zero primitives
- # (gateway-gateway Phase 5). Pure logic lives in gateway/scale_to_zero.py; the
- # methods here bind it to the live runner/transport. See ~/nous/specs/
- # scale-to-zero (decisions.md) for the design + the F12/F14 distinctions.
+ @property
+ def exit_reason(self) -> Optional[str]:
+ return self._exit_reason
- def _scale_to_zero_has_live_background_work(self) -> bool:
- """Live background work that must block a suspend (D3/F7).
+ @property
+ def exit_code(self) -> Optional[int]:
+ return self._exit_code
- Backgrounded delegate_task / kanban / terminal(background=true) are NOT
- counted by _running_agent_count(), but suspending mid-flight loses them.
- Checks the runner's own tracked tasks + the process registry's running
- processes + any pending process-completion watchers.
- """
- if any(not t.done() for t in self._background_tasks):
- return True
- try:
- from tools.async_delegation import active_count
+ def _session_key_for_source(self, source: SessionSource) -> str:
+ """Resolve the current session key for a source, honoring gateway config when available."""
+ if hasattr(self, "session_store") and self.session_store is not None:
+ try:
+ session_key = self.session_store._generate_session_key(source)
+ if isinstance(session_key, str) and session_key:
+ return session_key
+ except Exception:
+ pass
+ config = getattr(self, "config", None)
+ # Mirror SessionStore._resolve_profile_for_key so this fallback path
+ # produces the same namespace as the primary path: None (legacy
+ # agent:main) unless multiplexing is on, then the active profile.
+ _profile = None
+ if getattr(config, "multiplex_profiles", False):
+ if source.profile:
+ _profile = source.profile
+ else:
+ try:
+ from hermes_cli.profiles import get_active_profile_name
+ _profile = get_active_profile_name() or "default"
+ except Exception:
+ _profile = None
+ return build_session_key(
+ source,
+ group_sessions_per_user=getattr(config, "group_sessions_per_user", True),
+ thread_sessions_per_user=getattr(config, "thread_sessions_per_user", False),
+ profile=_profile,
+ )
- if active_count() > 0:
- return True
- except Exception: # noqa: BLE001 - never let the idle check raise
- logger.debug("scale-to-zero async-delegation check failed", exc_info=True)
+ def _telegram_topic_mode_enabled(self, source: SessionSource) -> bool:
+ """Return whether Telegram DM topic mode is active for this chat."""
+ if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
+ return False
+ session_db = getattr(self, "_session_db", None)
+ if session_db is None:
+ return False
+ # Runs off-loop (always via asyncio.to_thread); use the sync handle.
+ session_db = getattr(session_db, "_db", session_db)
try:
- from tools.process_registry import process_registry
+ raw = session_db.is_telegram_topic_mode_enabled(
+ chat_id=str(source.chat_id),
+ user_id=str(source.user_id),
+ )
+ except Exception:
+ logger.debug("Failed to read Telegram topic mode state", exc_info=True)
+ return False
+ # Only honor a real True from the SessionDB. Any other value
+ # (including MagicMock instances from test fixtures that didn't
+ # opt into topic mode) means topic mode is off for this chat.
+ return raw is True
- if process_registry.has_any_active():
- return True
- if process_registry.pending_watchers:
- return True
- except Exception: # noqa: BLE001 - never let the idle check raise
- logger.debug("scale-to-zero bg-work check failed", exc_info=True)
- return False
+ # Telegram's General (pinned top) topic in forum-enabled private chats.
+ # Bot API behavior varies: some clients omit message_thread_id for
+ # General, others send "1". Treat both as "root" for lobby/lane purposes.
+ _TELEGRAM_GENERAL_TOPIC_IDS = frozenset({"", "1"})
- def _scale_to_zero_idle_timeout_seconds(self) -> float:
- from gateway.scale_to_zero import parse_idle_timeout_seconds
+ def _is_telegram_topic_root_lobby(self, source: SessionSource) -> bool:
+ """True for the main Telegram DM (or General topic) when topic mode has made it a lobby."""
+ if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
+ return False
+ if not self._telegram_topic_mode_enabled(source):
+ return False
+ tid = str(source.thread_id or "")
+ return tid in self._TELEGRAM_GENERAL_TOPIC_IDS
- raw = None
- try:
- user_cfg = _load_gateway_config()
- gw = user_cfg.get("gateway") if isinstance(user_cfg, dict) else None
- stz = gw.get("scale_to_zero") if isinstance(gw, dict) else None
- if isinstance(stz, dict):
- raw = stz.get("idle_timeout_minutes")
- except Exception: # noqa: BLE001
- raw = None
- return parse_idle_timeout_seconds(raw)
+ def _is_telegram_topic_lane(self, source: SessionSource) -> bool:
+ """True for a user-created Telegram private-chat topic lane."""
+ if source.platform != Platform.TELEGRAM or source.chat_type != "dm":
+ return False
+ if not self._telegram_topic_mode_enabled(source):
+ return False
+ tid = str(source.thread_id or "")
+ if not tid or tid in self._TELEGRAM_GENERAL_TOPIC_IDS:
+ return False
+ return True
- def _restart_loop_guard_config(self) -> tuple:
- """Return ``(max_restarts, window_seconds)`` for the auto-resume
- restart-loop breaker (#30719, defense-3), read from
- ``gateway.restart_loop_guard`` in config.yaml with the module defaults
- as fallback. ``max_restarts <= 0`` disables the breaker.
- """
- from gateway import restart_loop_guard as _rlg
+ _TELEGRAM_LOBBY_REMINDER_COOLDOWN_S = 30.0
- max_restarts = _rlg.DEFAULT_MAX_RESTARTS
- window_seconds = _rlg.DEFAULT_WINDOW_SECONDS
- try:
- user_cfg = _load_gateway_config()
- gw = user_cfg.get("gateway") if isinstance(user_cfg, dict) else None
- rlg = gw.get("restart_loop_guard") if isinstance(gw, dict) else None
- if isinstance(rlg, dict):
- if isinstance(rlg.get("max_restarts"), int):
- max_restarts = rlg["max_restarts"]
- if isinstance(rlg.get("window_seconds"), int) and rlg["window_seconds"] > 0:
- window_seconds = rlg["window_seconds"]
- except Exception: # noqa: BLE001
- pass
- return max_restarts, window_seconds
+ def _should_send_telegram_lobby_reminder(self, source: SessionSource) -> bool:
+ """Rate-limit root-DM lobby reminders to one message per cooldown window.
- def _scale_to_zero_should_arm(self) -> bool:
- """Whether to start the idle watcher (D1/D11/§3.4(1))."""
- from gateway.relay import relay_wake_url
- from gateway.scale_to_zero import (
- messaging_is_relay_only_or_absent,
- scale_to_zero_enabled,
- should_arm,
+ A user who forgets multi-session mode is enabled and types several
+ prompts in the root DM would otherwise get a reminder for every
+ message. Cap it so the first one lands and the rest stay quiet.
+ """
+ if not hasattr(self, "_telegram_lobby_reminder_ts"):
+ self._telegram_lobby_reminder_ts = {}
+ chat_id = str(source.chat_id or "")
+ if not chat_id:
+ return True
+ import time as _time
+ now = _time.monotonic()
+ last = self._telegram_lobby_reminder_ts.get(chat_id, 0.0)
+ if now - last < self._TELEGRAM_LOBBY_REMINDER_COOLDOWN_S:
+ return False
+ self._telegram_lobby_reminder_ts[chat_id] = now
+ return True
+
+ def _telegram_topic_root_lobby_message(self) -> str:
+ return (
+ "This main chat is reserved for system commands.\n\n"
+ "To start a new Hermes chat, open the All Messages topic at the top "
+ "of this bot interface and send any message there. Telegram will "
+ "create a new topic for that message; each topic works as an "
+ "independent Hermes session."
)
- try:
- # Only ENABLED platforms count. `config.platforms` is pre-seeded with a
- # disabled placeholder PlatformConfig for every KNOWN platform (telegram,
- # discord, slack, …), so `.keys()` is the full ~20-entry catalog regardless
- # of what this instance actually runs. Passing the bare keys made
- # `messaging_is_relay_only_or_absent` see those placeholders as live
- # direct-socket platforms and return False, so scale-to-zero NEVER armed on
- # a real relay-only instance. Mirror the connect loop, which already gates on
- # `platform_config.enabled` (see the `if not platform_config.enabled: continue`
- # in the adapter-connect loop) — arm off the same notion of "active platform."
- platforms = (
- [p for p, pc in self.config.platforms.items() if getattr(pc, "enabled", False)]
- if self.config
- else []
- )
- except Exception: # noqa: BLE001
- platforms = []
- try:
- wake_url = relay_wake_url()
- except Exception: # noqa: BLE001
- wake_url = None
- return should_arm(
- enabled=scale_to_zero_enabled(),
- relay_only_or_absent=messaging_is_relay_only_or_absent(platforms),
- wake_url=wake_url,
+ def _telegram_topic_root_new_message(self) -> str:
+ return (
+ "To start a new parallel Hermes chat, open the All Messages topic "
+ "at the top of this bot interface and send any message there. "
+ "Telegram will create a new topic for it.\n\n"
+ "Each topic is an independent Hermes session. Use /new inside an "
+ "existing topic only if you want to replace that topic's current session."
)
- def _log_scale_to_zero_not_armed_reason(self) -> None:
- """Log why the idle watcher did NOT arm — but only for an OPTED-IN instance.
+ def _telegram_topic_new_header(self, source: SessionSource) -> Optional[str]:
+ if not self._is_telegram_topic_lane(source):
+ return None
+ return (
+ "Started a new Hermes session in this topic.\n\n"
+ "Tip: for parallel work, open All Messages and send a message there "
+ "to create a separate topic instead of using /new here. /new replaces "
+ "the session attached to the current topic."
+ )
- A non-opted instance (no HERMES_SCALE_TO_ZERO stamp) not arming is the normal
- case and must stay silent. When the Labs stamp IS set but the watcher still
- didn't arm, that's the surprising case worth one INFO line so "why won't it
- suspend/wake?" is a log grep, not a box-dive.
- """
- from gateway.relay import relay_wake_url
- from gateway.scale_to_zero import (
- messaging_is_relay_only_or_absent,
- scale_to_zero_enabled,
+ def _record_telegram_topic_binding(
+ self,
+ source: SessionSource,
+ session_entry,
+ ) -> None:
+ """Persist the Telegram topic -> Hermes session binding for topic lanes."""
+ session_db = getattr(self, "_session_db", None)
+ if session_db is None or not source.chat_id or not source.thread_id:
+ return
+ # Runs off-loop (always via asyncio.to_thread); use the sync handle.
+ session_db = getattr(session_db, "_db", session_db)
+ session_db.bind_telegram_topic(
+ chat_id=str(source.chat_id),
+ thread_id=str(source.thread_id),
+ user_id=str(source.user_id or ""),
+ session_key=session_entry.session_key,
+ session_id=session_entry.session_id,
)
- try:
- enabled = scale_to_zero_enabled()
- if not enabled:
- return # not opted in — normal, stay quiet
- try:
- active = (
- [
- getattr(p, "value", p)
- for p, pc in self.config.platforms.items()
- if getattr(pc, "enabled", False)
- ]
- if self.config
- else []
- )
- except Exception: # noqa: BLE001
- active = []
- relay_only = messaging_is_relay_only_or_absent(active)
- try:
- wake_url = relay_wake_url()
- except Exception: # noqa: BLE001
- wake_url = None
- logger.info(
- "scale-to-zero: NOT armed despite opt-in — "
- "relay_only_or_absent=%s (enabled platforms=%s), wake_url=%s. "
- "Need relay-only messaging + a registered wake URL.",
- relay_only,
- active or "none",
- "set" if wake_url else "MISSING",
- )
- except Exception: # noqa: BLE001 - diagnostics must never block startup
- logger.debug("scale-to-zero: not-armed reason logging failed", exc_info=True)
+ def _sync_telegram_topic_binding(
+ self,
+ source: SessionSource,
+ session_entry,
+ *,
+ reason: str,
+ ) -> None:
+ """Update the topic binding to point at ``session_entry.session_id``.
- def _scale_to_zero_is_idle(self) -> bool:
- from gateway.scale_to_zero import is_idle
+ Telegram topic lanes persist a (chat_id, thread_id) -> session_id row
+ so reopening a topic in a fresh process resumes the right Hermes
+ session. When compression rotates ``session_entry.session_id`` mid-turn,
+ the binding goes stale and the next inbound message in that topic
+ reloads the oversized parent transcript instead of the compressed
+ child, retriggering preflight compression — sometimes in a loop
+ (#20470, #29712, #33414).
+ """
+ if not self._is_telegram_topic_lane(source):
+ return
+ try:
+ self._record_telegram_topic_binding(source, session_entry)
+ except Exception:
+ logger.debug(
+ "telegram topic binding refresh failed (%s)", reason, exc_info=True,
+ )
- return is_idle(
- running_agent_count=self._running_agent_count(),
- seconds_since_last_inbound=time.time() - self._last_inbound_at,
- idle_timeout_seconds=self._scale_to_zero_idle_timeout_seconds(),
- has_live_background_work=self._scale_to_zero_has_live_background_work(),
- )
+ def _recover_telegram_topic_thread_id(
+ self,
+ source: SessionSource,
+ ) -> Optional[str]:
+ """Pin DM-topic routing to the user's last-active topic.
- def _scale_to_zero_note_real_inbound(self) -> None:
- """Stamp real inbound and restore lifecycle after a dormant wake.
+ Telegram can omit ``message_thread_id`` or surface General (``1``)
+ for some topic-mode DM replies. In those lobby-shaped cases, keep the
+ conversation attached to the user's most-recent bound topic.
- The watcher marks runtime status `draining` as it quiesces the relay, but
- dormancy is not the stop/restart drain path: the process remains alive and
- should present as running once real traffic wakes it and re-enters the
- gateway. Internal completion/replay events intentionally do not call this
- helper, so they do not keep an otherwise idle gateway awake.
+ Do not rewrite a non-lobby, previously-unbound thread id: a newly
+ created Telegram DM topic is also "unknown" until the first inbound
+ message is recorded, and rewriting it would send that brand-new topic's
+ answer into an older lane. Returns None to leave the source alone.
"""
- self._last_inbound_at = time.time()
- if getattr(self, "_scale_to_zero_cooldown_until", 0.0) > 0:
- try:
- self._update_runtime_status("running")
- except Exception: # noqa: BLE001 - status restoration is best-effort
- logger.debug("scale-to-zero: status restore failed", exc_info=True)
- self._scale_to_zero_cooldown_until = 0.0
-
- def _relay_adapter_for_dormancy(self):
- """Return the connected RELAY adapter, if any (the one go_dormant targets)."""
+ if (
+ source.platform != Platform.TELEGRAM
+ or source.chat_type != "dm"
+ or not source.chat_id
+ or not source.user_id
+ or not self._telegram_topic_mode_enabled(source)
+ ):
+ return None
+ inbound = str(source.thread_id or "")
+ is_lobby = not inbound or inbound in self._TELEGRAM_GENERAL_TOPIC_IDS
+ if not is_lobby:
+ # A non-lobby, unknown thread_id is most likely the first message in
+ # a brand-new Telegram DM topic. Preserve it so it can be recorded
+ # as a new independent lane below instead of hijacking the latest
+ # existing topic binding.
+ return None
+ session_db = getattr(self, "_session_db", None)
+ if session_db is None:
+ return None
+ # Runs off-loop (always via asyncio.to_thread); use the sync handle.
+ session_db = getattr(session_db, "_db", session_db)
try:
- from gateway.platforms.base import Platform
- except Exception: # noqa: BLE001
+ bindings = session_db.list_telegram_topic_bindings_for_chat(
+ chat_id=str(source.chat_id),
+ )
+ except Exception:
+ logger.debug("topic-recover: read failed", exc_info=True)
return None
- return self.adapters.get(Platform.RELAY)
-
- async def _scale_to_zero_watcher(self, interval: float = 30.0) -> None:
- """Watch for idle and drive the relay dormant so the platform can suspend.
-
- Started ONLY when _scale_to_zero_should_arm() (opted in via the Labs
- HERMES_SCALE_TO_ZERO stamp + relay-only/absent messaging + a wakeUrl).
- On a sustained idle window it runs the DORMANT sequence (D12/F12/F14):
- - mark runtime status `draining` (composes with the existing state
- machine, §3.4(6); does NOT set _running=False),
- - relay adapter.go_dormant() — going_idle->ack + supervisor-preserving
- socket close (NOT disconnect(), NOT the run.py stop path),
- - deliberately NO mark_resume_pending (D13 — suspend preserves RAM).
- The process stays alive; the platform (Fly autostop:"suspend") suspends
- the now-traffic-idle machine and autostart wakes it on the wakeUrl poke,
- at which point the preserved reconnect supervisor re-dials and the
- connector drains the buffered backlog. After driving dormant we set a
- re-arm cooldown so a wake's drained backlog isn't immediately re-quiesced.
- """
- await asyncio.sleep(min(interval, 30.0)) # let startup settle
- while self._running:
- try:
- await asyncio.sleep(interval)
- if not self._running:
- return
- if time.time() < self._scale_to_zero_cooldown_until:
- continue
- if not self._scale_to_zero_is_idle():
- continue
- adapter = self._relay_adapter_for_dormancy()
- if adapter is None:
- continue
- go_dormant = getattr(adapter, "go_dormant", None)
- if not callable(go_dormant):
- continue
- logger.info(
- "scale-to-zero: gateway idle for >= %.0fs — going dormant "
- "(relay buffered, socket closed, awaiting platform suspend)",
- self._scale_to_zero_idle_timeout_seconds(),
- )
- try:
- self._update_runtime_status("draining")
- except Exception: # noqa: BLE001 - status is best-effort
- logger.debug("scale-to-zero: status mark failed", exc_info=True)
- try:
- result = go_dormant()
- if asyncio.iscoroutine(result):
- await result
- except Exception: # noqa: BLE001 - dormancy is best-effort
- logger.debug("scale-to-zero: go_dormant failed", exc_info=True)
- # 0.F: after a wake the drained inbound updates _last_inbound_at,
- # but give it a window so we don't immediately re-go-dormant on the
- # same idle reading before traffic lands.
- self._scale_to_zero_cooldown_until = time.time() + max(interval, 60.0)
- except asyncio.CancelledError:
- raise
- except Exception: # noqa: BLE001 - the watcher must never crash the gateway
- logger.debug("scale-to-zero watcher iteration error", exc_info=True)
-
- def _status_action_label(self) -> str:
- return "restart" if self._restart_requested else "shutdown"
-
- def _status_action_gerund(self) -> str:
- return "restarting" if self._restart_requested else "shutting down"
+ if not bindings:
+ return None
+ user_id = str(source.user_id)
+ for b in bindings: # newest-first
+ if str(b.get("user_id") or "") == user_id:
+ recovered = str(b.get("thread_id") or "")
+ if recovered and recovered != inbound:
+ return recovered
+ return None
+ return None
- def _queue_during_drain_enabled(self) -> bool:
- # Both "queue" and "steer" modes imply the user doesn't want messages
- # to be lost during restart — queue them for the newly-spawned gateway
- # process to pick up. "interrupt" mode drops them (current behaviour).
- return self._restart_requested and self._busy_input_mode in {"queue", "steer"}
+ def _normalize_source_for_session_key(
+ self,
+ source: SessionSource,
+ ) -> SessionSource:
+ """Apply Telegram DM topic recovery to a source for session-key purposes.
- # -------- /queue FIFO helpers --------------------------------------
- # /queue must produce one full agent turn per invocation, in FIFO
- # order, with no merging. The adapter's _pending_messages dict is a
- # single "next-up" slot (shared with photo-burst follow-ups), so we
- # use it for the head of the queue and an overflow list for the
- # tail. Enqueue puts new items in the slot when free, otherwise in
- # the overflow. Promotion (called after each run's drain) moves the
- # next overflow item into the slot so the following recursion picks
- # it up. Clearing happens on /new and /reset via
- # _handle_reset_command.
+ ``_handle_message_with_agent`` rewrites ``source.thread_id`` via
+ ``_recover_telegram_topic_thread_id`` *before* deriving the session
+ key for a normal message turn (a lobby/stripped reply gets pinned to
+ the user's last-active topic). Session-scoped command handlers like
+ ``/model`` and ``/reasoning`` derive their override key from the raw
+ inbound ``event.source``, which skips that recovery — so the override
+ is stored under a different key than the next message turn reads,
+ and the override is silently dropped on Telegram forum topics and
+ after compression session splits (#30479).
- def _enqueue_fifo(self, session_key: str, queued_event: "MessageEvent", adapter: Any) -> None:
- """Append a /queue event to the FIFO chain for a session."""
- if adapter is None:
- return
- pending_slot = getattr(adapter, "_pending_messages", None)
- if pending_slot is None:
- return
- if session_key in pending_slot:
- self._session_state(session_key).conversation.queued_events.append(
- queued_event
- )
- else:
- pending_slot[session_key] = queued_event
+ Returns a recovery-normalized copy when a rewrite applies, otherwise
+ the original source unchanged. Always derive the override storage key
+ from the result so storage and read use an identical key.
+ """
+ try:
+ recovered = self._recover_telegram_topic_thread_id(source)
+ except Exception:
+ return source
+ if recovered is None:
+ return source
+ return dataclasses.replace(source, thread_id=recovered)
- def _promote_queued_event(
+ def _resolve_session_agent_runtime(
self,
- session_key: str,
- adapter: Any,
- pending_event: Optional["MessageEvent"],
- ) -> Optional["MessageEvent"]:
- """Promote the next overflow item after the slot was drained.
+ *,
+ source: Optional[SessionSource] = None,
+ session_key: Optional[str] = None,
+ user_config: Optional[dict] = None,
+ ) -> tuple[str, dict]:
+ """Resolve model/runtime for a session.
- Called at the drain site after _dequeue_pending_event consumed
- (or failed to consume) the slot. If there's an overflow item:
- - When pending_event is None (slot was empty), return the
- overflow head as the new pending_event.
- - When pending_event already exists (slot was populated by an
- interrupt follow-up or similar), stage the overflow head in
- the slot so the NEXT recursion picks it up.
- Returns the (possibly updated) pending_event for drain to use.
+ Priority (highest first): session ``/model`` → ``channel_overrides`` →
+ global config/env (``_resolve_gateway_model(user_config)`` and default
+ provider resolution).
"""
- _q_state = self._peek_session_state(session_key)
- overflow = _q_state.conversation.queued_events if _q_state else None
- if not overflow:
- return pending_event
- next_queued = overflow.pop(0)
- if pending_event is None:
- return next_queued
- if adapter is not None and hasattr(adapter, "_pending_messages"):
- adapter._pending_messages[session_key] = next_queued
- else:
- # No adapter — push back so we don't silently drop the item.
- overflow.insert(0, next_queued)
- return pending_event
-
- def _queue_depth(self, session_key: str, *, adapter: Any = None) -> int:
- """Total pending /queue items for a session — slot + overflow."""
- _q_state = self._peek_session_state(session_key)
- depth = len(_q_state.conversation.queued_events) if _q_state else 0
- if adapter is not None and session_key in getattr(adapter, "_pending_messages", {}):
- depth += 1
- return depth
-
- @staticmethod
- def _is_goal_continuation_event(event_or_text: Any) -> bool:
- """Return True for synthetic /goal continuation turns.
+ resolved_session_key = session_key
+ if not resolved_session_key and source is not None:
+ try:
+ resolved_session_key = self._session_key_for_source(source)
+ except Exception:
+ resolved_session_key = None
- Goal continuations are normal queued user-role events, so pause/clear
- must distinguish them from real user /queue messages before removing or
- suppressing them.
- """
- text = getattr(event_or_text, "text", event_or_text) or ""
- return str(text).startswith("[Continuing toward your standing goal]\nGoal:")
+ model = _resolve_gateway_model(user_config)
+ if resolved_session_key:
+ self._rehydrate_session_model_override(resolved_session_key)
+ _override_state = (
+ self._peek_session_state(resolved_session_key)
+ if resolved_session_key
+ else None
+ )
+ override = (
+ _override_state.conversation.model_override if _override_state else None
+ )
+ if override:
+ override_model = override.get("model", model)
+ override_runtime = {
+ "provider": override.get("provider"),
+ "api_key": override.get("api_key"),
+ "base_url": override.get("base_url"),
+ "api_mode": override.get("api_mode"),
+ "max_tokens": override.get("max_tokens"),
+ "credential_pool": override.get("credential_pool"),
+ }
+ if override_runtime.get("api_key"):
+ if override_runtime.get("credential_pool") is None:
+ override_runtime["credential_pool"] = _credential_pool_for_provider(
+ override.get("provider")
+ )
+ logger.debug(
+ "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",
+ resolved_session_key or "", model, override_model,
+ override_runtime.get("provider"),
+ )
+ return override_model, override_runtime
+ # Override exists but has no api_key — fall through to env-based
+ # resolution and apply model/provider from the override on top.
+ logger.debug(
+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",
+ resolved_session_key or "", model, override_model,
+ )
+ else:
+ logger.debug(
+ "No session model override: session=%s config_model=%s override_keys=%s",
+ resolved_session_key or "", model,
+ [
+ _key
+ for _key, _st in list(self._sessions_map().items())
+ if _st.conversation.model_override is not None
+ ][:5] or "[]",
+ )
- def _clear_goal_pending_continuations(self, session_key: str, adapter: Any) -> int:
- """Remove queued synthetic /goal continuations for one session.
+ runtime_kwargs = _resolve_runtime_agent_kwargs()
+ runtime_model = runtime_kwargs.pop("model", None)
+ if runtime_model:
+ logger.info(
+ "Runtime provider supplied explicit model override: %s -> %s",
+ model,
+ runtime_model,
+ )
+ model = runtime_model
- User-issued /goal pause/clear can race with a continuation already
- queued by the judge. Remove only synthetic goal continuations while
- preserving normal /queue and user follow-up events.
- """
- removed = 0
- pending_slot = getattr(adapter, "_pending_messages", None) if adapter is not None else None
- if isinstance(pending_slot, dict):
- pending_event = pending_slot.get(session_key)
- if self._is_goal_continuation_event(pending_event):
- pending_slot.pop(session_key, None)
- removed += 1
+ cfg = getattr(self, "config", None)
+ if cfg and source is not None:
+ chat_id = str(source.chat_id) if source.chat_id else ""
+ thread_id = (
+ str(source.thread_id) if getattr(source, "thread_id", None) else None
+ )
+ parent_id = (
+ str(source.parent_chat_id)
+ if getattr(source, "parent_chat_id", None)
+ else None
+ )
+ ch = _get_channel_override(
+ cfg,
+ source.platform,
+ chat_id,
+ thread_id=thread_id,
+ parent_id=parent_id,
+ )
+ if ch:
+ if ch.model:
+ model = ch.model
+ if ch.provider:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(
+ ch.provider
+ )
+ ch_runtime_model = runtime_kwargs.pop("model", None)
+ # Only adopt the provider's bundled model when the override
+ # did not specify an explicit model.
+ if ch_runtime_model and not ch.model:
+ model = ch_runtime_model
- _q_state = self._peek_session_state(session_key)
- overflow = _q_state.conversation.queued_events if _q_state else []
- if overflow:
- kept = []
- for queued_event in overflow:
- if self._is_goal_continuation_event(queued_event):
- removed += 1
- else:
- kept.append(queued_event)
- _q_state.conversation.queued_events = kept
- return removed
+ if override and resolved_session_key:
+ model, runtime_kwargs = self._apply_session_model_override(
+ resolved_session_key, model, runtime_kwargs
+ )
- def _goal_still_active_for_session(self, session_id: str) -> bool:
- """Best-effort fresh DB check before running a queued continuation."""
- if not session_id:
- return False
- try:
- from hermes_cli.goals import GoalManager
- return GoalManager(session_id=session_id).is_active()
- except Exception as exc:
- logger.debug("goal continuation: active-state recheck failed: %s", exc)
- return False
+ # When the config has no model.default but a provider was resolved
+ # (e.g. user ran `hermes auth add openai-codex` without `hermes model`),
+ # fall back to the provider's first catalog model so the API call
+ # doesn't fail with "model must be a non-empty string".
+ if not model and runtime_kwargs.get("provider"):
+ try:
+ from hermes_cli.models import get_default_model_for_provider
+ model = get_default_model_for_provider(runtime_kwargs["provider"])
+ if model:
+ logger.info(
+ "No model configured — defaulting to %s for provider %s",
+ model, runtime_kwargs["provider"],
+ )
+ except Exception:
+ pass
- def _update_runtime_status(self, gateway_state: Optional[str] = None, exit_reason: Optional[str] = None) -> None:
- try:
- from gateway.status import write_runtime_status
- write_runtime_status(
- gateway_state=gateway_state,
- exit_reason=exit_reason,
- restart_requested=self._restart_requested,
- active_agents=self._active_work_count(),
+ # Final safety net (#35314): if resolution still produced an empty
+ # model — e.g. a transient config-cache miss during a post-interrupt
+ # recovery turn returned an empty user_config — reuse the last model we
+ # successfully resolved for this session (or, failing that, the most
+ # recent one resolved process-wide). Building an agent with model=""
+ # makes every API call fail HTTP 400 "No models provided" and the
+ # session goes silent until the user manually re-sends. ``getattr``
+ # guards against bare test runners built via ``object.__new__``.
+ if not model:
+ _lr_state = (
+ self._peek_session_state(resolved_session_key)
+ if resolved_session_key
+ else None
)
- except Exception:
- pass
+ _lr_star = self._peek_session_state("*")
+ _recovered = (
+ (_lr_state.conversation.last_resolved_model if _lr_state else "")
+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")
+ )
+ if _recovered:
+ logger.warning(
+ "Empty model resolved for session=%s — recovering "
+ "last-known-good model %s (config read likely returned "
+ "empty; see #35314)",
+ resolved_session_key or "", _recovered,
+ )
+ model = _recovered
+ elif model:
+ # Cache the good resolution for future recovery turns.
+ if resolved_session_key:
+ self._session_state(
+ resolved_session_key
+ ).conversation.last_resolved_model = model
+ self._session_state("*").conversation.last_resolved_model = model
- def _persist_active_agents(self) -> None:
- """Persist the live in-flight agent count to ``gateway_state.json``.
+ return model, runtime_kwargs
- Called at every turn boundary (a running-agent slot is claimed or
- released) so the dashboard ``/api/status`` readout reflects in-flight
- gateway turns in near-real-time. Without this the file is only
- rewritten on lifecycle transitions, so any ``active_agents`` read
- between transitions is stale (a turn could start and finish without the
- file ever moving).
+ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:
+ """Build the effective model/runtime config for a single turn.
- Deliberately passes ONLY ``active_agents`` — ``gateway_state`` and the
- other fields stay ``_UNSET`` so ``write_runtime_status``'s
- read-merge-write preserves the current lifecycle state (``running`` /
- ``draining`` / …). Passing ``gateway_state=None`` here would clobber it.
- Best-effort: a failed status write must never disrupt a turn.
+ Always uses the session's primary model/provider. If `/fast` is
+ enabled and the model supports Priority Processing / Anthropic fast
+ mode, attach `request_overrides` so the API call is marked
+ accordingly.
"""
- try:
- from gateway.status import write_runtime_status
- write_runtime_status(active_agents=self._active_work_count())
- except Exception:
- pass
+ from hermes_cli.models import resolve_fast_mode_overrides
- # ------------------------------------------------------------------
- # External drain control (NAS-driven quiesce-without-restart, Phase 2).
- # The dashboard's begin/cancel-drain endpoint writes/removes the
- # ``.drain_request.json`` marker (gateway/drain_control.py); this watcher
- # observes the marker and flips the gateway between accepting and refusing
- # NEW turns, WITHOUT exiting the process. Reversible by design (D4a): NAS
- # POSTs begin-drain, polls /api/status until active_agents hits 0, proceeds
- # with its lifecycle action, then (on cancel/abort) the marker is removed
- # and the gateway re-accepts turns.
- # ------------------------------------------------------------------
- def _enter_external_drain(self) -> None:
- """Begin external drain: stop accepting new turns, flip state.
-
- Idempotent — re-entering while already draining is a no-op beyond a
- best-effort status re-write. In-flight turns are NOT interrupted (the
- whole point is to let them finish); only NEW turns are refused.
- """
- if self._external_drain_active:
- return
- self._external_drain_active = True
- logger.info(
- "External drain ENGAGED (.drain_request.json present) — refusing "
- "new turns; %d in-flight turn(s) will finish. Process stays up.",
- self._active_work_count(),
- )
- # Flip the persisted lifecycle state so /api/status.gateway_busy /
- # gateway_drainable track the drain. Preserve active_agents (the
- # read-merge keeps the live count); only the state changes.
- self._update_runtime_status("draining")
-
- def _exit_external_drain(self) -> None:
- """Cancel external drain: revert state, re-accept new turns.
-
- Idempotent. Only reverts to ``running`` when we are actually mid-drain
- AND not also shutting down (a real shutdown ``_draining`` must win —
- never resurrect a stopping gateway to ``running``).
- """
- if not self._external_drain_active:
- return
- self._external_drain_active = False
- if self._draining or not self._running:
- # A shutdown drain is in progress / the loop has stopped — do not
- # clobber the terminal state back to running.
- logger.info(
- "External drain marker cleared during shutdown — not reverting "
- "to running (shutdown takes precedence)."
- )
- return
- logger.info(
- "External drain RELEASED (.drain_request.json removed) — "
- "re-accepting new turns; gateway_state -> running."
- )
- self._update_runtime_status("running")
-
- async def _drain_control_watcher(self, interval: float = 1.0) -> None:
- """Background task: reconcile gateway accept-state with the drain marker.
-
- Polls ``.drain_request.json`` (presence-based contract,
- gateway/drain_control.py). Marker present -> ``_enter_external_drain``;
- marker absent -> ``_exit_external_drain``. The 1s cadence bounds the
- observe-the-marker latency the live-validation gate checks (point a).
- Reconciles once at startup. A marker stamped with a PRIOR
- instantiation epoch (one that survived a machine restart on the durable
- HERMES_HOME volume — NS-570) is treated as absent by ``drain_requested``
- and is NOT honoured; only a marker from the current instantiation flips
- the gateway into drain. Best-effort: any tick error is logged and the
- loop continues (a transient stat() failure must not wedge the gateway).
- """
- from gateway.drain_control import drain_requested
+ runtime = {
+ "api_key": runtime_kwargs.get("api_key"),
+ "base_url": runtime_kwargs.get("base_url"),
+ "provider": runtime_kwargs.get("provider"),
+ "requested_provider": runtime_kwargs.get("requested_provider"),
+ "api_mode": runtime_kwargs.get("api_mode"),
+ "command": runtime_kwargs.get("command"),
+ "args": list(runtime_kwargs.get("args") or []),
+ "credential_pool": runtime_kwargs.get("credential_pool"),
+ "max_tokens": runtime_kwargs.get("max_tokens"),
+ }
+ route = {
+ "model": model,
+ "runtime": runtime,
+ "signature": (
+ model,
+ runtime["provider"],
+ runtime["requested_provider"],
+ runtime["base_url"],
+ runtime["api_mode"],
+ runtime["command"],
+ tuple(runtime["args"]),
+ ),
+ }
- while self._running:
- try:
- if drain_requested():
- self._enter_external_drain()
- # API and cron work live outside messaging's
- # _running_agents map. Refresh the aggregate while an
- # external caller polls this reversible drain state.
- self._persist_active_agents()
- else:
- self._exit_external_drain()
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- logger.debug("Drain-control watcher tick error: %s", exc, exc_info=True)
- await asyncio.sleep(interval)
+ service_tier = getattr(self, "_service_tier", None)
+ if not service_tier:
+ route["request_overrides"] = {}
+ return route
- def _update_platform_runtime_status(
- self,
- platform: str,
- *,
- platform_state: Optional[str] = None,
- error_code: Optional[str] = None,
- error_message: Optional[str] = None,
- ) -> None:
try:
- from gateway.status import write_runtime_status
- write_runtime_status(
- platform=platform,
- platform_state=platform_state,
- error_code=error_code,
- error_message=error_message,
- )
+ overrides = resolve_fast_mode_overrides(route["model"])
except Exception:
- pass
+ overrides = None
+ route["request_overrides"] = overrides or {}
+ return route
- # ------------------------------------------------------------------
- # Per-platform circuit breaker (pause/resume) — used by the reconnect
- # watcher when a retryable failure recurs past a threshold, and by the
- # /platform pause|resume slash command for manual control.
- # ------------------------------------------------------------------
- def _pause_failed_platform(self, platform, *, reason: str = "") -> None:
- """Mark a queued platform as paused — keep it in ``_failed_platforms``
- but stop the reconnect watcher from hammering it.
+ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:
+ """Persist the runtime model/provider actually used by a gateway turn.
- Used by ``/platform pause <name>`` for manual operator intervention.
- Paused platforms are surfaced in ``/platform list`` and resumed with
- ``/platform resume <name>``. Note: the reconnect watcher does NOT
- auto-pause — retryable (network/DNS) failures keep retrying at the
- backoff cap indefinitely so a transient outage self-heals without
- manual intervention.
+ Provider fallback can switch ``agent.model``/``agent.provider`` after the
+ session row was created. Keep the session DB metadata in sync so session
+ lists, desktop/dashboard details, and follow-up session tooling report the
+ backend that actually answered the latest turn.
+
+ Called from the ``run_sync`` closure, which executes off the event loop
+ in the executor thread — so the synchronous ``SessionDB`` (``_db``) is
+ used directly rather than awaiting the AsyncSessionDB forwarder.
"""
- info = getattr(self, "_failed_platforms", {}).get(platform)
- if info is None:
+ if not session_id or agent is None or self._session_db is None:
return
- if info.get("paused"):
+ model = getattr(agent, "model", None)
+ if not model:
return
- info["paused"] = True
- info["pause_reason"] = reason or "auto-paused after repeated failures"
- # Push next_retry far enough out that even if "paused" is missed
- # by a stale code path, the watcher won't fire on it.
- info["next_retry"] = float("inf")
+ runtime = {
+ "provider": getattr(agent, "provider", None),
+ "base_url": getattr(agent, "base_url", None),
+ "api_mode": getattr(agent, "api_mode", None),
+ "fallback_active": bool(getattr(agent, "_fallback_activated", False)),
+ }
+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}
+
try:
- self._update_platform_runtime_status(
- platform.value,
- platform_state="paused",
- error_code=None,
- error_message=info["pause_reason"],
- )
+ db = self._session_db._db
+ row = db.get_session(session_id)
+ if not row:
+ return
+ current_model = row.get("model")
+ raw_config = row.get("model_config")
+ try:
+ config = json.loads(raw_config) if raw_config else {}
+ except Exception:
+ config = {}
+ if not isinstance(config, dict):
+ config = {}
+ gateway_runtime = dict(config.get("gateway_runtime") or {})
+ if current_model == model and all(
+ gateway_runtime.get(k) == v for k, v in runtime.items()
+ ):
+ return
+ config["gateway_runtime"] = runtime
+ db.update_session_meta(session_id, json.dumps(config), model=model)
except Exception:
- pass
- logger.warning(
- "%s paused after %d consecutive failures (%s) — "
- "fix the underlying issue then run `/platform resume %s` "
- "to retry, or `hermes gateway restart` to restart the gateway.",
- platform.value, info.get("attempts", 0),
- info["pause_reason"], platform.value,
- )
+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)
- def _resume_paused_platform(self, platform) -> bool:
- """Unpause a platform — reset its attempt counter and schedule an
- immediate retry. Returns True if the platform was paused and is
- now queued; False if it wasn't paused (or wasn't in the queue).
+ async def _handle_reaction_event(self, ctx: Dict[str, Any]) -> None:
+ """Fan a normalised platform reaction event out to the HookRegistry.
+
+ Adapters call this via ``set_reaction_handler`` for every
+ platform-native reaction event they surface. The adapter-supplied
+ ``event_name`` ("reaction:added" / "reaction:removed") becomes the
+ hook event so user hooks subscribe with the same name scheme as the
+ existing ``agent:*`` family. Errors never block the adapter's event
+ loop — the hook contract is non-blocking.
"""
- info = getattr(self, "_failed_platforms", {}).get(platform)
- if info is None:
- return False
- if not info.get("paused"):
- return False
- info["paused"] = False
- info.pop("pause_reason", None)
- info["attempts"] = 0
- info["next_retry"] = time.monotonic() # retry on next watcher tick
+ event_name = str(ctx.get("event_name") or "reaction:added")
try:
- self._update_platform_runtime_status(
- platform.value,
- platform_state="retrying",
- error_code=None,
- error_message=None,
- )
+ await self.hooks.emit(event_name, ctx)
except Exception:
- pass
- logger.info("%s resumed — retrying on next watcher tick", platform.value)
- return True
+ logger.debug("[Gateway] reaction hook emit failed", exc_info=True)
- @staticmethod
- def _load_prefill_messages() -> List[Dict[str, Any]]:
- """Load ephemeral prefill messages from config or env var.
-
- Checks HERMES_PREFILL_MESSAGES_FILE env var first, then falls back to
- the top-level prefill_messages_file key in ~/.hermes/config.yaml.
- agent.prefill_messages_file is accepted as a legacy fallback.
- Relative paths are resolved from ~/.hermes/.
- """
- file_path = os.getenv("HERMES_PREFILL_MESSAGES_FILE", "")
- if not file_path:
- cfg = _load_gateway_runtime_config()
- file_path = str(cfg.get("prefill_messages_file", "") or "")
- if not file_path:
- file_path = str(cfg_get(cfg, "agent", "prefill_messages_file", default="") or "")
- if not file_path:
- return []
- path = Path(file_path).expanduser()
- if not path.is_absolute():
- path = _hermes_home / path
- if not path.exists():
- logger.warning("Prefill messages file not found: %s", path)
- return []
- try:
- with open(path, "r", encoding="utf-8") as f:
- data = json.load(f)
- if not isinstance(data, list):
- logger.warning("Prefill messages file must contain a JSON array: %s", path)
- return []
- return data
- except Exception as e:
- logger.warning("Failed to load prefill messages from %s: %s", path, e)
- return []
-
- @staticmethod
- def _load_ephemeral_system_prompt() -> str:
- """Load ephemeral system prompt from config or env var.
-
- Checks HERMES_EPHEMERAL_SYSTEM_PROMPT env var first, then falls back to
- agent.system_prompt in ~/.hermes/config.yaml.
- """
- prompt = os.getenv("HERMES_EPHEMERAL_SYSTEM_PROMPT", "")
- if prompt:
- return prompt
- cfg = _load_gateway_runtime_config()
- return str(cfg_get(cfg, "agent", "system_prompt", default="") or "").strip()
+ async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> None:
+ """React to an adapter failure after startup.
- def _resolve_model_for_channel(
- self,
- platform: Platform,
- chat_id: str,
- *,
- user_config: Optional[dict] = None,
- thread_id: Optional[str] = None,
- parent_id: Optional[str] = None,
- ) -> str:
- """Resolve model for this channel: channel_overrides else global default.
+ If the error is retryable (e.g. network blip, DNS failure), queue the
+ platform for background reconnection instead of giving up permanently.
- Delegates the precedence rule to
- :func:`hermes_cli.model_switch.resolve_effective_model` (session
- override > channel override > global default) — the single owner
- shared with the API server, so the two surfaces cannot diverge
- again (see 7dd00bb47d). This call site has no session tier: session
- /model overrides are applied later by
- ``_apply_session_model_override`` on the resolved runtime.
+ The notification arrives on the failing adapter's own polling task,
+ and the disconnect inside the handler can cancel that task mid-flight:
+ disconnect()'s current-task guard misses it because
+ _safe_adapter_disconnect runs the close in a wrapper task. A cancelled
+ handler dies between the fatal log and the reconnect queue, silently
+ stranding the platform (observed 2026-07-21: telegram popped from
+ adapters but never queued after a travel network outage). Run the real
+ work in a detached task that adapter teardown cannot cancel.
"""
- from hermes_cli.model_switch import resolve_effective_model
+ tasks = getattr(self, "_fatal_handler_tasks", None)
+ if tasks is None:
+ tasks = self._fatal_handler_tasks = set()
+ task = asyncio.create_task(self._handle_adapter_fatal_error_detached(adapter))
+ tasks.add(task)
+ task.add_done_callback(tasks.discard)
+ # Await so callers that expect completion still get it — but through
+ # shield(): Task.cancel() on the caller also cancels the future it is
+ # awaiting (_fut_waiter), so a plain `await task` would tunnel the
+ # cancellation straight into the "detached" task. shield() absorbs
+ # it: the caller sees CancelledError, the handler runs to completion.
+ await asyncio.shield(task)
- override = None
- config = getattr(self, "config", None)
- if config:
- override = _get_channel_override(
- config,
- platform,
- chat_id,
- thread_id=thread_id,
- parent_id=parent_id,
+ async def _handle_adapter_fatal_error_detached(
+ self, adapter: BasePlatformAdapter
+ ) -> None:
+ """Run the fatal handler; if the platform still ends up stranded
+ (not reconnected, not queued, not intentionally disabled), exit the
+ gateway with failure so the service manager restarts it instead of
+ leaving a silent partial outage."""
+ try:
+ await self._handle_adapter_fatal_error_impl(adapter)
+ except Exception:
+ logger.exception(
+ "Fatal-error handling for %s raised unexpectedly",
+ adapter.platform.value,
)
- return resolve_effective_model(
- None, # session tier applied downstream (_apply_session_model_override)
- override,
- _resolve_gateway_model(user_config),
- )
-
- def _get_system_prompt_for_channel(
- self,
- platform: Platform,
- chat_id: str,
- *,
- thread_id: Optional[str] = None,
- parent_id: Optional[str] = None,
- ) -> str:
- """Ephemeral system prompt for this channel/thread.
-
- Uses ``channel_overrides`` when set, else the global gateway prompt.
- Legacy ``channel_prompts`` are applied separately via ``event.channel_prompt``
- in ``run_sync`` (adapter ``resolve_channel_prompt``), so they are not
- duplicated here.
- """
- config = getattr(self, "config", None)
- if config:
- override = _get_channel_override(
- config,
- platform,
- chat_id,
- thread_id=thread_id,
- parent_id=parent_id,
+ finally:
+ platform = adapter.platform
+ shutdown_event = getattr(self, "_shutdown_event", None)
+ stranded = (
+ adapter.fatal_error_retryable
+ and platform not in self.adapters
+ and platform not in getattr(self, "_failed_platforms", {})
+ and not (shutdown_event is not None and shutdown_event.is_set())
)
- if override and override.system_prompt:
- return (override.system_prompt or "").strip()
- return getattr(self, "_ephemeral_system_prompt", None) or ""
-
- @staticmethod
- def _load_reasoning_config(model: str = "") -> dict | None:
- """Load reasoning effort from config.yaml, respecting per-model overrides.
-
- Thin wrapper over the shared chokepoint
- :func:`hermes_constants.resolve_reasoning_config` (per-model override >
- global ``agent.reasoning_effort``; YAML boolean False = disabled).
- Closes #21256.
+ if stranded:
+ logger.error(
+ "%s adapter was lost without entering the reconnection "
+ "queue; exiting gateway so the service manager restarts it.",
+ platform.value,
+ )
+ self._exit_reason = (
+ f"{platform.value} adapter lost without reconnection queue"
+ )
+ self._exit_with_failure = True
+ await self.stop()
- Args:
- model: The effective model for the calling session. When empty,
- the config's ``model.default`` is used.
- """
- from hermes_constants import resolve_reasoning_config
- cfg = _load_gateway_runtime_config()
- return resolve_reasoning_config(cfg, model)
+ async def _handle_adapter_fatal_error_impl(self, adapter: BasePlatformAdapter) -> None:
+ # Snapshot the current owner of this platform slot before doing
+ # anything else. If it's neither this adapter nor empty, a different
+ # adapter has already taken over (e.g. this is a delayed notification
+ # from a background retry chain that raced with, and lost to, a
+ # reconnect that already succeeded). Acting on a stale notification
+ # would overwrite an already-healthy platform's runtime status and
+ # incorrectly re-queue it for reconnection, so bail out before any of
+ # that happens.
+ existing = self.adapters.get(adapter.platform)
+ if existing is not None and existing is not adapter:
+ logger.debug(
+ "Ignoring stale fatal error from a superseded %s adapter instance: %s",
+ adapter.platform.value,
+ adapter.fatal_error_code or "unknown",
+ )
+ return
- @staticmethod
- def _parse_reasoning_command_args(raw_args: str) -> tuple[str, bool]:
- """Parse `/reasoning` args into `(value, persist_global)`.
+ logger.error(
+ "Fatal %s adapter error (%s): %s",
+ adapter.platform.value,
+ adapter.fatal_error_code or "unknown",
+ adapter.fatal_error_message or "unknown error",
+ )
+ # Phase 7 Unit 7d-B: a relay credential revoked by opt-out is not an
+ # error to retry — render it as a clean "disabled" state, not red
+ # "fatal"/"retrying". (The code is set non-retryable, so it also drops
+ # out of the reconnect queue below.)
+ if adapter.fatal_error_code == "relay_disabled":
+ platform_state = "disabled"
+ elif adapter.fatal_error_retryable:
+ platform_state = "retrying"
+ else:
+ platform_state = "fatal"
+ self._update_platform_runtime_status(
+ adapter.platform.value,
+ platform_state=platform_state,
+ error_code=adapter.fatal_error_code,
+ error_message=adapter.fatal_error_message,
+ )
- `/reasoning <level>` is session-scoped by default. `--global` may be
- supplied in any position to persist the change to config.yaml.
- """
- import shlex
+ if existing is adapter:
+ # Claim this adapter for teardown before awaiting disconnect() —
+ # a second fatal-error notification for the same adapter (e.g.
+ # from a concurrent recovery path) would otherwise still see
+ # itself as "existing" during the await below and disconnect()
+ # the same object twice.
+ self.adapters.pop(adapter.platform, None)
+ self.delivery_router.adapters = self.adapters
+ # A half-closed transport can wedge an adapter's native close()
+ # indefinitely. Reuse the shutdown-path timeout so this runtime
+ # fatal handler always reaches the reconnect queue.
+ await self._safe_adapter_disconnect(adapter, adapter.platform)
- text = str(raw_args or "").strip().replace("—", "--")
- if not text:
- return "", False
- try:
- tokens = shlex.split(text)
- except ValueError:
- tokens = text.split()
+ # Queue retryable failures for background reconnection
+ if adapter.fatal_error_retryable:
+ platform_config = self.config.platforms.get(adapter.platform)
+ if platform_config and adapter.platform not in self._failed_platforms:
+ self._failed_platforms[adapter.platform] = {
+ "config": platform_config,
+ "attempts": 0,
+ "next_retry": time.monotonic(),
+ }
+ logger.info(
+ "%s queued for background reconnection",
+ adapter.platform.value,
+ )
+ # Ensure the reconnect watcher is alive — if it died (e.g. from
+ # exhausting its restart budget), respawn it so queued platforms
+ # are not permanently stranded (#70344).
+ self._ensure_reconnect_watcher_running()
- persist_global = False
- value_tokens = []
- for token in tokens:
- if token == "--global":
- persist_global = True
+ if not self.adapters and not self._failed_platforms:
+ self._exit_reason = adapter.fatal_error_message or "All messaging adapters disconnected"
+ if adapter.fatal_error_retryable:
+ self._exit_with_failure = True
+ logger.error("No connected messaging platforms remain. Shutting down gateway for service restart.")
else:
- value_tokens.append(token)
- return " ".join(value_tokens).strip().lower(), persist_global
-
- def _resolve_session_reasoning_config(
- self,
- *,
- source: Optional[SessionSource] = None,
- session_key: Optional[str] = None,
- model: str = "",
- ) -> dict | None:
- """Resolve reasoning effort for a session, honoring session overrides.
+ logger.error("No connected messaging platforms remain. Shutting down gateway cleanly.")
+ await self.stop()
+ elif not self.adapters and self._failed_platforms:
+ # All platforms are down and queued for background reconnection.
+ # Keep the gateway alive so:
+ # • cron jobs still run
+ # • the reconnect watcher can recover platforms when the
+ # underlying problem clears (proxy comes back, user runs
+ # `hermes whatsapp`, etc.)
+ # We used to exit-with-failure here to trigger systemd restart,
+ # but that converted a transient outage into a restart loop and
+ # killed in-process state every time. The reconnect watcher
+ # already handles long-running recovery — let it do its job.
+ logger.warning(
+ "No connected messaging platforms remain, but %d platform(s) "
+ "queued for reconnection — gateway staying alive, watcher will "
+ "retry in background.",
+ len(self._failed_platforms),
+ )
- Priority: session-scoped ``/reasoning --session`` override >
- per-model override (``agent.reasoning_overrides``) > global
- ``agent.reasoning_effort``. ``model`` should be the session's
- *effective* model (session ``/model`` override included) so
- per-model overrides track what the session actually runs — when
- empty, the config's ``model.default`` is used.
- """
- resolved_session_key = session_key
- if not resolved_session_key and source is not None:
- try:
- resolved_session_key = self._session_key_for_source(source)
- except Exception:
- resolved_session_key = None
+ def _request_clean_exit(self, reason: str) -> None:
+ self._exit_cleanly = True
+ self._exit_reason = reason
+ self._shutdown_event.set()
- if resolved_session_key:
- _r_state = self._peek_session_state(resolved_session_key)
- if _r_state is not None and _r_state.conversation.reasoning_override is not None:
- return _r_state.conversation.reasoning_override
- return self._load_reasoning_config(model)
+ def _running_agent_count(self) -> int:
+ return len(self._running_agents)
- def _set_session_reasoning_override(
- self,
- session_key: str,
- reasoning_config: Optional[dict],
- ) -> None:
- """Set or clear the session-scoped reasoning override."""
- if not session_key:
- return
- # Per-session field write — the old lazy ``self._session_reasoning_overrides
- # = {}`` init replaced the WHOLE dict, racing concurrent sessions'
- # overrides; a SessionState field reset cannot cross sessions.
- self._session_state(session_key).conversation.reasoning_override = (
- None if reasoning_config is None else dict(reasoning_config)
+ def _active_work_count(self) -> int:
+ """All agent work the gateway must expose and drain as one total."""
+ return (
+ self._running_agent_count()
+ + self._active_cron_job_count()
+ + self._active_api_run_count()
)
- def _resolve_session_service_tier(
- self,
- source=None,
- session_key: Optional[str] = None,
- ) -> Optional[str]:
- """Resolve the effective service tier for a session.
+ def _active_cron_job_count(self) -> int:
+ """Count of cron jobs currently executing, from the cron scheduler's
+ own in-flight tracking (``cron.scheduler._running_job_ids``).
- A session-scoped /fast override wins over the config default. The
- override dict stores "priority" or None (explicit normal), so key
- presence — not value truthiness — decides whether it applies.
+ Cron jobs run through a standalone ``AIAgent`` on the scheduler's own
+ thread pool (``cron/scheduler.py::run_job``), entirely outside
+ ``self._running_agents`` — the dict every OTHER active-work check on
+ this class (``_running_agent_count``, ``_drain_active_agents``) reads.
+ Without this, the shutdown drain is structurally blind to in-flight
+ cron work: it can report ``active_at_start=0`` and proceed straight
+ to killing tool subprocesses while a cron job's terminal command is
+ still running (#60432). Best-effort: returns 0 if the cron module
+ can't be imported (e.g. a minimal test double for this class).
"""
- resolved_session_key = session_key
- if not resolved_session_key and source is not None:
- try:
- resolved_session_key = self._session_key_for_source(source)
- except Exception:
- resolved_session_key = None
-
- if resolved_session_key:
- _t_state = self._peek_session_state(resolved_session_key)
- if (
- _t_state is not None
- and _t_state.conversation.service_tier_override
- is not _SERVICE_TIER_UNSET
- ):
- return _t_state.conversation.service_tier_override
- return self._load_service_tier()
+ try:
+ from cron.scheduler import get_running_job_ids
+ return len(get_running_job_ids())
+ except Exception:
+ return 0
- def _set_session_service_tier_override(
- self,
- session_key: str,
- service_tier,
- clear: bool = False,
- ) -> None:
- """Set or clear the session-scoped /fast override.
+ def _active_api_run_count(self) -> int:
+ """Count API-server work that is outside ``_running_agents``.
- ``service_tier`` is "priority" or None (explicit normal). Pass
- ``clear=True`` to remove the override entirely (fall back to config).
+ The primary API server owns the sole HTTP listener. Secondary multiplex
+ profiles cannot create an ``api_server`` adapter because it binds a port,
+ so only the primary registry is a supported source of this work.
"""
- if not session_key:
- return
- # Presence-sensitive: "priority" or None (explicit normal) both count
- # as an override; the sentinel means "no override". Old code
- # wholesale-replaced the dict on lazy init (cross-session race) —
- # per-session field writes eliminate that class of bug.
- self._session_state(session_key).conversation.service_tier_override = (
- _SERVICE_TIER_UNSET if clear else service_tier
- )
+ try:
+ adapter = getattr(self, "adapters", {}).get(Platform.API_SERVER)
+ helper = getattr(adapter, "active_agent_work_count", None)
+ return max(0, int(helper())) if callable(helper) else 0
+ except Exception:
+ return 0
- @staticmethod
- def _load_service_tier() -> str | None:
- """Load Priority Processing setting from config.yaml.
+ # ── scale-to-zero idle detection / dormant-quiesce (Phase 0) ──────────────
+ # The gateway-side BEHAVIOUR that consumes the relay scale-to-zero primitives
+ # (gateway-gateway Phase 5). Pure logic lives in gateway/scale_to_zero.py; the
+ # methods here bind it to the live runner/transport. See ~/nous/specs/
+ # scale-to-zero (decisions.md) for the design + the F12/F14 distinctions.
- Reads agent.service_tier from config.yaml. Accepted values mirror the CLI:
- "fast"/"priority"/"on" => "priority", while "normal"/"off" disables it.
- Returns None when unset or unsupported.
+ def _scale_to_zero_has_live_background_work(self) -> bool:
+ """Live background work that must block a suspend (D3/F7).
+
+ Backgrounded delegate_task / kanban / terminal(background=true) are NOT
+ counted by _running_agent_count(), but suspending mid-flight loses them.
+ Checks the runner's own tracked tasks + the process registry's running
+ processes + any pending process-completion watchers.
"""
- cfg = _load_gateway_runtime_config()
- raw = str(cfg_get(cfg, "agent", "service_tier", default="") or "").strip()
+ if any(not t.done() for t in self._background_tasks):
+ return True
+ try:
+ from tools.async_delegation import active_count
- value = raw.lower()
- if not value or value in {"normal", "default", "standard", "off", "none"}:
- return None
- if value in {"fast", "priority", "on"}:
- return "priority"
- logger.warning("Unknown service_tier '%s', ignoring", raw)
- return None
+ if active_count() > 0:
+ return True
+ except Exception: # noqa: BLE001 - never let the idle check raise
+ logger.debug("scale-to-zero async-delegation check failed", exc_info=True)
+ try:
+ from tools.process_registry import process_registry
- @staticmethod
- def _load_show_reasoning() -> bool:
- """Load show_reasoning toggle from config.yaml display section."""
- cfg = _load_gateway_runtime_config()
- return is_truthy_value(
- cfg_get(cfg, "display", "show_reasoning"),
- default=False,
- )
+ if process_registry.has_any_active():
+ return True
+ if process_registry.pending_watchers:
+ return True
+ except Exception: # noqa: BLE001 - never let the idle check raise
+ logger.debug("scale-to-zero bg-work check failed", exc_info=True)
+ return False
- @staticmethod
- def _load_busy_input_mode() -> str:
- """Load gateway drain-time busy-input behavior from config/env."""
- mode = os.getenv("HERMES_GATEWAY_BUSY_INPUT_MODE", "").strip().lower()
- if not mode:
- cfg = _load_gateway_runtime_config()
- mode = str(cfg_get(cfg, "display", "busy_input_mode", default="") or "").strip().lower()
- if mode == "queue":
- return "queue"
- if mode == "steer":
- return "steer"
- return "interrupt"
+ def _scale_to_zero_idle_timeout_seconds(self) -> float:
+ from gateway.scale_to_zero import parse_idle_timeout_seconds
- @staticmethod
- def _load_busy_text_mode() -> str:
- """Resolve normal busy TEXT follow-up behavior.
+ raw = None
+ try:
+ user_cfg = _load_gateway_config()
+ gw = user_cfg.get("gateway") if isinstance(user_cfg, dict) else None
+ stz = gw.get("scale_to_zero") if isinstance(gw, dict) else None
+ if isinstance(stz, dict):
+ raw = stz.get("idle_timeout_minutes")
+ except Exception: # noqa: BLE001
+ raw = None
+ return parse_idle_timeout_seconds(raw)
- ``busy_input_mode`` is the single source of truth (default
- ``interrupt``). The legacy ``busy_text_mode`` knob is honored only
- when a user explicitly set it, so existing queue setups keep
- working; new installs follow ``busy_input_mode``. Returns one of
- ``interrupt`` | ``queue`` (``steer`` is handled upstream by
- ``busy_input_mode`` and maps to non-queue text handling here).
+ def _restart_loop_guard_config(self) -> tuple:
+ """Return ``(max_restarts, window_seconds)`` for the auto-resume
+ restart-loop breaker (#30719, defense-3), read from
+ ``gateway.restart_loop_guard`` in config.yaml with the module defaults
+ as fallback. ``max_restarts <= 0`` disables the breaker.
"""
- # Legacy explicit override wins for backward compat.
- legacy = os.getenv("HERMES_GATEWAY_BUSY_TEXT_MODE", "").strip().lower()
- if not legacy:
- cfg = _load_gateway_runtime_config()
- legacy = str(cfg_get(cfg, "display", "busy_text_mode", default="") or "").strip().lower()
- if legacy == "interrupt":
- return "interrupt"
- if legacy == "queue":
- return "queue"
- # No explicit legacy knob → follow busy_input_mode.
- input_mode = GatewayRunner._load_busy_input_mode()
- return "queue" if input_mode == "queue" else "interrupt"
+ from gateway import restart_loop_guard as _rlg
- @staticmethod
- def _load_restart_drain_timeout() -> float:
- """Load graceful gateway restart/stop drain timeout in seconds."""
- raw = os.getenv("HERMES_RESTART_DRAIN_TIMEOUT", "").strip()
- if not raw:
- cfg = _load_gateway_runtime_config()
- raw = str(cfg_get(cfg, "agent", "restart_drain_timeout", default="") or "").strip()
- value = parse_restart_drain_timeout(raw)
- if raw and value == DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT:
- try:
- float(raw)
- except (TypeError, ValueError):
- logger.warning(
- "Invalid restart_drain_timeout '%s', using default %.0fs",
- raw,
- DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,
- )
- return value
-
- @staticmethod
- def _load_background_notifications_mode() -> str:
- """Load background process notification mode from config or env var.
-
- Modes:
- - ``all`` — push running-output updates *and* the final message (default)
- - ``result`` — only the final completion message (regardless of exit code)
- - ``error`` — only the final message when exit code is non-zero
- - ``off`` — no watcher messages at all
- """
- mode = os.getenv("HERMES_BACKGROUND_NOTIFICATIONS", "")
- if not mode:
- cfg = _load_gateway_runtime_config()
- raw = cfg_get(cfg, "display", "background_process_notifications")
- if raw is False:
- mode = "off"
- elif raw not in {None, ""}:
- mode = str(raw)
- mode = (mode or "all").strip().lower()
- valid = {"all", "result", "error", "off"}
- if mode not in valid:
- logger.warning(
- "Unknown background_process_notifications '%s', defaulting to 'all'",
- mode,
- )
- return "all"
- return mode
-
- @staticmethod
- def _load_provider_routing() -> dict:
- """Load OpenRouter provider routing preferences from config.yaml."""
+ max_restarts = _rlg.DEFAULT_MAX_RESTARTS
+ window_seconds = _rlg.DEFAULT_WINDOW_SECONDS
try:
- # Canonical gateway loader (fail-open): managed overlay + ${VAR}
- # expansion now apply to provider_routing too.
- cfg = _load_gateway_runtime_config()
- return cfg.get("provider_routing", {}) or {}
- except Exception:
+ user_cfg = _load_gateway_config()
+ gw = user_cfg.get("gateway") if isinstance(user_cfg, dict) else None
+ rlg = gw.get("restart_loop_guard") if isinstance(gw, dict) else None
+ if isinstance(rlg, dict):
+ if isinstance(rlg.get("max_restarts"), int):
+ max_restarts = rlg["max_restarts"]
+ if isinstance(rlg.get("window_seconds"), int) and rlg["window_seconds"] > 0:
+ window_seconds = rlg["window_seconds"]
+ except Exception: # noqa: BLE001
pass
- return {}
+ return max_restarts, window_seconds
- @staticmethod
- def _load_fallback_model() -> list | None:
- """Load fallback provider chain from config.yaml.
+ def _scale_to_zero_should_arm(self) -> bool:
+ """Whether to start the idle watcher (D1/D11/§3.4(1))."""
+ from gateway.relay import relay_wake_url
+ from gateway.scale_to_zero import (
+ messaging_is_relay_only_or_absent,
+ scale_to_zero_enabled,
+ should_arm,
+ )
- Returns the merged effective chain from ``fallback_providers`` plus any
- legacy ``fallback_model`` entries. ``fallback_providers`` stays first
- when both keys are present.
- """
try:
- # Canonical gateway loader (fail-open): managed overlay + ${VAR}
- # expansion now apply to the fallback chain too.
- cfg = _load_gateway_runtime_config()
- fb = get_fallback_chain(cfg)
- if fb:
- return fb
- except Exception:
- pass
- return None
-
- def _refresh_fallback_model(self) -> list | None:
- """Re-read fallback_providers from disk for the next agent create/reuse.
+ # Only ENABLED platforms count. `config.platforms` is pre-seeded with a
+ # disabled placeholder PlatformConfig for every KNOWN platform (telegram,
+ # discord, slack, …), so `.keys()` is the full ~20-entry catalog regardless
+ # of what this instance actually runs. Passing the bare keys made
+ # `messaging_is_relay_only_or_absent` see those placeholders as live
+ # direct-socket platforms and return False, so scale-to-zero NEVER armed on
+ # a real relay-only instance. Mirror the connect loop, which already gates on
+ # `platform_config.enabled` (see the `if not platform_config.enabled: continue`
+ # in the adapter-connect loop) — arm off the same notion of "active platform."
+ platforms = (
+ [p for p, pc in self.config.platforms.items() if getattr(pc, "enabled", False)]
+ if self.config
+ else []
+ )
+ except Exception: # noqa: BLE001
+ platforms = []
+ try:
+ wake_url = relay_wake_url()
+ except Exception: # noqa: BLE001
+ wake_url = None
+ return should_arm(
+ enabled=scale_to_zero_enabled(),
+ relay_only_or_absent=messaging_is_relay_only_or_absent(platforms),
+ wake_url=wake_url,
+ )
- Cron already does this per job via ``get_fallback_chain``; the gateway
- previously froze ``self._fallback_model`` at process start, so a chain
- configured (or changed) after ``hermes gateway`` was running never
- reached messaging sessions even though the same process's cron jobs
- fell back correctly. Fixes #60955.
+ def _log_scale_to_zero_not_armed_reason(self) -> None:
+ """Log why the idle watcher did NOT arm — but only for an OPTED-IN instance.
- A TRANSIENT read/parse failure (user mid-edit of config.yaml with a
- non-atomic write) keeps the last known-good chain instead of wiping a
- cached agent's working fallback for that turn. Only a successful read
- that genuinely lacks the key clears the chain.
+ A non-opted instance (no HERMES_SCALE_TO_ZERO stamp) not arming is the normal
+ case and must stay silent. When the Labs stamp IS set but the watcher still
+ didn't arm, that's the surprising case worth one INFO line so "why won't it
+ suspend/wake?" is a log grep, not a box-dive.
"""
+ from gateway.relay import relay_wake_url
+ from gateway.scale_to_zero import (
+ messaging_is_relay_only_or_absent,
+ scale_to_zero_enabled,
+ )
+
try:
- from hermes_cli.config import read_user_config_raw
- cfg_path = _hermes_home / "config.yaml"
- if not cfg_path.exists():
- self._fallback_model = None
- return self._fallback_model
- # Raw primitive (raises on parse failure) is required here: the
- # canonical fail-open loader would return {} on a torn mid-edit
- # write and WIPE the last known-good chain. The overlay/expansion
- # below fixes the managed-scope/${VAR} drift without losing that.
- cfg = read_user_config_raw(cfg_path)
+ enabled = scale_to_zero_enabled()
+ if not enabled:
+ return # not opted in — normal, stay quiet
try:
- from hermes_cli import managed_scope
- cfg = managed_scope.apply_managed_overlay(cfg)
- except Exception:
- pass
+ active = (
+ [
+ getattr(p, "value", p)
+ for p, pc in self.config.platforms.items()
+ if getattr(pc, "enabled", False)
+ ]
+ if self.config
+ else []
+ )
+ except Exception: # noqa: BLE001
+ active = []
+ relay_only = messaging_is_relay_only_or_absent(active)
try:
- from hermes_cli.config import _expand_env_vars
- expanded = _expand_env_vars(cfg)
- if isinstance(expanded, dict):
- cfg = expanded
- except Exception:
- pass
- except Exception:
- # Transient failure — keep last known-good chain.
- logger.debug(
- "fallback_providers refresh: config.yaml read failed; "
- "keeping last known-good chain", exc_info=True,
+ wake_url = relay_wake_url()
+ except Exception: # noqa: BLE001
+ wake_url = None
+ logger.info(
+ "scale-to-zero: NOT armed despite opt-in — "
+ "relay_only_or_absent=%s (enabled platforms=%s), wake_url=%s. "
+ "Need relay-only messaging + a registered wake URL.",
+ relay_only,
+ active or "none",
+ "set" if wake_url else "MISSING",
)
- return self._fallback_model
- self._fallback_model = get_fallback_chain(cfg) or None
- return self._fallback_model
-
- @staticmethod
- def _apply_fallback_chain_to_agent(agent: Any, chain: list | None) -> None:
- """Keep a cached agent's fallback chain aligned with current config.
+ except Exception: # noqa: BLE001 - diagnostics must never block startup
+ logger.debug("scale-to-zero: not-armed reason logging failed", exc_info=True)
- Skips rewrite while a cooldown is holding the agent on an already-
- activated fallback provider — ``restore_primary_runtime`` owns that
- turn-scoped lifecycle. When primary is active (or cooldown expired),
- replace the chain so mid-uptime ``fallback_providers`` edits take
- effect without requiring a gateway restart (#60955).
- """
- if agent is None:
- return
- new_chain = list(chain or [])
- rate_limited_until = getattr(agent, "_rate_limited_until", 0) or 0
- if (
- getattr(agent, "_fallback_activated", False)
- and rate_limited_until > time.monotonic()
- ):
- return
- old_chain = list(getattr(agent, "_fallback_chain", []) or [])
- agent._fallback_chain = new_chain
- agent._fallback_model = new_chain[0] if new_chain else None
- if not getattr(agent, "_fallback_activated", False):
- agent._fallback_index = 0
- # A config edit signals the user changed something — drop the
- # session-scoped unavailability memo so re-configured entries
- # (e.g. credentials added mid-uptime for a previously-failing
- # provider) get retried instead of staying suppressed for the
- # cached agent's lifetime. Only on actual content change, so
- # the per-message no-op refresh keeps the memo's rate-limiting
- # benefit (#60955).
- if new_chain != old_chain:
- unavailable = getattr(agent, "_unavailable_fallback_keys", None)
- if unavailable:
- unavailable.clear()
+ def _scale_to_zero_is_idle(self) -> bool:
+ from gateway.scale_to_zero import is_idle
- def _snapshot_running_agents(self) -> Dict[str, Any]:
- return {
- session_key: agent
- for session_key, agent in self._running_agent_items()
- if agent is not _AGENT_PENDING_SENTINEL
- }
+ return is_idle(
+ running_agent_count=self._running_agent_count(),
+ seconds_since_last_inbound=time.time() - self._last_inbound_at,
+ idle_timeout_seconds=self._scale_to_zero_idle_timeout_seconds(),
+ has_live_background_work=self._scale_to_zero_has_live_background_work(),
+ )
- def _get_max_concurrent_sessions(self) -> Optional[int]:
- """Return the configured active chat session cap, if enabled."""
- try:
- from hermes_cli.active_sessions import resolve_max_concurrent_sessions
+ def _scale_to_zero_note_real_inbound(self) -> None:
+ """Stamp real inbound and restore lifecycle after a dormant wake.
- return resolve_max_concurrent_sessions(getattr(self, "config", None))
- except Exception:
- return None
+ The watcher marks runtime status `draining` as it quiesces the relay, but
+ dormancy is not the stop/restart drain path: the process remains alive and
+ should present as running once real traffic wakes it and re-enters the
+ gateway. Internal completion/replay events intentionally do not call this
+ helper, so they do not keep an otherwise idle gateway awake.
+ """
+ self._last_inbound_at = time.time()
+ if getattr(self, "_scale_to_zero_cooldown_until", 0.0) > 0:
+ try:
+ self._update_runtime_status("running")
+ except Exception: # noqa: BLE001 - status restoration is best-effort
+ logger.debug("scale-to-zero: status restore failed", exc_info=True)
+ self._scale_to_zero_cooldown_until = 0.0
- def _active_session_limit_message(self, session_key: str) -> Optional[str]:
- """Return a user-facing rejection when starting a new session exceeds the cap."""
- max_sessions = self._get_max_concurrent_sessions()
- if max_sessions is None:
- return None
- if self._is_session_running(session_key):
- return None
- active_count = self._running_agent_count()
- if active_count < max_sessions:
+ def _relay_adapter_for_dormancy(self):
+ """Return the connected RELAY adapter, if any (the one go_dormant targets)."""
+ try:
+ from gateway.platforms.base import Platform
+ except Exception: # noqa: BLE001
return None
- from hermes_cli.active_sessions import active_session_limit_message
+ return self.adapters.get(Platform.RELAY)
- return active_session_limit_message(active_count, max_sessions)
+ async def _scale_to_zero_watcher(self, interval: float = 30.0) -> None:
+ """Watch for idle and drive the relay dormant so the platform can suspend.
- def _claim_active_session_slot(
+ Started ONLY when _scale_to_zero_should_arm() (opted in via the Labs
+ HERMES_SCALE_TO_ZERO stamp + relay-only/absent messaging + a wakeUrl).
+ On a sustained idle window it runs the DORMANT sequence (D12/F12/F14):
+ - mark runtime status `draining` (composes with the existing state
+ machine, §3.4(6); does NOT set _running=False),
+ - relay adapter.go_dormant() — going_idle->ack + supervisor-preserving
+ socket close (NOT disconnect(), NOT the run.py stop path),
+ - deliberately NO mark_resume_pending (D13 — suspend preserves RAM).
+ The process stays alive; the platform (Fly autostop:"suspend") suspends
+ the now-traffic-idle machine and autostart wakes it on the wakeUrl poke,
+ at which point the preserved reconnect supervisor re-dials and the
+ connector drains the buffered backlog. After driving dormant we set a
+ re-arm cooldown so a wake's drained backlog isn't immediately re-quiesced.
+ """
+ await asyncio.sleep(min(interval, 30.0)) # let startup settle
+ while self._running:
+ try:
+ await asyncio.sleep(interval)
+ if not self._running:
+ return
+ if time.time() < self._scale_to_zero_cooldown_until:
+ continue
+ if not self._scale_to_zero_is_idle():
+ continue
+ adapter = self._relay_adapter_for_dormancy()
+ if adapter is None:
+ continue
+ go_dormant = getattr(adapter, "go_dormant", None)
+ if not callable(go_dormant):
+ continue
+ logger.info(
+ "scale-to-zero: gateway idle for >= %.0fs — going dormant "
+ "(relay buffered, socket closed, awaiting platform suspend)",
+ self._scale_to_zero_idle_timeout_seconds(),
+ )
+ try:
+ self._update_runtime_status("draining")
+ except Exception: # noqa: BLE001 - status is best-effort
+ logger.debug("scale-to-zero: status mark failed", exc_info=True)
+ try:
+ result = go_dormant()
+ if asyncio.iscoroutine(result):
+ await result
+ except Exception: # noqa: BLE001 - dormancy is best-effort
+ logger.debug("scale-to-zero: go_dormant failed", exc_info=True)
+ # 0.F: after a wake the drained inbound updates _last_inbound_at,
+ # but give it a window so we don't immediately re-go-dormant on the
+ # same idle reading before traffic lands.
+ self._scale_to_zero_cooldown_until = time.time() + max(interval, 60.0)
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 - the watcher must never crash the gateway
+ logger.debug("scale-to-zero watcher iteration error", exc_info=True)
+
+ def _status_action_label(self) -> str:
+ return "restart" if self._restart_requested else "shutdown"
+
+ def _status_action_gerund(self) -> str:
+ return "restarting" if self._restart_requested else "shutting down"
+
+ def _queue_during_drain_enabled(self) -> bool:
+ # Both "queue" and "steer" modes imply the user doesn't want messages
+ # to be lost during restart — queue them for the newly-spawned gateway
+ # process to pick up. "interrupt" mode drops them (current behaviour).
+ return self._restart_requested and self._busy_input_mode in {"queue", "steer"}
+
+ # -------- /queue FIFO helpers --------------------------------------
+ # /queue must produce one full agent turn per invocation, in FIFO
+ # order, with no merging. The adapter's _pending_messages dict is a
+ # single "next-up" slot (shared with photo-burst follow-ups), so we
+ # use it for the head of the queue and an overflow list for the
+ # tail. Enqueue puts new items in the slot when free, otherwise in
+ # the overflow. Promotion (called after each run's drain) moves the
+ # next overflow item into the slot so the following recursion picks
+ # it up. Clearing happens on /new and /reset via
+ # _handle_reset_command.
+
+ def _enqueue_fifo(self, session_key: str, queued_event: "MessageEvent", adapter: Any) -> None:
+ """Append a /queue event to the FIFO chain for a session."""
+ if adapter is None:
+ return
+ pending_slot = getattr(adapter, "_pending_messages", None)
+ if pending_slot is None:
+ return
+ if session_key in pending_slot:
+ self._session_state(session_key).conversation.queued_events.append(
+ queued_event
+ )
+ else:
+ pending_slot[session_key] = queued_event
+
+ def _promote_queued_event(
self,
session_key: str,
- source: SessionSource,
- ) -> tuple[Any, Optional[str]]:
- """Claim a cross-process active-session slot for a new gateway turn."""
- if self._is_session_running(session_key):
- return None, None
- local_limit_message = self._active_session_limit_message(session_key)
- if local_limit_message is not None:
- return None, local_limit_message
- try:
- from hermes_cli.active_sessions import try_acquire_active_session
+ adapter: Any,
+ pending_event: Optional["MessageEvent"],
+ ) -> Optional["MessageEvent"]:
+ """Promote the next overflow item after the slot was drained.
- platform = source.platform.value if source and source.platform else "gateway"
- return try_acquire_active_session(
- session_id=session_key,
- surface=f"gateway:{platform}",
- config=getattr(self, "config", None),
- metadata={
- "platform": platform,
- "chat_id": getattr(source, "chat_id", "") or "",
- "user_id": getattr(source, "user_id", "") or "",
- },
- )
- except Exception as exc:
- logger.warning("Failed to claim active session slot: %s", exc)
- return None, None
+ Called at the drain site after _dequeue_pending_event consumed
+ (or failed to consume) the slot. If there's an overflow item:
+ - When pending_event is None (slot was empty), return the
+ overflow head as the new pending_event.
+ - When pending_event already exists (slot was populated by an
+ interrupt follow-up or similar), stage the overflow head in
+ the slot so the NEXT recursion picks it up.
+ Returns the (possibly updated) pending_event for drain to use.
+ """
+ _q_state = self._peek_session_state(session_key)
+ overflow = _q_state.conversation.queued_events if _q_state else None
+ if not overflow:
+ return pending_event
+ next_queued = overflow.pop(0)
+ if pending_event is None:
+ return next_queued
+ if adapter is not None and hasattr(adapter, "_pending_messages"):
+ adapter._pending_messages[session_key] = next_queued
+ else:
+ # No adapter — push back so we don't silently drop the item.
+ overflow.insert(0, next_queued)
+ return pending_event
+
+ def _queue_depth(self, session_key: str, *, adapter: Any = None) -> int:
+ """Total pending /queue items for a session — slot + overflow."""
+ _q_state = self._peek_session_state(session_key)
+ depth = len(_q_state.conversation.queued_events) if _q_state else 0
+ if adapter is not None and session_key in getattr(adapter, "_pending_messages", {}):
+ depth += 1
+ return depth
@staticmethod
- def _agent_has_active_subagents(running_agent: Any) -> bool:
- """Return True when *running_agent* is currently driving subagents
- via the ``delegate_task`` tool.
+ def _is_goal_continuation_event(event_or_text: Any) -> bool:
+ """Return True for synthetic /goal continuation turns.
- Background (#30170): ``AIAgent.interrupt()`` cascades through the
- parent's ``_active_children`` list and calls ``interrupt()`` on
- every child synchronously, which aborts in-flight subagent work
- and produces a fallback cascade with no actionable signal.
- Demoting ``busy_input_mode='interrupt'`` to ``queue`` semantics
- whenever this helper returns True protects subagent work from
- conversational follow-ups while leaving the explicit ``/stop``
- path (which goes through ``_interrupt_and_clear_session``)
- untouched. Safe-by-default: returns False on any attribute or
- lock error so a missing/broken parent never blocks the existing
- interrupt path.
+ Goal continuations are normal queued user-role events, so pause/clear
+ must distinguish them from real user /queue messages before removing or
+ suppressing them.
"""
- if running_agent is None or running_agent is _AGENT_PENDING_SENTINEL:
- return False
- children = getattr(running_agent, "_active_children", None)
- # AIAgent always initialises this as a concrete list (see
- # agent/agent_init.py). Reject anything that isn't a real
- # collection — this guards against ``MagicMock()._active_children``
- # auto-creating a truthy stub in tests and triggering the demotion
- # against an agent that doesn't actually have subagents.
- if not isinstance(children, (list, tuple, set)):
- return False
- if not children:
- return False
- lock = getattr(running_agent, "_active_children_lock", None)
- try:
- if lock is not None:
- with lock:
- return bool(children)
- return bool(children)
- except Exception:
- return False
-
- async def _session_has_compression_in_flight(self, session_key: str) -> bool:
- """Return True when a compression lock is held for this session's id.
+ text = getattr(event_or_text, "text", event_or_text) or ""
+ return str(text).startswith("[Continuing toward your standing goal]\nGoal:")
- Context compression is interrupt-protected (#23975) but gateway
- ``interrupt`` busy-input mode can still start a follow-up turn against
- the pre-rotation parent while compression is mid-flight, producing
- orphaned compression siblings (#56391). Callers demote interrupt to
- queue when this returns True.
+ def _clear_goal_pending_continuations(self, session_key: str, adapter: Any) -> int:
+ """Remove queued synthetic /goal continuations for one session.
- Both blocking sources — the ``session_store`` lock + JSON load, and the
- SQLite ``get_compression_lock_holder`` SELECT — are offloaded to a
- worker thread so a large state.db never freezes the event loop (#5).
+ User-issued /goal pause/clear can race with a continuation already
+ queued by the judge. Remove only synthetic goal continuations while
+ preserving normal /queue and user follow-up events.
"""
- session_store = getattr(self, "session_store", None)
- if not session_key or session_store is None:
+ removed = 0
+ pending_slot = getattr(adapter, "_pending_messages", None) if adapter is not None else None
+ if isinstance(pending_slot, dict):
+ pending_event = pending_slot.get(session_key)
+ if self._is_goal_continuation_event(pending_event):
+ pending_slot.pop(session_key, None)
+ removed += 1
+
+ _q_state = self._peek_session_state(session_key)
+ overflow = _q_state.conversation.queued_events if _q_state else []
+ if overflow:
+ kept = []
+ for queued_event in overflow:
+ if self._is_goal_continuation_event(queued_event):
+ removed += 1
+ else:
+ kept.append(queued_event)
+ _q_state.conversation.queued_events = kept
+ return removed
+
+ def _goal_still_active_for_session(self, session_id: str) -> bool:
+ """Best-effort fresh DB check before running a queued continuation."""
+ if not session_id:
return False
try:
- session_id = await asyncio.to_thread(
- self._lookup_session_id_under_store_lock, session_store, session_key
- )
- except (AttributeError, TypeError):
- return False
- except Exception:
- logger.warning(
- "Compression in-flight check failed while reading session %s; "
- "treating compression as active to avoid interrupting a possible "
- "parent-session rotation",
- session_key,
- exc_info=True,
- )
- return True
- if not session_id:
- return False
- session_db = getattr(self, "_session_db", None)
- if session_db is None:
+ from hermes_cli.goals import GoalManager
+ return GoalManager(session_id=session_id).is_active()
+ except Exception as exc:
+ logger.debug("goal continuation: active-state recheck failed: %s", exc)
return False
- raw_db = getattr(session_db, "_db", session_db)
+
+ def _update_runtime_status(self, gateway_state: Optional[str] = None, exit_reason: Optional[str] = None) -> None:
try:
- holder = await asyncio.to_thread(
- raw_db.get_compression_lock_holder, str(session_id)
+ from gateway.status import write_runtime_status
+ write_runtime_status(
+ gateway_state=gateway_state,
+ exit_reason=exit_reason,
+ restart_requested=self._restart_requested,
+ active_agents=self._active_work_count(),
)
- return bool(holder)
- except (AttributeError, TypeError):
- return False
except Exception:
- logger.warning(
- "Compression in-flight check failed while reading lock holder "
- "for session %s; treating compression as active to avoid "
- "interrupting a possible parent-session rotation",
- session_id,
- exc_info=True,
- )
- return True
+ pass
- @staticmethod
- def _lookup_session_id_under_store_lock(session_store, session_key: str):
- """Sync helper run in the thread pool: read session_id under the store lock."""
- # noqa: SLF001 — intentional private access; runs off the event loop.
- with session_store._lock: # noqa: SLF001
- session_store._ensure_loaded_locked() # noqa: SLF001
- entry = session_store._entries.get(session_key) # noqa: SLF001
- return getattr(entry, "session_id", None) if entry is not None else None
+ def _persist_active_agents(self) -> None:
+ """Persist the live in-flight agent count to ``gateway_state.json``.
- # Hard cap on per-session pending follow-ups for busy_input_mode=queue
- # (and the draining/steer-fallback/subagent-demotion paths that share
- # this entry point). Without a cap, a stuck agent + a rapid-fire user
- # could grow the overflow list unboundedly. 32 turns of queued
- # follow-ups is far beyond any realistic conversational backlog while
- # still small enough to never threaten memory.
- _BUSY_QUEUE_MAX_PENDING = 32
+ Called at every turn boundary (a running-agent slot is claimed or
+ released) so the dashboard ``/api/status`` readout reflects in-flight
+ gateway turns in near-real-time. Without this the file is only
+ rewritten on lifecycle transitions, so any ``active_agents`` read
+ between transitions is stale (a turn could start and finish without the
+ file ever moving).
- def _queue_or_replace_pending_event(self, session_key: str, event: MessageEvent) -> None:
- adapter = self._adapter_for_source(event.source)
- if not adapter:
- return
- # #28503 — Previously this called ``merge_pending_message_event``
- # with the default ``merge_text=False``, which silently OVERWROTE
- # the single pending slot when consecutive text messages arrived
- # in ``busy_input_mode: queue``. Route through the FIFO
- # infrastructure shared with ``/queue`` so each follow-up gets
- # its own turn in arrival order. Photo bursts still merge into
- # the head slot via ``merge_pending_message_event`` (album
- # semantics); everything else appends to the overflow tail.
- pending_slot = getattr(adapter, "_pending_messages", None)
- existing = pending_slot.get(session_key) if isinstance(pending_slot, dict) else None
- if existing is not None and (
- getattr(existing, "message_type", None) == MessageType.PHOTO
- or event.message_type == MessageType.PHOTO
- or bool(getattr(existing, "media_urls", None))
- or bool(getattr(event, "media_urls", None))
- ):
- # Preserve photo-burst / media-merge semantics for the head slot.
- merge_pending_message_event(
- adapter._pending_messages,
- session_key,
- event,
- merge_text=event.message_type == MessageType.TEXT,
- )
- return
+ Deliberately passes ONLY ``active_agents`` — ``gateway_state`` and the
+ other fields stay ``_UNSET`` so ``write_runtime_status``'s
+ read-merge-write preserves the current lifecycle state (``running`` /
+ ``draining`` / …). Passing ``gateway_state=None`` here would clobber it.
+ Best-effort: a failed status write must never disrupt a turn.
+ """
+ try:
+ from gateway.status import write_runtime_status
+ write_runtime_status(active_agents=self._active_work_count())
+ except Exception:
+ pass
- if self._queue_depth(session_key, adapter=adapter) >= self._BUSY_QUEUE_MAX_PENDING:
- logger.warning(
- "Dropping busy-mode follow-up for session %s — pending queue at cap (%d).",
- session_key,
- self._BUSY_QUEUE_MAX_PENDING,
- )
- return
+ # ------------------------------------------------------------------
+ # External drain control (NAS-driven quiesce-without-restart, Phase 2).
+ # The dashboard's begin/cancel-drain endpoint writes/removes the
+ # ``.drain_request.json`` marker (gateway/drain_control.py); this watcher
+ # observes the marker and flips the gateway between accepting and refusing
+ # NEW turns, WITHOUT exiting the process. Reversible by design (D4a): NAS
+ # POSTs begin-drain, polls /api/status until active_agents hits 0, proceeds
+ # with its lifecycle action, then (on cancel/abort) the marker is removed
+ # and the gateway re-accepts turns.
+ # ------------------------------------------------------------------
+ def _enter_external_drain(self) -> None:
+ """Begin external drain: stop accepting new turns, flip state.
- self._enqueue_fifo(session_key, event, adapter)
+ Idempotent — re-entering while already draining is a no-op beyond a
+ best-effort status re-write. In-flight turns are NOT interrupted (the
+ whole point is to let them finish); only NEW turns are refused.
+ """
+ if self._external_drain_active:
+ return
+ self._external_drain_active = True
+ logger.info(
+ "External drain ENGAGED (.drain_request.json present) — refusing "
+ "new turns; %d in-flight turn(s) will finish. Process stays up.",
+ self._active_work_count(),
+ )
+ # Flip the persisted lifecycle state so /api/status.gateway_busy /
+ # gateway_drainable track the drain. Preserve active_agents (the
+ # read-merge keeps the live count); only the state changes.
+ self._update_runtime_status("draining")
- async def _prepare_busy_steer_text(self, event: MessageEvent) -> str:
- """Return steerable text for a busy follow-up, transcribing voice first.
+ def _exit_external_drain(self) -> None:
+ """Cancel external drain: revert state, re-accept new turns.
- Fresh and queued voice messages reach the normal inbound STT pipeline,
- but successful steer messages intentionally bypass that queue. Without
- preprocessing here, a media-only voice follow-up has an empty text
- payload and steer mode silently degrades to queue mode.
+ Idempotent. Only reverts to ``running`` when we are actually mid-drain
+ AND not also shutting down (a real shutdown ``_draining`` must win —
+ never resurrect a stopping gateway to ``running``).
+ """
+ if not self._external_drain_active:
+ return
+ self._external_drain_active = False
+ if self._draining or not self._running:
+ # A shutdown drain is in progress / the loop has stopped — do not
+ # clobber the terminal state back to running.
+ logger.info(
+ "External drain marker cleared during shutdown — not reverting "
+ "to running (shutdown takes precedence)."
+ )
+ return
+ logger.info(
+ "External drain RELEASED (.drain_request.json removed) — "
+ "re-accepting new turns; gateway_state -> running."
+ )
+ self._update_runtime_status("running")
- Audio file attachments remain files; only voice-message media follows
- the automatic STT contract used by ``_prepare_inbound_message_text``.
- If transcription fails, preserve any caption and let the existing
- steer fallback handle an otherwise empty event without losing it.
+ async def _drain_control_watcher(self, interval: float = 1.0) -> None:
+ """Background task: reconcile gateway accept-state with the drain marker.
- Routes through ``_transcribe_and_echo_pending_voice`` — the single
- out-of-band transcription choke point shared with the interrupt
- monitor and the pending-drain path — so the STT call is made at most
- once per platform message (cached on the event) and the transcript
- echo respects the count-based ledger. If steering later falls back
- to queue mode, the drain path reuses the cached transcript instead of
- paying for a second STT call or re-echoing the same line.
+ Polls ``.drain_request.json`` (presence-based contract,
+ gateway/drain_control.py). Marker present -> ``_enter_external_drain``;
+ marker absent -> ``_exit_external_drain``. The 1s cadence bounds the
+ observe-the-marker latency the live-validation gate checks (point a).
+ Reconciles once at startup. A marker stamped with a PRIOR
+ instantiation epoch (one that survived a machine restart on the durable
+ HERMES_HOME volume — NS-570) is treated as absent by ``drain_requested``
+ and is NOT honoured; only a marker from the current instantiation flips
+ the gateway into drain. Best-effort: any tick error is logged and the
+ loop continues (a transient stat() failure must not wedge the gateway).
"""
- text = (event.text or "").strip()
- if not self._pending_event_audio_paths(event):
- return text
+ from gateway.drain_control import drain_requested
- adapter = self._adapter_for_source(event.source)
- enriched_text, successful_transcripts = await self._transcribe_and_echo_pending_voice(
- event,
- adapter,
- event.source,
- text,
- log_context="Busy-steer",
- )
- if not successful_transcripts:
- return text
- return (enriched_text or text).strip()
+ while self._running:
+ try:
+ if drain_requested():
+ self._enter_external_drain()
+ # API and cron work live outside messaging's
+ # _running_agents map. Refresh the aggregate while an
+ # external caller polls this reversible drain state.
+ self._persist_active_agents()
+ else:
+ self._exit_external_drain()
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ logger.debug("Drain-control watcher tick error: %s", exc, exc_info=True)
+ await asyncio.sleep(interval)
- async def _handle_active_session_busy_message(self, event: MessageEvent, session_key: str) -> bool:
- # --- Authorization gate (#17775) ---
- # The cold path (_handle_message) checks _is_user_authorized before
- # creating a session. The busy path must enforce the same check;
- # otherwise unauthorized users in shared threads (Slack/Telegram/Discord)
- # can inject messages into an active session they don't own.
- if not self._is_user_authorized(event.source):
- logger.warning(
- "Dropping message from unauthorized user in active session: "
- "user=%s (%s), platform=%s, session=%s",
- event.source.user_id,
- event.source.user_name,
- event.source.platform.value if event.source.platform else "unknown",
- session_key,
+ def _update_platform_runtime_status(
+ self,
+ platform: str,
+ *,
+ platform_state: Optional[str] = None,
+ error_code: Optional[str] = None,
+ error_message: Optional[str] = None,
+ ) -> None:
+ try:
+ from gateway.status import write_runtime_status
+ write_runtime_status(
+ platform=platform,
+ platform_state=platform_state,
+ error_code=error_code,
+ error_message=error_message,
)
- return True # handled (silently dropped); do not fall through
+ except Exception:
+ pass
- # --- Draining case (gateway restarting/stopping) ---
- if self._draining:
- adapter = self._adapter_for_source(event.source)
- if not adapter:
- return True
-
- reply_anchor = self._reply_anchor_for_event(event)
- thread_meta = self._thread_metadata_for_source(event.source, reply_anchor)
- if self._queue_during_drain_enabled():
- self._queue_or_replace_pending_event(session_key, event)
- message = f"⏳ Gateway {self._status_action_gerund()} — queued for the next turn after it comes back."
- else:
- message = f"⏳ Gateway is {self._status_action_gerund()} and is not accepting another turn right now."
+ # ------------------------------------------------------------------
+ # Per-platform circuit breaker (pause/resume) — used by the reconnect
+ # watcher when a retryable failure recurs past a threshold, and by the
+ # /platform pause|resume slash command for manual control.
+ # ------------------------------------------------------------------
+ def _pause_failed_platform(self, platform, *, reason: str = "") -> None:
+ """Mark a queued platform as paused — keep it in ``_failed_platforms``
+ but stop the reconnect watcher from hammering it.
- await adapter._send_with_retry(
- chat_id=event.source.chat_id,
- content=message,
- reply_to=(
- reply_anchor
- if event.source.platform == Platform.TELEGRAM
- and event.source.chat_type == "dm"
- and event.source.thread_id
- else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id)
- ),
- metadata=thread_meta,
+ Used by ``/platform pause <name>`` for manual operator intervention.
+ Paused platforms are surfaced in ``/platform list`` and resumed with
+ ``/platform resume <name>``. Note: the reconnect watcher does NOT
+ auto-pause — retryable (network/DNS) failures keep retrying at the
+ backoff cap indefinitely so a transient outage self-heals without
+ manual intervention.
+ """
+ info = getattr(self, "_failed_platforms", {}).get(platform)
+ if info is None:
+ return
+ if info.get("paused"):
+ return
+ info["paused"] = True
+ info["pause_reason"] = reason or "auto-paused after repeated failures"
+ # Push next_retry far enough out that even if "paused" is missed
+ # by a stale code path, the watcher won't fire on it.
+ info["next_retry"] = float("inf")
+ try:
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="paused",
+ error_code=None,
+ error_message=info["pause_reason"],
)
- return True
+ except Exception:
+ pass
+ logger.warning(
+ "%s paused after %d consecutive failures (%s) — "
+ "fix the underlying issue then run `/platform resume %s` "
+ "to retry, or `hermes gateway restart` to restart the gateway.",
+ platform.value, info.get("attempts", 0),
+ info["pause_reason"], platform.value,
+ )
- # --- Approval response routing (#46866) ---
- # When the agent is blocked waiting for a dangerous-command approval,
- # plain-text responses like "yes" or "approve" must be routed to the
- # approval handler instead of being steered/queued/interrupted.
- # Otherwise approval via messaging platforms never succeeds — the
- # reply is queued behind a turn that can't start until the approval
- # resolves, so the approval times out and auto-denies (a deadlock).
- #
- # Slash forms (/approve, /deny) already bypass to the runner at the
- # base-adapter guard. This handles the bare-word forms (Signal/SMS
- # users naturally type "yes" rather than "/approve"). Gating on
- # has_blocking_approval(session_key) is the disambiguator that keeps
- # a conversational "yes" from triggering a dangerous command when no
- # approval is actually pending (design intent — see run.py "Pending
- # exec approvals are handled by /approve and /deny" note).
- #
- # We reuse the canonical /approve and /deny handlers rather than
- # re-deriving the resolution + i18n messaging: they resolve the
- # waiting thread, resume typing, AND return a localized confirmation
- # string. The busy-handler path does not auto-send that return, so
- # we deliver it ourselves (mirroring the draining-case send above).
+ def _resume_paused_platform(self, platform) -> bool:
+ """Unpause a platform — reset its attempt counter and schedule an
+ immediate retry. Returns True if the platform was paused and is
+ now queued; False if it wasn't paused (or wasn't in the queue).
+ """
+ info = getattr(self, "_failed_platforms", {}).get(platform)
+ if info is None:
+ return False
+ if not info.get("paused"):
+ return False
+ info["paused"] = False
+ info.pop("pause_reason", None)
+ info["attempts"] = 0
+ info["next_retry"] = time.monotonic() # retry on next watcher tick
try:
- from tools.approval import has_blocking_approval
- if has_blocking_approval(session_key):
- _raw_text = (event.text or "").strip().lower()
- _approve_words = {"approve", "yes", "ok", "okay", "confirm", "y", "👍"}
- _deny_words = {"deny", "no", "reject", "cancel", "n", "👎"}
- _approval_handler = None
- _normalized_args = ""
- if _raw_text in _approve_words:
- _approval_handler = self._handle_approve_command
- elif _raw_text in _deny_words:
- _approval_handler = self._handle_deny_command
- elif _raw_text in {"always", "approve always", "always approve"}:
- _approval_handler = self._handle_approve_command
- _normalized_args = "always"
- elif _raw_text in {"session", "approve session", "session approve"}:
- _approval_handler = self._handle_approve_command
- _normalized_args = "session"
- if _approval_handler is not None:
- # Synthesize the canonical "/approve [args]" / "/deny"
- # command text so the slash handlers parse modifiers via
- # event.get_command_args(). Always use a literal "/" —
- # MessageEvent.is_command()/get_command_args() only
- # recognize the "/" prefix, not the per-platform display
- # prefix ("!" on Slack/Matrix).
- _verb = "approve" if _approval_handler is self._handle_approve_command else "deny"
- _synth = f"/{_verb}"
- if _normalized_args:
- _synth = f"{_synth} {_normalized_args}"
- event.text = _synth
- _reply = await _approval_handler(event)
- logger.info(
- "Approval response via plain text: session=%s verb=%s args=%r",
- session_key, _verb, _normalized_args,
- )
- _adapter = self._adapter_for_source(event.source)
- if _adapter and _reply:
- _text, _eph_ttl = _adapter._unwrap_ephemeral(_reply)
- if _text:
- _anchor = self._reply_anchor_for_event(event)
- await _adapter._send_with_retry(
- chat_id=event.source.chat_id,
- content=_text,
- reply_to=_anchor,
- metadata=self._thread_metadata_for_source(event.source, _anchor),
- )
- return True
- except Exception:
- logger.warning(
- "Plain-text approval routing failed for session %s; "
- "falling through to busy handling",
- session_key, exc_info=True,
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="retrying",
+ error_code=None,
+ error_message=None,
)
+ except Exception:
+ pass
+ logger.info("%s resumed — retrying on next watcher tick", platform.value)
+ return True
- # Normal busy case (agent actively running a task)
- adapter = self._adapter_for_source(event.source)
- if not adapter:
- return False # let default path handle it
+ @staticmethod
+ def _load_prefill_messages() -> List[Dict[str, Any]]:
+ """Load ephemeral prefill messages from config or env var.
+
+ Checks HERMES_PREFILL_MESSAGES_FILE env var first, then falls back to
+ the top-level prefill_messages_file key in ~/.hermes/config.yaml.
+ agent.prefill_messages_file is accepted as a legacy fallback.
+ Relative paths are resolved from ~/.hermes/.
+ """
+ file_path = os.getenv("HERMES_PREFILL_MESSAGES_FILE", "")
+ if not file_path:
+ cfg = _load_gateway_runtime_config()
+ file_path = str(cfg.get("prefill_messages_file", "") or "")
+ if not file_path:
+ file_path = str(cfg_get(cfg, "agent", "prefill_messages_file", default="") or "")
+ if not file_path:
+ return []
+ path = Path(file_path).expanduser()
+ if not path.is_absolute():
+ path = _hermes_home / path
+ if not path.exists():
+ logger.warning("Prefill messages file not found: %s", path)
+ return []
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ if not isinstance(data, list):
+ logger.warning("Prefill messages file must contain a JSON array: %s", path)
+ return []
+ return data
+ except Exception as e:
+ logger.warning("Failed to load prefill messages from %s: %s", path, e)
+ return []
- # --- Internal synthetic events must never interrupt/steer ---
- # Async-delegation completions (delegate_task(background=true)) and
- # background-process completions (terminal notify_on_complete) re-enter
- # the originating session as internal MessageEvents. When the session
- # is busy, treating them like a user TEXT message means interrupt-mode
- # (the default busy_text_mode) aborts the active turn AND sends a "⚡
- # Interrupting current task" ack — exactly the opposite of the design
- # invariant that a completion surfaces as a NEW turn only when idle and
- # never splices into a running turn. Fall through to the base adapter,
- # which queues internal events silently (no interrupt, no ack) so they
- # cascade after the current turn finishes.
- if getattr(event, "internal", False):
- return False
+ @staticmethod
+ def _load_ephemeral_system_prompt() -> str:
+ """Load ephemeral system prompt from config or env var.
+
+ Checks HERMES_EPHEMERAL_SYSTEM_PROMPT env var first, then falls back to
+ agent.system_prompt in ~/.hermes/config.yaml.
+ """
+ prompt = os.getenv("HERMES_EPHEMERAL_SYSTEM_PROMPT", "")
+ if prompt:
+ return prompt
+ cfg = _load_gateway_runtime_config()
+ return str(cfg_get(cfg, "agent", "system_prompt", default="") or "").strip()
- _busy_state = self._peek_session_state(session_key)
- running_agent = _busy_state.turn.agent if _busy_state else None
+ def _resolve_model_for_channel(
+ self,
+ platform: Platform,
+ chat_id: str,
+ *,
+ user_config: Optional[dict] = None,
+ thread_id: Optional[str] = None,
+ parent_id: Optional[str] = None,
+ ) -> str:
+ """Resolve model for this channel: channel_overrides else global default.
- effective_mode = self._busy_input_mode
- busy_text_mode = getattr(self, "_busy_text_mode", "interrupt")
- if (
- event.message_type == MessageType.TEXT
- and busy_text_mode == "queue"
- and effective_mode != "steer"
- ):
- return False
+ Delegates the precedence rule to
+ :func:`hermes_cli.model_switch.resolve_effective_model` (session
+ override > channel override > global default) — the single owner
+ shared with the API server, so the two surfaces cannot diverge
+ again (see 7dd00bb47d). This call site has no session tier: session
+ /model overrides are applied later by
+ ``_apply_session_model_override`` on the resolved runtime.
+ """
+ from hermes_cli.model_switch import resolve_effective_model
- # Steer mode: inject mid-run via running_agent.steer() instead of
- # queueing + interrupting. If the agent isn't running yet
- # (sentinel) or lacks steer(), or the payload is empty, fall back
- # to queue semantics so nothing is lost.
- # #30170 — Subagent protection. ``AIAgent.interrupt()`` cascades
- # to every entry in the parent's ``_active_children`` list and
- # aborts in-flight ``delegate_task`` work. Demote ``interrupt``
- # to ``queue`` when the parent is currently driving subagents so
- # a conversational follow-up doesn't destroy minutes of subagent
- # work. Explicit ``/stop`` and ``/new`` slash commands go through
- # ``_interrupt_and_clear_session`` and are unaffected — the
- # operator still has a way to force-cancel everything.
- demoted_for_subagents = (
- effective_mode == "interrupt"
- and self._agent_has_active_subagents(running_agent)
- )
- if demoted_for_subagents:
- logger.info(
- "Demoting busy_input_mode 'interrupt' to 'queue' for session %s "
- "because the running agent has active subagents (#30170)",
- session_key,
+ override = None
+ config = getattr(self, "config", None)
+ if config:
+ override = _get_channel_override(
+ config,
+ platform,
+ chat_id,
+ thread_id=thread_id,
+ parent_id=parent_id,
)
- effective_mode = "queue"
- demoted_for_compression = (
- effective_mode == "interrupt"
- and await self._session_has_compression_in_flight(session_key)
+ return resolve_effective_model(
+ None, # session tier applied downstream (_apply_session_model_override)
+ override,
+ _resolve_gateway_model(user_config),
)
- if demoted_for_compression:
- logger.info(
- "Demoting busy_input_mode 'interrupt' to 'queue' for session %s "
- "because context compression is in flight (#56391)",
- session_key,
- )
- effective_mode = "queue"
- steered = False
- redirected = False
- if effective_mode == "steer":
- steer_text = await self._prepare_busy_steer_text(event)
- # A follow-up qualifies for steering when it is plain text, OR
- # when every attachment is STT-eligible voice media whose
- # transcript was just folded into steer_text — otherwise a voice
- # note in steer mode silently degrades to queue mode (#58780).
- _steer_media_urls = getattr(event, "media_urls", None) or []
- _steer_all_voice = bool(_steer_media_urls) and (
- len(self._pending_event_audio_paths(event)) == len(_steer_media_urls)
- )
- can_steer = (
- steer_text
- and (
- (
- event.message_type == MessageType.TEXT
- and not event.media_urls
- and not event.media_types
- )
- or _steer_all_voice
- )
- and running_agent is not None
- and running_agent is not _AGENT_PENDING_SENTINEL
- and hasattr(running_agent, "steer")
+
+ def _get_system_prompt_for_channel(
+ self,
+ platform: Platform,
+ chat_id: str,
+ *,
+ thread_id: Optional[str] = None,
+ parent_id: Optional[str] = None,
+ ) -> str:
+ """Ephemeral system prompt for this channel/thread.
+
+ Uses ``channel_overrides`` when set, else the global gateway prompt.
+ Legacy ``channel_prompts`` are applied separately via ``event.channel_prompt``
+ in ``run_sync`` (adapter ``resolve_channel_prompt``), so they are not
+ duplicated here.
+ """
+ config = getattr(self, "config", None)
+ if config:
+ override = _get_channel_override(
+ config,
+ platform,
+ chat_id,
+ thread_id=thread_id,
+ parent_id=parent_id,
)
- if can_steer:
- try:
- steered = bool(running_agent.steer(steer_text))
- except Exception as exc:
- logger.warning("Gateway steer failed for session %s: %s", session_key, exc)
- steered = False
- if not steered:
- # Fall back to queue (merge into pending messages, no interrupt)
- effective_mode = "queue"
- elif (
- effective_mode == "interrupt"
- and event.message_type == MessageType.TEXT
- and not event.media_urls
- and not event.media_types
- and running_agent is not None
- and running_agent is not _AGENT_PENDING_SENTINEL
- and getattr(running_agent, "_supports_active_turn_redirect", False) is True
- and hasattr(running_agent, "redirect")
- ):
- try:
- redirected = bool(running_agent.redirect((event.text or "").strip()))
- except Exception as exc:
- logger.warning("Gateway redirect failed for session %s: %s", session_key, exc)
- redirected = False
+ if override and override.system_prompt:
+ return (override.system_prompt or "").strip()
+ return getattr(self, "_ephemeral_system_prompt", None) or ""
- # Store the message so it's processed as the next turn after the
- # current run finishes (or is interrupted). Skip this for a
- # successful steer — the text already landed inside the run and
- # must NOT also be replayed as a next-turn user message.
- #
- # Route through _queue_or_replace_pending_event (the same FIFO
- # infrastructure used by busy queue-mode and /queue) rather than a
- # raw merge_pending_message_event(merge_text=True). The raw merge
- # newline-joins consecutive TEXT follow-ups into a SINGLE pending
- # turn, destroying message boundaries — so two separate user
- # messages sent while the agent was busy (interrupt mode, or a
- # steer that fell back to queue) arrived as one mashed-together
- # turn (#43066 sub-bug 2). The FIFO path gives each text its own
- # turn in arrival order while still preserving photo-burst / album
- # merge semantics for media.
- if not steered and not redirected:
- self._queue_or_replace_pending_event(session_key, event)
+ @staticmethod
+ def _load_reasoning_config(model: str = "") -> dict | None:
+ """Load reasoning effort from config.yaml, respecting per-model overrides.
- is_queue_mode = effective_mode == "queue"
- is_steer_mode = effective_mode == "steer"
- is_redirect_mode = effective_mode == "interrupt" and redirected
+ Thin wrapper over the shared chokepoint
+ :func:`hermes_constants.resolve_reasoning_config` (per-model override >
+ global ``agent.reasoning_effort``; YAML boolean False = disabled).
+ Closes #21256.
- # If not in queue/steer mode, interrupt the running agent immediately.
- # This aborts in-flight tool calls and causes the agent loop to exit
- # at the next check point.
- if (
- effective_mode == "interrupt"
- and not redirected
- and running_agent
- and running_agent is not _AGENT_PENDING_SENTINEL
- ):
- try:
- _interrupt_text = event.text
- _media_urls = getattr(event, "media_urls", None) or []
- if self._pending_event_audio_paths(event):
- _interrupt_text, _ = await self._transcribe_and_echo_pending_voice(
- event,
- adapter,
- event.source,
- event.text or "",
- log_context="Voice-busy-interrupt",
- )
- elif not _interrupt_text and _media_urls:
- _interrupt_text = _build_media_placeholder(event)
- running_agent.interrupt(_interrupt_text)
- except Exception:
- pass # don't let interrupt failure block the ack
+ Args:
+ model: The effective model for the calling session. When empty,
+ the config's ``model.default`` is used.
+ """
+ from hermes_constants import resolve_reasoning_config
+ cfg = _load_gateway_runtime_config()
+ return resolve_reasoning_config(cfg, model)
- # Check if busy ack is disabled — skip sending but still process the input.
- # Placed before debounce so we don't stamp a "last ack" timestamp that was
- # never actually delivered.
- busy_ack_enabled = os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() == "true"
- if not busy_ack_enabled:
- logger.debug("Busy ack suppressed for session %s", session_key)
- return True # input still processed, just no ack sent
+ @staticmethod
+ def _parse_reasoning_command_args(raw_args: str) -> tuple[str, bool]:
+ """Parse `/reasoning` args into `(value, persist_global)`.
- # Debounce before consulting config-heavy display settings. Rapid
- # follow-ups should be processed but should not trigger another config
- # read just to discover that no ack will be sent.
- _BUSY_ACK_COOLDOWN = 30
- now = time.time()
- last_ack = _busy_state.turn.busy_ack_ts if _busy_state else 0
- if now - last_ack < _BUSY_ACK_COOLDOWN:
- return True # interrupt sent (if not queue), ack already delivered recently
+ `/reasoning <level>` is session-scoped by default. `--global` may be
+ supplied in any position to persist the change to config.yaml.
+ """
+ import shlex
- from gateway.display_config import resolve_display_setting
- platform_key = _platform_config_key(event.source.platform)
+ text = str(raw_args or "").strip().replace("—", "--")
+ if not text:
+ return "", False
+ try:
+ tokens = shlex.split(text)
+ except ValueError:
+ tokens = text.split()
- # In steer mode the user's text has already been injected into the
- # active run. Some mobile chat setups want that steering to be silent,
- # like STT transcript echo suppression: keep the behavior, drop only
- # the confirmation bubble.
- if is_steer_mode:
- steer_ack_env = os.environ.get("HERMES_GATEWAY_BUSY_STEER_ACK_ENABLED")
- if steer_ack_env is not None:
- steer_ack_enabled = steer_ack_env.strip().lower() in {"1", "true", "yes", "on"}
+ persist_global = False
+ value_tokens = []
+ for token in tokens:
+ if token == "--global":
+ persist_global = True
else:
- steer_ack_enabled = bool(
- resolve_display_setting(
- _load_gateway_config(),
- platform_key,
- "busy_steer_ack_enabled",
- True,
- )
- )
- if not steer_ack_enabled:
- logger.debug("Busy steer ack suppressed for session %s", session_key)
- return True
-
- self._session_state(session_key).turn.busy_ack_ts = now
+ value_tokens.append(token)
+ return " ".join(value_tokens).strip().lower(), persist_global
- # Build a status-rich acknowledgment. Mobile chat defaults keep this
- # terse; detailed iteration/tool state is still available in logs and
- # can be opted in per platform via display.platforms.<platform>.busy_ack_detail.
- status_parts = []
- busy_ack_detail_enabled = bool(
- resolve_display_setting(
- _load_gateway_config(),
- _platform_config_key(event.source.platform),
- "busy_ack_detail",
- True,
- )
- )
+ def _resolve_session_reasoning_config(
+ self,
+ *,
+ source: Optional[SessionSource] = None,
+ session_key: Optional[str] = None,
+ model: str = "",
+ ) -> dict | None:
+ """Resolve reasoning effort for a session, honoring session overrides.
- if busy_ack_detail_enabled and running_agent and running_agent is not _AGENT_PENDING_SENTINEL:
- try:
- summary = running_agent.get_activity_summary()
- iteration = summary.get("api_call_count", 0)
- max_iter = summary.get("max_iterations", 0)
- current_tool = summary.get("current_tool")
- start_ts = _busy_state.turn.started_ts if _busy_state else 0
- if start_ts:
- elapsed_min = int((now - start_ts) / 60)
- if elapsed_min > 0:
- status_parts.append(f"{elapsed_min} min elapsed")
- if max_iter:
- status_parts.append(f"iteration {iteration}/{max_iter}")
- if current_tool:
- status_parts.append(f"running: {current_tool}")
+ Priority: session-scoped ``/reasoning --session`` override >
+ per-model override (``agent.reasoning_overrides``) > global
+ ``agent.reasoning_effort``. ``model`` should be the session's
+ *effective* model (session ``/model`` override included) so
+ per-model overrides track what the session actually runs — when
+ empty, the config's ``model.default`` is used.
+ """
+ resolved_session_key = session_key
+ if not resolved_session_key and source is not None:
+ try:
+ resolved_session_key = self._session_key_for_source(source)
except Exception:
- pass
-
- status_detail = f" ({', '.join(status_parts)})" if status_parts else ""
- if is_steer_mode:
- message = (
- f"⏩ Steered into current run{status_detail}. "
- f"Your message arrives after the next tool call."
- )
- elif is_redirect_mode:
- message = (
- f"↪ Redirected current run{status_detail}. "
- f"I'll adjust using your correction."
- )
- elif is_queue_mode and demoted_for_subagents:
- # #30170 — explain the demotion so the user knows their
- # follow-up didn't accidentally kill the subagent and
- # discovers `/stop` as the explicit escape hatch.
- message = (
- f"⏳ Subagent working{status_detail} — your message is queued for "
- f"when it finishes (use /stop to cancel everything)."
- )
- elif is_queue_mode and demoted_for_compression:
- message = (
- f"⏳ Compressing context{status_detail} — your message is queued for "
- f"when it finishes (use /stop to cancel everything)."
- )
- elif is_queue_mode:
- message = (
- f"⏳ Queued for the next turn{status_detail}. "
- f"I'll respond once the current task finishes."
- )
- else:
- message = (
- f"⚡ Interrupting current task{status_detail}. "
- f"I'll respond to your message shortly."
- )
+ resolved_session_key = None
- # First-touch onboarding: the very first time a user sends a message
- # while the agent is busy, append a one-time hint explaining the
- # queue/interrupt knob. Flag is persisted to config.yaml so it never
- # fires again on this install.
- try:
- from agent.onboarding import (
- BUSY_INPUT_FLAG,
- busy_input_hint_gateway,
- is_seen,
- mark_seen,
- )
- _user_cfg = _load_gateway_config()
- if not is_seen(_user_cfg, BUSY_INPUT_FLAG):
- if is_steer_mode:
- _hint_mode = "steer"
- elif is_queue_mode:
- _hint_mode = "queue"
- elif is_redirect_mode:
- _hint_mode = "redirect"
- else:
- _hint_mode = "interrupt"
- message = (
- f"{message}\n\n"
- f"{busy_input_hint_gateway(_hint_mode)}"
- )
- mark_seen(_hermes_home / "config.yaml", BUSY_INPUT_FLAG)
- except Exception as _onb_err:
- logger.debug("Failed to apply busy-input onboarding hint: %s", _onb_err)
+ if resolved_session_key:
+ _r_state = self._peek_session_state(resolved_session_key)
+ if _r_state is not None and _r_state.conversation.reasoning_override is not None:
+ return _r_state.conversation.reasoning_override
+ return self._load_reasoning_config(model)
- reply_anchor = self._reply_anchor_for_event(event)
- thread_meta = self._thread_metadata_for_source(event.source, reply_anchor)
- try:
- await adapter._send_with_retry(
- chat_id=event.source.chat_id,
- content=message,
- reply_to=(
- reply_anchor
- if event.source.platform == Platform.TELEGRAM
- and event.source.chat_type == "dm"
- and event.source.thread_id
- else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id)
- ),
- metadata=thread_meta,
- )
- except Exception as e:
- logger.debug("Failed to send busy-ack: %s", e)
+ def _set_session_reasoning_override(
+ self,
+ session_key: str,
+ reasoning_config: Optional[dict],
+ ) -> None:
+ """Set or clear the session-scoped reasoning override."""
+ if not session_key:
+ return
+ # Per-session field write — the old lazy ``self._session_reasoning_overrides
+ # = {}`` init replaced the WHOLE dict, racing concurrent sessions'
+ # overrides; a SessionState field reset cannot cross sessions.
+ self._session_state(session_key).conversation.reasoning_override = (
+ None if reasoning_config is None else dict(reasoning_config)
+ )
- return True
+ def _resolve_session_service_tier(
+ self,
+ source=None,
+ session_key: Optional[str] = None,
+ ) -> Optional[str]:
+ """Resolve the effective service tier for a session.
- async def _drain_active_agents(self, timeout: float) -> tuple[Dict[str, Any], bool]:
- snapshot = self._snapshot_running_agents()
- last_active_count = self._running_agent_count()
- last_cron_count = self._active_cron_job_count()
- last_api_count = self._active_api_run_count()
- last_status_at = 0.0
+ A session-scoped /fast override wins over the config default. The
+ override dict stores "priority" or None (explicit normal), so key
+ presence — not value truthiness — decides whether it applies.
+ """
+ resolved_session_key = session_key
+ if not resolved_session_key and source is not None:
+ try:
+ resolved_session_key = self._session_key_for_source(source)
+ except Exception:
+ resolved_session_key = None
- def _maybe_update_status(force: bool = False) -> None:
- nonlocal last_active_count, last_cron_count, last_api_count, last_status_at
- now = asyncio.get_running_loop().time()
- active_count = self._running_agent_count()
- cron_count = self._active_cron_job_count()
- api_count = self._active_api_run_count()
+ if resolved_session_key:
+ _t_state = self._peek_session_state(resolved_session_key)
if (
- force
- or active_count != last_active_count
- or cron_count != last_cron_count
- or api_count != last_api_count
- or (now - last_status_at) >= 1.0
+ _t_state is not None
+ and _t_state.conversation.service_tier_override
+ is not _SERVICE_TIER_UNSET
):
- self._update_runtime_status("draining")
- last_active_count = active_count
- last_cron_count = cron_count
- last_api_count = api_count
- last_status_at = now
-
- # Cron jobs run on the scheduler's own thread pool, outside
- # ``self._running_agents`` — fold their in-flight count into the
- # same wait/timeout this method already applies to chat sessions,
- # or a cron job's tool work gets killed with zero warning the
- # instant it's the only active thing running (#60432).
- # API-server / desk sessions have the same structural gap (#63529).
- if not self._running_agents and last_cron_count == 0 and last_api_count == 0:
- _maybe_update_status(force=True)
- return snapshot, False
+ return _t_state.conversation.service_tier_override
+ return self._load_service_tier()
- _maybe_update_status(force=True)
- if timeout <= 0:
- return snapshot, True
+ def _set_session_service_tier_override(
+ self,
+ session_key: str,
+ service_tier,
+ clear: bool = False,
+ ) -> None:
+ """Set or clear the session-scoped /fast override.
- deadline = asyncio.get_running_loop().time() + timeout
- while (
- (
- len(self._running_agents)
- or self._active_cron_job_count()
- or self._active_api_run_count()
- )
- and asyncio.get_running_loop().time() < deadline
- ):
- _maybe_update_status()
- await asyncio.sleep(0.1)
- timed_out = (
- bool(len(self._running_agents))
- or bool(self._active_cron_job_count())
- or bool(self._active_api_run_count())
+ ``service_tier`` is "priority" or None (explicit normal). Pass
+ ``clear=True`` to remove the override entirely (fall back to config).
+ """
+ if not session_key:
+ return
+ # Presence-sensitive: "priority" or None (explicit normal) both count
+ # as an override; the sentinel means "no override". Old code
+ # wholesale-replaced the dict on lazy init (cross-session race) —
+ # per-session field writes eliminate that class of bug.
+ self._session_state(session_key).conversation.service_tier_override = (
+ _SERVICE_TIER_UNSET if clear else service_tier
)
- _maybe_update_status(force=True)
- return snapshot, timed_out
-
- def _interrupt_running_agents(self, reason: str) -> None:
- for session_key, agent in list(self._running_agents.items()):
- if agent is _AGENT_PENDING_SENTINEL:
- continue
- try:
- agent.interrupt(reason)
- logger.debug("Interrupted running agent for session %s during shutdown", session_key)
- except Exception as e:
- logger.debug("Failed interrupting agent during shutdown: %s", e)
- async def _notify_active_sessions_of_shutdown(self) -> None:
- """Send shutdown/restart notifications to active chats and home channels.
+ @staticmethod
+ def _load_service_tier() -> str | None:
+ """Load Priority Processing setting from config.yaml.
- Called at the very start of stop() — adapters are still connected so
- messages can be delivered. Best-effort: individual send failures are
- logged and swallowed so they never block the shutdown sequence.
+ Reads agent.service_tier from config.yaml. Accepted values mirror the CLI:
+ "fast"/"priority"/"on" => "priority", while "normal"/"off" disables it.
+ Returns None when unset or unsupported.
"""
- active = self._snapshot_running_agents()
- restart_source = self._restart_command_source if self._restart_requested else None
+ cfg = _load_gateway_runtime_config()
+ raw = str(cfg_get(cfg, "agent", "service_tier", default="") or "").strip()
- action = "restarting" if self._restart_requested else "shutting down"
- hint = (
- "Your current task will be interrupted. "
- "Send any message after restart and I'll try to resume where you left off."
- if self._restart_requested
- else "Your current task will be interrupted."
- )
- msg = f"⚠️ Gateway {action} — {hint}"
+ value = raw.lower()
+ if not value or value in {"normal", "default", "standard", "off", "none"}:
+ return None
+ if value in {"fast", "priority", "on"}:
+ return "priority"
+ logger.warning("Unknown service_tier '%s', ignoring", raw)
+ return None
- notified: set[tuple[str, str, Optional[str]]] = set()
- for session_key in active:
- source = None
- try:
- if getattr(self, "session_store", None) is not None:
- await self.async_session_store._ensure_loaded()
- entry = self.session_store._entries.get(session_key)
- source = getattr(entry, "origin", None) if entry else None
- except Exception as e:
- logger.debug(
- "Failed to load session origin for shutdown notification %s: %s",
- session_key,
- e,
- )
+ @staticmethod
+ def _load_show_reasoning() -> bool:
+ """Load show_reasoning toggle from config.yaml display section."""
+ cfg = _load_gateway_runtime_config()
+ return is_truthy_value(
+ cfg_get(cfg, "display", "show_reasoning"),
+ default=False,
+ )
- if source is None:
- source = self._get_cached_session_source(session_key)
+ @staticmethod
+ def _load_busy_input_mode() -> str:
+ """Load gateway drain-time busy-input behavior from config/env."""
+ mode = os.getenv("HERMES_GATEWAY_BUSY_INPUT_MODE", "").strip().lower()
+ if not mode:
+ cfg = _load_gateway_runtime_config()
+ mode = str(cfg_get(cfg, "display", "busy_input_mode", default="") or "").strip().lower()
+ if mode == "queue":
+ return "queue"
+ if mode == "steer":
+ return "steer"
+ return "interrupt"
- if source is not None:
- platform_str = source.platform.value
- chat_id = str(source.chat_id)
- thread_id = source.thread_id
- else:
- # Fall back to parsing the session key when no persisted
- # origin is available (legacy sessions/tests).
- _parsed = _parse_session_key(session_key)
- if not _parsed:
- continue
- platform_str = _parsed["platform"]
- chat_id = _parsed["chat_id"]
- thread_id = _parsed.get("thread_id")
+ @staticmethod
+ def _load_busy_text_mode() -> str:
+ """Resolve normal busy TEXT follow-up behavior.
- # Deduplicate only identical delivery targets. Thread/topic-aware
- # platforms can share a parent chat while still routing to distinct
- # destinations via metadata.
- dedup_key = (platform_str, chat_id, str(thread_id) if thread_id else None)
- if dedup_key in notified:
- continue
+ ``busy_input_mode`` is the single source of truth (default
+ ``interrupt``). The legacy ``busy_text_mode`` knob is honored only
+ when a user explicitly set it, so existing queue setups keep
+ working; new installs follow ``busy_input_mode``. Returns one of
+ ``interrupt`` | ``queue`` (``steer`` is handled upstream by
+ ``busy_input_mode`` and maps to non-queue text handling here).
+ """
+ # Legacy explicit override wins for backward compat.
+ legacy = os.getenv("HERMES_GATEWAY_BUSY_TEXT_MODE", "").strip().lower()
+ if not legacy:
+ cfg = _load_gateway_runtime_config()
+ legacy = str(cfg_get(cfg, "display", "busy_text_mode", default="") or "").strip().lower()
+ if legacy == "interrupt":
+ return "interrupt"
+ if legacy == "queue":
+ return "queue"
+ # No explicit legacy knob → follow busy_input_mode.
+ input_mode = GatewayRunner._load_busy_input_mode()
+ return "queue" if input_mode == "queue" else "interrupt"
+ @staticmethod
+ def _load_restart_drain_timeout() -> float:
+ """Load graceful gateway restart/stop drain timeout in seconds."""
+ raw = os.getenv("HERMES_RESTART_DRAIN_TIMEOUT", "").strip()
+ if not raw:
+ cfg = _load_gateway_runtime_config()
+ raw = str(cfg_get(cfg, "agent", "restart_drain_timeout", default="") or "").strip()
+ value = parse_restart_drain_timeout(raw)
+ if raw and value == DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT:
try:
- platform = Platform(platform_str)
- adapter = self.adapters.get(platform)
- if not adapter:
- continue
-
- platform_cfg = self.config.platforms.get(platform)
- if platform_cfg is not None and not platform_cfg.gateway_restart_notification:
- logger.info(
- "Shutdown notification suppressed for active session: %s has gateway_restart_notification=false",
- platform_str,
- )
- continue
-
- reply_to_message_id = getattr(source, "message_id", None) if source is not None else None
- if reply_to_message_id is None and restart_source is not None:
- try:
- restart_platform = restart_source.platform.value
- restart_chat_id = str(restart_source.chat_id)
- restart_thread_id = str(restart_source.thread_id) if restart_source.thread_id else None
- if (restart_platform, restart_chat_id, restart_thread_id) == dedup_key:
- reply_to_message_id = getattr(restart_source, "message_id", None)
- except Exception:
- pass
-
- metadata = self._thread_metadata_for_target(
- platform,
- chat_id,
- thread_id,
- chat_type=getattr(source, "chat_type", None) if source is not None else None,
- reply_to_message_id=reply_to_message_id,
- adapter=adapter,
+ float(raw)
+ except (TypeError, ValueError):
+ logger.warning(
+ "Invalid restart_drain_timeout '%s', using default %.0fs",
+ raw,
+ DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,
)
+ return value
- result = await adapter.send(chat_id, msg, metadata=metadata)
- if result is not None and getattr(result, "success", True) is False:
- logger.debug(
- "Failed to send shutdown notification to %s:%s: %s",
- platform_str,
- chat_id,
- getattr(result, "error", "send returned success=False"),
- )
- continue
-
- notified.add(dedup_key)
- logger.info(
- "Sent shutdown notification to active chat %s:%s",
- platform_str, chat_id,
- )
- except Exception as e:
- logger.debug(
- "Failed to send shutdown notification to %s:%s: %s",
- platform_str, chat_id, e,
- )
+ @staticmethod
+ def _load_background_notifications_mode() -> str:
+ """Load background process notification mode from config or env var.
- if self._restart_requested and restart_source is not None:
- logger.debug("Skipping home-channel shutdown notifications for in-chat restart")
- return
+ Modes:
+ - ``all`` — push running-output updates *and* the final message (default)
+ - ``result`` — only the final completion message (regardless of exit code)
+ - ``error`` — only the final message when exit code is non-zero
+ - ``off`` — no watcher messages at all
+ """
+ mode = os.getenv("HERMES_BACKGROUND_NOTIFICATIONS", "")
+ if not mode:
+ cfg = _load_gateway_runtime_config()
+ raw = cfg_get(cfg, "display", "background_process_notifications")
+ if raw is False:
+ mode = "off"
+ elif raw not in {None, ""}:
+ mode = str(raw)
+ mode = (mode or "all").strip().lower()
+ valid = {"all", "result", "error", "off"}
+ if mode not in valid:
+ logger.warning(
+ "Unknown background_process_notifications '%s', defaulting to 'all'",
+ mode,
+ )
+ return "all"
+ return mode
- # Suppress ONLY the home-channel broadcast when the drain that is ending
- # in this shutdown asked us to be quiet (e.g. a NAS auto-update image
- # migration — drain-gated, then the machine is recreated). On the
- # always-on Hermes Cloud fleet that broadcast would otherwise fire on
- # every routine auto-update, spamming home channels with operator-
- # flavoured "gateway shutting down" pings the user doesn't care about.
- # The per-active-session interrupt pings above are deliberately NOT
- # gated: on a drained shutdown they're empty by construction, and in the
- # force-interrupt (deadline-exceeded) case they carry the genuinely
- # useful "your task was cut off, message me to resume" hint. The flag is
- # only honoured for a CURRENT-epoch marker (drain_notification_suppressed
- # reuses the NS-570 staleness check), so an orphaned marker can never
- # silence a fresh gateway's legitimate broadcast.
+ @staticmethod
+ def _load_provider_routing() -> dict:
+ """Load OpenRouter provider routing preferences from config.yaml."""
try:
- from gateway.drain_control import drain_notification_suppressed
- if drain_notification_suppressed():
- logger.info(
- "Home-channel shutdown broadcast suppressed by drain marker "
- "(suppress_notification=true)"
- )
- return
- except Exception as e:
- # Never let the suppression check block the shutdown broadcast —
- # fail toward the louder, more-visible behaviour.
- logger.debug("drain_notification_suppressed check failed: %s", e)
+ # Canonical gateway loader (fail-open): managed overlay + ${VAR}
+ # expansion now apply to provider_routing too.
+ cfg = _load_gateway_runtime_config()
+ return cfg.get("provider_routing", {}) or {}
+ except Exception:
+ pass
+ return {}
- # Snapshot adapters up front: adapter.send() can hit a fatal error
- # path that pops the adapter from self.adapters (see _handle_fatal
- # elsewhere), which would otherwise trigger
- # ``RuntimeError: dictionary changed size during iteration`` —
- # observed in a user report during gateway shutdown.
- for platform, adapter in list(self.adapters.items()):
- home = self.config.get_home_channel(platform)
- if not home or not home.chat_id:
- continue
+ @staticmethod
+ def _load_fallback_model() -> list | None:
+ """Load fallback provider chain from config.yaml.
- platform_cfg = self.config.platforms.get(platform)
- if platform_cfg is not None and not platform_cfg.gateway_restart_notification:
- logger.info(
- "Shutdown notification suppressed for home channel: %s has gateway_restart_notification=false",
- platform.value,
- )
- continue
+ Returns the merged effective chain from ``fallback_providers`` plus any
+ legacy ``fallback_model`` entries. ``fallback_providers`` stays first
+ when both keys are present.
+ """
+ try:
+ # Canonical gateway loader (fail-open): managed overlay + ${VAR}
+ # expansion now apply to the fallback chain too.
+ cfg = _load_gateway_runtime_config()
+ fb = get_fallback_chain(cfg)
+ if fb:
+ return fb
+ except Exception:
+ pass
+ return None
- dedup_key = (platform.value, str(home.chat_id), str(home.thread_id) if home.thread_id else None)
- if dedup_key in notified:
- continue
+ def _refresh_fallback_model(self) -> list | None:
+ """Re-read fallback_providers from disk for the next agent create/reuse.
- try:
- metadata = self._thread_metadata_for_target(
- platform,
- home.chat_id,
- home.thread_id,
- adapter=adapter,
- )
- if metadata:
- result = await adapter.send(str(home.chat_id), msg, metadata=metadata)
- else:
- result = await adapter.send(str(home.chat_id), msg)
- if result is not None and getattr(result, "success", True) is False:
- logger.debug(
- "Failed to send shutdown notification to home channel %s:%s: %s",
- platform.value,
- home.chat_id,
- getattr(result, "error", "send returned success=False"),
- )
- continue
-
- notified.add(dedup_key)
- logger.info(
- "Sent shutdown notification to home channel %s:%s",
- platform.value,
- home.chat_id,
- )
- except Exception as e:
- logger.debug(
- "Failed to send shutdown notification to home channel %s:%s: %s",
- platform.value,
- home.chat_id,
- e,
- )
+ Cron already does this per job via ``get_fallback_chain``; the gateway
+ previously froze ``self._fallback_model`` at process start, so a chain
+ configured (or changed) after ``hermes gateway`` was running never
+ reached messaging sessions even though the same process's cron jobs
+ fell back correctly. Fixes #60955.
- async def _finalize_shutdown_agents(self, active_agents: Dict[str, Any]) -> None:
- for agent in active_agents.values():
- # Persist any in-flight transcript to the SQLite session store
- # before teardown (#13121). An agent forcibly interrupted by the
- # drain-timeout escalation may never reach
- # ``turn_finalizer.finalize_turn`` (the only place that flushes the
- # turn to state.db) — e.g. it was blocked in a tool call that did
- # not abort within the post-interrupt grace window. Its in-flight
- # tool rounds live only in the in-memory ``_session_messages``
- # (refreshed per tool round in ``conversation_loop`` but never
- # written to SQLite mid-turn), so the immediate pre-restart turn is
- # silently dropped from ``load_transcript()`` on resume. Flushing
- # here closes that gap; the resume_pending / fresh-tool-tail
- # branches in ``_handle_message_with_agent`` already expect a
- # transcript whose tail may be a pending tool result. The flush is
- # idempotent (identity-tracked in ``_flush_messages_to_session_db``),
- # so agents that DID finish gracefully re-flush nothing.
+ A TRANSIENT read/parse failure (user mid-edit of config.yaml with a
+ non-atomic write) keeps the last known-good chain instead of wiping a
+ cached agent's working fallback for that turn. Only a successful read
+ that genuinely lacks the key clears the chain.
+ """
+ try:
+ from hermes_cli.config import read_user_config_raw
+ cfg_path = _hermes_home / "config.yaml"
+ if not cfg_path.exists():
+ self._fallback_model = None
+ return self._fallback_model
+ # Raw primitive (raises on parse failure) is required here: the
+ # canonical fail-open loader would return {} on a torn mid-edit
+ # write and WIPE the last known-good chain. The overlay/expansion
+ # below fixes the managed-scope/${VAR} drift without losing that.
+ cfg = read_user_config_raw(cfg_path)
try:
- _flush = getattr(agent, "_flush_messages_to_session_db", None)
- _session_messages = getattr(agent, "_session_messages", None)
- if callable(_flush) and isinstance(_session_messages, list) and _session_messages:
- # Strip private empty-response retry scaffolding from the
- # tail first, mirroring the graceful ``_persist_session``
- # path, so a resumed turn doesn't replay synthetic recovery
- # nudges.
- _strip = getattr(
- agent, "_drop_trailing_empty_response_scaffolding", None
- )
- if callable(_strip):
- try:
- _strip(_session_messages)
- except Exception:
- pass
- try:
- _flush(_session_messages)
- except Exception as _flush_err:
- # The in-memory transcript could not be persisted
- # (e.g. FTS/SQLite index corruption — #72680). A plain
- # debug log loses the conversation permanently when the
- # process exits. Dump the live agent history to an
- # external JSON recovery snapshot so an operator can
- # salvage it after repairing state.db. The flush is
- # non-fatal; shutdown must never block on a best-effort
- # backup.
- logger.warning(
- "Shutdown transcript flush failed (%s); preserving "
- "%d in-memory message(s) to recovery snapshot",
- _flush_err,
- len(_session_messages),
- )
- from gateway.shutdown_flush import flush_agent_history_to_file
- flush_agent_history_to_file(
- getattr(agent, "session_id", None),
- _session_messages,
- )
- except Exception as _e:
- logger.debug("Shutdown transcript flush failed: %s", _e)
+ from hermes_cli import managed_scope
+ cfg = managed_scope.apply_managed_overlay(cfg)
+ except Exception:
+ pass
try:
- from hermes_cli.lifecycle import finalize_session
- finalize_session(
- session_id=getattr(agent, "session_id", None),
- platform="gateway",
- reason="shutdown",
- )
+ from hermes_cli.config import _expand_env_vars
+ expanded = _expand_env_vars(cfg)
+ if isinstance(expanded, dict):
+ cfg = expanded
except Exception:
pass
- # Off-loop + bounded: a wedged memory provider here used to hang
- # the whole shutdown so SIGTERM never completed (#53175).
- await self._cleanup_agent_resources_off_loop(
- agent, context="shutdown finalize"
+ except Exception:
+ # Transient failure — keep last known-good chain.
+ logger.debug(
+ "fallback_providers refresh: config.yaml read failed; "
+ "keeping last known-good chain", exc_info=True,
)
+ return self._fallback_model
+ self._fallback_model = get_fallback_chain(cfg) or None
+ return self._fallback_model
- def _should_emit_long_running_notification(
- self,
- session_key: Optional[str],
- agent: Any,
- executor_task: Optional[Any],
- ) -> bool:
- """Only emit the heartbeat while this task still owns the live run.
+ @staticmethod
+ def _apply_fallback_chain_to_agent(agent: Any, chain: list | None) -> None:
+ """Keep a cached agent's fallback chain aligned with current config.
- Guards against a stale ``running: delegate_task`` heartbeat outliving the
- run that started it: stop once the executor finishes, the agent is gone,
- or the session key has been rebound to a different live agent (e.g. the
- user sent ``/new`` and a fresh agent took the slot mid-run, #12029).
+ Skips rewrite while a cooldown is holding the agent on an already-
+ activated fallback provider — ``restore_primary_runtime`` owns that
+ turn-scoped lifecycle. When primary is active (or cooldown expired),
+ replace the chain so mid-uptime ``fallback_providers`` edits take
+ effect without requiring a gateway restart (#60955).
"""
if agent is None:
- return False
- if executor_task is not None and executor_task.done():
- return False
- if session_key:
- _hb_state = self._peek_session_state(session_key)
- if (_hb_state.turn.agent if _hb_state else None) is not agent:
- return False
- return True
-
- # Upper bound on off-loop agent-resource cleanup invoked from coroutines
- # running on the gateway's event loop (session-expiry sweep, in-turn
- # cache-hygiene re-eviction). _cleanup_agent_resources is synchronous and
- # can block for a long time (agent.close() does subprocess teardown;
- # shutdown_memory_provider() may do network/SQLite IO via a memory plugin).
- # Calling it inline wedges the whole loop — the bot goes silent, the
- # runtime-status updated_at heartbeat freezes, and SIGTERM cannot be
- # serviced (#53175). Offload to a worker thread under this timeout so the
- # loop is never blocked; mirrors the /new reset path's fix (#35994).
- _CLEANUP_TIMEOUT_S = 30.0
+ return
+ new_chain = list(chain or [])
+ rate_limited_until = getattr(agent, "_rate_limited_until", 0) or 0
+ if (
+ getattr(agent, "_fallback_activated", False)
+ and rate_limited_until > time.monotonic()
+ ):
+ return
+ old_chain = list(getattr(agent, "_fallback_chain", []) or [])
+ agent._fallback_chain = new_chain
+ agent._fallback_model = new_chain[0] if new_chain else None
+ if not getattr(agent, "_fallback_activated", False):
+ agent._fallback_index = 0
+ # A config edit signals the user changed something — drop the
+ # session-scoped unavailability memo so re-configured entries
+ # (e.g. credentials added mid-uptime for a previously-failing
+ # provider) get retried instead of staying suppressed for the
+ # cached agent's lifetime. Only on actual content change, so
+ # the per-message no-op refresh keeps the memo's rate-limiting
+ # benefit (#60955).
+ if new_chain != old_chain:
+ unavailable = getattr(agent, "_unavailable_fallback_keys", None)
+ if unavailable:
+ unavailable.clear()
- def _defer_agent_cleanup_until_future_done(
- self,
- future: asyncio.Future,
- agent: Any,
- *,
- context: str,
- ) -> None:
- """Clean up ``agent`` only after its executor future has finished.
+ def _snapshot_running_agents(self) -> Dict[str, Any]:
+ return {
+ session_key: agent
+ for session_key, agent in self._running_agent_items()
+ if agent is not _AGENT_PENDING_SENTINEL
+ }
- A timed-out executor call keeps running in its worker thread. Closing
- the agent before that thread exits can tear down clients or providers
- it is still using. Keep a strong task reference and wait for the real
- future before invoking the normal bounded, off-loop cleanup path.
- """
+ def _get_max_concurrent_sessions(self) -> Optional[int]:
+ """Return the configured active chat session cap, if enabled."""
+ try:
+ from hermes_cli.active_sessions import resolve_max_concurrent_sessions
- async def _cleanup_when_done() -> None:
- try:
- await asyncio.shield(future)
- except asyncio.CancelledError:
- # Loop shutdown can cancel this waiter while the executor still
- # runs. Never turn that cancellation into premature cleanup.
- return
- except Exception as exc:
- logger.debug(
- "Deferred agent worker%s finished with an error: %s",
- f" ({context})" if context else "",
- exc,
- )
- await self._cleanup_agent_resources_off_loop(agent, context=context)
+ return resolve_max_concurrent_sessions(getattr(self, "config", None))
+ except Exception:
+ return None
- task = asyncio.create_task(_cleanup_when_done())
- tasks = getattr(self, "_deferred_agent_cleanup_tasks", None)
- if tasks is None:
- tasks = set()
- self._deferred_agent_cleanup_tasks = tasks
- tasks.add(task)
- task.add_done_callback(tasks.discard)
+ def _active_session_limit_message(self, session_key: str) -> Optional[str]:
+ """Return a user-facing rejection when starting a new session exceeds the cap."""
+ max_sessions = self._get_max_concurrent_sessions()
+ if max_sessions is None:
+ return None
+ if self._is_session_running(session_key):
+ return None
+ active_count = self._running_agent_count()
+ if active_count < max_sessions:
+ return None
+ from hermes_cli.active_sessions import active_session_limit_message
- async def _cleanup_agent_resources_off_loop(
- self, agent: Any, *, context: str = ""
- ) -> None:
- """Run _cleanup_agent_resources in a worker thread with a bounded wait.
+ return active_session_limit_message(active_count, max_sessions)
- Safe to await from coroutines on the gateway event loop: a slow or
- wedged teardown (memory provider IO, subprocess close) can no longer
- block message processing. On timeout the await is cancelled and the
- worker thread is left to finish (or leak) on its own — the caller
- proceeds regardless, exactly as the /new reset path does (#35994).
- """
- if agent is None:
- return
- if context.startswith("shutdown") or context == "session expiry":
- try:
- agent._end_session_on_close = False
- except Exception:
- pass
- try:
- await asyncio.wait_for(
- self._run_in_executor_with_context(
- self._cleanup_agent_resources, agent
- ),
- timeout=self._CLEANUP_TIMEOUT_S,
- )
- except asyncio.TimeoutError:
- logger.warning(
- "Agent resource cleanup%s exceeded %ss; proceeding without "
- "blocking the event loop (the worker thread is left to finish "
- "on its own). (#53175)",
- f" ({context})" if context else "",
- self._CLEANUP_TIMEOUT_S,
- )
- except Exception as cleanup_exc:
- logger.warning(
- "Agent resource cleanup%s failed: %s (#53175)",
- f" ({context})" if context else "",
- cleanup_exc,
- )
-
- def _cleanup_agent_resources(self, agent: Any) -> None:
- """Best-effort cleanup for temporary or cached agent instances."""
- if agent is None:
- return
- try:
- if hasattr(agent, "shutdown_memory_provider"):
- # Drain queued memory writes BEFORE tearing the provider down.
- # The memory manager persists per-turn sync and end-of-session
- # extraction on a single serialized background worker.
- # shutdown_memory_provider() -> shutdown_all() only gives that
- # worker a ~5s bounded drain and abandons (cancels) anything
- # still queued past it, so a /reset — or any gateway session
- # rotation that reaches this cleanup path — could silently drop
- # writes the session had already handed off. The next session
- # then loads stale memory (#73297). Give pending work a bounded
- # head start through the manager's own barrier first, mirroring
- # the CLI exit path (cli.py). Best-effort: a flush failure must
- # never block teardown.
- _mm = getattr(agent, "_memory_manager", None)
- if _mm is not None and hasattr(_mm, "flush_pending"):
- try:
- _mm.flush_pending(timeout=10)
- except Exception:
- pass
- # Pass the agent's own conversation transcript so memory
- # providers' ``on_session_end`` hooks see the real messages
- # instead of the empty default (#15165). ``_session_messages``
- # is set on ``AIAgent`` (run_agent.py:1518) and refreshed at
- # the end of every ``run_conversation`` turn via
- # ``_persist_session``; on an agent built through
- # ``object.__new__`` (test stubs) the attribute may be
- # absent, so ``getattr`` with a ``None`` default keeps the
- # call signature-compatible with the pre-fix behaviour
- # (``shutdown_memory_provider(messages=None)``).
- session_messages = getattr(agent, "_session_messages", None)
- if isinstance(session_messages, list):
- agent.shutdown_memory_provider(session_messages)
- else:
- agent.shutdown_memory_provider()
- except Exception:
- pass
- # Close tool resources (terminal sandboxes, browser daemons,
- # background processes, httpx clients) to prevent zombie
- # process accumulation.
- try:
- if hasattr(agent, "close"):
- agent.close()
- except Exception:
- pass
- # Auxiliary async clients (session_search/web/vision/etc.) live in a
- # process-global cache and are created inside worker threads. Clean up
- # any entries whose event loop is now dead so their httpx transports do
- # not accumulate across gateway turns.
+ def _claim_active_session_slot(
+ self,
+ session_key: str,
+ source: SessionSource,
+ ) -> tuple[Any, Optional[str]]:
+ """Claim a cross-process active-session slot for a new gateway turn."""
+ if self._is_session_running(session_key):
+ return None, None
+ local_limit_message = self._active_session_limit_message(session_key)
+ if local_limit_message is not None:
+ return None, local_limit_message
try:
- from agent.auxiliary_client import cleanup_stale_async_clients
- cleanup_stale_async_clients()
- except Exception:
- pass
+ from hermes_cli.active_sessions import try_acquire_active_session
- _STUCK_LOOP_THRESHOLD = 3 # restarts while active before auto-suspend
- _STUCK_LOOP_FILE = ".restart_failure_counts"
+ platform = source.platform.value if source and source.platform else "gateway"
+ return try_acquire_active_session(
+ session_id=session_key,
+ surface=f"gateway:{platform}",
+ config=getattr(self, "config", None),
+ metadata={
+ "platform": platform,
+ "chat_id": getattr(source, "chat_id", "") or "",
+ "user_id": getattr(source, "user_id", "") or "",
+ },
+ )
+ except Exception as exc:
+ logger.warning("Failed to claim active session slot: %s", exc)
+ return None, None
- def _increment_restart_failure_counts(self, active_session_keys: set) -> None:
- """Increment restart-failure counters for sessions active at shutdown.
+ @staticmethod
+ def _agent_has_active_subagents(running_agent: Any) -> bool:
+ """Return True when *running_agent* is currently driving subagents
+ via the ``delegate_task`` tool.
- Persists to a JSON file so counters survive across restarts.
- Sessions NOT in active_session_keys are removed (they completed
- successfully, so the loop is broken).
+ Background (#30170): ``AIAgent.interrupt()`` cascades through the
+ parent's ``_active_children`` list and calls ``interrupt()`` on
+ every child synchronously, which aborts in-flight subagent work
+ and produces a fallback cascade with no actionable signal.
+ Demoting ``busy_input_mode='interrupt'`` to ``queue`` semantics
+ whenever this helper returns True protects subagent work from
+ conversational follow-ups while leaving the explicit ``/stop``
+ path (which goes through ``_interrupt_and_clear_session``)
+ untouched. Safe-by-default: returns False on any attribute or
+ lock error so a missing/broken parent never blocks the existing
+ interrupt path.
"""
- import json
-
- path = _hermes_home / self._STUCK_LOOP_FILE
+ if running_agent is None or running_agent is _AGENT_PENDING_SENTINEL:
+ return False
+ children = getattr(running_agent, "_active_children", None)
+ # AIAgent always initialises this as a concrete list (see
+ # agent/agent_init.py). Reject anything that isn't a real
+ # collection — this guards against ``MagicMock()._active_children``
+ # auto-creating a truthy stub in tests and triggering the demotion
+ # against an agent that doesn't actually have subagents.
+ if not isinstance(children, (list, tuple, set)):
+ return False
+ if not children:
+ return False
+ lock = getattr(running_agent, "_active_children_lock", None)
try:
- counts = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
+ if lock is not None:
+ with lock:
+ return bool(children)
+ return bool(children)
except Exception:
- counts = {}
-
- # Increment active sessions, remove inactive ones (loop broken)
- new_counts = {}
- for key in active_session_keys:
- new_counts[key] = counts.get(key, 0) + 1
- # Keep any entries that are still above 0 even if not active now
- # (they might become active again next restart)
+ return False
- try:
- atomic_json_write(path, new_counts, indent=None)
- except Exception:
- pass
+ async def _session_has_compression_in_flight(self, session_key: str) -> bool:
+ """Return True when a compression lock is held for this session's id.
- def _suspend_stuck_loop_sessions(self) -> int:
- """Suspend sessions that have been active across too many restarts.
+ Context compression is interrupt-protected (#23975) but gateway
+ ``interrupt`` busy-input mode can still start a follow-up turn against
+ the pre-rotation parent while compression is mid-flight, producing
+ orphaned compression siblings (#56391). Callers demote interrupt to
+ queue when this returns True.
- Returns the number of sessions suspended. Called on gateway startup
- AFTER suspend_recently_active() to catch the stuck-loop pattern:
- session loads → agent gets stuck → gateway restarts → repeat.
+ Both blocking sources — the ``session_store`` lock + JSON load, and the
+ SQLite ``get_compression_lock_holder`` SELECT — are offloaded to a
+ worker thread so a large state.db never freezes the event loop (#5).
"""
- import json
-
- path = _hermes_home / self._STUCK_LOOP_FILE
- if not path.exists():
- return 0
-
+ session_store = getattr(self, "session_store", None)
+ if not session_key or session_store is None:
+ return False
try:
- counts = json.loads(path.read_text(encoding="utf-8"))
+ session_id = await asyncio.to_thread(
+ self._lookup_session_id_under_store_lock, session_store, session_key
+ )
+ except (AttributeError, TypeError):
+ return False
except Exception:
- return 0
-
- suspended = 0
- stuck_keys = [k for k, v in counts.items() if v >= self._STUCK_LOOP_THRESHOLD]
-
- for session_key in stuck_keys:
- try:
- entry = self.session_store._entries.get(session_key)
- if entry and not entry.suspended:
- entry.suspended = True
- suspended += 1
- logger.warning(
- "Auto-suspended stuck session %s (active across %d "
- "consecutive restarts — likely a stuck loop)",
- session_key, counts[session_key],
- )
- except Exception:
- pass
-
- if suspended:
- try:
- self.session_store._save()
- except Exception:
- pass
-
- # Clear the file — counters start fresh after suspension
+ logger.warning(
+ "Compression in-flight check failed while reading session %s; "
+ "treating compression as active to avoid interrupting a possible "
+ "parent-session rotation",
+ session_key,
+ exc_info=True,
+ )
+ return True
+ if not session_id:
+ return False
+ session_db = getattr(self, "_session_db", None)
+ if session_db is None:
+ return False
+ raw_db = getattr(session_db, "_db", session_db)
try:
- path.unlink(missing_ok=True)
+ holder = await asyncio.to_thread(
+ raw_db.get_compression_lock_holder, str(session_id)
+ )
+ return bool(holder)
+ except (AttributeError, TypeError):
+ return False
except Exception:
- pass
-
- return suspended
+ logger.warning(
+ "Compression in-flight check failed while reading lock holder "
+ "for session %s; treating compression as active to avoid "
+ "interrupting a possible parent-session rotation",
+ session_id,
+ exc_info=True,
+ )
+ return True
- def _clear_restart_failure_count(self, session_key: str) -> None:
- """Clear the restart-failure counter for a session that completed OK.
+ @staticmethod
+ def _lookup_session_id_under_store_lock(session_store, session_key: str):
+ """Sync helper run in the thread pool: read session_id under the store lock."""
+ # noqa: SLF001 — intentional private access; runs off the event loop.
+ with session_store._lock: # noqa: SLF001
+ session_store._ensure_loaded_locked() # noqa: SLF001
+ entry = session_store._entries.get(session_key) # noqa: SLF001
+ return getattr(entry, "session_id", None) if entry is not None else None
- Called after a successful agent turn to signal the loop is broken.
- """
- import json
+ # Hard cap on per-session pending follow-ups for busy_input_mode=queue
+ # (and the draining/steer-fallback/subagent-demotion paths that share
+ # this entry point). Without a cap, a stuck agent + a rapid-fire user
+ # could grow the overflow list unboundedly. 32 turns of queued
+ # follow-ups is far beyond any realistic conversational backlog while
+ # still small enough to never threaten memory.
+ _BUSY_QUEUE_MAX_PENDING = 32
- path = _hermes_home / self._STUCK_LOOP_FILE
- if not path.exists():
+ def _queue_or_replace_pending_event(self, session_key: str, event: MessageEvent) -> None:
+ adapter = self._adapter_for_source(event.source)
+ if not adapter:
return
- try:
- counts = json.loads(path.read_text(encoding="utf-8"))
- if session_key in counts:
- del counts[session_key]
- if counts:
- atomic_json_write(path, counts, indent=None)
- else:
- path.unlink(missing_ok=True)
- except Exception:
- pass
-
- async def _launch_detached_restart_command(self) -> None:
- import shutil
- import subprocess
-
- hermes_cmd = _resolve_hermes_bin()
- if not hermes_cmd:
- logger.error("Could not locate hermes binary for detached /restart")
+ # #28503 — Previously this called ``merge_pending_message_event``
+ # with the default ``merge_text=False``, which silently OVERWROTE
+ # the single pending slot when consecutive text messages arrived
+ # in ``busy_input_mode: queue``. Route through the FIFO
+ # infrastructure shared with ``/queue`` so each follow-up gets
+ # its own turn in arrival order. Photo bursts still merge into
+ # the head slot via ``merge_pending_message_event`` (album
+ # semantics); everything else appends to the overflow tail.
+ pending_slot = getattr(adapter, "_pending_messages", None)
+ existing = pending_slot.get(session_key) if isinstance(pending_slot, dict) else None
+ if existing is not None and (
+ getattr(existing, "message_type", None) == MessageType.PHOTO
+ or event.message_type == MessageType.PHOTO
+ or bool(getattr(existing, "media_urls", None))
+ or bool(getattr(event, "media_urls", None))
+ ):
+ # Preserve photo-burst / media-merge semantics for the head slot.
+ merge_pending_message_event(
+ adapter._pending_messages,
+ session_key,
+ event,
+ merge_text=event.message_type == MessageType.TEXT,
+ )
return
- if self._detached_restart_helper_started:
+
+ if self._queue_depth(session_key, adapter=adapter) >= self._BUSY_QUEUE_MAX_PENDING:
+ logger.warning(
+ "Dropping busy-mode follow-up for session %s — pending queue at cap (%d).",
+ session_key,
+ self._BUSY_QUEUE_MAX_PENDING,
+ )
return
- self._detached_restart_helper_started = True
- current_pid = os.getpid()
- restart_after_s = max(float(getattr(self, "_restart_drain_timeout", 0.0) or 0.0) + 5.0, 5.0)
+ self._enqueue_fifo(session_key, event, adapter)
- # On Windows there's no bash/setsid chain — spawn a tiny Python
- # watcher directly via sys.executable instead. The watcher polls
- # current_pid, waits for our exit, then runs `hermes gateway
- # restart` with detach flags so the respawn survives the CLI
- # that triggered the /restart command closing its console.
- if sys.platform == "win32":
- import textwrap
- from hermes_cli._subprocess_compat import (
- windows_detach_flags_without_breakaway,
- windows_detach_popen_kwargs,
- )
+ async def _prepare_busy_steer_text(self, event: MessageEvent) -> str:
+ """Return steerable text for a busy follow-up, transcribing voice first.
- cmd_argv = [*hermes_cmd, "gateway", "restart"]
- watcher = textwrap.dedent(
- """
- import os, subprocess, sys, time
- from hermes_cli._subprocess_compat import windows_detach_flags_without_breakaway
- pid = int(sys.argv[1])
- restart_after_s = float(sys.argv[2])
- cmd = sys.argv[3:]
- deadline = time.monotonic() + restart_after_s
+ Fresh and queued voice messages reach the normal inbound STT pipeline,
+ but successful steer messages intentionally bypass that queue. Without
+ preprocessing here, a media-only voice follow-up has an empty text
+ payload and steer mode silently degrades to queue mode.
- def _alive(p):
- # On Windows, os.kill(pid, 0) is NOT a no-op — it maps to
- # GenerateConsoleCtrlEvent(0, pid) (bpo-14484). Use the
- # Win32 handle-based existence check instead.
- if os.name == 'nt':
- import ctypes
- k32 = ctypes.windll.kernel32
- k32.OpenProcess.restype = ctypes.c_void_p
- k32.WaitForSingleObject.restype = ctypes.c_uint
- k32.GetLastError.restype = ctypes.c_uint
- h = k32.OpenProcess(0x1000 | 0x100000, False, int(p))
- if not h:
- return k32.GetLastError() != 87
- try:
- return k32.WaitForSingleObject(h, 0) == 0x102
- finally:
- k32.CloseHandle(h)
- try:
- os.kill(int(p), 0)
- return True
- except ProcessLookupError:
- return False
- except PermissionError:
- return True
- except OSError:
- return False
+ Audio file attachments remain files; only voice-message media follows
+ the automatic STT contract used by ``_prepare_inbound_message_text``.
+ If transcription fails, preserve any caption and let the existing
+ steer fallback handle an otherwise empty event without losing it.
- while time.monotonic() < deadline:
- if not _alive(pid):
- break
- time.sleep(0.2)
- subprocess.Popen(
- cmd,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- creationflags=windows_detach_flags_without_breakaway(),
- )
- """
- ).strip()
- from tools.environments.local import build_subprocess_env
- watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
- # This watcher is intentionally outside the running gateway. If it
- # inherits the gateway marker, `hermes gateway restart` refuses to
- # run as a self-restart loop guard and the gateway stays stopped.
- watcher_env.pop("_HERMES_GATEWAY", None)
- project_root = Path(__file__).resolve().parent.parent
- # The watcher runs sys.executable (console python) under the
- # CREATE_NO_WINDOW detach kwargs below: it owns one hidden
- # console, inherited by the `hermes gateway restart` child, so
- # nothing flashes. Do NOT swap in GUI-subsystem pythonw.exe —
- # a console-less watcher forces every console-subsystem
- # descendant to allocate a visible conhost (#54220/#56747).
- watcher_python = sys.executable
- venv_dir = Path(watcher_env.get("VIRTUAL_ENV") or project_root / "venv")
- site_packages = venv_dir / "Lib" / "site-packages"
- if site_packages.exists():
- watcher_env["VIRTUAL_ENV"] = str(venv_dir)
- pythonpath = [str(project_root), str(site_packages)]
- if watcher_env.get("PYTHONPATH"):
- pythonpath.append(watcher_env["PYTHONPATH"])
- watcher_env["PYTHONPATH"] = os.pathsep.join(dict.fromkeys(pythonpath))
- watcher_argv = [
- watcher_python,
- "-c",
- watcher,
- str(current_pid),
- str(restart_after_s),
- *cmd_argv,
- ]
- # The watcher process must itself break away from any job object the
- # parent CLI lives in (Electron/Tauri-wrapped Hermes Desktop, Windows
- # Terminal, schtasks shells); otherwise it is reaped when the CLI
- # exits and the gateway never respawns. windows_detach_popen_kwargs()
- # carries CREATE_BREAKAWAY_FROM_JOB, but a restrictive job object
- # (no JOB_OBJECT_LIMIT_BREAKAWAY_OK) rejects that bit with
- # ERROR_ACCESS_DENIED, surfaced as OSError. Retry once without the
- # breakaway bit, preserving argv and the scrubbed watcher_env.
- # Mirrors the canonical fallback in
- # hermes_cli/gateway_windows.py::_spawn_detached.
- try:
- subprocess.Popen(
- watcher_argv,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=watcher_env,
- **windows_detach_popen_kwargs(),
- )
- except OSError:
- try:
- subprocess.Popen(
- watcher_argv,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=watcher_env,
- creationflags=windows_detach_flags_without_breakaway(),
- )
- except OSError as exc:
- # Both spawn attempts failed (a breakaway-denying job object
- # is the common cause, but OSError covers others too).
- # Record a minimal, path-safe diagnostic and return without
- # crashing the caller: state plainly that no watcher was
- # started, and log only the interpreter basename and a
- # numeric error code — never argv, env, watcher source, or
- # str(exc) (which can carry a full interpreter path for a
- # FileNotFoundError).
- winerror = getattr(exc, "winerror", None)
- error_code = winerror if winerror is not None else exc.errno
- error_field = "winerror" if winerror is not None else "errno"
- logger.warning(
- "Detached restart watcher was not started after the "
- "no-breakaway retry (%s; %s=%r). The gateway will not "
- "be respawned by this restart attempt.",
- os.path.basename(watcher_python),
- error_field,
- error_code,
- )
- return
+ Routes through ``_transcribe_and_echo_pending_voice`` — the single
+ out-of-band transcription choke point shared with the interrupt
+ monitor and the pending-drain path — so the STT call is made at most
+ once per platform message (cached on the event) and the transcript
+ echo respects the count-based ledger. If steering later falls back
+ to queue mode, the drain path reuses the cached transcript instead of
+ paying for a second STT call or re-echoing the same line.
+ """
+ text = (event.text or "").strip()
+ if not self._pending_event_audio_paths(event):
+ return text
- cmd = " ".join(shlex.quote(part) for part in hermes_cmd)
- shell_cmd = (
- f"deadline=$(( $(date +%s) + {int(restart_after_s)} )); "
- f"while kill -0 {current_pid} 2>/dev/null && [ $(date +%s) -lt $deadline ]; do sleep 0.2; done; "
- f"{cmd} gateway restart"
+ adapter = self._adapter_for_source(event.source)
+ enriched_text, successful_transcripts = await self._transcribe_and_echo_pending_voice(
+ event,
+ adapter,
+ event.source,
+ text,
+ log_context="Busy-steer",
)
- # Same marker scrub as the Windows watcher above: this watcher runs
- # `hermes gateway restart` from outside the gateway, but it inherits
- # _HERMES_GATEWAY=1 from us, and the CLI's self-restart loop guard
- # refuses to run when that marker is set — silently (DEVNULL), so the
- # gateway stops and never comes back.
- from tools.environments.local import build_subprocess_env
- watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
- watcher_env.pop("_HERMES_GATEWAY", None)
- setsid_bin = shutil.which("setsid")
- if setsid_bin:
- subprocess.Popen(
- [setsid_bin, "bash", "-lc", shell_cmd],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=watcher_env,
- start_new_session=True,
- )
- else:
- subprocess.Popen(
- ["bash", "-lc", shell_cmd],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=watcher_env,
- start_new_session=True,
- )
-
- def _launch_systemd_restart_shortcut(self) -> None:
- """Best-effort helper to bypass systemd's automatic restart delay.
-
- For planned in-chat restarts, the gateway exits cleanly so systemd does
- not record a failure. However, units with RestartSteps still count
- automatic restarts and can delay repeated /restart tests. A transient
- user service survives our cgroup teardown and explicitly starts the
- gateway as soon as this PID exits, while the unit keeps its normal
- backoff for real crash loops.
- """
- if sys.platform != "linux" or not os.environ.get("INVOCATION_ID"):
- return
-
- try:
- import shutil
- import subprocess
-
- systemd_run = shutil.which("systemd-run")
- systemctl = shutil.which("systemctl")
- if not systemd_run or not systemctl:
- return
-
- try:
- from hermes_cli.gateway import get_service_name
-
- service_name = get_service_name()
- except Exception:
- service_name = "hermes-gateway"
+ if not successful_transcripts:
+ return text
+ return (enriched_text or text).strip()
- current_pid = os.getpid()
+ async def _handle_active_session_busy_message(self, event: MessageEvent, session_key: str) -> bool:
+ # --- Authorization gate (#17775) ---
+ # The cold path (_handle_message) checks _is_user_authorized before
+ # creating a session. The busy path must enforce the same check;
+ # otherwise unauthorized users in shared threads (Slack/Telegram/Discord)
+ # can inject messages into an active session they don't own.
+ if not self._is_user_authorized(event.source):
+ logger.warning(
+ "Dropping message from unauthorized user in active session: "
+ "user=%s (%s), platform=%s, session=%s",
+ event.source.user_id,
+ event.source.user_name,
+ event.source.platform.value if event.source.platform else "unknown",
+ session_key,
+ )
+ return True # handled (silently dropped); do not fall through
- # Detect whether the gateway unit is registered as a system or
- # user service. Daemon-style deployments are typically system
- # units (e.g. /etc/systemd/system/hermes-gateway.service), while
- # `hermes setup` under a non-root account may register a user
- # unit. Hard-coding ``--user`` broke system-unit deployments:
- # systemctl returned an empty MainPID, the PID-equality check
- # below failed, and the planned-restart helper was never
- # launched — leaving the gateway dead until a manual reboot.
- def _query_pid(scope_flags):
- try:
- out = subprocess.run(
- [systemctl, *scope_flags, "show", service_name,
- "--property=MainPID", "--value"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=2,
- )
- return (out.stdout or "").strip()
- except Exception:
- return ""
+ # --- Draining case (gateway restarting/stopping) ---
+ if self._draining:
+ adapter = self._adapter_for_source(event.source)
+ if not adapter:
+ return True
- system_pid = _query_pid([])
- user_pid = _query_pid(["--user"])
- if str(current_pid) == system_pid:
- scope_flags = []
- systemctl_scope = "systemctl"
- elif str(current_pid) == user_pid:
- scope_flags = ["--user"]
- systemctl_scope = "systemctl --user"
+ reply_anchor = self._reply_anchor_for_event(event)
+ thread_meta = self._thread_metadata_for_source(event.source, reply_anchor)
+ if self._queue_during_drain_enabled():
+ self._queue_or_replace_pending_event(session_key, event)
+ message = f"⏳ Gateway {self._status_action_gerund()} — queued for the next turn after it comes back."
else:
- # MainPID does not match in either scope — likely invoked
- # outside of systemd or the unit was renamed. Bail out
- # rather than restart the wrong unit.
- return
+ message = f"⏳ Gateway is {self._status_action_gerund()} and is not accepting another turn right now."
- service_arg = shlex.quote(service_name)
- shell_cmd = (
- f"while kill -0 {current_pid} 2>/dev/null; do sleep 0.2; done; "
- f"{systemctl_scope} reset-failed {service_arg}; "
- f"{systemctl_scope} restart {service_arg}"
- )
- unit_name = f"{service_name}-planned-restart-{current_pid}".replace(".", "-")
- subprocess.Popen(
- [
- systemd_run,
- *scope_flags,
- "--collect",
- "--unit",
- unit_name,
- "/bin/sh",
- "-lc",
- shell_cmd,
- ],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- start_new_session=True,
+ await adapter._send_with_retry(
+ chat_id=event.source.chat_id,
+ content=message,
+ reply_to=(
+ reply_anchor
+ if event.source.platform == Platform.TELEGRAM
+ and event.source.chat_type == "dm"
+ and event.source.thread_id
+ else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id)
+ ),
+ metadata=thread_meta,
)
- logger.info(
- "Launched systemd planned-restart helper for %s (pid=%s, scope=%s)",
- service_name,
- current_pid,
- "user" if scope_flags else "system",
+ return True
+
+ # --- Approval response routing (#46866) ---
+ # When the agent is blocked waiting for a dangerous-command approval,
+ # plain-text responses like "yes" or "approve" must be routed to the
+ # approval handler instead of being steered/queued/interrupted.
+ # Otherwise approval via messaging platforms never succeeds — the
+ # reply is queued behind a turn that can't start until the approval
+ # resolves, so the approval times out and auto-denies (a deadlock).
+ #
+ # Slash forms (/approve, /deny) already bypass to the runner at the
+ # base-adapter guard. This handles the bare-word forms (Signal/SMS
+ # users naturally type "yes" rather than "/approve"). Gating on
+ # has_blocking_approval(session_key) is the disambiguator that keeps
+ # a conversational "yes" from triggering a dangerous command when no
+ # approval is actually pending (design intent — see run.py "Pending
+ # exec approvals are handled by /approve and /deny" note).
+ #
+ # We reuse the canonical /approve and /deny handlers rather than
+ # re-deriving the resolution + i18n messaging: they resolve the
+ # waiting thread, resume typing, AND return a localized confirmation
+ # string. The busy-handler path does not auto-send that return, so
+ # we deliver it ourselves (mirroring the draining-case send above).
+ try:
+ from tools.approval import has_blocking_approval
+ if has_blocking_approval(session_key):
+ _raw_text = (event.text or "").strip().lower()
+ _approve_words = {"approve", "yes", "ok", "okay", "confirm", "y", "👍"}
+ _deny_words = {"deny", "no", "reject", "cancel", "n", "👎"}
+ _approval_handler = None
+ _normalized_args = ""
+ if _raw_text in _approve_words:
+ _approval_handler = self._handle_approve_command
+ elif _raw_text in _deny_words:
+ _approval_handler = self._handle_deny_command
+ elif _raw_text in {"always", "approve always", "always approve"}:
+ _approval_handler = self._handle_approve_command
+ _normalized_args = "always"
+ elif _raw_text in {"session", "approve session", "session approve"}:
+ _approval_handler = self._handle_approve_command
+ _normalized_args = "session"
+ if _approval_handler is not None:
+ # Synthesize the canonical "/approve [args]" / "/deny"
+ # command text so the slash handlers parse modifiers via
+ # event.get_command_args(). Always use a literal "/" —
+ # MessageEvent.is_command()/get_command_args() only
+ # recognize the "/" prefix, not the per-platform display
+ # prefix ("!" on Slack/Matrix).
+ _verb = "approve" if _approval_handler is self._handle_approve_command else "deny"
+ _synth = f"/{_verb}"
+ if _normalized_args:
+ _synth = f"{_synth} {_normalized_args}"
+ event.text = _synth
+ _reply = await _approval_handler(event)
+ logger.info(
+ "Approval response via plain text: session=%s verb=%s args=%r",
+ session_key, _verb, _normalized_args,
+ )
+ _adapter = self._adapter_for_source(event.source)
+ if _adapter and _reply:
+ _text, _eph_ttl = _adapter._unwrap_ephemeral(_reply)
+ if _text:
+ _anchor = self._reply_anchor_for_event(event)
+ await _adapter._send_with_retry(
+ chat_id=event.source.chat_id,
+ content=_text,
+ reply_to=_anchor,
+ metadata=self._thread_metadata_for_source(event.source, _anchor),
+ )
+ return True
+ except Exception:
+ logger.warning(
+ "Plain-text approval routing failed for session %s; "
+ "falling through to busy handling",
+ session_key, exc_info=True,
)
- except Exception as e:
- logger.debug("Failed to launch systemd planned-restart helper: %s", e)
- def request_restart(self, *, detached: bool = False, via_service: bool = False) -> bool:
- if self._restart_task_started:
+ # Normal busy case (agent actively running a task)
+ adapter = self._adapter_for_source(event.source)
+ if not adapter:
+ return False # let default path handle it
+
+ # --- Internal synthetic events must never interrupt/steer ---
+ # Async-delegation completions (delegate_task(background=true)) and
+ # background-process completions (terminal notify_on_complete) re-enter
+ # the originating session as internal MessageEvents. When the session
+ # is busy, treating them like a user TEXT message means interrupt-mode
+ # (the default busy_text_mode) aborts the active turn AND sends a "⚡
+ # Interrupting current task" ack — exactly the opposite of the design
+ # invariant that a completion surfaces as a NEW turn only when idle and
+ # never splices into a running turn. Fall through to the base adapter,
+ # which queues internal events silently (no interrupt, no ack) so they
+ # cascade after the current turn finishes.
+ if getattr(event, "internal", False):
return False
- self._restart_requested = True
- self._restart_detached = detached
- self._restart_via_service = via_service
- self._restart_task_started = True
- async def _run_restart() -> None:
- if detached:
- try:
- await self._launch_detached_restart_command()
- except Exception as e:
- logger.error("Failed to launch detached gateway restart helper: %s", e)
- await asyncio.sleep(0.05)
- await self.stop(restart=True, detached_restart=detached, service_restart=via_service)
+ _busy_state = self._peek_session_state(session_key)
+ running_agent = _busy_state.turn.agent if _busy_state else None
- # _run_restart is a short-lived self-terminating task (calls stop()
- # then returns). Don't add it to _background_tasks — _stop_impl
- # cancels all entries in that set, which would cancel _run_restart
- # while it's awaiting _stop_task, propagating CancelledError into
- # _stop_impl and preventing _shutdown_event.set() / _exit_code = 75.
- # See #12875.
- #
- # We still hold a strong reference in self._restart_task: a bare
- # asyncio.create_task() keeps only a weak reference, so the event
- # loop may garbage-collect a still-pending task mid-flight. The
- # cancel loop in _stop_impl explicitly skips _restart_task for the
- # same reason it skips _stop_task.
- self._restart_task = asyncio.create_task(_run_restart())
- return True
-
- # Drain-timeout reasons set by _stop_impl() when a still-running turn is
- # force-interrupted; "restart_interrupted" is set by
- # SessionStore.suspend_recently_active() on crash recovery (no
- # .clean_shutdown marker). All three mean "the agent was mid-turn and
- # we killed it" — eligible for startup auto-resume.
- _AUTO_RESUME_REASONS = frozenset(
- {"restart_timeout", "shutdown_timeout", "restart_interrupted"}
- )
-
- async def _run_startup_resume_event(
- self,
- adapter: BasePlatformAdapter,
- event: MessageEvent,
- session_key: str,
- ) -> None:
- """Dispatch one synthetic startup resume and wait for its agent turn.
-
- ``BasePlatformAdapter.handle_message()`` returns after it installs the
- adapter-level guard and spawns the background processing task. Startup
- restore needs a stronger boundary: inbound messages must stay queued
- until the resumed agent turn itself has finished, otherwise a user
- message can race the restore turn immediately after ``handle_message``
- returns.
- """
- try:
- await adapter.handle_message(event)
- session_tasks = getattr(adapter, "_session_tasks", {})
- task = session_tasks.get(session_key) if isinstance(session_tasks, dict) else None
- if task is not None:
- await asyncio.shield(task)
- finally:
- # _schedule_resume_pending_sessions pre-claims the runner slot
- # before spawning this task. If adapter.handle_message raises
- # before _handle_message takes ownership, release that pre-claim;
- # otherwise the real run's normal cleanup owns the slot.
- _pre_state = self._peek_session_state(session_key)
- if (_pre_state.turn.agent if _pre_state else None) is _AGENT_PENDING_SENTINEL:
- self._release_running_agent_state(session_key)
+ effective_mode = self._busy_input_mode
+ busy_text_mode = getattr(self, "_busy_text_mode", "interrupt")
+ if (
+ event.message_type == MessageType.TEXT
+ and busy_text_mode == "queue"
+ and effective_mode != "steer"
+ ):
+ return False
- def _queue_startup_restore_event(self, event: MessageEvent) -> None:
- queue = getattr(self, "_startup_restore_queue", None)
- if queue is None:
- queue = []
- self._startup_restore_queue = queue
- queue.append(event)
- try:
- source = event.source
+ # Steer mode: inject mid-run via running_agent.steer() instead of
+ # queueing + interrupting. If the agent isn't running yet
+ # (sentinel) or lacks steer(), or the payload is empty, fall back
+ # to queue semantics so nothing is lost.
+ # #30170 — Subagent protection. ``AIAgent.interrupt()`` cascades
+ # to every entry in the parent's ``_active_children`` list and
+ # aborts in-flight ``delegate_task`` work. Demote ``interrupt``
+ # to ``queue`` when the parent is currently driving subagents so
+ # a conversational follow-up doesn't destroy minutes of subagent
+ # work. Explicit ``/stop`` and ``/new`` slash commands go through
+ # ``_interrupt_and_clear_session`` and are unaffected — the
+ # operator still has a way to force-cancel everything.
+ demoted_for_subagents = (
+ effective_mode == "interrupt"
+ and self._agent_has_active_subagents(running_agent)
+ )
+ if demoted_for_subagents:
logger.info(
- "Queued inbound message during gateway startup restore: platform=%s chat=%s",
- source.platform.value if source and source.platform else "unknown",
- source.chat_id if source else "unknown",
+ "Demoting busy_input_mode 'interrupt' to 'queue' for session %s "
+ "because the running agent has active subagents (#30170)",
+ session_key,
)
- except Exception:
- pass
-
- async def _drain_startup_restore_queue(self) -> int:
- """Replay inbound messages queued while startup auto-resume ran."""
- drained = 0
- queue = getattr(self, "_startup_restore_queue", None)
- if queue is None:
- return 0
- while queue:
- event = queue.pop(0)
- source = getattr(event, "source", None)
- adapter = self._adapter_for_source(source)
- if adapter is None:
- logger.debug(
- "Dropping startup-restore queued message: adapter unavailable for %s",
- getattr(getattr(source, "platform", None), "value", None),
+ effective_mode = "queue"
+ demoted_for_compression = (
+ effective_mode == "interrupt"
+ and await self._session_has_compression_in_flight(session_key)
+ )
+ if demoted_for_compression:
+ logger.info(
+ "Demoting busy_input_mode 'interrupt' to 'queue' for session %s "
+ "because context compression is in flight (#56391)",
+ session_key,
+ )
+ effective_mode = "queue"
+ steered = False
+ redirected = False
+ if effective_mode == "steer":
+ steer_text = await self._prepare_busy_steer_text(event)
+ # A follow-up qualifies for steering when it is plain text, OR
+ # when every attachment is STT-eligible voice media whose
+ # transcript was just folded into steer_text — otherwise a voice
+ # note in steer mode silently degrades to queue mode (#58780).
+ _steer_media_urls = getattr(event, "media_urls", None) or []
+ _steer_all_voice = bool(_steer_media_urls) and (
+ len(self._pending_event_audio_paths(event)) == len(_steer_media_urls)
+ )
+ can_steer = (
+ steer_text
+ and (
+ (
+ event.message_type == MessageType.TEXT
+ and not event.media_urls
+ and not event.media_types
+ )
+ or _steer_all_voice
)
- continue
- # Mark this replay so _handle_message does not queue it again while
- # the restore gate remains closed for any fresh inbound arrivals.
+ and running_agent is not None
+ and running_agent is not _AGENT_PENDING_SENTINEL
+ and hasattr(running_agent, "steer")
+ )
+ if can_steer:
+ try:
+ steered = bool(running_agent.steer(steer_text))
+ except Exception as exc:
+ logger.warning("Gateway steer failed for session %s: %s", session_key, exc)
+ steered = False
+ if not steered:
+ # Fall back to queue (merge into pending messages, no interrupt)
+ effective_mode = "queue"
+ elif (
+ effective_mode == "interrupt"
+ and event.message_type == MessageType.TEXT
+ and not event.media_urls
+ and not event.media_types
+ and running_agent is not None
+ and running_agent is not _AGENT_PENDING_SENTINEL
+ and getattr(running_agent, "_supports_active_turn_redirect", False) is True
+ and hasattr(running_agent, "redirect")
+ ):
try:
- setattr(event, "_hermes_startup_restore_replay", True)
- except Exception:
- pass
- await adapter.handle_message(event)
- drained += 1
- return drained
+ redirected = bool(running_agent.redirect((event.text or "").strip()))
+ except Exception as exc:
+ logger.warning("Gateway redirect failed for session %s: %s", session_key, exc)
+ redirected = False
- async def _finish_startup_restore(self) -> None:
- """Wait (BOUNDED) for startup auto-resume, then release + drain inbound.
+ # Store the message so it's processed as the next turn after the
+ # current run finishes (or is interrupted). Skip this for a
+ # successful steer — the text already landed inside the run and
+ # must NOT also be replayed as a next-turn user message.
+ #
+ # Route through _queue_or_replace_pending_event (the same FIFO
+ # infrastructure used by busy queue-mode and /queue) rather than a
+ # raw merge_pending_message_event(merge_text=True). The raw merge
+ # newline-joins consecutive TEXT follow-ups into a SINGLE pending
+ # turn, destroying message boundaries — so two separate user
+ # messages sent while the agent was busy (interrupt mode, or a
+ # steer that fell back to queue) arrived as one mashed-together
+ # turn (#43066 sub-bug 2). The FIFO path gives each text its own
+ # turn in arrival order while still preserving photo-burst / album
+ # merge semantics for media.
+ if not steered and not redirected:
+ self._queue_or_replace_pending_event(session_key, event)
- The wait is bounded by ``_startup_restore_drain_timeout_secs`` so that
- a single pathologically long boot-resume turn cannot hold the inbound
- gate shut for every channel. On timeout we release the gate and let
- the still-running resume turn(s) finish in the background — they are
- NOT cancelled. This is safe because duplicate-agent protection does
- not depend on the wait: ``_schedule_resume_pending_sessions`` claims
- each session's ``_running_agents`` slot SYNCHRONOUSLY before this gate
- runs, so any inbound message drained while a resume turn is still in
- flight queues behind that slot instead of spawning a second agent.
- """
- tasks = list(getattr(self, "_startup_restore_tasks", []) or [])
- if tasks:
- timeout = _startup_restore_drain_timeout_secs()
- if timeout > 0:
- # asyncio.wait (unlike wait_for / gather+timeout) does NOT
- # cancel the pending tasks on timeout — the slow resume turn
- # keeps running in the background instead of being killed.
- done, pending = await asyncio.wait(tasks, timeout=timeout)
- if pending:
- logger.warning(
- "Startup-restore gate released after %.0fs with %d boot "
- "auto-resume turn(s) still running; draining inbound "
- "queue now (resume slots already claimed, so no "
- "duplicate agents). Slow turn(s) continue in the "
- "background.",
- timeout,
- len(pending),
- )
- # These tasks outlive the gate. Their normal done-callback
- # only discards them from _background_tasks, so a LATER
- # failure would be silently swallowed. Attach a logging
- # callback so a background resume turn that fails after the
- # timeout is still recorded.
- for task in pending:
- task.add_done_callback(self._log_background_resume_result)
- else:
- # Non-positive timeout => opt out of the bound (historical
- # "wait forever" behaviour).
- await asyncio.gather(*tasks, return_exceptions=True)
- done = set(tasks)
- for task in done:
- if task.cancelled():
- continue
- exc = task.exception()
- if exc is not None:
- logger.debug(
- "startup auto-resume task failed",
- exc_info=(type(exc), exc, exc.__traceback__),
- )
- self._startup_restore_tasks = []
- drained = await self._drain_startup_restore_queue()
- self._startup_restore_in_progress = False
- if drained:
- logger.info("Drained %d inbound message(s) queued during startup restore", drained)
+ is_queue_mode = effective_mode == "queue"
+ is_steer_mode = effective_mode == "steer"
+ is_redirect_mode = effective_mode == "interrupt" and redirected
- @staticmethod
- def _log_background_resume_result(task: "asyncio.Task") -> None:
- """Done-callback for a boot-resume turn that outlived the
- startup-restore gate. Logs a late failure that would otherwise be
- swallowed once the task is discarded from ``_background_tasks``.
- Cancellation is expected (shutdown) and is not an error."""
- if task.cancelled():
- return
- exc = task.exception()
- if exc is not None:
- logger.debug(
- "background startup auto-resume task failed after gate release",
- exc_info=(type(exc), exc, exc.__traceback__),
- )
-
- async def _redeliver_pending_obligations(self) -> int:
- """Redeliver final responses recorded in the delivery ledger by a
- previous (now dead) gateway process.
-
- Runs at startup BEFORE ``_schedule_resume_pending_sessions``. A
- session with a recoverable obligation already produced its answer —
- the turn completed and only delivery is owed — so this method sends
- the stored text and clears ``resume_pending`` for that session,
- preventing the resume path from re-running (and re-paying for) a
- turn whose output we hold.
-
- Crash-ambiguity contract (see gateway/delivery_ledger.py):
- rows that were mid-send or previously rejected carry a visible
- recovered-reply marker so a possible duplicate is labeled, never
- silent. Returns the number of redeliveries attempted.
- """
- try:
- from gateway.delivery_ledger import (
- RECOVERED_MARKER,
- ledger_enabled,
- mark_delivered,
- mark_failed,
- sweep_recoverable,
- )
-
- if not ledger_enabled():
- return 0
- # Only claim rows we can actually send this boot: self.adapters
- # holds a platform only after its connect() succeeded, and each
- # claim spends one of the row's three redelivery attempts.
- _deliverable = {
- getattr(p, "value", str(p)) for p in self.adapters
- }
- claimed = await asyncio.to_thread(
- sweep_recoverable, None, deliverable_platforms=_deliverable
- )
- except Exception:
- logger.debug("delivery ledger sweep failed", exc_info=True)
- return 0
- if not claimed:
- return 0
-
- redelivered = 0
- for row in claimed:
- try:
- platform = Platform(row["platform"])
- except Exception:
- logger.debug(
- "obligation %s: unknown platform %r",
- row["obligation_id"], row.get("platform"),
- )
- continue
- adapter = self.adapters.get(platform)
- if adapter is None:
- # Platform not connected this boot — leave the row claimed;
- # attempts cap + stale cutoff bound the retries on later boots.
- continue
- content = row["content"]
- if row.get("needs_marker"):
- content = RECOVERED_MARKER + content
- metadata = (
- {"thread_id": row["thread_id"]} if row.get("thread_id") else None
- )
- try:
- result = await adapter.send(
- chat_id=row["chat_id"],
- content=content,
- metadata=metadata,
- )
- except Exception as send_err:
- logger.warning(
- "obligation %s: redelivery send raised: %s",
- row["obligation_id"], send_err,
- )
- result = None
+ # If not in queue/steer mode, interrupt the running agent immediately.
+ # This aborts in-flight tool calls and causes the agent loop to exit
+ # at the next check point.
+ if (
+ effective_mode == "interrupt"
+ and not redirected
+ and running_agent
+ and running_agent is not _AGENT_PENDING_SENTINEL
+ ):
try:
- if result is not None and getattr(result, "success", False):
- mark_delivered(row["obligation_id"])
- redelivered += 1
- logger.info(
- "Redelivered recovered final response to %s:%s "
- "(obligation %s, attempt %d)",
- row["platform"], row["chat_id"],
- row["obligation_id"], row["attempts"],
- )
- else:
- mark_failed(
- row["obligation_id"],
- str(getattr(result, "error", "") or "send failed"),
+ _interrupt_text = event.text
+ _media_urls = getattr(event, "media_urls", None) or []
+ if self._pending_event_audio_paths(event):
+ _interrupt_text, _ = await self._transcribe_and_echo_pending_voice(
+ event,
+ adapter,
+ event.source,
+ event.text or "",
+ log_context="Voice-busy-interrupt",
)
+ elif not _interrupt_text and _media_urls:
+ _interrupt_text = _build_media_placeholder(event)
+ running_agent.interrupt(_interrupt_text)
except Exception:
- logger.debug("delivery ledger update failed", exc_info=True)
+ pass # don't let interrupt failure block the ack
- # The answer reached (or was owed to) this session — don't ALSO
- # re-run the turn via the resume path.
- session_key = row.get("session_key") or ""
- if session_key:
- try:
- await self.async_session_store.clear_resume_pending(session_key)
- except Exception:
- logger.debug(
- "clear_resume_pending failed for %s", session_key,
- exc_info=True,
- )
- return redelivered
+ # Check if busy ack is disabled — skip sending but still process the input.
+ # Placed before debounce so we don't stamp a "last ack" timestamp that was
+ # never actually delivered.
+ busy_ack_enabled = os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() == "true"
+ if not busy_ack_enabled:
+ logger.debug("Busy ack suppressed for session %s", session_key)
+ return True # input still processed, just no ack sent
- def _schedule_resume_pending_sessions(self, platform=None) -> int:
- """Auto-continue fresh restart-interrupted sessions after startup.
+ # Debounce before consulting config-heavy display settings. Rapid
+ # follow-ups should be processed but should not trigger another config
+ # read just to discover that no ack will be sent.
+ _BUSY_ACK_COOLDOWN = 30
+ now = time.time()
+ last_ack = _busy_state.turn.busy_ack_ts if _busy_state else 0
+ if now - last_ack < _BUSY_ACK_COOLDOWN:
+ return True # interrupt sent (if not queue), ack already delivered recently
- ``resume_pending`` already preserves the transcript AND the existing
- ``_is_resume_pending`` branch in ``_handle_message_with_agent``
- injects a reason-aware recovery system note on the next turn. This
- method closes the UX gap by synthesizing that next turn once
- adapters are back online — the event text is empty so the existing
- injection path owns the wording and we never double up.
+ from gateway.display_config import resolve_display_setting
+ platform_key = _platform_config_key(event.source.platform)
- Adapters that are not yet ready (adapter missing from
- ``self.adapters``) are skipped silently; their sessions stay
- ``resume_pending`` and will auto-resume on the next real user
- message, or when the platform reconnects — the reconnect watcher
- calls this again scoped to that ``platform``.
+ # In steer mode the user's text has already been injected into the
+ # active run. Some mobile chat setups want that steering to be silent,
+ # like STT transcript echo suppression: keep the behavior, drop only
+ # the confirmation bubble.
+ if is_steer_mode:
+ steer_ack_env = os.environ.get("HERMES_GATEWAY_BUSY_STEER_ACK_ENABLED")
+ if steer_ack_env is not None:
+ steer_ack_enabled = steer_ack_env.strip().lower() in {"1", "true", "yes", "on"}
+ else:
+ steer_ack_enabled = bool(
+ resolve_display_setting(
+ _load_gateway_config(),
+ platform_key,
+ "busy_steer_ack_enabled",
+ True,
+ )
+ )
+ if not steer_ack_enabled:
+ logger.debug("Busy steer ack suppressed for session %s", session_key)
+ return True
- ``platform`` (a ``Platform``) restricts the pass to sessions that
- originated on that platform. The reconnect path passes it so a
- platform coming back online retries only its own sessions and never
- re-touches another platform's in-flight recoveries. Sessions whose
- agent is already running are skipped regardless, so a session
- scheduled at startup is never resumed a second time.
- """
- window = _auto_continue_freshness_window()
- try:
- with self.session_store._lock: # noqa: SLF001 — snapshot under lock
- self.session_store._ensure_loaded_locked() # noqa: SLF001
- candidates = [
- entry for entry in self.session_store._entries.values() # noqa: SLF001
- if entry.resume_pending
- and not entry.suspended
- and entry.origin is not None
- and entry.resume_reason in self._AUTO_RESUME_REASONS
- and (platform is None or entry.origin.platform == platform)
- ]
- except Exception as exc:
- logger.warning("Failed to enumerate resume-pending sessions: %s", exc)
- return 0
+ self._session_state(session_key).turn.busy_ack_ts = now
- # Defense-3 (#30719): break the SIGTERM-respawn loop. Only count this
- # boot when there are restart-interrupted sessions to resume — a clean
- # boot must not accrue toward the breaker. If too many such boots have
- # happened in the configured window, skip auto-resume for THIS boot:
- # the gateway still comes up and serves real inbound messages, it just
- # stops replaying the session that keeps killing it. The session stays
- # resume_pending, so a real user message can still continue it (a human
- # is now in the loop). Defenses 1-2 cover the cron/CLI/terminal paths;
- # this catches every other SIGTERM source (e.g. a raw `terminal(
- # "launchctl kickstart ai.hermes.gateway")`).
- if candidates:
- try:
- from gateway import restart_loop_guard as _rlg
+ # Build a status-rich acknowledgment. Mobile chat defaults keep this
+ # terse; detailed iteration/tool state is still available in logs and
+ # can be opted in per platform via display.platforms.<platform>.busy_ack_detail.
+ status_parts = []
+ busy_ack_detail_enabled = bool(
+ resolve_display_setting(
+ _load_gateway_config(),
+ _platform_config_key(event.source.platform),
+ "busy_ack_detail",
+ True,
+ )
+ )
- _max_restarts, _window = self._restart_loop_guard_config()
- if _rlg.check_and_record(_max_restarts, _window):
- return 0
- except Exception as exc: # noqa: BLE001 — breaker must fail OPEN
- logger.debug("Restart-loop guard check skipped: %s", exc)
+ if busy_ack_detail_enabled and running_agent and running_agent is not _AGENT_PENDING_SENTINEL:
+ try:
+ summary = running_agent.get_activity_summary()
+ iteration = summary.get("api_call_count", 0)
+ max_iter = summary.get("max_iterations", 0)
+ current_tool = summary.get("current_tool")
+ start_ts = _busy_state.turn.started_ts if _busy_state else 0
+ if start_ts:
+ elapsed_min = int((now - start_ts) / 60)
+ if elapsed_min > 0:
+ status_parts.append(f"{elapsed_min} min elapsed")
+ if max_iter:
+ status_parts.append(f"iteration {iteration}/{max_iter}")
+ if current_tool:
+ status_parts.append(f"running: {current_tool}")
+ except Exception:
+ pass
- now = datetime.now()
- scheduled = 0
- for entry in candidates:
- marker = entry.last_resume_marked_at or entry.updated_at
- if marker is not None and (now - marker).total_seconds() > window:
- continue
-
- # Already being resumed (e.g. scheduled at startup and still
- # in-flight) — don't synthesize a second continuation turn.
- if self._is_session_running(entry.session_key):
- continue
+ status_detail = f" ({', '.join(status_parts)})" if status_parts else ""
+ if is_steer_mode:
+ message = (
+ f"⏩ Steered into current run{status_detail}. "
+ f"Your message arrives after the next tool call."
+ )
+ elif is_redirect_mode:
+ message = (
+ f"↪ Redirected current run{status_detail}. "
+ f"I'll adjust using your correction."
+ )
+ elif is_queue_mode and demoted_for_subagents:
+ # #30170 — explain the demotion so the user knows their
+ # follow-up didn't accidentally kill the subagent and
+ # discovers `/stop` as the explicit escape hatch.
+ message = (
+ f"⏳ Subagent working{status_detail} — your message is queued for "
+ f"when it finishes (use /stop to cancel everything)."
+ )
+ elif is_queue_mode and demoted_for_compression:
+ message = (
+ f"⏳ Compressing context{status_detail} — your message is queued for "
+ f"when it finishes (use /stop to cancel everything)."
+ )
+ elif is_queue_mode:
+ message = (
+ f"⏳ Queued for the next turn{status_detail}. "
+ f"I'll respond once the current task finishes."
+ )
+ else:
+ message = (
+ f"⚡ Interrupting current task{status_detail}. "
+ f"I'll respond to your message shortly."
+ )
- source = entry.origin
- adapter = self._adapter_for_source(source)
- if adapter is None:
- logger.debug(
- "Skipping auto-resume for %s: adapter not ready for %s",
- entry.session_key,
- getattr(source.platform, "value", source.platform),
+ # First-touch onboarding: the very first time a user sends a message
+ # while the agent is busy, append a one-time hint explaining the
+ # queue/interrupt knob. Flag is persisted to config.yaml so it never
+ # fires again on this install.
+ try:
+ from agent.onboarding import (
+ BUSY_INPUT_FLAG,
+ busy_input_hint_gateway,
+ is_seen,
+ mark_seen,
+ )
+ _user_cfg = _load_gateway_config()
+ if not is_seen(_user_cfg, BUSY_INPUT_FLAG):
+ if is_steer_mode:
+ _hint_mode = "steer"
+ elif is_queue_mode:
+ _hint_mode = "queue"
+ elif is_redirect_mode:
+ _hint_mode = "redirect"
+ else:
+ _hint_mode = "interrupt"
+ message = (
+ f"{message}\n\n"
+ f"{busy_input_hint_gateway(_hint_mode)}"
)
- continue
+ mark_seen(_hermes_home / "config.yaml", BUSY_INPUT_FLAG)
+ except Exception as _onb_err:
+ logger.debug("Failed to apply busy-input onboarding hint: %s", _onb_err)
- # Validate the session owner against the current allowlist
- # before auto-resuming. A session created before
- # TELEGRAM_ALLOWED_USERS (or equivalent) was configured, or
- # before the owner was removed from it, must not silently
- # receive a full agent response on gateway restart just
- # because it has a resume-pending marker (issue #23778).
- try:
- if not self._is_user_authorized(source):
- logger.warning(
- "Skipping auto-resume for %s: session owner is no "
- "longer authorized under the current allowlist",
- entry.session_key,
- )
- continue
- except Exception as exc:
- logger.warning(
- "Skipping auto-resume for %s: authorization check failed: %s",
- entry.session_key, exc,
- )
- continue
+ reply_anchor = self._reply_anchor_for_event(event)
+ thread_meta = self._thread_metadata_for_source(event.source, reply_anchor)
+ try:
+ await adapter._send_with_retry(
+ chat_id=event.source.chat_id,
+ content=message,
+ reply_to=(
+ reply_anchor
+ if event.source.platform == Platform.TELEGRAM
+ and event.source.chat_type == "dm"
+ and event.source.thread_id
+ else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id)
+ ),
+ metadata=thread_meta,
+ )
+ except Exception as e:
+ logger.debug("Failed to send busy-ack: %s", e)
- # Claim the session slot *before* spawning the task so that an
- # inbound message arriving between task creation and the task's
- # first await (where _process_message_background sets the real
- # sentinel) sees the slot as occupied and queues behind it
- # instead of spinning up a duplicate AIAgent (#45456).
- _resume_state = self._session_state(entry.session_key)
- _resume_state.turn.agent = _AGENT_PENDING_SENTINEL
- _resume_state.turn.started_ts = time.time()
- self._persist_active_agents()
+ return True
- # Empty-text internal event — the _is_resume_pending branch in
- # _handle_message_with_agent prepends the proper reason-aware
- # system note before the turn runs.
- event = MessageEvent(
- text="",
- message_type=MessageType.TEXT,
- source=source,
- internal=True,
- )
- task = asyncio.create_task(
- self._run_startup_resume_event(adapter, event, entry.session_key)
- )
- self._background_tasks.add(task)
- task.add_done_callback(self._background_tasks.discard)
- if getattr(self, "_startup_restore_in_progress", False):
- tasks = getattr(self, "_startup_restore_tasks", None)
- if tasks is None:
- tasks = []
- self._startup_restore_tasks = tasks
- tasks.append(task)
- scheduled += 1
- if scheduled:
- logger.info(
- "Scheduled auto-resume for %d restart-interrupted session(s)",
- scheduled,
- )
- return scheduled
+ async def _drain_active_agents(self, timeout: float) -> tuple[Dict[str, Any], bool]:
+ snapshot = self._snapshot_running_agents()
+ last_active_count = self._running_agent_count()
+ last_cron_count = self._active_cron_job_count()
+ last_api_count = self._active_api_run_count()
+ last_status_at = 0.0
- def _startup_should_abort(self) -> bool:
- return (
- self._restart_requested
- or self._draining
- or self._shutdown_event.is_set()
+ def _maybe_update_status(force: bool = False) -> None:
+ nonlocal last_active_count, last_cron_count, last_api_count, last_status_at
+ now = asyncio.get_running_loop().time()
+ active_count = self._running_agent_count()
+ cron_count = self._active_cron_job_count()
+ api_count = self._active_api_run_count()
+ if (
+ force
+ or active_count != last_active_count
+ or cron_count != last_cron_count
+ or api_count != last_api_count
+ or (now - last_status_at) >= 1.0
+ ):
+ self._update_runtime_status("draining")
+ last_active_count = active_count
+ last_cron_count = cron_count
+ last_api_count = api_count
+ last_status_at = now
+
+ # Cron jobs run on the scheduler's own thread pool, outside
+ # ``self._running_agents`` — fold their in-flight count into the
+ # same wait/timeout this method already applies to chat sessions,
+ # or a cron job's tool work gets killed with zero warning the
+ # instant it's the only active thing running (#60432).
+ # API-server / desk sessions have the same structural gap (#63529).
+ if not self._running_agents and last_cron_count == 0 and last_api_count == 0:
+ _maybe_update_status(force=True)
+ return snapshot, False
+
+ _maybe_update_status(force=True)
+ if timeout <= 0:
+ return snapshot, True
+
+ deadline = asyncio.get_running_loop().time() + timeout
+ while (
+ (
+ len(self._running_agents)
+ or self._active_cron_job_count()
+ or self._active_api_run_count()
+ )
+ and asyncio.get_running_loop().time() < deadline
+ ):
+ _maybe_update_status()
+ await asyncio.sleep(0.1)
+ timed_out = (
+ bool(len(self._running_agents))
+ or bool(self._active_cron_job_count())
+ or bool(self._active_api_run_count())
)
+ _maybe_update_status(force=True)
+ return snapshot, timed_out
- async def _abort_startup_if_shutdown_requested(
- self,
- adapter: Optional[BasePlatformAdapter] = None,
- platform: Optional[Platform] = None,
- ) -> bool:
- """Clean up and exit startup when restart/shutdown begins mid-startup."""
- if not self._startup_should_abort():
- return False
- if adapter is not None and platform is not None:
+ def _interrupt_running_agents(self, reason: str) -> None:
+ for session_key, agent in list(self._running_agents.items()):
+ if agent is _AGENT_PENDING_SENTINEL:
+ continue
try:
- await adapter.cancel_background_tasks()
+ agent.interrupt(reason)
+ logger.debug("Interrupted running agent for session %s during shutdown", session_key)
except Exception as e:
- logger.debug("✗ %s background-task cancel error: %s", platform.value, e)
- await self._safe_adapter_disconnect(adapter, platform)
- stop_task = self._stop_task
- current_task = asyncio.current_task()
- if stop_task is not None and stop_task is not current_task:
- await stop_task
- elif not self._shutdown_event.is_set():
- await self.stop(
- restart=self._restart_requested,
- detached_restart=self._restart_detached,
- service_restart=self._restart_via_service,
- )
- return True
+ logger.debug("Failed interrupting agent during shutdown: %s", e)
- def _start_loop_liveness_guards(self, loop: asyncio.AbstractEventLoop) -> None:
- """Arm the selector floor and out-of-loop watchdog before adapters.
+ async def _notify_active_sessions_of_shutdown(self) -> None:
+ """Send shutdown/restart notifications to active chats and home channels.
- Disabled entirely with ``gateway.loop_watchdog: false`` in config.yaml
- (no env override — config-only knob, #69089).
+ Called at the very start of stop() — adapters are still connected so
+ messages can be delivered. Best-effort: individual send failures are
+ logged and swallowed so they never block the shutdown sequence.
"""
- config = getattr(self, "config", None)
- if config is not None and not getattr(config, "loop_watchdog", True):
- return
- if getattr(self, "_loop_floor_timer_handle", None) is None:
- try:
- self._loop_floor_timer_handle = _arm_loop_floor_timer(loop)
- except Exception:
- logger.debug("Failed to arm gateway loop floor timer", exc_info=True)
+ active = self._snapshot_running_agents()
+ restart_source = self._restart_command_source if self._restart_requested else None
- watchdog = getattr(self, "_loop_liveness_watchdog", None)
- if watchdog is None or not watchdog.is_alive():
- try:
- self._loop_liveness_watchdog = start_loop_liveness_watchdog(loop)
- except Exception:
- logger.debug("Failed to start gateway loop liveness watchdog", exc_info=True)
+ action = "restarting" if self._restart_requested else "shutting down"
+ hint = (
+ "Your current task will be interrupted. "
+ "Send any message after restart and I'll try to resume where you left off."
+ if self._restart_requested
+ else "Your current task will be interrupted."
+ )
+ msg = f"⚠️ Gateway {action} — {hint}"
- def _stop_loop_liveness_guards(self) -> None:
- """Disarm lifetime liveness guards before shutdown can load the loop."""
- watchdog = getattr(self, "_loop_liveness_watchdog", None)
- self._loop_liveness_watchdog = None
- if watchdog is not None:
+ notified: set[tuple[str, str, Optional[str]]] = set()
+ for session_key in active:
+ source = None
try:
- watchdog.stop()
- except Exception:
- logger.debug("Failed to stop gateway loop liveness watchdog", exc_info=True)
+ if getattr(self, "session_store", None) is not None:
+ await self.async_session_store._ensure_loaded()
+ entry = self.session_store._entries.get(session_key)
+ source = getattr(entry, "origin", None) if entry else None
+ except Exception as e:
+ logger.debug(
+ "Failed to load session origin for shutdown notification %s: %s",
+ session_key,
+ e,
+ )
- floor_timer = getattr(self, "_loop_floor_timer_handle", None)
- self._loop_floor_timer_handle = None
- if floor_timer is not None:
- try:
- floor_timer.cancel()
- except Exception:
- logger.debug("Failed to cancel gateway loop floor timer", exc_info=True)
+ if source is None:
+ source = self._get_cached_session_source(session_key)
+
+ if source is not None:
+ platform_str = source.platform.value
+ chat_id = str(source.chat_id)
+ thread_id = source.thread_id
+ else:
+ # Fall back to parsing the session key when no persisted
+ # origin is available (legacy sessions/tests).
+ _parsed = _parse_session_key(session_key)
+ if not _parsed:
+ continue
+ platform_str = _parsed["platform"]
+ chat_id = _parsed["chat_id"]
+ thread_id = _parsed.get("thread_id")
+
+ # Deduplicate only identical delivery targets. Thread/topic-aware
+ # platforms can share a parent chat while still routing to distinct
+ # destinations via metadata.
+ dedup_key = (platform_str, chat_id, str(thread_id) if thread_id else None)
+ if dedup_key in notified:
+ continue
- async def start(self) -> bool:
- """
- Start the gateway and all configured platform adapters.
-
- Returns True if at least one adapter connected successfully.
- """
- logger.info("Starting Hermes Gateway...")
- # Enable faulthandler for stack dumps on freezes/crashes (#70344).
- # Falls back to a log file when sys.stderr is None (Windows VBS /
- # pythonw / detached service) — otherwise the gateway would die
- # here and take every adapter offline. See #71671.
- try:
- faulthandler.enable()
- except (RuntimeError, ValueError, OSError):
try:
- _fh_log_dir = getattr(self.config, "log_dir", None) or os.path.join(
- str(get_hermes_home()),
- "logs",
+ platform = Platform(platform_str)
+ adapter = self.adapters.get(platform)
+ if not adapter:
+ continue
+
+ platform_cfg = self.config.platforms.get(platform)
+ if platform_cfg is not None and not platform_cfg.gateway_restart_notification:
+ logger.info(
+ "Shutdown notification suppressed for active session: %s has gateway_restart_notification=false",
+ platform_str,
+ )
+ continue
+
+ reply_to_message_id = getattr(source, "message_id", None) if source is not None else None
+ if reply_to_message_id is None and restart_source is not None:
+ try:
+ restart_platform = restart_source.platform.value
+ restart_chat_id = str(restart_source.chat_id)
+ restart_thread_id = str(restart_source.thread_id) if restart_source.thread_id else None
+ if (restart_platform, restart_chat_id, restart_thread_id) == dedup_key:
+ reply_to_message_id = getattr(restart_source, "message_id", None)
+ except Exception:
+ pass
+
+ metadata = self._thread_metadata_for_target(
+ platform,
+ chat_id,
+ thread_id,
+ chat_type=getattr(source, "chat_type", None) if source is not None else None,
+ reply_to_message_id=reply_to_message_id,
+ adapter=adapter,
)
- os.makedirs(_fh_log_dir, exist_ok=True)
- _fh_enable_path = os.path.join(_fh_log_dir, "gateway_faulthandler.log")
- _fh_enable_file = open(_fh_enable_path, "a", encoding="utf-8")
- faulthandler.enable(file=_fh_enable_file, all_threads=True)
- except Exception:
- logger.debug("faulthandler.enable() unavailable", exc_info=True)
- # Also dump stacks to a rotating file for off-line analysis when
- # the gateway is running under a service manager that doesn't
- # capture stderr.
- # faulthandler.register() and SIGUSR2 are POSIX-only; skip the
- # signal-triggered file dump on Windows (faulthandler.enable()
- # above still covers fatal-error dumps there).
- _sigusr2 = getattr(signal, "SIGUSR2", None)
- if _sigusr2 is not None and hasattr(faulthandler, "register"):
- try:
- _log_dir = getattr(self.config, "log_dir", None) or os.path.join(
- str(get_hermes_home()),
- "logs",
+
+ result = await adapter.send(chat_id, msg, metadata=metadata)
+ if result is not None and getattr(result, "success", True) is False:
+ logger.debug(
+ "Failed to send shutdown notification to %s:%s: %s",
+ platform_str,
+ chat_id,
+ getattr(result, "error", "send returned success=False"),
+ )
+ continue
+
+ notified.add(dedup_key)
+ logger.info(
+ "Sent shutdown notification to active chat %s:%s",
+ platform_str, chat_id,
)
- _faulthandler_path = os.path.join(_log_dir, "gateway_faulthandler.log")
- os.makedirs(_log_dir, exist_ok=True)
- _fh = open(_faulthandler_path, "a", encoding="utf-8")
- faulthandler.register(
- _sigusr2,
- file=_fh,
- all_threads=True,
- chain=True,
+ except Exception as e:
+ logger.debug(
+ "Failed to send shutdown notification to %s:%s: %s",
+ platform_str, chat_id, e,
)
- except Exception:
- logger.debug("Could not set up faulthandler file logging", exc_info=True)
- try:
- self._gateway_loop = asyncio.get_running_loop()
- except RuntimeError:
- self._gateway_loop = None
- if self._gateway_loop is not None:
- self._start_loop_liveness_guards(self._gateway_loop)
- logger.info("Session storage: %s", self.config.sessions_dir)
+ if self._restart_requested and restart_source is not None:
+ logger.debug("Skipping home-channel shutdown notifications for in-chat restart")
+ return
- # Sanity-check that systemd's TimeoutStopSec covers our drain
- # window. When the user upgraded hermes-agent without re-running
- # ``hermes setup``, their unit file may still encode the old
- # default — in which case SIGKILL hits mid-drain and looks like
- # a phantom kill in the journal. Best-effort, never raises.
+ # Suppress ONLY the home-channel broadcast when the drain that is ending
+ # in this shutdown asked us to be quiet (e.g. a NAS auto-update image
+ # migration — drain-gated, then the machine is recreated). On the
+ # always-on Hermes Cloud fleet that broadcast would otherwise fire on
+ # every routine auto-update, spamming home channels with operator-
+ # flavoured "gateway shutting down" pings the user doesn't care about.
+ # The per-active-session interrupt pings above are deliberately NOT
+ # gated: on a drained shutdown they're empty by construction, and in the
+ # force-interrupt (deadline-exceeded) case they carry the genuinely
+ # useful "your task was cut off, message me to resume" hint. The flag is
+ # only honoured for a CURRENT-epoch marker (drain_notification_suppressed
+ # reuses the NS-570 staleness check), so an orphaned marker can never
+ # silence a fresh gateway's legitimate broadcast.
try:
- from gateway.shutdown_forensics import check_systemd_timing_alignment
- _alignment = check_systemd_timing_alignment(self._restart_drain_timeout)
- if _alignment is not None and _alignment.get("mismatch"):
- logger.warning(
- "Stale systemd unit detected: %s has TimeoutStopSec=%.0fs but "
- "drain_timeout=%.0fs (expected >=%.0fs). systemd may SIGKILL the "
- "gateway mid-drain. Run `hermes gateway install --force` "
- "to regenerate the unit, or shorten agent.restart_drain_timeout.",
- _alignment.get("unit", "(unknown)"),
- _alignment["timeout_stop_sec"],
- _alignment["drain_timeout"],
- _alignment["expected_min"],
+ from gateway.drain_control import drain_notification_suppressed
+ if drain_notification_suppressed():
+ logger.info(
+ "Home-channel shutdown broadcast suppressed by drain marker "
+ "(suppress_notification=true)"
)
- except Exception as _e:
- logger.debug("check_systemd_timing_alignment failed: %s", _e)
- # Log the resolved max_iterations budget so operators can verify the
- # config.yaml → env bridge did the right thing at a glance (instead
- # of silently running at a stale .env value for weeks).
- try:
- _effective_max_iter = int(os.getenv("HERMES_MAX_ITERATIONS", "500"))
- logger.info(
- "Agent budget: max_iterations=%d (agent.max_turns from config.yaml, "
- "or HERMES_MAX_ITERATIONS from .env, or default 500)",
- _effective_max_iter,
- )
- except Exception:
- pass
- # Redaction status: ON by default (#17691). Surface a prominent
- # warning if an operator has explicitly opted out so they don't
- # forget the downgrade is active — the redactor snapshots its
- # state at import time, so this log line is the source of truth
- # for this process's lifetime.
- try:
- _redact_raw = os.getenv("HERMES_REDACT_SECRETS", "true")
- _redact_on = _redact_raw.lower() in {"1", "true", "yes", "on"}
- if _redact_on:
+ return
+ except Exception as e:
+ # Never let the suppression check block the shutdown broadcast —
+ # fail toward the louder, more-visible behaviour.
+ logger.debug("drain_notification_suppressed check failed: %s", e)
+
+ # Snapshot adapters up front: adapter.send() can hit a fatal error
+ # path that pops the adapter from self.adapters (see _handle_fatal
+ # elsewhere), which would otherwise trigger
+ # ``RuntimeError: dictionary changed size during iteration`` —
+ # observed in a user report during gateway shutdown.
+ for platform, adapter in list(self.adapters.items()):
+ home = self.config.get_home_channel(platform)
+ if not home or not home.chat_id:
+ continue
+
+ platform_cfg = self.config.platforms.get(platform)
+ if platform_cfg is not None and not platform_cfg.gateway_restart_notification:
logger.info(
- "Secret redaction: ENABLED (tool output, logs, and chat "
- "responses are scrubbed before delivery)"
+ "Shutdown notification suppressed for home channel: %s has gateway_restart_notification=false",
+ platform.value,
)
- else:
- logger.warning(
- "Secret redaction: DISABLED (HERMES_REDACT_SECRETS=%s). "
- "API keys and tokens may appear verbatim in chat output, "
- "session JSONs, and logs. Set security.redact_secrets: true "
- "in config.yaml to re-enable.",
- _redact_raw,
+ continue
+
+ dedup_key = (platform.value, str(home.chat_id), str(home.thread_id) if home.thread_id else None)
+ if dedup_key in notified:
+ continue
+
+ try:
+ metadata = self._thread_metadata_for_target(
+ platform,
+ home.chat_id,
+ home.thread_id,
+ adapter=adapter,
)
- except Exception:
- pass
- try:
- from hermes_cli.profiles import get_active_profile_name
- _profile = get_active_profile_name()
- if _profile and _profile != "default":
- logger.info("Active profile: %s", _profile)
- except Exception:
- pass
- try:
- from gateway.status import write_runtime_status
- write_runtime_status(gateway_state="starting", exit_reason=None)
- except Exception:
- pass
- try:
- from hermes_cli.config import load_config
- from agent.monitoring.gateway_health_export import start_gateway_health_export
- self._gateway_health_export_runtime = start_gateway_health_export(load_config())
- if getattr(self._gateway_health_export_runtime, "enabled", False):
- logger.info("Gateway health OTLP export: enabled")
- except Exception:
- logger.debug("gateway health OTLP export startup failed", exc_info=True)
+ if metadata:
+ result = await adapter.send(str(home.chat_id), msg, metadata=metadata)
+ else:
+ result = await adapter.send(str(home.chat_id), msg)
+ if result is not None and getattr(result, "success", True) is False:
+ logger.debug(
+ "Failed to send shutdown notification to home channel %s:%s: %s",
+ platform.value,
+ home.chat_id,
+ getattr(result, "error", "send returned success=False"),
+ )
+ continue
- # Log any active supply-chain security advisories. Operators see this
- # in gateway.log and `hermes status` surfaces it; we do NOT block
- # startup or surface it inline to user messages, since the gateway
- # operator is the one who can act on it (uninstall the package,
- # rotate credentials). See hermes_cli/security_advisories.py.
- try:
- from hermes_cli.security_advisories import (
- detect_compromised,
- gateway_log_message,
- )
- _adv_hits = detect_compromised()
- _adv_msg = gateway_log_message(_adv_hits)
- if _adv_msg:
- logger.warning("%s", _adv_msg)
- logger.warning(
- "Run `hermes doctor` on the gateway host for full "
- "remediation steps."
+ notified.add(dedup_key)
+ logger.info(
+ "Sent shutdown notification to home channel %s:%s",
+ platform.value,
+ home.chat_id,
+ )
+ except Exception as e:
+ logger.debug(
+ "Failed to send shutdown notification to home channel %s:%s: %s",
+ platform.value,
+ home.chat_id,
+ e,
)
- except Exception:
- logger.debug(
- "security advisory check failed at gateway startup",
- exc_info=True,
- )
- if await self._abort_startup_if_shutdown_requested():
- return True
-
- # Warn if no user allowlists are configured and open access is not opted in
- _builtin_allowed_vars = (
- "TELEGRAM_ALLOWED_USERS", "DISCORD_ALLOWED_USERS",
- "WHATSAPP_ALLOWED_USERS", "WHATSAPP_CLOUD_ALLOWED_USERS",
- "SLACK_ALLOWED_USERS",
- "SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
- "TELEGRAM_GROUP_ALLOWED_USERS",
- "TELEGRAM_GROUP_ALLOWED_CHATS",
- "EMAIL_ALLOWED_USERS",
- "SMS_ALLOWED_USERS", "MATTERMOST_ALLOWED_USERS",
- "MATRIX_ALLOWED_USERS", "DINGTALK_ALLOWED_USERS",
- "FEISHU_ALLOWED_USERS",
- "WECOM_ALLOWED_USERS",
- "WECOM_CALLBACK_ALLOWED_USERS",
- "WEIXIN_ALLOWED_USERS",
- "BLUEBUBBLES_ALLOWED_USERS",
- "QQ_ALLOWED_USERS",
- "YUANBAO_ALLOWED_USERS",
- "GATEWAY_ALLOWED_USERS",
- )
- _builtin_allow_all_vars = (
- "TELEGRAM_ALLOW_ALL_USERS", "DISCORD_ALLOW_ALL_USERS",
- "WHATSAPP_ALLOW_ALL_USERS", "WHATSAPP_CLOUD_ALLOW_ALL_USERS",
- "SLACK_ALLOW_ALL_USERS",
- "SIGNAL_ALLOW_ALL_USERS", "EMAIL_ALLOW_ALL_USERS",
- "SMS_ALLOW_ALL_USERS", "MATTERMOST_ALLOW_ALL_USERS",
- "MATRIX_ALLOW_ALL_USERS", "DINGTALK_ALLOW_ALL_USERS",
- "FEISHU_ALLOW_ALL_USERS",
- "WECOM_ALLOW_ALL_USERS",
- "WECOM_CALLBACK_ALLOW_ALL_USERS",
- "WEIXIN_ALLOW_ALL_USERS",
- "BLUEBUBBLES_ALLOW_ALL_USERS",
- "QQ_ALLOW_ALL_USERS",
- "YUANBAO_ALLOW_ALL_USERS",
- )
- # Also pick up plugin-registered platforms — each entry can declare
- # its own allowed_users_env / allow_all_env, so the warning stays
- # accurate as plugins like IRC come online.
- _plugin_allowed_vars: tuple = ()
- _plugin_allow_all_vars: tuple = ()
- try:
- from gateway.platform_registry import platform_registry
- _plugin_allowed_vars = tuple(
- e.allowed_users_env for e in platform_registry.plugin_entries()
- if e.allowed_users_env
- )
- _plugin_allow_all_vars = tuple(
- e.allow_all_env for e in platform_registry.plugin_entries()
- if e.allow_all_env
- )
- except Exception:
- pass
- _any_allowlist = any(
- os.getenv(v) for v in _builtin_allowed_vars + _plugin_allowed_vars
- )
- _allow_all = os.getenv("GATEWAY_ALLOW_ALL_USERS", "").lower() in {"true", "1", "yes"} or any(
- os.getenv(v, "").lower() in {"true", "1", "yes"}
- for v in _builtin_allow_all_vars + _plugin_allow_all_vars
- )
- if not _any_allowlist and not _allow_all:
- logger.warning(
- "No env user allowlists configured. Messaging platforms default to "
- "pairing/allowlist policies and will deny unknown senders unless you "
- "configure platform allowlists (e.g., TELEGRAM_ALLOWED_USERS=your_id) "
- "or explicitly opt in with GATEWAY_ALLOW_ALL_USERS=true plus "
- "dm_policy/group_policy: open on the platform."
- )
- reason = _own_policy_open_startup_violation(self.config)
- if reason:
- platform_value = reason.split(":", 1)[0]
- allow_all_env = None
- for platform, open_env in _OWN_POLICY_OPEN_ENV.items():
- if platform.value == platform_value:
- allow_all_env = open_env[2]
- break
- logger.error(
- "Refusing to start: %s has dm_policy/group_policy set to 'open' "
- "but neither GATEWAY_ALLOW_ALL_USERS nor %s is enabled.",
- platform_value,
- allow_all_env or "a platform allow-all flag",
- )
+ async def _finalize_shutdown_agents(self, active_agents: Dict[str, Any]) -> None:
+ for agent in active_agents.values():
+ # Persist any in-flight transcript to the SQLite session store
+ # before teardown (#13121). An agent forcibly interrupted by the
+ # drain-timeout escalation may never reach
+ # ``turn_finalizer.finalize_turn`` (the only place that flushes the
+ # turn to state.db) — e.g. it was blocked in a tool call that did
+ # not abort within the post-interrupt grace window. Its in-flight
+ # tool rounds live only in the in-memory ``_session_messages``
+ # (refreshed per tool round in ``conversation_loop`` but never
+ # written to SQLite mid-turn), so the immediate pre-restart turn is
+ # silently dropped from ``load_transcript()`` on resume. Flushing
+ # here closes that gap; the resume_pending / fresh-tool-tail
+ # branches in ``_handle_message_with_agent`` already expect a
+ # transcript whose tail may be a pending tool result. The flush is
+ # idempotent (identity-tracked in ``_flush_messages_to_session_db``),
+ # so agents that DID finish gracefully re-flush nothing.
try:
- from gateway.status import write_runtime_status
- write_runtime_status(gateway_state="startup_failed", exit_reason=reason)
+ _flush = getattr(agent, "_flush_messages_to_session_db", None)
+ _session_messages = getattr(agent, "_session_messages", None)
+ if callable(_flush) and isinstance(_session_messages, list) and _session_messages:
+ # Strip private empty-response retry scaffolding from the
+ # tail first, mirroring the graceful ``_persist_session``
+ # path, so a resumed turn doesn't replay synthetic recovery
+ # nudges.
+ _strip = getattr(
+ agent, "_drop_trailing_empty_response_scaffolding", None
+ )
+ if callable(_strip):
+ try:
+ _strip(_session_messages)
+ except Exception:
+ pass
+ try:
+ _flush(_session_messages)
+ except Exception as _flush_err:
+ # The in-memory transcript could not be persisted
+ # (e.g. FTS/SQLite index corruption — #72680). A plain
+ # debug log loses the conversation permanently when the
+ # process exits. Dump the live agent history to an
+ # external JSON recovery snapshot so an operator can
+ # salvage it after repairing state.db. The flush is
+ # non-fatal; shutdown must never block on a best-effort
+ # backup.
+ logger.warning(
+ "Shutdown transcript flush failed (%s); preserving "
+ "%d in-memory message(s) to recovery snapshot",
+ _flush_err,
+ len(_session_messages),
+ )
+ from gateway.shutdown_flush import flush_agent_history_to_file
+ flush_agent_history_to_file(
+ getattr(agent, "session_id", None),
+ _session_messages,
+ )
+ except Exception as _e:
+ logger.debug("Shutdown transcript flush failed: %s", _e)
+ try:
+ from hermes_cli.lifecycle import finalize_session
+ finalize_session(
+ session_id=getattr(agent, "session_id", None),
+ platform="gateway",
+ reason="shutdown",
+ )
except Exception:
pass
- self._request_clean_exit(reason)
- return True
-
- # Discover Python plugins before shell hooks so plugin block
- # decisions take precedence in tie cases. The CLI startup path
- # does this via an explicit call in hermes_cli/main.py; the
- # gateway lazily imports run_agent inside per-request handlers,
- # so the discover_plugins() side-effect in model_tools.py is NOT
- # guaranteed to have run by the time we reach this point.
- try:
- from hermes_cli.plugins import discover_plugins
- discover_plugins()
- except Exception:
- logger.warning(
- "plugin discovery failed at gateway startup", exc_info=True,
+ # Off-loop + bounded: a wedged memory provider here used to hang
+ # the whole shutdown so SIGTERM never completed (#53175).
+ await self._cleanup_agent_resources_off_loop(
+ agent, context="shutdown finalize"
)
- # Register the generic relay adapter when a connector relay URL is
- # configured (GATEWAY_RELAY_URL / gateway.relay_url). No URL -> no-op, so
- # direct/single-tenant deployments are unaffected. When configured, the
- # adapter dials the connector over a WebSocket, negotiates its capability
- # descriptor at handshake, and bridges inbound/outbound like any platform.
- try:
- from gateway.relay import (
- register_relay_adapter,
- relay_url,
- self_provision_relay,
- send_relay_policy,
- )
+ def _should_emit_long_running_notification(
+ self,
+ session_key: Optional[str],
+ agent: Any,
+ executor_task: Optional[Any],
+ ) -> bool:
+ """Only emit the heartbeat while this task still owns the live run.
- # Boot-time relay self-provision: resolve the agent's NAS token ->
- # POST /relay/provision -> set GATEWAY_RELAY_* in os.environ BEFORE
- # registration reads them. No-op when relay is unconfigured, a secret
- # is already pinned, or no NAS token resolves (self-hosted, unenrolled).
- # Never raises.
- self_provision_relay()
+ Guards against a stale ``running: delegate_task`` heartbeat outliving the
+ run that started it: stop once the executor finishes, the agent is gone,
+ or the session key has been rebound to a different live agent (e.g. the
+ user sent ``/new`` and a fresh agent took the slot mid-run, #12029).
+ """
+ if agent is None:
+ return False
+ if executor_task is not None and executor_task.done():
+ return False
+ if session_key:
+ _hb_state = self._peek_session_state(session_key)
+ if (_hb_state.turn.agent if _hb_state else None) is not agent:
+ return False
+ return True
- if register_relay_adapter():
- logger.info("relay adapter registered (connector at %s)", relay_url())
- # Declare this gateway's relevance policy (mention-gating /
- # free-response / allow-bots) to the connector so the SAME
- # behavior governs relay delivery (Phase 6 Unit ζ). Runs after
- # the secret is resolved; never raises, never blocks boot.
- send_relay_policy()
- except Exception:
- logger.warning(
- "relay adapter registration failed at gateway startup", exc_info=True,
- )
+ # Upper bound on off-loop agent-resource cleanup invoked from coroutines
+ # running on the gateway's event loop (session-expiry sweep, in-turn
+ # cache-hygiene re-eviction). _cleanup_agent_resources is synchronous and
+ # can block for a long time (agent.close() does subprocess teardown;
+ # shutdown_memory_provider() may do network/SQLite IO via a memory plugin).
+ # Calling it inline wedges the whole loop — the bot goes silent, the
+ # runtime-status updated_at heartbeat freezes, and SIGTERM cannot be
+ # serviced (#53175). Offload to a worker thread under this timeout so the
+ # loop is never blocked; mirrors the /new reset path's fix (#35994).
+ _CLEANUP_TIMEOUT_S = 30.0
- # Register declarative shell hooks from cli-config.yaml. Gateway
- # has no TTY, so consent has to come from one of the three opt-in
- # channels (--accept-hooks on launch, HERMES_ACCEPT_HOOKS env var,
- # or hooks_auto_accept: true in config.yaml). We pass
- # accept_hooks=False here and let register_from_config resolve
- # the effective value from env + config itself — the CLI-side
- # registration already honored --accept-hooks, and re-reading
- # hooks_auto_accept here would just duplicate that lookup.
- # Failures are logged but must never block gateway startup.
- try:
- from hermes_cli.config import load_config
- from agent.shell_hooks import register_from_config
- register_from_config(load_config(), accept_hooks=False)
- except Exception:
- logger.debug(
- "shell-hook registration failed at gateway startup",
- exc_info=True,
- )
+ def _defer_agent_cleanup_until_future_done(
+ self,
+ future: asyncio.Future,
+ agent: Any,
+ *,
+ context: str,
+ ) -> None:
+ """Clean up ``agent`` only after its executor future has finished.
- # Discover and load event hooks
- self.hooks.discover_and_load()
+ A timed-out executor call keeps running in its worker thread. Closing
+ the agent before that thread exits can tear down clients or providers
+ it is still using. Keep a strong task reference and wait for the real
+ future before invoking the normal bounded, off-loop cleanup path.
+ """
-
- # Recover background processes from checkpoint (crash recovery)
- try:
- from tools.process_registry import process_registry
- recovered = process_registry.recover_from_checkpoint()
- if recovered:
- logger.info("Recovered %s background process(es) from previous run", recovered)
- except Exception as e:
- logger.warning("Process checkpoint recovery: %s", e)
+ async def _cleanup_when_done() -> None:
+ try:
+ await asyncio.shield(future)
+ except asyncio.CancelledError:
+ # Loop shutdown can cancel this waiter while the executor still
+ # runs. Never turn that cancellation into premature cleanup.
+ return
+ except Exception as exc:
+ logger.debug(
+ "Deferred agent worker%s finished with an error: %s",
+ f" ({context})" if context else "",
+ exc,
+ )
+ await self._cleanup_agent_resources_off_loop(agent, context=context)
- # Suspend sessions that were active when the gateway last exited.
- # This prevents stuck sessions from being blindly resumed on restart,
- # which can create an unrecoverable loop (#7536). Suspended sessions
- # auto-reset on the next incoming message, giving the user a clean start.
- #
- # SKIP suspension after a clean (graceful) shutdown — the previous
- # process already drained active agents, so sessions aren't stuck.
- # This prevents unwanted auto-resets after `hermes update`,
- # `hermes gateway restart`, or `/restart`.
- _clean_marker = _hermes_home / ".clean_shutdown"
- if _clean_marker.exists():
- logger.info("Previous gateway exited cleanly — skipping session suspension")
+ task = asyncio.create_task(_cleanup_when_done())
+ tasks = getattr(self, "_deferred_agent_cleanup_tasks", None)
+ if tasks is None:
+ tasks = set()
+ self._deferred_agent_cleanup_tasks = tasks
+ tasks.add(task)
+ task.add_done_callback(tasks.discard)
+
+ async def _cleanup_agent_resources_off_loop(
+ self, agent: Any, *, context: str = ""
+ ) -> None:
+ """Run _cleanup_agent_resources in a worker thread with a bounded wait.
+
+ Safe to await from coroutines on the gateway event loop: a slow or
+ wedged teardown (memory provider IO, subprocess close) can no longer
+ block message processing. On timeout the await is cancelled and the
+ worker thread is left to finish (or leak) on its own — the caller
+ proceeds regardless, exactly as the /new reset path does (#35994).
+ """
+ if agent is None:
+ return
+ if context.startswith("shutdown") or context == "session expiry":
try:
- _clean_marker.unlink()
+ agent._end_session_on_close = False
except Exception:
pass
- else:
- try:
- suspended = await self.async_session_store.suspend_recently_active()
- if suspended:
- logger.info("Marked %d in-flight session(s) as resumable from previous run", suspended)
- except Exception as e:
- logger.warning("Session suspension on startup failed: %s", e)
+ try:
+ await asyncio.wait_for(
+ self._run_in_executor_with_context(
+ self._cleanup_agent_resources, agent
+ ),
+ timeout=self._CLEANUP_TIMEOUT_S,
+ )
+ except asyncio.TimeoutError:
+ logger.warning(
+ "Agent resource cleanup%s exceeded %ss; proceeding without "
+ "blocking the event loop (the worker thread is left to finish "
+ "on its own). (#53175)",
+ f" ({context})" if context else "",
+ self._CLEANUP_TIMEOUT_S,
+ )
+ except Exception as cleanup_exc:
+ logger.warning(
+ "Agent resource cleanup%s failed: %s (#53175)",
+ f" ({context})" if context else "",
+ cleanup_exc,
+ )
- # Stuck-loop detection (#7536): if a session has been active across
- # 3+ consecutive restarts, it's probably stuck in a loop (the same
- # history keeps causing the agent to hang). Auto-suspend it so the
- # user gets a clean slate on the next message.
+ def _cleanup_agent_resources(self, agent: Any) -> None:
+ """Best-effort cleanup for temporary or cached agent instances."""
+ if agent is None:
+ return
try:
- stuck = self._suspend_stuck_loop_sessions()
- if stuck:
- logger.warning("Auto-suspended %d stuck-loop session(s)", stuck)
- except Exception as e:
- logger.debug("Stuck-loop detection failed: %s", e)
+ if hasattr(agent, "shutdown_memory_provider"):
+ # Drain queued memory writes BEFORE tearing the provider down.
+ # The memory manager persists per-turn sync and end-of-session
+ # extraction on a single serialized background worker.
+ # shutdown_memory_provider() -> shutdown_all() only gives that
+ # worker a ~5s bounded drain and abandons (cancels) anything
+ # still queued past it, so a /reset — or any gateway session
+ # rotation that reaches this cleanup path — could silently drop
+ # writes the session had already handed off. The next session
+ # then loads stale memory (#73297). Give pending work a bounded
+ # head start through the manager's own barrier first, mirroring
+ # the CLI exit path (cli.py). Best-effort: a flush failure must
+ # never block teardown.
+ _mm = getattr(agent, "_memory_manager", None)
+ if _mm is not None and hasattr(_mm, "flush_pending"):
+ try:
+ _mm.flush_pending(timeout=10)
+ except Exception:
+ pass
+ # Pass the agent's own conversation transcript so memory
+ # providers' ``on_session_end`` hooks see the real messages
+ # instead of the empty default (#15165). ``_session_messages``
+ # is set on ``AIAgent`` (run_agent.py:1518) and refreshed at
+ # the end of every ``run_conversation`` turn via
+ # ``_persist_session``; on an agent built through
+ # ``object.__new__`` (test stubs) the attribute may be
+ # absent, so ``getattr`` with a ``None`` default keeps the
+ # call signature-compatible with the pre-fix behaviour
+ # (``shutdown_memory_provider(messages=None)``).
+ session_messages = getattr(agent, "_session_messages", None)
+ if isinstance(session_messages, list):
+ agent.shutdown_memory_provider(session_messages)
+ else:
+ agent.shutdown_memory_provider()
+ except Exception:
+ pass
+ # Close tool resources (terminal sandboxes, browser daemons,
+ # background processes, httpx clients) to prevent zombie
+ # process accumulation.
+ try:
+ if hasattr(agent, "close"):
+ agent.close()
+ except Exception:
+ pass
+ # Auxiliary async clients (session_search/web/vision/etc.) live in a
+ # process-global cache and are created inside worker threads. Clean up
+ # any entries whose event loop is now dead so their httpx transports do
+ # not accumulate across gateway turns.
+ try:
+ from agent.auxiliary_client import cleanup_stale_async_clients
+ cleanup_stale_async_clients()
+ except Exception:
+ pass
- # Serialize startup restore against inbound dispatch. Platform
- # adapters can begin receiving messages as soon as they connect, but
- # restart-interrupted sessions are not auto-resumed until all startup
- # wiring below completes. Queue inbound messages until the resume
- # pass runs and every synthetic resume turn has finished.
- self._startup_restore_in_progress = True
- self._startup_restore_queue = []
- self._startup_restore_tasks = []
+ _STUCK_LOOP_THRESHOLD = 3 # restarts while active before auto-suspend
+ _STUCK_LOOP_FILE = ".restart_failure_counts"
- connected_count = 0
- enabled_platform_count = 0
- startup_nonretryable_errors: list[str] = []
- startup_retryable_errors: list[str] = []
-
- # Initialize and connect each configured platform
- _multiplex_on = bool(getattr(self.config, "multiplex_profiles", False))
- _multiplex_skipped_platforms: list[Platform] = []
- for platform, platform_config in self.config.platforms.items():
- if await self._abort_startup_if_shutdown_requested():
- return True
- if not platform_config.enabled:
- continue
- # Under multiplexing, a platform may be enabled on the default
- # profile's config.yaml while its bot token lives only in a
- # secondary profile's .env. Starting that primary adapter with an
- # empty token fails immediately and queues an infinite reconnect
- # loop that can never heal (#64674). Secondary profiles still
- # start their own adapters under _profile_runtime_scope with the
- # real token — skip the empty primary instead of failing loudly.
- if _multiplex_on and not _platform_has_bot_credential(platform, platform_config):
- logger.info(
- "Skipping %s on default profile: no bot credential in this "
- "profile's secrets. Secondary multiplexed profiles that "
- "provide the token will still connect.",
- platform.value,
- )
- _multiplex_skipped_platforms.append(platform)
- continue
- enabled_platform_count += 1
-
- adapter = self._create_adapter(platform, platform_config)
- if not adapter:
- # Distinguish between missing builtin deps and missing plugin
- _pval = platform.value
- _builtin_names = {m.value for m in Platform.__members__.values()}
- if _pval not in _builtin_names:
- logger.warning(
- "No adapter for '%s' — is the plugin installed? "
- "(platform is enabled in config.yaml but no plugin registered it)",
- _pval,
- )
- else:
- logger.warning("No adapter available for %s", _pval)
- continue
-
- # Set up message + fatal error handlers
- adapter.set_message_handler(self._handle_message)
- adapter.set_fatal_error_handler(self._handle_adapter_fatal_error)
- adapter.set_session_store(self.session_store)
- adapter.set_busy_session_handler(self._handle_active_session_busy_message)
- _set_reaction = getattr(adapter, "set_reaction_handler", None)
- if callable(_set_reaction):
- _set_reaction(self._handle_reaction_event)
- adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
- adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))
- adapter._busy_text_mode = self._busy_text_mode
-
- # Try to connect
- logger.info("Connecting to %s...", platform.value)
- self._update_platform_runtime_status(
- platform.value,
- platform_state="connecting",
- error_code=None,
- error_message=None,
- )
+ def _increment_restart_failure_counts(self, active_session_keys: set) -> None:
+ """Increment restart-failure counters for sessions active at shutdown.
+
+ Persists to a JSON file so counters survive across restarts.
+ Sessions NOT in active_session_keys are removed (they completed
+ successfully, so the loop is broken).
+ """
+ import json
+
+ path = _hermes_home / self._STUCK_LOOP_FILE
+ try:
+ counts = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
+ except Exception:
+ counts = {}
+
+ # Increment active sessions, remove inactive ones (loop broken)
+ new_counts = {}
+ for key in active_session_keys:
+ new_counts[key] = counts.get(key, 0) + 1
+ # Keep any entries that are still above 0 even if not active now
+ # (they might become active again next restart)
+
+ try:
+ atomic_json_write(path, new_counts, indent=None)
+ except Exception:
+ pass
+
+ def _suspend_stuck_loop_sessions(self) -> int:
+ """Suspend sessions that have been active across too many restarts.
+
+ Returns the number of sessions suspended. Called on gateway startup
+ AFTER suspend_recently_active() to catch the stuck-loop pattern:
+ session loads → agent gets stuck → gateway restarts → repeat.
+ """
+ import json
+
+ path = _hermes_home / self._STUCK_LOOP_FILE
+ if not path.exists():
+ return 0
+
+ try:
+ counts = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return 0
+
+ suspended = 0
+ stuck_keys = [k for k, v in counts.items() if v >= self._STUCK_LOOP_THRESHOLD]
+
+ for session_key in stuck_keys:
try:
- success = await self._connect_initial_adapter_with_timeout(
- adapter, platform
- )
- if await self._abort_startup_if_shutdown_requested(adapter, platform):
- return True
- if success:
- self.adapters[platform] = adapter
- self._sync_voice_mode_state_to_adapter(adapter)
- # Wire voice input callback at connect time so voice
- # transcription is forwarded without requiring /voice join.
- if hasattr(adapter, "_voice_input_callback"):
- adapter._voice_input_callback = self._handle_voice_channel_input
- connected_count += 1
- self._update_platform_runtime_status(
- platform.value,
- platform_state="connected",
- error_code=None,
- error_message=None,
+ entry = self.session_store._entries.get(session_key)
+ if entry and not entry.suspended:
+ entry.suspended = True
+ suspended += 1
+ logger.warning(
+ "Auto-suspended stuck session %s (active across %d "
+ "consecutive restarts — likely a stuck loop)",
+ session_key, counts[session_key],
)
- logger.info("✓ %s connected", platform.value)
- else:
- logger.warning("✗ %s failed to connect", platform.value)
- # Defensive cleanup: a failed connect() may have
- # allocated resources (aiohttp.ClientSession, poll
- # tasks, bridge subprocesses) before giving up.
- # Without this call, those resources are orphaned
- # and Python logs "Unclosed client session" at
- # process exit. Adapter disconnect() implementations
- # are expected to be idempotent and tolerate
- # partial-init state.
- await self._safe_adapter_disconnect(adapter, platform)
- if adapter.has_fatal_error:
- self._update_platform_runtime_status(
- platform.value,
- platform_state="retrying" if adapter.fatal_error_retryable else "fatal",
- error_code=adapter.fatal_error_code,
- error_message=adapter.fatal_error_message,
- )
- target = (
- startup_retryable_errors
- if adapter.fatal_error_retryable
- else startup_nonretryable_errors
- )
- target.append(
- f"{platform.value}: {adapter.fatal_error_message}"
- )
- # Queue for reconnection if the error is retryable
- if adapter.fatal_error_retryable:
- self._failed_platforms[platform] = {
- "config": platform_config,
- "attempts": 1,
- "next_retry": time.monotonic() + 30,
- "credential_claim": self._adapter_credential_claim(
- platform, adapter
- ),
- "listener_claim": self._adapter_listener_claim(
- platform, adapter
- ),
- }
- else:
- self._update_platform_runtime_status(
- platform.value,
- platform_state="retrying",
- error_code=None,
- error_message="failed to connect",
- )
- startup_retryable_errors.append(
- f"{platform.value}: failed to connect"
- )
- # No fatal error info means likely a transient issue — queue for retry
- self._failed_platforms[platform] = {
- "config": platform_config,
- "attempts": 1,
- "next_retry": time.monotonic() + 30,
- "credential_claim": self._adapter_credential_claim(
- platform, adapter
- ),
- "listener_claim": self._adapter_listener_claim(
- platform, adapter
- ),
- }
- except Exception as e:
- logger.error("✗ %s error: %s", platform.value, e)
- # Same defensive cleanup path for exceptions — an adapter
- # that raised mid-connect may still have a live
- # aiohttp.ClientSession or child subprocess.
- await self._safe_adapter_disconnect(adapter, platform)
- self._update_platform_runtime_status(
- platform.value,
- platform_state="retrying",
- error_code=None,
- error_message=str(e),
- )
- startup_retryable_errors.append(f"{platform.value}: {e}")
- # Unexpected exceptions are typically transient — queue for retry
- self._failed_platforms[platform] = {
- "config": platform_config,
- "attempts": 1,
- "next_retry": time.monotonic() + 30,
- "credential_claim": self._adapter_credential_claim(
- platform, adapter
- ),
- "listener_claim": self._adapter_listener_claim(
- platform, adapter
- ),
- }
- if await self._abort_startup_if_shutdown_requested():
- return True
+ except Exception:
+ pass
- # Multi-profile multiplexing: bring up adapters for every OTHER profile
- # this gateway serves. Each profile's adapters connect under that
- # profile's home + credential scope and stamp their inbound events with
- # the profile so the agent turn resolves correctly. No-op when off.
- try:
- _secondary_connected = await self._start_secondary_profile_adapters()
- connected_count += _secondary_connected
- except MultiplexConfigError as e:
- # Invalid multiplexer config — abort startup cleanly so the operator
- # fixes config.yaml rather than running a half-wired gateway.
- reason = str(e)
- logger.error("Gateway multiplexer config error: %s", reason)
+ if suspended:
try:
- from gateway.status import write_runtime_status
- write_runtime_status(gateway_state="startup_failed", exit_reason=reason)
+ self.session_store._save()
except Exception:
pass
- self._exit_code = GATEWAY_FATAL_CONFIG_EXIT_CODE
- self._request_clean_exit(reason)
- self._startup_restore_in_progress = False
- return True
- except Exception as e:
- logger.error("Secondary-profile adapter startup failed: %s", e, exc_info=True)
- finally:
- # Startup authority is one phase, not a persistent runner mode.
- # From this point onward every adapter retry is non-evicting.
- self._platform_lock_takeover_on_start = False
- # A platform we skipped on the primary for a missing credential was
- # supposed to be picked up by a secondary profile that owns the token.
- # If none did, the platform is enabled in config.yaml yet silently
- # unserved — surface it loudly so the operator sees a config problem
- # instead of a quiet dead channel (#64674 follow-up).
- for _skipped in _multiplex_skipped_platforms:
- _served_by_secondary = any(
- _skipped in _profile_map
- for _profile_map in self._profile_adapters.values()
- )
- if not _served_by_secondary:
- logger.warning(
- "%s is enabled but no profile (default or secondary) "
- "provided a bot credential for it — the platform is not "
- "being served. Add its token to the profile that should "
- "own it, or disable the platform.",
- _skipped.value,
- )
+ # Clear the file — counters start fresh after suspension
+ try:
+ path.unlink(missing_ok=True)
+ except Exception:
+ pass
- if connected_count == 0:
- if startup_nonretryable_errors and not startup_retryable_errors:
- reason = "; ".join(startup_nonretryable_errors)
- logger.error("Gateway hit a non-retryable startup conflict: %s", reason)
- try:
- from gateway.status import write_runtime_status
- write_runtime_status(gateway_state="startup_failed", exit_reason=reason)
- except Exception:
- pass
- self._exit_code = GATEWAY_FATAL_CONFIG_EXIT_CODE
- self._request_clean_exit(reason)
- self._startup_restore_in_progress = False
- return True
- if startup_nonretryable_errors:
- # Mixed failure mode (NS-609): some platforms are fatally
- # misconfigured (e.g. WhatsApp enabled but never paired) while
- # others hit merely transient errors (e.g. Telegram TimedOut
- # during polling startup). Exiting with
- # GATEWAY_FATAL_CONFIG_EXIT_CODE here is wrong in both
- # supervision worlds: under supervisors that honor the
- # exit-78 contract (systemd RestartPreventExitStatus, s6
- # finish→125 since #51228) the gateway goes PERMANENTLY down
- # over a network blip; under anything else it crash-loops.
- # Either way the retryable platforms never get their retry.
- # Log the fatal side loudly, then fall through to the
- # degraded/retry path below: the reconnect watcher recovers
- # the retryable platforms; the non-retryable ones remain
- # fatal-parked and visible in runtime status.
- logger.error(
- "%d platform(s) fatally misconfigured and parked: %s. "
- "Staying alive so retryable platforms can recover.",
- len(startup_nonretryable_errors),
- "; ".join(startup_nonretryable_errors),
- )
- if enabled_platform_count > 0:
- if startup_retryable_errors:
- # All enabled platforms hit retryable failures (network
- # blip, bridge not paired, npm install timeout, etc.).
- # Keep the gateway alive so:
- # • cron jobs still run
- # • the reconnect watcher gets a chance to recover the
- # failing platforms once the underlying problem is
- # fixed (e.g. user runs `hermes whatsapp`, fixes
- # proxy, etc.)
- # Exiting here used to convert a single misconfigured
- # platform into an infinite systemd restart loop.
- reason = "; ".join(startup_retryable_errors)
- logger.warning(
- "Gateway started with no connected platforms — "
- "%d platform(s) queued for retry: %s",
- len(self._failed_platforms), reason,
- )
- try:
- from gateway.status import write_runtime_status
- write_runtime_status(
- gateway_state="degraded",
- exit_reason=None,
- )
- except Exception:
- pass
- # Fall through to the normal "running" state — reconnect
- # watcher takes it from here.
- # All enabled platforms had no adapter (missing library or credentials).
- # In fleet deployments the same config.yaml is shared across nodes that
- # may only have credentials for a subset of platforms. Rather than
- # failing hard, degrade gracefully and allow cron jobs to run (#5196).
- logger.warning(
- "No adapter could be created for any of the %d configured platform(s). "
- "Check that required dependencies are installed and credentials are set. "
- "Gateway will continue for cron job execution.",
- enabled_platform_count,
- )
- else:
- logger.warning("No messaging platforms enabled.")
- logger.info("Gateway will continue running for cron job execution.")
-
- # Update delivery router with adapters
- if await self._abort_startup_if_shutdown_requested():
- return True
- self.delivery_router.adapters = self.adapters
- self._wire_teams_pipeline_runtime()
+ return suspended
- self._running = True
- self._update_runtime_status("running")
+ def _clear_restart_failure_count(self, session_key: str) -> None:
+ """Clear the restart-failure counter for a session that completed OK.
- # Loop-liveness heartbeat (#66892): an asyncio task so a frozen loop
- # stops refreshing ``state/gateway.heartbeat``. Cancelled with the
- # other background tasks during stop(). Best-effort — a liveness probe
- # must never be able to abort startup.
+ Called after a successful agent turn to signal the loop is broken.
+ """
+ import json
+
+ path = _hermes_home / self._STUCK_LOOP_FILE
+ if not path.exists():
+ return
try:
- _existing_hb = getattr(self, "_loop_heartbeat_task", None)
- if _existing_hb is None or _existing_hb.done():
- self._loop_heartbeat_task = asyncio.create_task(
- loop_heartbeat_forever(
- interval_s=DEFAULT_HEARTBEAT_INTERVAL_S,
- start_time=getattr(self, "_gateway_started_at", 0.0),
- )
- )
- _bg = getattr(self, "_background_tasks", None)
- if _bg is not None:
- _bg.add(self._loop_heartbeat_task)
- self._loop_heartbeat_task.add_done_callback(_bg.discard)
+ counts = json.loads(path.read_text(encoding="utf-8"))
+ if session_key in counts:
+ del counts[session_key]
+ if counts:
+ atomic_json_write(path, counts, indent=None)
+ else:
+ path.unlink(missing_ok=True)
except Exception:
- logger.debug("Failed to start gateway loop heartbeat", exc_info=True)
+ pass
- # Emit gateway:startup hook
- hook_count = len(self.hooks.loaded_hooks)
- if hook_count:
- logger.info("%s hook(s) loaded", hook_count)
- await self.hooks.emit("gateway:startup", {
- "platforms": [p.value for p in self.adapters.keys()],
- })
-
- if connected_count > 0:
- logger.info("Gateway running with %s platform(s)", connected_count)
-
- # Build initial channel directory for send_message name resolution
- try:
- from gateway.channel_directory import build_channel_directory
- directory = await build_channel_directory(self.adapters)
- ch_count = sum(len(chs) for chs in directory.get("platforms", {}).values())
- logger.info("Channel directory built: %d target(s)", ch_count)
- except Exception as e:
- logger.warning("Channel directory build failed: %s", e)
-
- # Check if we're restarting after a /update command. If the update is
- # still running, keep watching so we notify once it actually finishes.
- notified = await self._send_update_notification()
- if not notified and any(
- path.exists()
- for path in (
- _hermes_home / ".update_pending.json",
- _hermes_home / ".update_pending.claimed.json",
- )
- ):
- self._schedule_update_notification_watch()
+ async def _launch_detached_restart_command(self) -> None:
+ import shutil
+ import subprocess
- # Give freshly connected platform adapters a brief moment to settle
- # before sending restart/startup lifecycle messages. In practice this
- # helps Discord thread deliveries right after reconnect.
- if connected_count > 0:
- await asyncio.sleep(1.0)
+ hermes_cmd = _resolve_hermes_bin()
+ if not hermes_cmd:
+ logger.error("Could not locate hermes binary for detached /restart")
+ return
+ if self._detached_restart_helper_started:
+ return
+ self._detached_restart_helper_started = True
- # Notify the chat that initiated /restart that the gateway is back.
- chat_restart_notification_pending = _restart_notification_pending()
- planned_restart_notification_pending = _planned_restart_notification_pending()
- # Capture, before _send_restart_notification() unlinks the marker,
- # whether this process booted from a chat-originated /restart. Used as
- # a one-shot signal by the /restart redelivery guard so a missing
- # dedup marker only suppresses a /restart when we KNOW we just came out
- # of a restart cycle (see _is_stale_restart_redelivery).
- if chat_restart_notification_pending:
- self._booted_from_restart = True
- await self._send_restart_notification()
+ current_pid = os.getpid()
+ restart_after_s = max(float(getattr(self, "_restart_drain_timeout", 0.0) or 0.0) + 5.0, 5.0)
- # Broadcast a lightweight "gateway is back" message to configured home
- # channels only for non-chat planned restarts (terminal/SIGUSR1/service
- # paths). Chat-originated /restart already has a precise reply target
- # in .restart_notify.json, so keep that lifecycle in the originating
- # chat/topic instead of also leaking it to the configured home channel.
- if planned_restart_notification_pending:
- try:
- await self._send_home_channel_startup_notifications(
- skip_targets=None,
- )
- finally:
- _clear_planned_restart_notification()
+ # On Windows there's no bash/setsid chain — spawn a tiny Python
+ # watcher directly via sys.executable instead. The watcher polls
+ # current_pid, waits for our exit, then runs `hermes gateway
+ # restart` with detach flags so the respawn survives the CLI
+ # that triggered the /restart command closing its console.
+ if sys.platform == "win32":
+ import textwrap
+ from hermes_cli._subprocess_compat import (
+ windows_detach_flags_without_breakaway,
+ windows_detach_popen_kwargs,
+ )
- # Automatically continue fresh sessions that were interrupted by the
- # previous gateway restart/shutdown. The resume_pending flag is cleared
- # by the normal successful-turn path, so a failed auto-resume remains
- # visible for manual recovery on the next user message.
- #
- # Delivery-obligation redelivery runs FIRST: a session whose final
- # response was generated but never confirmed-delivered has its answer
- # in the ledger — redelivering it (and clearing resume_pending for
- # that session) is strictly cheaper and more correct than re-running
- # the whole turn.
- await self._redeliver_pending_obligations()
- self._schedule_resume_pending_sessions()
- await self._finish_startup_restore()
+ cmd_argv = [*hermes_cmd, "gateway", "restart"]
+ watcher = textwrap.dedent(
+ """
+ import os, subprocess, sys, time
+ from hermes_cli._subprocess_compat import windows_detach_flags_without_breakaway
+ pid = int(sys.argv[1])
+ restart_after_s = float(sys.argv[2])
+ cmd = sys.argv[3:]
+ deadline = time.monotonic() + restart_after_s
- # Drain any recovered process watchers (from crash recovery checkpoint)
- try:
- from tools.process_registry import process_registry
- # Detach the current batch atomically: reassigning to a fresh list
- # takes ownership of exactly the watchers present now, so any watcher
- # appended concurrently during the yield below isn't silently dropped
- # by a clear() on the shared list.
- watchers = process_registry.pending_watchers
- process_registry.pending_watchers = []
- # Process in batches of 100 with event-loop yield points to avoid
- # O(n^2) event-loop blocking when recovering thousands of watchers.
- for i, watcher in enumerate(watchers):
- self._spawn_supervised(
- lambda w=watcher: self._run_process_watcher(w),
- f"process_watcher:{watcher.get('session_id')}",
- restart=False,
- )
- logger.info("Resumed watcher for recovered process %s", watcher.get("session_id"))
- if i % 100 == 99:
- await asyncio.sleep(0)
- except Exception as e:
- logger.error("Recovered watcher setup error: %s", e)
-
- # Start background session expiry watcher to finalize expired sessions
- self._spawn_supervised(self._session_expiry_watcher, "session_expiry_watcher")
-
- # Start background kanban notifier — delivers `completed`, `blocked`,
- # `spawn_auto_blocked`, and `crashed` events to gateway subscribers
- # so human-in-the-loop workflows hear back without polling.
- self._spawn_supervised(self._kanban_notifier_watcher, "kanban_notifier_watcher")
+ def _alive(p):
+ # On Windows, os.kill(pid, 0) is NOT a no-op — it maps to
+ # GenerateConsoleCtrlEvent(0, pid) (bpo-14484). Use the
+ # Win32 handle-based existence check instead.
+ if os.name == 'nt':
+ import ctypes
+ k32 = ctypes.windll.kernel32
+ k32.OpenProcess.restype = ctypes.c_void_p
+ k32.WaitForSingleObject.restype = ctypes.c_uint
+ k32.GetLastError.restype = ctypes.c_uint
+ h = k32.OpenProcess(0x1000 | 0x100000, False, int(p))
+ if not h:
+ return k32.GetLastError() != 87
+ try:
+ return k32.WaitForSingleObject(h, 0) == 0x102
+ finally:
+ k32.CloseHandle(h)
+ try:
+ os.kill(int(p), 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except OSError:
+ return False
- # Start background kanban dispatcher — spawns workers for ready
- # tasks. Gated by `kanban.dispatch_in_gateway` (default True).
- # When false, users run `hermes kanban daemon` externally or
- # simply don't use kanban; this loop becomes a no-op.
- self._spawn_supervised(self._kanban_dispatcher_watcher, "kanban_dispatcher_watcher")
+ while time.monotonic() < deadline:
+ if not _alive(pid):
+ break
+ time.sleep(0.2)
+ subprocess.Popen(
+ cmd,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ creationflags=windows_detach_flags_without_breakaway(),
+ )
+ """
+ ).strip()
+ from tools.environments.local import build_subprocess_env
+ watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
+ # This watcher is intentionally outside the running gateway. If it
+ # inherits the gateway marker, `hermes gateway restart` refuses to
+ # run as a self-restart loop guard and the gateway stays stopped.
+ watcher_env.pop("_HERMES_GATEWAY", None)
+ project_root = Path(__file__).resolve().parent.parent
+ # The watcher runs sys.executable (console python) under the
+ # CREATE_NO_WINDOW detach kwargs below: it owns one hidden
+ # console, inherited by the `hermes gateway restart` child, so
+ # nothing flashes. Do NOT swap in GUI-subsystem pythonw.exe —
+ # a console-less watcher forces every console-subsystem
+ # descendant to allocate a visible conhost (#54220/#56747).
+ watcher_python = sys.executable
+ venv_dir = Path(watcher_env.get("VIRTUAL_ENV") or project_root / "venv")
+ site_packages = venv_dir / "Lib" / "site-packages"
+ if site_packages.exists():
+ watcher_env["VIRTUAL_ENV"] = str(venv_dir)
+ pythonpath = [str(project_root), str(site_packages)]
+ if watcher_env.get("PYTHONPATH"):
+ pythonpath.append(watcher_env["PYTHONPATH"])
+ watcher_env["PYTHONPATH"] = os.pathsep.join(dict.fromkeys(pythonpath))
+ watcher_argv = [
+ watcher_python,
+ "-c",
+ watcher,
+ str(current_pid),
+ str(restart_after_s),
+ *cmd_argv,
+ ]
+ # The watcher process must itself break away from any job object the
+ # parent CLI lives in (Electron/Tauri-wrapped Hermes Desktop, Windows
+ # Terminal, schtasks shells); otherwise it is reaped when the CLI
+ # exits and the gateway never respawns. windows_detach_popen_kwargs()
+ # carries CREATE_BREAKAWAY_FROM_JOB, but a restrictive job object
+ # (no JOB_OBJECT_LIMIT_BREAKAWAY_OK) rejects that bit with
+ # ERROR_ACCESS_DENIED, surfaced as OSError. Retry once without the
+ # breakaway bit, preserving argv and the scrubbed watcher_env.
+ # Mirrors the canonical fallback in
+ # hermes_cli/gateway_windows.py::_spawn_detached.
+ try:
+ subprocess.Popen(
+ watcher_argv,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ env=watcher_env,
+ **windows_detach_popen_kwargs(),
+ )
+ except OSError:
+ try:
+ subprocess.Popen(
+ watcher_argv,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ env=watcher_env,
+ creationflags=windows_detach_flags_without_breakaway(),
+ )
+ except OSError as exc:
+ # Both spawn attempts failed (a breakaway-denying job object
+ # is the common cause, but OSError covers others too).
+ # Record a minimal, path-safe diagnostic and return without
+ # crashing the caller: state plainly that no watcher was
+ # started, and log only the interpreter basename and a
+ # numeric error code — never argv, env, watcher source, or
+ # str(exc) (which can carry a full interpreter path for a
+ # FileNotFoundError).
+ winerror = getattr(exc, "winerror", None)
+ error_code = winerror if winerror is not None else exc.errno
+ error_field = "winerror" if winerror is not None else "errno"
+ logger.warning(
+ "Detached restart watcher was not started after the "
+ "no-breakaway retry (%s; %s=%r). The gateway will not "
+ "be respawned by this restart attempt.",
+ os.path.basename(watcher_python),
+ error_field,
+ error_code,
+ )
+ return
- # Start background reconnection watcher for platforms that failed at startup
- if self._failed_platforms:
- logger.info(
- "Starting reconnection watcher for %d failed platform(s): %s",
- len(self._failed_platforms),
- ", ".join(p.value for p in self._failed_platforms),
- )
- # Track the reconnect watcher task so _ensure_reconnect_watcher_running
- # can detect if it dies and respawn it (#70344). Spawned via
- # _spawn_supervised (not a bare asyncio.create_task) so an exception
- # escaping the watcher's OUTER while-loop -- not just the per-platform
- # inner try/except -- is caught, logged, and auto-restarted with
- # backoff instead of silently killing the watcher forever. Without
- # this, a platform already queued in _failed_platforms when the
- # watcher dies stays stranded indefinitely: _ensure_reconnect_watcher_running()
- # only gets called from a NEW fatal-error arrival, so if no other
- # platform ever fails afterward, nothing ever notices the watcher is
- # dead (#71758 -- reported as 17.5h of silent downtime for a platform
- # whose transient upstream outage had long since recovered).
- # ``on_spawn`` keeps ``_reconnect_watcher_task`` pointed at the CURRENT
- # live task even when _spawn_supervised's own backoff respawns it — so
- # _ensure_reconnect_watcher_running never mistakes a superseded handle
- # for a dead watcher and spawns a duplicate.
- self._reconnect_watcher_task = self._spawn_supervised(
- self._platform_reconnect_watcher,
- "platform_reconnect_watcher",
- on_spawn=lambda t: setattr(self, "_reconnect_watcher_task", t),
+ cmd = " ".join(shlex.quote(part) for part in hermes_cmd)
+ shell_cmd = (
+ f"deadline=$(( $(date +%s) + {int(restart_after_s)} )); "
+ f"while kill -0 {current_pid} 2>/dev/null && [ $(date +%s) -lt $deadline ]; do sleep 0.2; done; "
+ f"{cmd} gateway restart"
)
+ # Same marker scrub as the Windows watcher above: this watcher runs
+ # `hermes gateway restart` from outside the gateway, but it inherits
+ # _HERMES_GATEWAY=1 from us, and the CLI's self-restart loop guard
+ # refuses to run when that marker is set — silently (DEVNULL), so the
+ # gateway stops and never comes back.
+ from tools.environments.local import build_subprocess_env
+ watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
+ watcher_env.pop("_HERMES_GATEWAY", None)
+ setsid_bin = shutil.which("setsid")
+ if setsid_bin:
+ subprocess.Popen(
+ [setsid_bin, "bash", "-lc", shell_cmd],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ env=watcher_env,
+ start_new_session=True,
+ )
+ else:
+ subprocess.Popen(
+ ["bash", "-lc", shell_cmd],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ env=watcher_env,
+ start_new_session=True,
+ )
- # Start background handoff watcher — picks up CLI sessions marked
- # handoff_state='pending' in state.db and re-binds them to the
- # destination platform's home channel, then forges a synthetic user
- # turn so the agent kicks off the new chat.
- self._spawn_supervised(self._handoff_watcher, "handoff_watcher")
+ def _launch_systemd_restart_shortcut(self) -> None:
+ """Best-effort helper to bypass systemd's automatic restart delay.
- # Start background async-delegation watcher — drains completion events
- # from delegate_task(background=true) subagents and injects each
- # result back into its originating session as a new turn, covering the
- # idle case where the subagent finishes with no agent turn running.
- self._spawn_supervised(self._async_delegation_watcher, "async_delegation_watcher")
+ For planned in-chat restarts, the gateway exits cleanly so systemd does
+ not record a failure. However, units with RestartSteps still count
+ automatic restarts and can delay repeated /restart tests. A transient
+ user service survives our cgroup teardown and explicitly starts the
+ gateway as soon as this PID exits, while the unit keeps its normal
+ backoff for real crash loops.
+ """
+ if sys.platform != "linux" or not os.environ.get("INVOCATION_ID"):
+ return
- # Start the scale-to-zero idle watcher ONLY when this instance is opted
- # in (the NAS "Labs" HERMES_SCALE_TO_ZERO stamp), messaging is
- # relay-only/absent, and a wakeUrl is registered (decisions.md D1/D11/
- # §3.4(1)). A non-opted instance never starts it, so behaviour is exactly
- # as today. When armed, the watcher drives the relay dormant on sustained
- # idle so the platform (Fly autostop:"suspend") can suspend the machine.
try:
- if self._scale_to_zero_should_arm():
- logger.info(
- "scale-to-zero: armed (idle timeout %.0fs) — watching for idle",
- self._scale_to_zero_idle_timeout_seconds(),
- )
- self._spawn_supervised(self._scale_to_zero_watcher, "scale_to_zero_watcher")
- else:
- # Surface WHY an OPTED-IN instance didn't arm (a non-opted instance
- # not arming is normal — stay silent there). Without this, a failed
- # arm is invisible and "why won't it suspend/wake?" needs a box-dive.
- self._log_scale_to_zero_not_armed_reason()
- except Exception: # noqa: BLE001 - arming must never block startup
- logger.debug("scale-to-zero: arm check failed at startup", exc_info=True)
+ import shutil
+ import subprocess
- # Start background drain-control watcher — reconciles the gateway's
- # new-turn accept-state with the external ``.drain_request.json`` marker
- # the dashboard begin/cancel-drain endpoint writes (Phase 2). A marker
- # left behind by a prior instantiation (durable-volume restart, NS-570)
- # is ignored via its instantiation epoch; only a current-epoch marker
- # engages drain on the first tick.
- self._spawn_supervised(self._drain_control_watcher, "drain_control_watcher")
+ systemd_run = shutil.which("systemd-run")
+ systemctl = shutil.which("systemctl")
+ if not systemd_run or not systemctl:
+ return
- logger.info("Press Ctrl+C to stop")
-
- return True
+ try:
+ from hermes_cli.gateway import get_service_name
- _MAX_SUPERVISED_RESTARTS = 5
- # A task that ran at least this long before crashing is treated as having
- # been HEALTHY — its crash is a fresh, isolated failure rather than part of
- # a rapid crash-loop, so the consecutive-restart counter resets to 0. Only
- # crashes that happen within this window of a (re)spawn accumulate toward
- # ``_MAX_SUPERVISED_RESTARTS``. Without this, a long-lived launchd daemon
- # whose watcher crashes a handful of times over days would hit the cap and
- # be permanently abandoned (NS: silent loss of platform-reconnect / kanban /
- # handoff for the rest of the process life).
- _SUPERVISED_HEALTHY_SECS = 300
-
- def _spawn_supervised(self, coro_factory, name, *, restart=True, _attempt=0, on_spawn=None):
- """Launch a long-lived background task with task-level supervision.
-
- Complements upstream's per-iteration inner-loop try/except (which only
- guards a single loop-body) by covering what that CANNOT: an exception
- raised in the watcher's OUTER ``while self._running:`` loop or its
- pre-try setup region, plus task-level death generally. A bare
- ``asyncio.create_task`` drops such an exception on the floor — no log,
- no restart, the watcher silently gone. This retains the handle in
- ``self._background_tasks``, logs any crash, and restarts with capped
- exponential backoff up to ``_MAX_SUPERVISED_RESTARTS`` failures in rapid
- succession (each within ``_SUPERVISED_HEALTHY_SECS`` of its restart).
- The counter resets after any run that stayed healthy for at least
- ``_SUPERVISED_HEALTHY_SECS`` — so a long-lived daemon that crashes
- occasionally over days is never permanently abandoned.
-
- ``on_spawn`` (optional) is invoked with the freshly-created task on
- every spawn, INCLUDING internal backoff respawns. Callers that also
- track the live handle elsewhere (e.g. ``self._reconnect_watcher_task``
- for ``_ensure_reconnect_watcher_running``) MUST pass it — otherwise the
- supervisor's own respawn creates a new task without updating that
- external handle, so ``_ensure_...`` later sees the stale/done handle
- and spawns a SECOND concurrent watcher (double reconnect attempts).
- """
- if getattr(self, "_background_tasks", None) is None:
- self._background_tasks = set()
+ service_name = get_service_name()
+ except Exception:
+ service_name = "hermes-gateway"
- # Monotonic spawn timestamp captured per spawn: the ``_done`` callback
- # uses it to distinguish a rapid crash-loop from a healthy-run-then-crash.
- _started = time.monotonic()
+ current_pid = os.getpid()
- # Deliberately do NOT pass name= to create_task — some test doubles mock
- # create_task with a signature that rejects the name kwarg.
- task = asyncio.create_task(coro_factory())
- self._background_tasks.add(task)
- if on_spawn is not None:
- # Record the live handle NOW so an external tracker (e.g.
- # _reconnect_watcher_task) always points at the current task, not a
- # dead one left behind by a prior supervised respawn.
- try:
- on_spawn(task)
- except Exception: # pragma: no cover - defensive; a tracker must never kill the spawn
- logger.debug("on_spawn callback for %s raised", name, exc_info=True)
+ # Detect whether the gateway unit is registered as a system or
+ # user service. Daemon-style deployments are typically system
+ # units (e.g. /etc/systemd/system/hermes-gateway.service), while
+ # `hermes setup` under a non-root account may register a user
+ # unit. Hard-coding ``--user`` broke system-unit deployments:
+ # systemctl returned an empty MainPID, the PID-equality check
+ # below failed, and the planned-restart helper was never
+ # launched — leaving the gateway dead until a manual reboot.
+ def _query_pid(scope_flags):
+ try:
+ out = subprocess.run(
+ [systemctl, *scope_flags, "show", service_name,
+ "--property=MainPID", "--value"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=2,
+ )
+ return (out.stdout or "").strip()
+ except Exception:
+ return ""
- def _done(t):
- self._background_tasks.discard(t)
- if t.cancelled():
- return
- exc = t.exception()
- if exc is None:
- # Clean return == deliberate shutdown or a self-disabling watcher
- # (e.g. a gated no-op that returns synchronously). Respawning here
- # would busy-spin such a watcher — so NEVER restart on clean exit.
+ system_pid = _query_pid([])
+ user_pid = _query_pid(["--user"])
+ if str(current_pid) == system_pid:
+ scope_flags = []
+ systemctl_scope = "systemctl"
+ elif str(current_pid) == user_pid:
+ scope_flags = ["--user"]
+ systemctl_scope = "systemctl --user"
+ else:
+ # MainPID does not match in either scope — likely invoked
+ # outside of systemd or the unit was renamed. Bail out
+ # rather than restart the wrong unit.
return
- logger.error("Supervised task %s died: %r", name, exc, exc_info=exc)
- if restart and self._running:
- ran_for = time.monotonic() - _started
- if ran_for >= self._SUPERVISED_HEALTHY_SECS:
- # Ran healthily for a while before crashing — this is a
- # FRESH failure, not part of a rapid crash-loop. Reset the
- # consecutive counter so a daemon that crashes a handful of
- # times over days is never permanently abandoned.
- effective_attempt = 0
- else:
- effective_attempt = _attempt
- if effective_attempt >= self._MAX_SUPERVISED_RESTARTS:
- logger.error(
- "Supervised task %s died %d times in rapid succession "
- "(each within %ds of restart) — giving up restarts",
- name,
- effective_attempt,
- self._SUPERVISED_HEALTHY_SECS,
- )
- return
- backoff = min(60, 2 ** min(effective_attempt, 6))
- async def _respawn():
- await asyncio.sleep(backoff)
- if self._running:
- self._spawn_supervised(
- coro_factory,
- name,
- restart=restart,
- _attempt=effective_attempt + 1,
- on_spawn=on_spawn,
- )
+ service_arg = shlex.quote(service_name)
+ shell_cmd = (
+ f"while kill -0 {current_pid} 2>/dev/null; do sleep 0.2; done; "
+ f"{systemctl_scope} reset-failed {service_arg}; "
+ f"{systemctl_scope} restart {service_arg}"
+ )
+ unit_name = f"{service_name}-planned-restart-{current_pid}".replace(".", "-")
+ subprocess.Popen(
+ [
+ systemd_run,
+ *scope_flags,
+ "--collect",
+ "--unit",
+ unit_name,
+ "/bin/sh",
+ "-lc",
+ shell_cmd,
+ ],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ logger.info(
+ "Launched systemd planned-restart helper for %s (pid=%s, scope=%s)",
+ service_name,
+ current_pid,
+ "user" if scope_flags else "system",
+ )
+ except Exception as e:
+ logger.debug("Failed to launch systemd planned-restart helper: %s", e)
- respawn_task = asyncio.create_task(_respawn())
- self._background_tasks.add(respawn_task)
- respawn_task.add_done_callback(self._background_tasks.discard)
+ def request_restart(self, *, detached: bool = False, via_service: bool = False) -> bool:
+ if self._restart_task_started:
+ return False
+ self._restart_requested = True
+ self._restart_detached = detached
+ self._restart_via_service = via_service
+ self._restart_task_started = True
- task.add_done_callback(_done)
- return task
+ async def _run_restart() -> None:
+ if detached:
+ try:
+ await self._launch_detached_restart_command()
+ except Exception as e:
+ logger.error("Failed to launch detached gateway restart helper: %s", e)
+ await asyncio.sleep(0.05)
+ await self.stop(restart=True, detached_restart=detached, service_restart=via_service)
- async def _handoff_watcher(self, interval: float = 2.0) -> None:
- """Background task that processes pending CLI→gateway session handoffs.
+ # _run_restart is a short-lived self-terminating task (calls stop()
+ # then returns). Don't add it to _background_tasks — _stop_impl
+ # cancels all entries in that set, which would cancel _run_restart
+ # while it's awaiting _stop_task, propagating CancelledError into
+ # _stop_impl and preventing _shutdown_event.set() / _exit_code = 75.
+ # See #12875.
+ #
+ # We still hold a strong reference in self._restart_task: a bare
+ # asyncio.create_task() keeps only a weak reference, so the event
+ # loop may garbage-collect a still-pending task mid-flight. The
+ # cancel loop in _stop_impl explicitly skips _restart_task for the
+ # same reason it skips _stop_task.
+ self._restart_task = asyncio.create_task(_run_restart())
+ return True
- Polls ``state.db`` for sessions in ``handoff_state='pending'`` and,
- for each one:
+ # Drain-timeout reasons set by _stop_impl() when a still-running turn is
+ # force-interrupted; "restart_interrupted" is set by
+ # SessionStore.suspend_recently_active() on crash recovery (no
+ # .clean_shutdown marker). All three mean "the agent was mid-turn and
+ # we killed it" — eligible for startup auto-resume.
+ _AUTO_RESUME_REASONS = frozenset(
+ {"restart_timeout", "shutdown_timeout", "restart_interrupted"}
+ )
- 1. Atomically claims it (pending → running).
- 2. Resolves the destination platform's configured home channel.
- 3. Re-binds the gateway's session_key for that home channel to the
- CLI's existing session_id via ``session_store.switch_session`` so
- the full role-aware transcript replays on the next agent turn.
- 4. Forges a synthetic ``MessageEvent`` (``internal=True``) with a
- handoff-notice text and dispatches through the normal gateway
- message pipeline so the agent runs and replies on the platform.
- 5. Marks the row ``completed`` (or ``failed`` with ``handoff_error``).
+ async def _run_startup_resume_event(
+ self,
+ adapter: BasePlatformAdapter,
+ event: MessageEvent,
+ session_key: str,
+ ) -> None:
+ """Dispatch one synthetic startup resume and wait for its agent turn.
- The CLI process is poll-blocked on the row's terminal state and
- prints the result to the user.
+ ``BasePlatformAdapter.handle_message()`` returns after it installs the
+ adapter-level guard and spawns the background processing task. Startup
+ restore needs a stronger boundary: inbound messages must stay queued
+ until the resumed agent turn itself has finished, otherwise a user
+ message can race the restore turn immediately after ``handle_message``
+ returns.
"""
- # Initial delay so the gateway is fully connected to its platforms
- # before we try to dispatch handoffs through them.
- await asyncio.sleep(5)
- while self._running:
- try:
- if self._session_db is None:
- await asyncio.sleep(interval)
- continue
- pending = await self._session_db.list_pending_handoffs()
- for row in pending:
- session_id = row.get("id")
- if not session_id:
- continue
- if not await self._session_db.claim_handoff(session_id):
- # Another tick or another gateway already claimed it.
- continue
- try:
- await self._process_handoff(row)
- await self._session_db.complete_handoff(session_id)
- except Exception as exc:
- logger.warning(
- "Handoff for session %s failed: %s",
- session_id, exc, exc_info=True,
- )
- await self._session_db.fail_handoff(session_id, str(exc))
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- logger.debug("Handoff watcher tick error: %s", exc, exc_info=True)
- await asyncio.sleep(interval)
-
- async def _process_handoff(self, row: Dict[str, Any]) -> None:
- """Execute one handoff row. Raises on failure (caller marks failed)."""
- from gateway.config import Platform
- from gateway.session import SessionSource, build_session_key
- from gateway.platforms.base import MessageEvent
-
- cli_session_id = row["id"]
- platform_name = (row.get("handoff_platform") or "").strip().lower()
- if not platform_name:
- raise RuntimeError("handoff_platform is empty")
-
- # Resolve platform enum
try:
- platform = Platform(platform_name)
- except (ValueError, KeyError):
- raise RuntimeError(f"unknown platform '{platform_name}'")
-
- # Adapter must be live. A relay-fronted gateway registers ONE adapter
- # under Platform.RELAY that fronts N logical platforms — so a literal
- # adapters.get(discord) misses even though "discord" is deliverable.
- # resolve_delivery_transport is the shared alias-aware resolver (native
- # adapter wins; relay eligible only when its authenticated transport
- # advertises it fronts the logical platform).
- transport = resolve_delivery_transport(platform, self.config, self.adapters)
- if not transport:
- raise RuntimeError(
- f"platform '{platform_name}' is not active in this gateway"
- )
- adapter = transport.adapter
-
- # Home channel must be configured
- home = self.config.get_home_channel(platform)
- if not home or not home.chat_id:
- raise RuntimeError(
- f"no home channel configured for {platform_name}; "
- f"run /sethome on the desired chat first"
- )
-
- cli_title = row.get("title") or cli_session_id[:8]
+ await adapter.handle_message(event)
+ session_tasks = getattr(adapter, "_session_tasks", {})
+ task = session_tasks.get(session_key) if isinstance(session_tasks, dict) else None
+ if task is not None:
+ await asyncio.shield(task)
+ finally:
+ # _schedule_resume_pending_sessions pre-claims the runner slot
+ # before spawning this task. If adapter.handle_message raises
+ # before _handle_message takes ownership, release that pre-claim;
+ # otherwise the real run's normal cleanup owns the slot.
+ _pre_state = self._peek_session_state(session_key)
+ if (_pre_state.turn.agent if _pre_state else None) is _AGENT_PENDING_SENTINEL:
+ self._release_running_agent_state(session_key)
- # Try to create a fresh thread on the destination so the handoff
- # has its own scrollback. Adapter returns None if threading isn't
- # supported (Matrix/WhatsApp/Signal/SMS) or if creation failed
- # (no permission, topics-mode off, parent is a DM, etc.). When
- # None we fall through to using the home channel directly — the
- # synthetic turn still lands; just without thread isolation.
- thread_name = f"Hermes — {cli_title}"
+ def _queue_startup_restore_event(self, event: MessageEvent) -> None:
+ queue = getattr(self, "_startup_restore_queue", None)
+ if queue is None:
+ queue = []
+ self._startup_restore_queue = queue
+ queue.append(event)
try:
- new_thread_id = await adapter.create_handoff_thread(
- str(home.chat_id), thread_name,
- )
- except Exception as exc:
- logger.debug(
- "Handoff: create_handoff_thread raised on %s: %s",
- platform_name, exc, exc_info=True,
+ source = event.source
+ logger.info(
+ "Queued inbound message during gateway startup restore: platform=%s chat=%s",
+ source.platform.value if source and source.platform else "unknown",
+ source.chat_id if source else "unknown",
)
- new_thread_id = None
+ except Exception:
+ pass
- # Use the new thread if the adapter created one; otherwise fall
- # back to whatever thread (if any) the home channel was configured
- # with.
- effective_thread_id = new_thread_id or (
- str(home.thread_id) if home.thread_id else None
- )
+ async def _drain_startup_restore_queue(self) -> int:
+ """Replay inbound messages queued while startup auto-resume ran."""
+ drained = 0
+ queue = getattr(self, "_startup_restore_queue", None)
+ if queue is None:
+ return 0
+ while queue:
+ event = queue.pop(0)
+ source = getattr(event, "source", None)
+ adapter = self._adapter_for_source(source)
+ if adapter is None:
+ logger.debug(
+ "Dropping startup-restore queued message: adapter unavailable for %s",
+ getattr(getattr(source, "platform", None), "value", None),
+ )
+ continue
+ # Mark this replay so _handle_message does not queue it again while
+ # the restore gate remains closed for any fresh inbound arrivals.
+ try:
+ setattr(event, "_hermes_startup_restore_replay", True)
+ except Exception:
+ pass
+ await adapter.handle_message(event)
+ drained += 1
+ return drained
- # Determine chat_type/user_id for the destination source.
- #
- # Telegram private-chat DM topics are represented differently from
- # group/forum threads by the inbound adapter. A handoff-created topic
- # in a positive Telegram chat_id must therefore use the same DM-topic
- # source shape as the user's next real message; otherwise the synthetic
- # handoff turn binds a generic `thread` session key while real replies
- # arrive on a `dm` session key.
- home_chat_id = str(home.chat_id)
- is_telegram_private_chat = (
- platform == Platform.TELEGRAM
- and looks_like_telegram_private_chat_id(home_chat_id)
- )
+ async def _finish_startup_restore(self) -> None:
+ """Wait (BOUNDED) for startup auto-resume, then release + drain inbound.
- if new_thread_id and not is_telegram_private_chat:
- dest_chat_type = "thread"
- dest_user_id = "system:handoff"
- else:
- # No thread — assume DM-style for the home channel. For Telegram
- # private-chat topics, use the real user id (same as chat_id) so
- # topic-mode checks and binding persistence see the same identity as
- # subsequent inbound user messages.
- dest_chat_type = "dm"
- dest_user_id = home_chat_id if is_telegram_private_chat else "system:handoff"
+ The wait is bounded by ``_startup_restore_drain_timeout_secs`` so that
+ a single pathologically long boot-resume turn cannot hold the inbound
+ gate shut for every channel. On timeout we release the gate and let
+ the still-running resume turn(s) finish in the background — they are
+ NOT cancelled. This is safe because duplicate-agent protection does
+ not depend on the wait: ``_schedule_resume_pending_sessions`` claims
+ each session's ``_running_agents`` slot SYNCHRONOUSLY before this gate
+ runs, so any inbound message drained while a resume turn is still in
+ flight queues behind that slot instead of spawning a second agent.
+ """
+ tasks = list(getattr(self, "_startup_restore_tasks", []) or [])
+ if tasks:
+ timeout = _startup_restore_drain_timeout_secs()
+ if timeout > 0:
+ # asyncio.wait (unlike wait_for / gather+timeout) does NOT
+ # cancel the pending tasks on timeout — the slow resume turn
+ # keeps running in the background instead of being killed.
+ done, pending = await asyncio.wait(tasks, timeout=timeout)
+ if pending:
+ logger.warning(
+ "Startup-restore gate released after %.0fs with %d boot "
+ "auto-resume turn(s) still running; draining inbound "
+ "queue now (resume slots already claimed, so no "
+ "duplicate agents). Slow turn(s) continue in the "
+ "background.",
+ timeout,
+ len(pending),
+ )
+ # These tasks outlive the gate. Their normal done-callback
+ # only discards them from _background_tasks, so a LATER
+ # failure would be silently swallowed. Attach a logging
+ # callback so a background resume turn that fails after the
+ # timeout is still recorded.
+ for task in pending:
+ task.add_done_callback(self._log_background_resume_result)
+ else:
+ # Non-positive timeout => opt out of the bound (historical
+ # "wait forever" behaviour).
+ await asyncio.gather(*tasks, return_exceptions=True)
+ done = set(tasks)
+ for task in done:
+ if task.cancelled():
+ continue
+ exc = task.exception()
+ if exc is not None:
+ logger.debug(
+ "startup auto-resume task failed",
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
+ self._startup_restore_tasks = []
+ drained = await self._drain_startup_restore_queue()
+ self._startup_restore_in_progress = False
+ if drained:
+ logger.info("Drained %d inbound message(s) queued during startup restore", drained)
- dest_source = SessionSource(
- platform=platform,
- chat_id=home_chat_id,
- chat_name=home.name,
- chat_type=dest_chat_type,
- user_id=dest_user_id,
- user_name="Handoff",
- thread_id=effective_thread_id,
- )
+ @staticmethod
+ def _log_background_resume_result(task: "asyncio.Task") -> None:
+ """Done-callback for a boot-resume turn that outlived the
+ startup-restore gate. Logs a late failure that would otherwise be
+ swallowed once the task is discarded from ``_background_tasks``.
+ Cancellation is expected (shutdown) and is not an error."""
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.debug(
+ "background startup auto-resume task failed after gate release",
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
- # Compute the gateway's session_key for that destination using the
- # same rules its adapters use, so switch_session targets the right
- # entry. For thread destinations build_session_key keys without
- # user_id (thread_sessions_per_user defaults to False) — so the
- # next real user message in the thread shares this same session.
- platform_cfg = self.config.platforms.get(platform)
- extra = platform_cfg.extra if platform_cfg else {}
- session_key = build_session_key(
- dest_source,
- group_sessions_per_user=extra.get("group_sessions_per_user", True),
- thread_sessions_per_user=extra.get("thread_sessions_per_user", False),
- )
+ async def _redeliver_pending_obligations(self) -> int:
+ """Redeliver final responses recorded in the delivery ledger by a
+ previous (now dead) gateway process.
- # Make sure there's an entry in the session_store for this key. If
- # the home channel has never been used, get_or_create_session
- # creates one; switch_session then re-points it.
- await self.async_session_store.get_or_create_session(dest_source)
+ Runs at startup BEFORE ``_schedule_resume_pending_sessions``. A
+ session with a recoverable obligation already produced its answer —
+ the turn completed and only delivery is owed — so this method sends
+ the stored text and clears ``resume_pending`` for that session,
+ preventing the resume path from re-running (and re-paying for) a
+ turn whose output we hold.
- # Re-bind the destination key to the CLI session_id. switch_session
- # ends the prior session in SQLite and reopens the CLI session under
- # the new key. The CLI's transcript becomes the active one for the
- # gateway from this moment on.
- switched = await self.async_session_store.switch_session(session_key, cli_session_id)
- if switched is None:
- raise RuntimeError(
- f"could not switch session key {session_key} → {cli_session_id}"
+ Crash-ambiguity contract (see gateway/delivery_ledger.py):
+ rows that were mid-send or previously rejected carry a visible
+ recovered-reply marker so a possible duplicate is labeled, never
+ silent. Returns the number of redeliveries attempted.
+ """
+ try:
+ from gateway.delivery_ledger import (
+ RECOVERED_MARKER,
+ ledger_enabled,
+ mark_delivered,
+ mark_failed,
+ sweep_recoverable,
)
- # Evict any cached AIAgent for this session_key so the next dispatch
- # rebuilds it against the CLI session_id (mirrors /resume / /branch).
- self._evict_cached_agent(session_key)
+ if not ledger_enabled():
+ return 0
+ # Only claim rows we can actually send this boot: self.adapters
+ # holds a platform only after its connect() succeeded, and each
+ # claim spends one of the row's three redelivery attempts.
+ _deliverable = {
+ getattr(p, "value", str(p)) for p in self.adapters
+ }
+ claimed = await asyncio.to_thread(
+ sweep_recoverable, None, deliverable_platforms=_deliverable
+ )
+ except Exception:
+ logger.debug("delivery ledger sweep failed", exc_info=True)
+ return 0
+ if not claimed:
+ return 0
- # Cancel any in-flight running-agent state for the destination key
- # so the synthetic turn isn't queued behind a stale running flag.
- self._release_running_agent_state(session_key)
+ redelivered = 0
+ for row in claimed:
+ try:
+ platform = Platform(row["platform"])
+ except Exception:
+ logger.debug(
+ "obligation %s: unknown platform %r",
+ row["obligation_id"], row.get("platform"),
+ )
+ continue
+ adapter = self.adapters.get(platform)
+ if adapter is None:
+ # Platform not connected this boot — leave the row claimed;
+ # attempts cap + stale cutoff bound the retries on later boots.
+ continue
+ content = row["content"]
+ if row.get("needs_marker"):
+ content = RECOVERED_MARKER + content
+ metadata = (
+ {"thread_id": row["thread_id"]} if row.get("thread_id") else None
+ )
+ try:
+ result = await adapter.send(
+ chat_id=row["chat_id"],
+ content=content,
+ metadata=metadata,
+ )
+ except Exception as send_err:
+ logger.warning(
+ "obligation %s: redelivery send raised: %s",
+ row["obligation_id"], send_err,
+ )
+ result = None
+ try:
+ if result is not None and getattr(result, "success", False):
+ mark_delivered(row["obligation_id"])
+ redelivered += 1
+ logger.info(
+ "Redelivered recovered final response to %s:%s "
+ "(obligation %s, attempt %d)",
+ row["platform"], row["chat_id"],
+ row["obligation_id"], row["attempts"],
+ )
+ else:
+ mark_failed(
+ row["obligation_id"],
+ str(getattr(result, "error", "") or "send failed"),
+ )
+ except Exception:
+ logger.debug("delivery ledger update failed", exc_info=True)
- synthetic_text = (
- f"[Session was just handed off from CLI (\"{cli_title}\") to this "
- f"channel. The full prior conversation history is loaded above. "
- f"Briefly confirm you're working here and summarize what we were "
- f"working on, so the user can continue from this device.]"
- )
+ # The answer reached (or was owed to) this session — don't ALSO
+ # re-run the turn via the resume path.
+ session_key = row.get("session_key") or ""
+ if session_key:
+ try:
+ await self.async_session_store.clear_resume_pending(session_key)
+ except Exception:
+ logger.debug(
+ "clear_resume_pending failed for %s", session_key,
+ exc_info=True,
+ )
+ return redelivered
- synthetic_event = MessageEvent(
- text=synthetic_text,
- source=dest_source,
- internal=True,
- )
+ def _schedule_resume_pending_sessions(self, platform=None) -> int:
+ """Auto-continue fresh restart-interrupted sessions after startup.
- logger.info(
- "Handoff: dispatching synthetic turn for CLI session %s → %s "
- "(home=%s, thread=%s, session_key=%s)",
- cli_session_id, platform_name, home.chat_id, effective_thread_id,
- session_key,
- )
+ ``resume_pending`` already preserves the transcript AND the existing
+ ``_is_resume_pending`` branch in ``_handle_message_with_agent``
+ injects a reason-aware recovery system note on the next turn. This
+ method closes the UX gap by synthesizing that next turn once
+ adapters are back online — the event text is empty so the existing
+ injection path owns the wording and we never double up.
- # Dispatch through the runner directly. Going through
- # adapter.handle_message would spawn a background task and we'd
- # lose synchronous error visibility; calling _handle_message inline
- # keeps the success/failure path observable for the watcher.
- response_text = await self._handle_message(synthetic_event)
- if not response_text:
- # Streaming may have already delivered the response inline.
- # Either way, agent ran without raising — count as success.
- return
+ Adapters that are not yet ready (adapter missing from
+ ``self.adapters``) are skipped silently; their sessions stay
+ ``resume_pending`` and will auto-resume on the next real user
+ message, or when the platform reconnects — the reconnect watcher
+ calls this again scoped to that ``platform``.
- # Send the agent's reply to the destination. Route to the new
- # thread if we created one; otherwise the configured home channel
- # (which may itself carry a thread_id). Send through the resolved
- # transport (not adapter.send directly) so a relay-fronted logical
- # platform is stamped on the outbound frame (send_for_platform).
- send_metadata: Dict[str, Any] = {}
- if effective_thread_id:
- send_metadata["thread_id"] = effective_thread_id
+ ``platform`` (a ``Platform``) restricts the pass to sessions that
+ originated on that platform. The reconnect path passes it so a
+ platform coming back online retries only its own sessions and never
+ re-touches another platform's in-flight recoveries. Sessions whose
+ agent is already running are skipped regardless, so a session
+ scheduled at startup is never resumed a second time.
+ """
+ window = _auto_continue_freshness_window()
try:
- result = await transport.send(
- platform,
- str(home.chat_id),
- response_text,
- send_metadata or None,
- )
+ with self.session_store._lock: # noqa: SLF001 — snapshot under lock
+ self.session_store._ensure_loaded_locked() # noqa: SLF001
+ candidates = [
+ entry for entry in self.session_store._entries.values() # noqa: SLF001
+ if entry.resume_pending
+ and not entry.suspended
+ and entry.origin is not None
+ and entry.resume_reason in self._AUTO_RESUME_REASONS
+ and (platform is None or entry.origin.platform == platform)
+ ]
except Exception as exc:
- raise RuntimeError(f"adapter.send failed: {exc}") from exc
+ logger.warning("Failed to enumerate resume-pending sessions: %s", exc)
+ return 0
- if not getattr(result, "success", True):
- err = getattr(result, "error", "send returned success=False")
- raise RuntimeError(f"adapter.send failed: {err}")
+ # Defense-3 (#30719): break the SIGTERM-respawn loop. Only count this
+ # boot when there are restart-interrupted sessions to resume — a clean
+ # boot must not accrue toward the breaker. If too many such boots have
+ # happened in the configured window, skip auto-resume for THIS boot:
+ # the gateway still comes up and serves real inbound messages, it just
+ # stops replaying the session that keeps killing it. The session stays
+ # resume_pending, so a real user message can still continue it (a human
+ # is now in the loop). Defenses 1-2 cover the cron/CLI/terminal paths;
+ # this catches every other SIGTERM source (e.g. a raw `terminal(
+ # "launchctl kickstart ai.hermes.gateway")`).
+ if candidates:
+ try:
+ from gateway import restart_loop_guard as _rlg
- async def _session_expiry_watcher(self, interval: int = 300):
- """Background task that finalizes expired sessions.
+ _max_restarts, _window = self._restart_loop_guard_config()
+ if _rlg.check_and_record(_max_restarts, _window):
+ return 0
+ except Exception as exc: # noqa: BLE001 — breaker must fail OPEN
+ logger.debug("Restart-loop guard check skipped: %s", exc)
- Runs every ``interval`` seconds (default 5 min). For each session
- whose reset policy has expired, invokes ``on_session_finalize``
- hooks, cleans up the cached AIAgent's tool resources, evicts the
- cache entry so it can be garbage-collected, and marks the session
- so it won't be finalized again.
- """
- await asyncio.sleep(60) # initial delay — let the gateway fully start
- _finalize_failures: dict[str, int] = {} # session_id -> consecutive failure count
- _MAX_FINALIZE_RETRIES = 3
- while self._running:
- try:
- await self.async_session_store._ensure_loaded()
- # Collect expired sessions first, then log a single summary.
- _expired_entries = []
- for key, entry in list(self.session_store._entries.items()):
- if entry.expiry_finalized:
- continue
- if not await self.async_session_store._is_session_expired(entry):
- continue
- _expired_entries.append((key, entry))
+ now = datetime.now()
+ scheduled = 0
+ for entry in candidates:
+ marker = entry.last_resume_marked_at or entry.updated_at
+ if marker is not None and (now - marker).total_seconds() > window:
+ continue
- if _expired_entries:
- # Extract platform names from session keys for a compact summary.
- # Keys look like "agent:main:telegram:dm:12345" — platform is field [2].
- _platforms: dict[str, int] = {}
- for _k, _e in _expired_entries:
- _parts = _k.split(":")
- _plat = _parts[2] if len(_parts) > 2 else "unknown"
- _platforms[_plat] = _platforms.get(_plat, 0) + 1
- _plat_summary = ", ".join(
- f"{p}:{c}" for p, c in sorted(_platforms.items())
- )
- logger.info(
- "Session expiry: %d sessions to finalize (%s)",
- len(_expired_entries), _plat_summary,
+ # Already being resumed (e.g. scheduled at startup and still
+ # in-flight) — don't synthesize a second continuation turn.
+ if self._is_session_running(entry.session_key):
+ continue
+
+ source = entry.origin
+ adapter = self._adapter_for_source(source)
+ if adapter is None:
+ logger.debug(
+ "Skipping auto-resume for %s: adapter not ready for %s",
+ entry.session_key,
+ getattr(source.platform, "value", source.platform),
+ )
+ continue
+
+ # Validate the session owner against the current allowlist
+ # before auto-resuming. A session created before
+ # TELEGRAM_ALLOWED_USERS (or equivalent) was configured, or
+ # before the owner was removed from it, must not silently
+ # receive a full agent response on gateway restart just
+ # because it has a resume-pending marker (issue #23778).
+ try:
+ if not self._is_user_authorized(source):
+ logger.warning(
+ "Skipping auto-resume for %s: session owner is no "
+ "longer authorized under the current allowlist",
+ entry.session_key,
)
+ continue
+ except Exception as exc:
+ logger.warning(
+ "Skipping auto-resume for %s: authorization check failed: %s",
+ entry.session_key, exc,
+ )
+ continue
- for key, entry in _expired_entries:
- try:
- try:
- from hermes_cli.lifecycle import finalize_session
- _parts = key.split(":")
- _platform = _parts[2] if len(_parts) > 2 else ""
- finalize_session(
- session_id=entry.session_id,
- platform=_platform,
- reason="session_expired",
- )
- except Exception:
- pass
- # Shut down memory provider and close tool resources
- # on the cached agent. Idle agents live in
- # _agent_cache (not _running_agents), so look there.
- _cached_agent = None
- _cache_lock = getattr(self, "_agent_cache_lock", None)
- if _cache_lock is not None:
- with _cache_lock:
- _cached = self._agent_cache.get(key)
- _cached_agent = _cached[0] if isinstance(_cached, tuple) else _cached if _cached else None
- # Fall back to _running_agents in case the agent is
- # still mid-turn when the expiry fires.
- if _cached_agent is None:
- _exp_state = self._peek_session_state(key)
- _cached_agent = _exp_state.turn.agent if _exp_state else None
- if _cached_agent and _cached_agent is not _AGENT_PENDING_SENTINEL:
- await self._cleanup_agent_resources_off_loop(
- _cached_agent, context="session expiry"
- )
- # Drop the cache entry so the AIAgent (and its LLM
- # clients, tool schemas, memory provider refs) can
- # be garbage-collected. Otherwise the cache grows
- # unbounded across the gateway's lifetime.
- self._evict_cached_agent(key)
- # Permanently finalizing this session — one funnel
- # call drops every conversation-scoped dict AND the
- # boundary security state (approvals, update
- # prompts, slash-confirm) so the dicts don't grow
- # unbounded across the gateway's lifetime. (Idle
- # agent-cache eviction must NOT do this: the
- # session is still alive and a resumed turn rebuilds
- # its agent from these overrides. Only true session
- # finalization, /new, and /reset clear them.) See
- # _CONVERSATION_SCOPED_STATE.
- self._clear_conversation_scope(
- key, reason="expiry_finalized"
- )
- # Persist the finalized flag to sessions.json AND
- # state.db (single write-path, #9006) — also drops
- # the persisted /model override, since finalization
- # is a conversation boundary.
- await self.async_session_store.set_expiry_finalized(entry)
- logger.debug(
- "Session expiry finalized for %s",
- entry.session_id,
- )
- _finalize_failures.pop(entry.session_id, None)
- except Exception as e:
- failures = _finalize_failures.get(entry.session_id, 0) + 1
- _finalize_failures[entry.session_id] = failures
- if failures >= _MAX_FINALIZE_RETRIES:
- logger.warning(
- "Session finalize gave up after %d attempts for %s: %s. "
- "Marking as finalized to prevent infinite retry loop.",
- failures, entry.session_id, e,
- )
- await self.async_session_store.set_expiry_finalized(
- entry, clear_model_override=False
- )
- _finalize_failures.pop(entry.session_id, None)
- else:
- logger.debug(
- "Session finalize failed (%d/%d) for %s: %s",
- failures, _MAX_FINALIZE_RETRIES, entry.session_id, e,
- )
+ # Claim the session slot *before* spawning the task so that an
+ # inbound message arriving between task creation and the task's
+ # first await (where _process_message_background sets the real
+ # sentinel) sees the slot as occupied and queues behind it
+ # instead of spinning up a duplicate AIAgent (#45456).
+ _resume_state = self._session_state(entry.session_key)
+ _resume_state.turn.agent = _AGENT_PENDING_SENTINEL
+ _resume_state.turn.started_ts = time.time()
+ self._persist_active_agents()
- if _expired_entries:
- _done = sum(
- 1 for _, e in _expired_entries if e.expiry_finalized
- )
- _failed = len(_expired_entries) - _done
- if _failed:
- logger.info(
- "Session expiry done: %d finalized, %d pending retry",
- _done, _failed,
- )
- else:
- logger.info(
- "Session expiry done: %d finalized", _done,
- )
+ # Empty-text internal event — the _is_resume_pending branch in
+ # _handle_message_with_agent prepends the proper reason-aware
+ # system note before the turn runs.
+ event = MessageEvent(
+ text="",
+ message_type=MessageType.TEXT,
+ source=source,
+ internal=True,
+ )
+ task = asyncio.create_task(
+ self._run_startup_resume_event(adapter, event, entry.session_key)
+ )
+ self._background_tasks.add(task)
+ task.add_done_callback(self._background_tasks.discard)
+ if getattr(self, "_startup_restore_in_progress", False):
+ tasks = getattr(self, "_startup_restore_tasks", None)
+ if tasks is None:
+ tasks = []
+ self._startup_restore_tasks = tasks
+ tasks.append(task)
+ scheduled += 1
+ if scheduled:
+ logger.info(
+ "Scheduled auto-resume for %d restart-interrupted session(s)",
+ scheduled,
+ )
+ return scheduled
- # Sweep agents that have been idle beyond the TTL regardless
- # of session reset policy. This catches sessions with very
- # long / "never" reset windows, whose cached AIAgents would
- # otherwise pin memory for the gateway's entire lifetime.
- try:
- _idle_evicted = self._sweep_idle_cached_agents()
- if _idle_evicted:
- logger.info(
- "Agent cache idle sweep: evicted %d agent(s)",
- _idle_evicted,
- )
- except Exception as _e:
- logger.debug("Idle agent sweep failed: %s", _e)
+ def _startup_should_abort(self) -> bool:
+ return (
+ self._restart_requested
+ or self._draining
+ or self._shutdown_event.is_set()
+ )
- # Periodically prune stale SessionStore entries. The
- # in-memory dict (and sessions.json) would otherwise grow
- # unbounded in gateways serving many rotating chats /
- # threads / users over long time windows. Pruning is
- # invisible to users — a resumed session just gets a
- # fresh session_id, exactly as if the reset policy fired.
- _last_prune_ts = getattr(self, "_last_session_store_prune_ts", 0.0)
- _prune_interval = 3600.0 # once per hour
- if time.time() - _last_prune_ts > _prune_interval:
- try:
- _max_age = int(
- getattr(self.config, "session_store_max_age_days", 0) or 0
- )
- if _max_age > 0:
- _pruned = await self.async_session_store.prune_old_entries(_max_age)
- if _pruned:
- logger.info(
- "SessionStore prune: dropped %d stale entries",
- _pruned,
- )
- except Exception as _e:
- logger.debug("SessionStore prune failed: %s", _e)
- self._last_session_store_prune_ts = time.time()
+ async def _abort_startup_if_shutdown_requested(
+ self,
+ adapter: Optional[BasePlatformAdapter] = None,
+ platform: Optional[Platform] = None,
+ ) -> bool:
+ """Clean up and exit startup when restart/shutdown begins mid-startup."""
+ if not self._startup_should_abort():
+ return False
+ if adapter is not None and platform is not None:
+ try:
+ await adapter.cancel_background_tasks()
except Exception as e:
- logger.debug("Session expiry watcher error: %s", e)
- # Sleep in small increments so we can stop quickly
- for _ in range(interval):
- if not self._running:
- break
- await asyncio.sleep(1)
-
- def _active_profile_name(self) -> str:
- """Return the profile name this gateway represents."""
- try:
- from hermes_cli.profiles import get_active_profile_name
- return get_active_profile_name() or "default"
- except Exception:
- return "default"
-
- # ── Kanban board watchers ───────────────────────────────────────────
- # The kanban notifier/dispatcher watcher loops + their helpers live in
- # GatewayKanbanWatchersMixin (gateway/kanban_watchers.py). They use only
- # self state, so inheriting the mixin keeps every self._kanban_* call site
- # working unchanged while lifting ~1,000 LOC out of this file.
+ logger.debug("✗ %s background-task cancel error: %s", platform.value, e)
+ await self._safe_adapter_disconnect(adapter, platform)
+ stop_task = self._stop_task
+ current_task = asyncio.current_task()
+ if stop_task is not None and stop_task is not current_task:
+ await stop_task
+ elif not self._shutdown_event.is_set():
+ await self.stop(
+ restart=self._restart_requested,
+ detached_restart=self._restart_detached,
+ service_restart=self._restart_via_service,
+ )
+ return True
- def _ensure_reconnect_watcher_running(self) -> None:
- """Ensure the platform reconnect watcher background task is alive.
+ def _start_loop_liveness_guards(self, loop: asyncio.AbstractEventLoop) -> None:
+ """Arm the selector floor and out-of-loop watchdog before adapters.
- If the tracked reconnect watcher task has died (e.g. from exhausting
- its restart budget, or a terminal exception that _spawn_supervised
- could not recover), respawns it so platforms queued for reconnection
- are not permanently stranded. Called after queueing a retryable fatal
- error in _handle_adapter_fatal_error (#70344).
+ Disabled entirely with ``gateway.loop_watchdog: false`` in config.yaml
+ (no env override — config-only knob, #69089).
"""
- if not getattr(self, "_running", False):
+ config = getattr(self, "config", None)
+ if config is not None and not getattr(config, "loop_watchdog", True):
return
- task = getattr(self, "_reconnect_watcher_task", None)
- if task is not None and not task.done():
- return # already alive
- logger.warning(
- "Reconnect watcher task is dead (done=%s) — respawning",
- task.done() if task is not None else "N/A",
- )
- self._reconnect_watcher_task = self._spawn_supervised(
- self._platform_reconnect_watcher,
- "platform_reconnect_watcher",
- on_spawn=lambda t: setattr(self, "_reconnect_watcher_task", t),
- )
+ if getattr(self, "_loop_floor_timer_handle", None) is None:
+ try:
+ self._loop_floor_timer_handle = _arm_loop_floor_timer(loop)
+ except Exception:
+ logger.debug("Failed to arm gateway loop floor timer", exc_info=True)
- async def _platform_reconnect_watcher(self) -> None:
- """Background task that periodically retries connecting failed platforms.
+ watchdog = getattr(self, "_loop_liveness_watchdog", None)
+ if watchdog is None or not watchdog.is_alive():
+ try:
+ self._loop_liveness_watchdog = start_loop_liveness_watchdog(loop)
+ except Exception:
+ logger.debug("Failed to start gateway loop liveness watchdog", exc_info=True)
- Uses exponential backoff: 30s → 60s → 120s → 240s → 300s (cap).
- Retryable failures (network/DNS blips) keep retrying at the backoff
- cap indefinitely — they self-heal once connectivity returns, so a
- transient outage never requires manual intervention. Non-retryable
- failures (bad auth, etc.) drop out of the queue immediately. The
- circuit breaker (``_pause_failed_platform`` / ``/platform pause``)
- remains available for manual operator control via ``/platform list``
- and ``/platform resume <name>``, but is no longer triggered
- automatically — auto-pausing a recovered platform was the cause of
- bots silently staying dead after a transient DNS failure.
- """
- await asyncio.sleep(10) # initial delay — let startup finish
- while self._running:
- if not self._failed_platforms:
- # Nothing to reconnect — sleep and check again
- for _ in range(30):
- if not self._running:
- return
- if self._failed_platforms:
- break
- await asyncio.sleep(1)
- continue
+ def _stop_loop_liveness_guards(self) -> None:
+ """Disarm lifetime liveness guards before shutdown can load the loop."""
+ watchdog = getattr(self, "_loop_liveness_watchdog", None)
+ self._loop_liveness_watchdog = None
+ if watchdog is not None:
+ try:
+ watchdog.stop()
+ except Exception:
+ logger.debug("Failed to stop gateway loop liveness watchdog", exc_info=True)
- now = time.monotonic()
- for platform in list(self._failed_platforms.keys()):
- if not self._running:
- return
- info = self._failed_platforms.get(platform)
- if info is None:
- # Removed concurrently (e.g. a manual /platform resume,
- # or a reconnect that succeeded via a different path)
- # between the snapshot above and this lookup. Not an
- # error -- just nothing to do for it this pass.
- continue
- # Skip paused platforms entirely — they need explicit
- # /platform resume to come back.
- if info.get("paused"):
- continue
- if now < info["next_retry"]:
- continue # not time yet
+ floor_timer = getattr(self, "_loop_floor_timer_handle", None)
+ self._loop_floor_timer_handle = None
+ if floor_timer is not None:
+ try:
+ floor_timer.cancel()
+ except Exception:
+ logger.debug("Failed to cancel gateway loop floor timer", exc_info=True)
- platform_config = info["config"]
- attempt = info["attempts"] + 1
- # Empty-token primary configs can never reconnect; drop them so
- # multiplex setups where a secondary profile owns the bot do
- # not spin forever (#64674).
- if not _platform_has_bot_credential(platform, platform_config):
- logger.warning(
- "Reconnect %s: no bot credential on queued config, "
- "removing from retry queue",
- platform.value,
- )
- del self._failed_platforms[platform]
- continue
- logger.info(
- "Reconnecting %s (attempt %d)...",
- platform.value, attempt,
+ async def start(self) -> bool:
+ """
+ Start the gateway and all configured platform adapters.
+
+ Returns True if at least one adapter connected successfully.
+ """
+ logger.info("Starting Hermes Gateway...")
+ # Enable faulthandler for stack dumps on freezes/crashes (#70344).
+ # Falls back to a log file when sys.stderr is None (Windows VBS /
+ # pythonw / detached service) — otherwise the gateway would die
+ # here and take every adapter offline. See #71671.
+ try:
+ faulthandler.enable()
+ except (RuntimeError, ValueError, OSError):
+ try:
+ _fh_log_dir = getattr(self.config, "log_dir", None) or os.path.join(
+ str(get_hermes_home()),
+ "logs",
)
+ os.makedirs(_fh_log_dir, exist_ok=True)
+ _fh_enable_path = os.path.join(_fh_log_dir, "gateway_faulthandler.log")
+ _fh_enable_file = open(_fh_enable_path, "a", encoding="utf-8")
+ faulthandler.enable(file=_fh_enable_file, all_threads=True)
+ except Exception:
+ logger.debug("faulthandler.enable() unavailable", exc_info=True)
+ # Also dump stacks to a rotating file for off-line analysis when
+ # the gateway is running under a service manager that doesn't
+ # capture stderr.
+ # faulthandler.register() and SIGUSR2 are POSIX-only; skip the
+ # signal-triggered file dump on Windows (faulthandler.enable()
+ # above still covers fatal-error dumps there).
+ _sigusr2 = getattr(signal, "SIGUSR2", None)
+ if _sigusr2 is not None and hasattr(faulthandler, "register"):
+ try:
+ _log_dir = getattr(self.config, "log_dir", None) or os.path.join(
+ str(get_hermes_home()),
+ "logs",
+ )
+ _faulthandler_path = os.path.join(_log_dir, "gateway_faulthandler.log")
+ os.makedirs(_log_dir, exist_ok=True)
+ _fh = open(_faulthandler_path, "a", encoding="utf-8")
+ faulthandler.register(
+ _sigusr2,
+ file=_fh,
+ all_threads=True,
+ chain=True,
+ )
+ except Exception:
+ logger.debug("Could not set up faulthandler file logging", exc_info=True)
- adapter = None
- try:
- adapter = self._create_adapter(platform, platform_config)
- if not adapter:
- logger.warning(
- "Reconnect %s: adapter creation returned None, removing from retry queue",
- platform.value,
- )
- del self._failed_platforms[platform]
- continue
-
- adapter.set_message_handler(self._handle_message)
- adapter.set_fatal_error_handler(self._handle_adapter_fatal_error)
- adapter.set_session_store(self.session_store)
- adapter.set_busy_session_handler(self._handle_active_session_busy_message)
- _set_reaction = getattr(adapter, "set_reaction_handler", None)
- if callable(_set_reaction):
- _set_reaction(self._handle_reaction_event)
- adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
- adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))
- adapter._busy_text_mode = self._busy_text_mode
-
- # Reconnect after an outage: preserve the platform's
- # server-side update queue so messages sent while the bot
- # was offline are delivered rather than dropped (#46621).
- success = await self._connect_adapter_with_timeout(
- adapter, platform, is_reconnect=True
- )
- if success:
- self.adapters[platform] = adapter
- self._sync_voice_mode_state_to_adapter(adapter)
- # Wire voice input callback on reconnect as well (#60623).
- if hasattr(adapter, "_voice_input_callback"):
- adapter._voice_input_callback = self._handle_voice_channel_input
- self.delivery_router.adapters = self.adapters
- del self._failed_platforms[platform]
- self._update_platform_runtime_status(
- platform.value,
- platform_state="connected",
- error_code=None,
- error_message=None,
- )
- logger.info("✓ %s reconnected successfully", platform.value)
+ try:
+ self._gateway_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ self._gateway_loop = None
+ if self._gateway_loop is not None:
+ self._start_loop_liveness_guards(self._gateway_loop)
+ logger.info("Session storage: %s", self.config.sessions_dir)
- # Rebuild channel directory with the new adapter
- try:
- from gateway.channel_directory import build_channel_directory
- await build_channel_directory(self.adapters)
- except Exception:
- pass
+ # Sanity-check that systemd's TimeoutStopSec covers our drain
+ # window. When the user upgraded hermes-agent without re-running
+ # ``hermes setup``, their unit file may still encode the old
+ # default — in which case SIGKILL hits mid-drain and looks like
+ # a phantom kill in the journal. Best-effort, never raises.
+ try:
+ from gateway.shutdown_forensics import check_systemd_timing_alignment
+ _alignment = check_systemd_timing_alignment(self._restart_drain_timeout)
+ if _alignment is not None and _alignment.get("mismatch"):
+ logger.warning(
+ "Stale systemd unit detected: %s has TimeoutStopSec=%.0fs but "
+ "drain_timeout=%.0fs (expected >=%.0fs). systemd may SIGKILL the "
+ "gateway mid-drain. Run `hermes gateway install --force` "
+ "to regenerate the unit, or shorten agent.restart_drain_timeout.",
+ _alignment.get("unit", "(unknown)"),
+ _alignment["timeout_stop_sec"],
+ _alignment["drain_timeout"],
+ _alignment["expected_min"],
+ )
+ except Exception as _e:
+ logger.debug("check_systemd_timing_alignment failed: %s", _e)
+ # Log the resolved max_iterations budget so operators can verify the
+ # config.yaml → env bridge did the right thing at a glance (instead
+ # of silently running at a stale .env value for weeks).
+ try:
+ _effective_max_iter = int(os.getenv("HERMES_MAX_ITERATIONS", "500"))
+ logger.info(
+ "Agent budget: max_iterations=%d (agent.max_turns from config.yaml, "
+ "or HERMES_MAX_ITERATIONS from .env, or default 500)",
+ _effective_max_iter,
+ )
+ except Exception:
+ pass
+ # Redaction status: ON by default (#17691). Surface a prominent
+ # warning if an operator has explicitly opted out so they don't
+ # forget the downgrade is active — the redactor snapshots its
+ # state at import time, so this log line is the source of truth
+ # for this process's lifetime.
+ try:
+ _redact_raw = os.getenv("HERMES_REDACT_SECRETS", "true")
+ _redact_on = _redact_raw.lower() in {"1", "true", "yes", "on"}
+ if _redact_on:
+ logger.info(
+ "Secret redaction: ENABLED (tool output, logs, and chat "
+ "responses are scrubbed before delivery)"
+ )
+ else:
+ logger.warning(
+ "Secret redaction: DISABLED (HERMES_REDACT_SECRETS=%s). "
+ "API keys and tokens may appear verbatim in chat output, "
+ "session JSONs, and logs. Set security.redact_secrets: true "
+ "in config.yaml to re-enable.",
+ _redact_raw,
+ )
+ except Exception:
+ pass
+ try:
+ from hermes_cli.profiles import get_active_profile_name
+ _profile = get_active_profile_name()
+ if _profile and _profile != "default":
+ logger.info("Active profile: %s", _profile)
+ except Exception:
+ pass
+ try:
+ from gateway.status import write_runtime_status
+ write_runtime_status(gateway_state="starting", exit_reason=None)
+ except Exception:
+ pass
+ try:
+ from hermes_cli.config import load_config
+ from agent.monitoring.gateway_health_export import start_gateway_health_export
+ self._gateway_health_export_runtime = start_gateway_health_export(load_config())
+ if getattr(self._gateway_health_export_runtime, "enabled", False):
+ logger.info("Gateway health OTLP export: enabled")
+ except Exception:
+ logger.debug("gateway health OTLP export startup failed", exc_info=True)
- # A platform that was offline at gateway startup never
- # got its restart-interrupted sessions auto-resumed —
- # the startup pass skips sessions whose adapter isn't
- # connected yet. Now that it's back, retry the
- # auto-resume scoped to this platform so recovery
- # doesn't silently wait for a manual user message.
- try:
- self._schedule_resume_pending_sessions(platform=platform)
- except Exception:
- logger.debug(
- "resume-pending reschedule after %s reconnect failed",
- platform.value,
- exc_info=True,
- )
- # Check if the failure is non-retryable
- elif adapter.has_fatal_error and not adapter.fatal_error_retryable:
- self._update_platform_runtime_status(
- platform.value,
- platform_state="fatal",
- error_code=adapter.fatal_error_code,
- error_message=adapter.fatal_error_message,
- )
- logger.warning(
- "Reconnect %s: non-retryable error (%s), removing from retry queue",
- platform.value, adapter.fatal_error_message,
- )
- # The adapter is about to be dropped from the queue
- # without ever being installed on self.adapters, so
- # nothing else will call disconnect() on it. We must
- # dispose it here, otherwise the resource owners it
- # constructed in __init__ (ResponseStore for
- # APIServerAdapter, etc.) leak 2 fds each. The
- # gateway hits the 2560-fd limit after ~12h of
- # failed reconnects at the 300s backoff cap (#37011).
- await _dispose_unused_adapter(adapter)
- del self._failed_platforms[platform]
- else:
- self._update_platform_runtime_status(
- platform.value,
- platform_state="retrying",
- error_code=adapter.fatal_error_code,
- error_message=adapter.fatal_error_message or "failed to reconnect",
- )
- backoff = _reconnect_backoff(attempt)
- info["attempts"] = attempt
- info["next_retry"] = time.monotonic() + backoff
- logger.info(
- "Reconnect %s failed, next retry in %ds",
- platform.value, backoff,
- )
- # Same fd-leak concern as the non-retryable branch
- # above: the adapter failed to connect and is being
- # thrown away. Without an explicit dispose call, the
- # resources it opened in __init__ stay open until
- # the next GC pass — and aiohttp/SQLite handles
- # don't get GC'd promptly, so 2 fds/retry leak at
- # 300s backoff cap = ~12 fds/hour (#37011).
- await _dispose_unused_adapter(adapter)
- # Retryable failures (network/DNS blips) keep retrying
- # at the backoff cap indefinitely — they self-heal once
- # connectivity returns. We do NOT auto-pause them: a
- # transient outage must never require manual `/platform
- # resume` to recover. Non-retryable failures (bad auth,
- # etc.) already drop out of the queue via the
- # `not fatal_error_retryable` branch above, so anything
- # reaching here is by definition retryable.
- except Exception as e:
- if adapter is not None:
- # An exception escaping the connect call path
- # (DNS timeout, aiohttp server.start() crash, etc.)
- # leaves the adapter in the same unowned state as
- # the two branches above. Dispose so __init__
- # resources don't accumulate while the watcher
- # keeps retrying.
- await _dispose_unused_adapter(adapter)
- self._update_platform_runtime_status(
- platform.value,
- platform_state="retrying",
- error_code=None,
- error_message=str(e),
- )
- backoff = _reconnect_backoff(attempt)
- info["attempts"] = attempt
- info["next_retry"] = time.monotonic() + backoff
- logger.warning(
- "Reconnect %s error: %s, next retry in %ds",
- platform.value, e, backoff,
- )
- # A raised exception during reconnect (connect timeout, DNS
- # resolution failure, etc.) is inherently transient — keep
- # retrying at the backoff cap rather than auto-pausing.
-
- # Check every 10 seconds for platforms that need reconnection
- for _ in range(10):
- if not self._running:
- return
- await asyncio.sleep(1)
-
- async def _cancel_secondary_profile_reconnect_tasks(self) -> None:
- """Cancel profile-scoped reconnects before tearing down their registry.
-
- A reconnect can be waiting in adapter setup while shutdown begins. It
- must not republish an adapter after the secondary registry is drained.
- Waiting is bounded by the same adapter-cleanup budget; if a task does
- not finish in time, the stopped runner state still prevents it from
- installing an adapter when it eventually resumes.
- """
- pending = self._profile_failed_platforms
- if not isinstance(pending, dict):
- return
- current = asyncio.current_task()
- tasks: list[asyncio.Task] = []
- for profile_pending in pending.values():
- if not isinstance(profile_pending, dict):
- continue
- for task in profile_pending.values():
- if isinstance(task, asyncio.Task) and task is not current and not task.done():
- tasks.append(task)
- for task in tasks:
- task.cancel()
- timeout = self._adapter_disconnect_timeout_secs()
- if tasks and timeout > 0:
- _done, unfinished = await asyncio.wait(tasks, timeout=timeout)
- if unfinished:
+ # Log any active supply-chain security advisories. Operators see this
+ # in gateway.log and `hermes status` surfaces it; we do NOT block
+ # startup or surface it inline to user messages, since the gateway
+ # operator is the one who can act on it (uninstall the package,
+ # rotate credentials). See hermes_cli/security_advisories.py.
+ try:
+ from hermes_cli.security_advisories import (
+ detect_compromised,
+ gateway_log_message,
+ )
+ _adv_hits = detect_compromised()
+ _adv_msg = gateway_log_message(_adv_hits)
+ if _adv_msg:
+ logger.warning("%s", _adv_msg)
logger.warning(
- "Timed out waiting for %d secondary profile reconnect task(s) during shutdown",
- len(unfinished),
+ "Run `hermes doctor` on the gateway host for full "
+ "remediation steps."
)
- pending.clear()
-
- def _start_systemd_watchdog(self) -> bool:
- """Start sd_notify only after a configured gateway is truly running."""
- if not self._running or self.config.systemd_watchdog_seconds <= 0:
- return False
- if self._systemd_watchdog is not None:
+ except Exception:
+ logger.debug(
+ "security advisory check failed at gateway startup",
+ exc_info=True,
+ )
+ if await self._abort_startup_if_shutdown_requested():
return True
+
+ # Warn if no user allowlists are configured and open access is not opted in
+ _builtin_allowed_vars = (
+ "TELEGRAM_ALLOWED_USERS", "DISCORD_ALLOWED_USERS",
+ "WHATSAPP_ALLOWED_USERS", "WHATSAPP_CLOUD_ALLOWED_USERS",
+ "SLACK_ALLOWED_USERS",
+ "SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
+ "TELEGRAM_GROUP_ALLOWED_USERS",
+ "TELEGRAM_GROUP_ALLOWED_CHATS",
+ "EMAIL_ALLOWED_USERS",
+ "SMS_ALLOWED_USERS", "MATTERMOST_ALLOWED_USERS",
+ "MATRIX_ALLOWED_USERS", "DINGTALK_ALLOWED_USERS",
+ "FEISHU_ALLOWED_USERS",
+ "WECOM_ALLOWED_USERS",
+ "WECOM_CALLBACK_ALLOWED_USERS",
+ "WEIXIN_ALLOWED_USERS",
+ "BLUEBUBBLES_ALLOWED_USERS",
+ "QQ_ALLOWED_USERS",
+ "YUANBAO_ALLOWED_USERS",
+ "GATEWAY_ALLOWED_USERS",
+ )
+ _builtin_allow_all_vars = (
+ "TELEGRAM_ALLOW_ALL_USERS", "DISCORD_ALLOW_ALL_USERS",
+ "WHATSAPP_ALLOW_ALL_USERS", "WHATSAPP_CLOUD_ALLOW_ALL_USERS",
+ "SLACK_ALLOW_ALL_USERS",
+ "SIGNAL_ALLOW_ALL_USERS", "EMAIL_ALLOW_ALL_USERS",
+ "SMS_ALLOW_ALL_USERS", "MATTERMOST_ALLOW_ALL_USERS",
+ "MATRIX_ALLOW_ALL_USERS", "DINGTALK_ALLOW_ALL_USERS",
+ "FEISHU_ALLOW_ALL_USERS",
+ "WECOM_ALLOW_ALL_USERS",
+ "WECOM_CALLBACK_ALLOW_ALL_USERS",
+ "WEIXIN_ALLOW_ALL_USERS",
+ "BLUEBUBBLES_ALLOW_ALL_USERS",
+ "QQ_ALLOW_ALL_USERS",
+ "YUANBAO_ALLOW_ALL_USERS",
+ )
+ # Also pick up plugin-registered platforms — each entry can declare
+ # its own allowed_users_env / allow_all_env, so the warning stays
+ # accurate as plugins like IRC come online.
+ _plugin_allowed_vars: tuple = ()
+ _plugin_allow_all_vars: tuple = ()
+ try:
+ from gateway.platform_registry import platform_registry
+ _plugin_allowed_vars = tuple(
+ e.allowed_users_env for e in platform_registry.plugin_entries()
+ if e.allowed_users_env
+ )
+ _plugin_allow_all_vars = tuple(
+ e.allow_all_env for e in platform_registry.plugin_entries()
+ if e.allow_all_env
+ )
+ except Exception:
+ pass
+ _any_allowlist = any(
+ os.getenv(v) for v in _builtin_allowed_vars + _plugin_allowed_vars
+ )
+ _allow_all = os.getenv("GATEWAY_ALLOW_ALL_USERS", "").lower() in {"true", "1", "yes"} or any(
+ os.getenv(v, "").lower() in {"true", "1", "yes"}
+ for v in _builtin_allow_all_vars + _plugin_allow_all_vars
+ )
+ if not _any_allowlist and not _allow_all:
+ logger.warning(
+ "No env user allowlists configured. Messaging platforms default to "
+ "pairing/allowlist policies and will deny unknown senders unless you "
+ "configure platform allowlists (e.g., TELEGRAM_ALLOWED_USERS=your_id) "
+ "or explicitly opt in with GATEWAY_ALLOW_ALL_USERS=true plus "
+ "dm_policy/group_policy: open on the platform."
+ )
- from gateway.systemd_notify import SystemdWatchdog
-
- watchdog = SystemdWatchdog(config_enabled=True)
- if not watchdog.start():
- return False
- self._systemd_watchdog = watchdog
- watchdog.ready("Hermes Gateway running")
- return True
+ reason = _own_policy_open_startup_violation(self.config)
+ if reason:
+ platform_value = reason.split(":", 1)[0]
+ allow_all_env = None
+ for platform, open_env in _OWN_POLICY_OPEN_ENV.items():
+ if platform.value == platform_value:
+ allow_all_env = open_env[2]
+ break
+ logger.error(
+ "Refusing to start: %s has dm_policy/group_policy set to 'open' "
+ "but neither GATEWAY_ALLOW_ALL_USERS nor %s is enabled.",
+ platform_value,
+ allow_all_env or "a platform allow-all flag",
+ )
+ try:
+ from gateway.status import write_runtime_status
+ write_runtime_status(gateway_state="startup_failed", exit_reason=reason)
+ except Exception:
+ pass
+ self._request_clean_exit(reason)
+ return True
+
+ # Discover Python plugins before shell hooks so plugin block
+ # decisions take precedence in tie cases. The CLI startup path
+ # does this via an explicit call in hermes_cli/main.py; the
+ # gateway lazily imports run_agent inside per-request handlers,
+ # so the discover_plugins() side-effect in model_tools.py is NOT
+ # guaranteed to have run by the time we reach this point.
+ try:
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
+ except Exception:
+ logger.warning(
+ "plugin discovery failed at gateway startup", exc_info=True,
+ )
- async def _stop_systemd_watchdog(self) -> None:
- """Stop heartbeats before any potentially long shutdown drain."""
- watchdog = self._systemd_watchdog
- if watchdog is None:
- return
- self._systemd_watchdog = None
- await watchdog.stop()
-
- async def stop(
- self,
- *,
- restart: bool = False,
- detached_restart: bool = False,
- service_restart: bool = False,
- ) -> None:
- """Stop the gateway and disconnect all adapters."""
- # getattr-guard: shutdown-path tests build bare runners via
- # object.__new__ that lack the liveness-guard machinery.
- _stop_guards = getattr(self, "_stop_loop_liveness_guards", None)
- if callable(_stop_guards):
- _stop_guards()
- if restart:
- self._restart_requested = True
- self._restart_detached = detached_restart
- self._restart_via_service = service_restart
- if self._stop_task is not None:
- await self._stop_task
- return
-
- async def _stop_impl() -> None:
- def _kill_tool_subprocesses(phase: str) -> None:
- """Kill tool subprocesses + tear down terminal envs + browsers.
-
- Called twice in the shutdown path: once eagerly after a
- drain timeout forces agent interrupt (so we reclaim bash/
- sleep children before systemd TimeoutStopSec escalates to
- SIGKILL on the cgroup — #8202), and once as a final
- catch-all at the end of _stop_impl() for the graceful
- path or anything respawned mid-teardown.
-
- All steps are best-effort; exceptions are swallowed so
- one subsystem's failure doesn't block the rest.
- """
- try:
- from tools.process_registry import process_registry
- _killed = process_registry.kill_all()
- if _killed:
- logger.info(
- "Shutdown (%s): killed %d tool subprocess(es)",
- phase, _killed,
- )
- except Exception as _e:
- logger.debug("process_registry.kill_all (%s) error: %s", phase, _e)
- try:
- # Any cron job still dispatched at this instant just had
- # its tool subprocess killed above (kill_all() has no
- # per-job-ID targeting — it's a global sweep). Its agent
- # thread is still alive in this process and may go on to
- # produce a plausible-looking final response from the
- # now-truncated tool output; mark the run interrupted so
- # the scheduler can never report that as success (#60432).
- # No-op when no cron job is in flight.
- from cron.scheduler import mark_running_jobs_interrupted
- _interrupted = mark_running_jobs_interrupted(
- f"Gateway shutdown ({phase}) killed the job's tool "
- "subprocess before the run finished."
- )
- if _interrupted:
- logger.warning(
- "Shutdown (%s): marked %d in-flight cron job(s) interrupted: %s",
- phase, len(_interrupted), ", ".join(_interrupted),
- )
- except Exception as _e:
- logger.debug("mark_running_jobs_interrupted (%s) error: %s", phase, _e)
- try:
- from tools.async_delegation import interrupt_all as _interrupt_async
- _async_n = _interrupt_async(reason=f"gateway shutdown ({phase})")
- if _async_n:
- logger.info(
- "Shutdown (%s): interrupted %d background delegation(s)",
- phase, _async_n,
- )
- except Exception as _e:
- logger.debug("async interrupt_all (%s) error: %s", phase, _e)
- try:
- from tools.terminal_tool import cleanup_all_environments
- cleanup_all_environments()
- except Exception as _e:
- logger.debug("cleanup_all_environments (%s) error: %s", phase, _e)
- try:
- from tools.browser_tool import cleanup_all_browsers
- cleanup_all_browsers()
- except Exception as _e:
- logger.debug("cleanup_all_browsers (%s) error: %s", phase, _e)
-
- # Thread-based shutdown watchdog (#66892): asyncio timeouts cannot
- # recover a frozen loop. Arm a plain OS thread at the start of
- # stop(); if teardown never finishes within drain+grace it dumps
- # faulthandler stacks and os._exit so KeepAlive/systemd can revive.
- # Skip under pytest so stop()-driving unit tests don't get a
- # delayed hard-exit in the worker.
- _watchdog_done = threading.Event()
- self._shutdown_watchdog_done = _watchdog_done
- _stop_started_at_box: dict[str, float] = {}
-
- def _shutdown_watchdog_snapshot() -> dict:
- started = _stop_started_at_box.get("t")
- return {
- "restart_requested": bool(self._restart_requested),
- "draining": bool(self._draining),
- "running": bool(self._running),
- "active_agents": self._running_agent_count(),
- "active_cron_jobs": self._active_cron_job_count(),
- "active_api_runs": self._active_api_run_count(),
- "restart_drain_timeout": self._restart_drain_timeout,
- "watchdog_delay_s": resolve_shutdown_watchdog_delay(
- self._restart_drain_timeout
- ),
- "phase_elapsed_s": (
- time.monotonic() - started if started is not None else None
- ),
- }
+ # Register the generic relay adapter when a connector relay URL is
+ # configured (GATEWAY_RELAY_URL / gateway.relay_url). No URL -> no-op, so
+ # direct/single-tenant deployments are unaffected. When configured, the
+ # adapter dials the connector over a WebSocket, negotiates its capability
+ # descriptor at handshake, and bridges inbound/outbound like any platform.
+ try:
+ from gateway.relay import (
+ register_relay_adapter,
+ relay_url,
+ self_provision_relay,
+ send_relay_policy,
+ )
- if not os.environ.get("PYTEST_CURRENT_TEST"):
- arm_shutdown_watchdog(
- resolve_shutdown_watchdog_delay(self._restart_drain_timeout),
- done_event=_watchdog_done,
- snapshot_fn=_shutdown_watchdog_snapshot,
- exit_code=1,
- )
+ # Boot-time relay self-provision: resolve the agent's NAS token ->
+ # POST /relay/provision -> set GATEWAY_RELAY_* in os.environ BEFORE
+ # registration reads them. No-op when relay is unconfigured, a secret
+ # is already pinned, or no NAS token resolves (self-hosted, unenrolled).
+ # Never raises.
+ self_provision_relay()
- try:
- await _stop_impl_body(
- _kill_tool_subprocesses,
- _stop_started_at_box,
- )
- finally:
- _watchdog_done.set()
+ if register_relay_adapter():
+ logger.info("relay adapter registered (connector at %s)", relay_url())
+ # Declare this gateway's relevance policy (mention-gating /
+ # free-response / allow-bots) to the connector so the SAME
+ # behavior governs relay delivery (Phase 6 Unit ζ). Runs after
+ # the secret is resolved; never raises, never blocks boot.
+ send_relay_policy()
+ except Exception:
+ logger.warning(
+ "relay adapter registration failed at gateway startup", exc_info=True,
+ )
- async def _stop_impl_body(_kill_tool_subprocesses, _stop_started_at_box) -> None:
- logger.info(
- "Stopping gateway%s...",
- " for restart" if self._restart_requested else "",
+ # Register declarative shell hooks from cli-config.yaml. Gateway
+ # has no TTY, so consent has to come from one of the three opt-in
+ # channels (--accept-hooks on launch, HERMES_ACCEPT_HOOKS env var,
+ # or hooks_auto_accept: true in config.yaml). We pass
+ # accept_hooks=False here and let register_from_config resolve
+ # the effective value from env + config itself — the CLI-side
+ # registration already honored --accept-hooks, and re-reading
+ # hooks_auto_accept here would just duplicate that lookup.
+ # Failures are logged but must never block gateway startup.
+ try:
+ from hermes_cli.config import load_config
+ from agent.shell_hooks import register_from_config
+ register_from_config(load_config(), accept_hooks=False)
+ except Exception:
+ logger.debug(
+ "shell-hook registration failed at gateway startup",
+ exc_info=True,
)
- _stop_started_at = time.monotonic()
- _stop_started_at_box["t"] = _stop_started_at
- def _phase_elapsed() -> float:
- return time.monotonic() - _stop_started_at
+ # Discover and load event hooks
+ self.hooks.discover_and_load()
- self._running = False
- self._draining = True
+
+ # Recover background processes from checkpoint (crash recovery)
+ try:
+ from tools.process_registry import process_registry
+ recovered = process_registry.recover_from_checkpoint()
+ if recovered:
+ logger.info("Recovered %s background process(es) from previous run", recovered)
+ except Exception as e:
+ logger.warning("Process checkpoint recovery: %s", e)
- stop_watchdog = getattr(self, "_stop_systemd_watchdog", None)
- if callable(stop_watchdog):
- await stop_watchdog()
+ # Suspend sessions that were active when the gateway last exited.
+ # This prevents stuck sessions from being blindly resumed on restart,
+ # which can create an unrecoverable loop (#7536). Suspended sessions
+ # auto-reset on the next incoming message, giving the user a clean start.
+ #
+ # SKIP suspension after a clean (graceful) shutdown — the previous
+ # process already drained active agents, so sessions aren't stuck.
+ # This prevents unwanted auto-resets after `hermes update`,
+ # `hermes gateway restart`, or `/restart`.
+ _clean_marker = _hermes_home / ".clean_shutdown"
+ if _clean_marker.exists():
+ logger.info("Previous gateway exited cleanly — skipping session suspension")
+ try:
+ _clean_marker.unlink()
+ except Exception:
+ pass
+ else:
+ try:
+ suspended = await self.async_session_store.suspend_recently_active()
+ if suspended:
+ logger.info("Marked %d in-flight session(s) as resumable from previous run", suspended)
+ except Exception as e:
+ logger.warning("Session suspension on startup failed: %s", e)
- await self._cancel_secondary_profile_reconnect_tasks()
+ # Stuck-loop detection (#7536): if a session has been active across
+ # 3+ consecutive restarts, it's probably stuck in a loop (the same
+ # history keeps causing the agent to hang). Auto-suspend it so the
+ # user gets a clean slate on the next message.
+ try:
+ stuck = self._suspend_stuck_loop_sessions()
+ if stuck:
+ logger.warning("Auto-suspended %d stuck-loop session(s)", stuck)
+ except Exception as e:
+ logger.debug("Stuck-loop detection failed: %s", e)
- # Notify all chats with active agents BEFORE draining.
- # Adapters are still connected here, so messages can be sent.
- await self._notify_active_sessions_of_shutdown()
- logger.info(
- "Shutdown phase: notify_active_sessions done at +%.2fs",
- _phase_elapsed(),
- )
+ # Serialize startup restore against inbound dispatch. Platform
+ # adapters can begin receiving messages as soon as they connect, but
+ # restart-interrupted sessions are not auto-resumed until all startup
+ # wiring below completes. Queue inbound messages until the resume
+ # pass runs and every synthetic resume turn has finished.
+ self._startup_restore_in_progress = True
+ self._startup_restore_queue = []
+ self._startup_restore_tasks = []
- timeout = self._restart_drain_timeout
-
- # Pre-mark sessions as resume_pending BEFORE the drain wait.
- # If the process is killed by the service manager during the
- # drain, the durable marker is already written so the next
- # gateway boot can recover in-flight sessions (#27856).
- _pre_drain_keys: list[str] = []
- for _sk, _agent in list(self._running_agents.items()):
- if _agent is _AGENT_PENDING_SENTINEL:
- continue
- try:
- await self.async_session_store.mark_resume_pending(
- _sk,
- "restart_timeout" if self._restart_requested else "shutdown_timeout",
- )
- _pre_drain_keys.append(_sk)
- except Exception as _e:
- logger.debug("pre-drain mark_resume_pending failed for %s: %s", _sk, _e)
-
- _cron_at_start = self._active_cron_job_count()
- _api_at_start = self._active_api_run_count()
- _drain_started_at = time.monotonic()
- active_agents, timed_out = await self._drain_active_agents(timeout)
- logger.info(
- "Shutdown phase: drain done at +%.2fs (drain took %.2fs, "
- "timed_out=%s, active_at_start=%d, active_now=%d, "
- "cron_at_start=%d, cron_now=%d, "
- "api_at_start=%d, api_now=%d)",
- _phase_elapsed(),
- time.monotonic() - _drain_started_at,
- timed_out,
- len(active_agents),
- self._running_agent_count(),
- _cron_at_start,
- self._active_cron_job_count(),
- _api_at_start,
- self._active_api_run_count(),
- )
-
- if not timed_out:
- # Drain completed gracefully — all running sessions finished.
- # Clear the pre-drain resume_pending markers so sessions that
- # completed during the drain window don't carry a stale flag.
- for _sk in _pre_drain_keys:
- if _sk not in self._running_agents:
- try:
- await self.async_session_store.clear_resume_pending(_sk)
- except Exception as _e:
- logger.debug(
- "clear_resume_pending after drain failed for %s: %s",
- _sk, _e,
- )
-
- if timed_out:
- logger.warning(
- "Gateway drain timed out after %.1fs with %d active agent(s), "
- "%d in-flight cron job(s), and %d api_server run(s); "
- "interrupting remaining work.",
- timeout,
- self._running_agent_count(),
- self._active_cron_job_count(),
- self._active_api_run_count(),
- )
- # Mark forcibly-interrupted sessions as resume_pending BEFORE
- # interrupting the agents. This preserves each session's
- # session_id + transcript so the next message on the same
- # session_key auto-resumes from the existing conversation
- # instead of getting routed through suspend_recently_active()
- # and converted into a fresh session. Terminal escalation
- # for genuinely stuck sessions still flows through the
- # existing ``.restart_failure_counts`` stuck-loop counter
- # (incremented below, threshold 3), which sets
- # ``suspended=True`` and overrides resume_pending.
- #
- # Iterate self._running_agents (current) rather than the
- # drain-start ``active_agents`` snapshot — the snapshot
- # may include sessions that finished gracefully during
- # the drain window, and marking those falsely would give
- # them a stray restart-interruption system note on their
- # next turn even though their previous turn completed
- # cleanly. Skip pending sentinels for the same reason
- # _interrupt_running_agents() does: their agent hasn't
- # started yet, there's nothing to interrupt, and the
- # session shouldn't carry a misleading resume flag.
- _resume_reason = (
- "restart_timeout" if self._restart_requested else "shutdown_timeout"
- )
- for _sk, _agent in list(self._running_agents.items()):
- if _agent is _AGENT_PENDING_SENTINEL:
- continue
- try:
- await self.async_session_store.mark_resume_pending(_sk, _resume_reason)
- except Exception as _e:
- logger.debug(
- "mark_resume_pending failed for %s: %s",
- _sk, _e,
- )
- self._interrupt_running_agents(
- _INTERRUPT_REASON_GATEWAY_RESTART if self._restart_requested else _INTERRUPT_REASON_GATEWAY_SHUTDOWN
- )
- interrupt_deadline = asyncio.get_running_loop().time() + 5.0
- while self._running_agents and asyncio.get_running_loop().time() < interrupt_deadline:
- self._update_runtime_status("draining")
- await asyncio.sleep(0.1)
-
- # Kill lingering tool subprocesses NOW, before we spend more
- # budget on adapter disconnect / session DB close. Under
- # systemd (TimeoutStopSec bounded by drain_timeout+headroom),
- # deferring this to the end of stop() risks systemd escalating
- # to SIGKILL on the cgroup first — at which point bash/sleep
- # children left behind by an interrupted terminal tool get
- # killed by systemd instead of us (issue #8202). The final
- # catch-all cleanup below still runs for the graceful path.
- _kill_tool_subprocesses("post-interrupt")
+ connected_count = 0
+ enabled_platform_count = 0
+ startup_nonretryable_errors: list[str] = []
+ startup_retryable_errors: list[str] = []
+
+ # Initialize and connect each configured platform
+ _multiplex_on = bool(getattr(self.config, "multiplex_profiles", False))
+ _multiplex_skipped_platforms: list[Platform] = []
+ for platform, platform_config in self.config.platforms.items():
+ if await self._abort_startup_if_shutdown_requested():
+ return True
+ if not platform_config.enabled:
+ continue
+ # Under multiplexing, a platform may be enabled on the default
+ # profile's config.yaml while its bot token lives only in a
+ # secondary profile's .env. Starting that primary adapter with an
+ # empty token fails immediately and queues an infinite reconnect
+ # loop that can never heal (#64674). Secondary profiles still
+ # start their own adapters under _profile_runtime_scope with the
+ # real token — skip the empty primary instead of failing loudly.
+ if _multiplex_on and not _platform_has_bot_credential(platform, platform_config):
logger.info(
- "Shutdown phase: post-interrupt tool kill done at +%.2fs",
- _phase_elapsed(),
+ "Skipping %s on default profile: no bot credential in this "
+ "profile's secrets. Secondary multiplexed profiles that "
+ "provide the token will still connect.",
+ platform.value,
)
-
- if self._restart_requested and self._restart_detached:
- try:
- await self._launch_detached_restart_command()
- except Exception as e:
- logger.error("Failed to launch detached gateway restart: %s", e)
-
- await self._finalize_shutdown_agents(active_agents)
-
- # Also shut down memory providers on idle cached agents.
- # _finalize_shutdown_agents only handles agents that were
- # mid-turn at drain time; the _agent_cache may still hold
- # idle agents whose MemoryProviders never received
- # on_session_end().
- _cache_lock = getattr(self, "_agent_cache_lock", None)
- _cache = getattr(self, "_agent_cache", None)
- if _cache_lock is not None and _cache is not None:
- with _cache_lock:
- _idle_agents = list(_cache.values())
- _cache.clear()
- for _entry in _idle_agents:
- _agent = (
- _entry[0] if isinstance(_entry, tuple) else _entry
- )
- # Bounded + off-loop so a wedged memory provider on one
- # idle agent can't hang shutdown indefinitely — that path
- # is why SIGTERM failed to kill the process (#53175).
- await self._cleanup_agent_resources_off_loop(
- _agent, context="shutdown idle-cache"
- )
-
- for platform, adapter in list(self.adapters.items()):
- await self._bounded_adapter_teardown(adapter, platform)
-
- # Disconnect secondary-profile adapters (multiplex mode).
- for _prof, _amap in list(getattr(self, "_profile_adapters", {}).items()):
- for platform, adapter in list(_amap.items()):
- await self._bounded_adapter_teardown(
- adapter, platform, profile=_prof
+ _multiplex_skipped_platforms.append(platform)
+ continue
+ enabled_platform_count += 1
+
+ adapter = self._create_adapter(platform, platform_config)
+ if not adapter:
+ # Distinguish between missing builtin deps and missing plugin
+ _pval = platform.value
+ _builtin_names = {m.value for m in Platform.__members__.values()}
+ if _pval not in _builtin_names:
+ logger.warning(
+ "No adapter for '%s' — is the plugin installed? "
+ "(platform is enabled in config.yaml but no plugin registered it)",
+ _pval,
)
- _amap.clear()
- if hasattr(self, "_profile_adapters"):
- self._profile_adapters.clear()
- logger.info(
- "Shutdown phase: all adapters disconnected at +%.2fs",
- _phase_elapsed(),
+ else:
+ logger.warning("No adapter available for %s", _pval)
+ continue
+
+ # Set up message + fatal error handlers
+ adapter.set_message_handler(self._handle_message)
+ adapter.set_fatal_error_handler(self._handle_adapter_fatal_error)
+ adapter.set_session_store(self.session_store)
+ adapter.set_busy_session_handler(self._handle_active_session_busy_message)
+ _set_reaction = getattr(adapter, "set_reaction_handler", None)
+ if callable(_set_reaction):
+ _set_reaction(self._handle_reaction_event)
+ adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
+ adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))
+ adapter._busy_text_mode = self._busy_text_mode
+
+ # Try to connect
+ logger.info("Connecting to %s...", platform.value)
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="connecting",
+ error_code=None,
+ error_message=None,
)
-
- for _task in list(self._background_tasks):
- if _task is self._stop_task:
- continue
- if _task is self._restart_task:
- # The restart orchestration task is awaiting _stop_task
- # right now; cancelling it would propagate CancelledError
- # into this _stop_impl and skip _shutdown_event.set() /
- # _exit_code = 75 (#12875). It self-terminates anyway.
- continue
- _task.cancel()
- self._background_tasks.clear()
-
- self.adapters.clear()
- for _session_key in list(self._running_agents):
- self._release_running_agent_state(_session_key)
- # Flush pending messages to disk before clearing (#72680).
- # When FTS5 corruption prevents message persistence, the
- # in-memory pending text is the only surviving copy. Clearing
- # without flushing causes permanent data loss.
try:
- from gateway.shutdown_flush import flush_pending_to_file
- flush_pending_to_file(dict(self._pending_messages), reason="shutdown")
- except Exception:
- pass
- # On the real runner these are live SessionState views whose
- # clear() resets one field per session — never a wholesale dict
- # swap, so a concurrent writer on another session can't lose its
- # entry. Test fakes borrowing _stop_impl keep plain dicts.
- self._running_agents.clear()
- self._running_agents_ts.clear()
- if hasattr(self, "_active_session_leases"):
- self._active_session_leases.clear()
- self._pending_messages.clear()
- self._pending_approvals.clear()
- if hasattr(self, '_busy_ack_ts'):
- self._busy_ack_ts.clear()
- self._shutdown_event.set()
-
- # Global cleanup: kill any remaining tool subprocesses not tied
- # to a specific agent (catch-all for zombie prevention). On the
- # drain-timeout path we already did this earlier after agent
- # interrupt — this second call catches (a) the graceful path
- # where drain succeeded without interrupt, and (b) anything
- # that got respawned between the earlier call and adapter
- # disconnect (defense in depth; safe to call repeatedly).
- _kill_tool_subprocesses("final-cleanup")
- logger.info(
- "Shutdown phase: final-cleanup tool kill done at +%.2fs",
- _phase_elapsed(),
- )
+ success = await self._connect_initial_adapter_with_timeout(
+ adapter, platform
+ )
+ if await self._abort_startup_if_shutdown_requested(adapter, platform):
+ return True
+ if success:
+ self.adapters[platform] = adapter
+ self._sync_voice_mode_state_to_adapter(adapter)
+ # Wire voice input callback at connect time so voice
+ # transcription is forwarded without requiring /voice join.
+ if hasattr(adapter, "_voice_input_callback"):
+ adapter._voice_input_callback = self._handle_voice_channel_input
+ connected_count += 1
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="connected",
+ error_code=None,
+ error_message=None,
+ )
+ logger.info("✓ %s connected", platform.value)
+ else:
+ logger.warning("✗ %s failed to connect", platform.value)
+ # Defensive cleanup: a failed connect() may have
+ # allocated resources (aiohttp.ClientSession, poll
+ # tasks, bridge subprocesses) before giving up.
+ # Without this call, those resources are orphaned
+ # and Python logs "Unclosed client session" at
+ # process exit. Adapter disconnect() implementations
+ # are expected to be idempotent and tolerate
+ # partial-init state.
+ await self._safe_adapter_disconnect(adapter, platform)
+ if adapter.has_fatal_error:
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="retrying" if adapter.fatal_error_retryable else "fatal",
+ error_code=adapter.fatal_error_code,
+ error_message=adapter.fatal_error_message,
+ )
+ target = (
+ startup_retryable_errors
+ if adapter.fatal_error_retryable
+ else startup_nonretryable_errors
+ )
+ target.append(
+ f"{platform.value}: {adapter.fatal_error_message}"
+ )
+ # Queue for reconnection if the error is retryable
+ if adapter.fatal_error_retryable:
+ self._failed_platforms[platform] = {
+ "config": platform_config,
+ "attempts": 1,
+ "next_retry": time.monotonic() + 30,
+ "credential_claim": self._adapter_credential_claim(
+ platform, adapter
+ ),
+ "listener_claim": self._adapter_listener_claim(
+ platform, adapter
+ ),
+ }
+ else:
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="retrying",
+ error_code=None,
+ error_message="failed to connect",
+ )
+ startup_retryable_errors.append(
+ f"{platform.value}: failed to connect"
+ )
+ # No fatal error info means likely a transient issue — queue for retry
+ self._failed_platforms[platform] = {
+ "config": platform_config,
+ "attempts": 1,
+ "next_retry": time.monotonic() + 30,
+ "credential_claim": self._adapter_credential_claim(
+ platform, adapter
+ ),
+ "listener_claim": self._adapter_listener_claim(
+ platform, adapter
+ ),
+ }
+ except Exception as e:
+ logger.error("✗ %s error: %s", platform.value, e)
+ # Same defensive cleanup path for exceptions — an adapter
+ # that raised mid-connect may still have a live
+ # aiohttp.ClientSession or child subprocess.
+ await self._safe_adapter_disconnect(adapter, platform)
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="retrying",
+ error_code=None,
+ error_message=str(e),
+ )
+ startup_retryable_errors.append(f"{platform.value}: {e}")
+ # Unexpected exceptions are typically transient — queue for retry
+ self._failed_platforms[platform] = {
+ "config": platform_config,
+ "attempts": 1,
+ "next_retry": time.monotonic() + 30,
+ "credential_claim": self._adapter_credential_claim(
+ platform, adapter
+ ),
+ "listener_claim": self._adapter_listener_claim(
+ platform, adapter
+ ),
+ }
+ if await self._abort_startup_if_shutdown_requested():
+ return True
- # Reap the process-global auxiliary-client cache once at the very
- # end of teardown. Per-turn cleanup runs in _cleanup_agent_resources
- # for each active agent, but clients bound to worker-thread loops
- # that died with their ThreadPoolExecutor (notably cron ticks) only
- # get swept here. Without this, long-running gateways accumulate
- # async httpx transports until they hit EMFILE on macOS's default
- # RLIMIT_NOFILE=256. See #14210.
+ # Multi-profile multiplexing: bring up adapters for every OTHER profile
+ # this gateway serves. Each profile's adapters connect under that
+ # profile's home + credential scope and stamp their inbound events with
+ # the profile so the agent turn resolves correctly. No-op when off.
+ try:
+ _secondary_connected = await self._start_secondary_profile_adapters()
+ connected_count += _secondary_connected
+ except MultiplexConfigError as e:
+ # Invalid multiplexer config — abort startup cleanly so the operator
+ # fixes config.yaml rather than running a half-wired gateway.
+ reason = str(e)
+ logger.error("Gateway multiplexer config error: %s", reason)
try:
- from agent.auxiliary_client import shutdown_cached_clients
- shutdown_cached_clients()
- except Exception as _e:
- logger.debug("shutdown_cached_clients error: %s", _e)
+ from gateway.status import write_runtime_status
+ write_runtime_status(gateway_state="startup_failed", exit_reason=reason)
+ except Exception:
+ pass
+ self._exit_code = GATEWAY_FATAL_CONFIG_EXIT_CODE
+ self._request_clean_exit(reason)
+ self._startup_restore_in_progress = False
+ return True
+ except Exception as e:
+ logger.error("Secondary-profile adapter startup failed: %s", e, exc_info=True)
+ finally:
+ # Startup authority is one phase, not a persistent runner mode.
+ # From this point onward every adapter retry is non-evicting.
+ self._platform_lock_takeover_on_start = False
- # Close SQLite session DBs so the WAL write lock is released.
- # Without this, --replace and similar restart flows leave the
- # old gateway's connection holding the WAL lock until Python
- # actually exits — causing 'database is locked' errors when
- # the new gateway tries to open the same file.
- # ``self`` holds the DB at ``_session_db`` (an AsyncSessionDB facade);
- # unwrap to the sync handle. ``session_store`` holds it at ``_db``.
- _self_db = getattr(self, "_session_db", None)
- _self_db = getattr(_self_db, "_db", _self_db)
- for _db in (_self_db, getattr(getattr(self, "session_store", None), "_db", None)):
- if _db is None or not hasattr(_db, "close"):
- continue
- try:
- _db.close()
- except Exception as _e:
- logger.debug("SessionDB close error: %s", _e)
- GatewayRunner._shutdown_executor(self)
- logger.info(
- "Shutdown phase: SessionDB close done at +%.2fs",
- _phase_elapsed(),
+ # A platform we skipped on the primary for a missing credential was
+ # supposed to be picked up by a secondary profile that owns the token.
+ # If none did, the platform is enabled in config.yaml yet silently
+ # unserved — surface it loudly so the operator sees a config problem
+ # instead of a quiet dead channel (#64674 follow-up).
+ for _skipped in _multiplex_skipped_platforms:
+ _served_by_secondary = any(
+ _skipped in _profile_map
+ for _profile_map in self._profile_adapters.values()
)
+ if not _served_by_secondary:
+ logger.warning(
+ "%s is enabled but no profile (default or secondary) "
+ "provided a bot credential for it — the platform is not "
+ "being served. Add its token to the profile that should "
+ "own it, or disable the platform.",
+ _skipped.value,
+ )
- from gateway.status import remove_pid_file, release_gateway_runtime_lock
- remove_pid_file()
- release_gateway_runtime_lock()
-
- # Write a clean-shutdown marker so the next startup knows this
- # wasn't a crash. suspend_recently_active() only needs to run
- # after unexpected exits. However, if the drain timed out and
- # agents were force-interrupted, their sessions may be in an
- # incomplete state (trailing tool response, no final assistant
- # message). Skip the marker in that case so the next startup
- # suspends those sessions — giving users a clean slate instead
- # of resuming a half-finished tool loop.
- if not timed_out:
+ if connected_count == 0:
+ if startup_nonretryable_errors and not startup_retryable_errors:
+ reason = "; ".join(startup_nonretryable_errors)
+ logger.error("Gateway hit a non-retryable startup conflict: %s", reason)
try:
- (_hermes_home / ".clean_shutdown").touch()
+ from gateway.status import write_runtime_status
+ write_runtime_status(gateway_state="startup_failed", exit_reason=reason)
except Exception:
pass
- else:
- logger.info(
- "Skipping .clean_shutdown marker — drain timed out with "
- "interrupted agents; next startup will suspend recently "
- "active sessions."
+ self._exit_code = GATEWAY_FATAL_CONFIG_EXIT_CODE
+ self._request_clean_exit(reason)
+ self._startup_restore_in_progress = False
+ return True
+ if startup_nonretryable_errors:
+ # Mixed failure mode (NS-609): some platforms are fatally
+ # misconfigured (e.g. WhatsApp enabled but never paired) while
+ # others hit merely transient errors (e.g. Telegram TimedOut
+ # during polling startup). Exiting with
+ # GATEWAY_FATAL_CONFIG_EXIT_CODE here is wrong in both
+ # supervision worlds: under supervisors that honor the
+ # exit-78 contract (systemd RestartPreventExitStatus, s6
+ # finish→125 since #51228) the gateway goes PERMANENTLY down
+ # over a network blip; under anything else it crash-loops.
+ # Either way the retryable platforms never get their retry.
+ # Log the fatal side loudly, then fall through to the
+ # degraded/retry path below: the reconnect watcher recovers
+ # the retryable platforms; the non-retryable ones remain
+ # fatal-parked and visible in runtime status.
+ logger.error(
+ "%d platform(s) fatally misconfigured and parked: %s. "
+ "Staying alive so retryable platforms can recover.",
+ len(startup_nonretryable_errors),
+ "; ".join(startup_nonretryable_errors),
)
-
- # Track sessions that were active at shutdown for stuck-loop
- # detection (#7536). On each restart, the counter increments
- # for sessions that were running. If a session hits the
- # threshold (3 consecutive restarts while active), the next
- # startup auto-suspends it — breaking the loop.
- if active_agents:
- self._increment_restart_failure_counts(set(active_agents.keys()))
-
- if self._restart_requested and self._restart_command_source is None:
- try:
- atomic_json_write(
- _planned_restart_notification_path(),
- {
- "requested_at": time.time(),
- "via_service": bool(self._restart_via_service),
- "detached": bool(self._restart_detached),
- },
- indent=None,
+ if enabled_platform_count > 0:
+ if startup_retryable_errors:
+ # All enabled platforms hit retryable failures (network
+ # blip, bridge not paired, npm install timeout, etc.).
+ # Keep the gateway alive so:
+ # • cron jobs still run
+ # • the reconnect watcher gets a chance to recover the
+ # failing platforms once the underlying problem is
+ # fixed (e.g. user runs `hermes whatsapp`, fixes
+ # proxy, etc.)
+ # Exiting here used to convert a single misconfigured
+ # platform into an infinite systemd restart loop.
+ reason = "; ".join(startup_retryable_errors)
+ logger.warning(
+ "Gateway started with no connected platforms — "
+ "%d platform(s) queued for retry: %s",
+ len(self._failed_platforms), reason,
)
- except Exception as e:
- logger.debug("Failed to write planned restart notification marker: %s", e)
-
- if self._restart_requested and self._restart_via_service:
- self._launch_systemd_restart_shortcut()
- # Always exit with TEMPFAIL (75) on service-managed
- # restarts. The shortcut helper above is best-effort and
- # commonly fails on real deployments: non-root gateway
- # units hit Polkit denials when invoking ``systemd-run
- # --system``, headless boxes have no user bus for
- # ``--user``, and operator-managed unit files may use
- # ``Restart=on-failure`` rather than ``Restart=always``.
- # Exit 75 paired with ``RestartForceExitStatus=75`` makes
- # systemd treat the planned restart as a controlled
- # failure and revive the unit via ``Restart=on-failure``,
- # regardless of whether the helper survived. Without
- # this, a clean exit (0) on Linux left the gateway dead
- # until someone rebooted the host. Only the planned code
- # (75) is whitelisted via ``RestartForceExitStatus``; a
- # genuine crash exits non-zero-but-not-75, so real crash
- # loops are still governed by the unit's normal
- # ``Restart=``/``RestartSec`` (and any StartLimit the
- # operator sets) rather than force-restarted here.
- self._exit_code = GATEWAY_SERVICE_RESTART_EXIT_CODE
- self._exit_reason = self._exit_reason or "Gateway restart requested"
-
- self._draining = False
- # Persist the terminal gateway_state. The default is "stopped",
- # but when this teardown was triggered by an UNEXPECTED external
- # signal (container/s6 SIGTERM on `docker restart` or image
- # upgrade, OOM-killer, bare `kill`) we instead persist "running"
- # to preserve the operator's run-intent across the restart.
- #
- # On Docker (s6-overlay), container_boot.py reads gateway_state
- # on the next boot and only auto-starts gateways whose last
- # state was "running" (_AUTOSTART_STATES). Persisting "stopped"
- # — or leaving the mid-shutdown "draining" marker in place — for
- # a routine `docker compose up --force-recreate` permanently
- # suppresses auto-start, so the messaging channels silently stay
- # dark until the operator manually restarts (issue #42675).
- #
- # An operator-initiated stop (`hermes gateway stop`,
- # systemd/launchd ExecStop, the s6 stop path, Ctrl+C) writes a
- # planned-stop marker BEFORE signalling, so it is classified as
- # a planned stop (not signal-initiated) and correctly persists
- # "stopped" — respecting the explicit intent. A restart also
- # persists "stopped" here; the restarting process brings the
- # gateway back up itself.
- if getattr(self, "_signal_initiated_shutdown", False) and not self._restart_requested:
- logger.info(
- "Gateway stopped by an unexpected signal — persisting "
- "gateway_state=running so container_boot auto-starts on "
- "the next boot (issue #42675)"
+ try:
+ from gateway.status import write_runtime_status
+ write_runtime_status(
+ gateway_state="degraded",
+ exit_reason=None,
+ )
+ except Exception:
+ pass
+ # Fall through to the normal "running" state — reconnect
+ # watcher takes it from here.
+ # All enabled platforms had no adapter (missing library or credentials).
+ # In fleet deployments the same config.yaml is shared across nodes that
+ # may only have credentials for a subset of platforms. Rather than
+ # failing hard, degrade gracefully and allow cron jobs to run (#5196).
+ logger.warning(
+ "No adapter could be created for any of the %d configured platform(s). "
+ "Check that required dependencies are installed and credentials are set. "
+ "Gateway will continue for cron job execution.",
+ enabled_platform_count,
)
- self._update_runtime_status("running", self._exit_reason)
else:
- self._update_runtime_status("stopped", self._exit_reason)
- _shutdown_gateway_health_export(self)
- logger.info("Gateway stopped (total teardown %.2fs)", _phase_elapsed())
-
- self._stop_task = asyncio.create_task(_stop_impl())
- await self._stop_task
-
- async def wait_for_shutdown(self) -> None:
- """Wait for shutdown signal."""
- await self._shutdown_event.wait()
-
- async def _start_secondary_profile_adapters(self) -> int:
- """Bring up adapters for every non-active profile this gateway serves.
-
- Returns the number of secondary adapters that connected. No-op (returns
- 0) unless ``gateway.multiplex_profiles`` is on.
+ logger.warning("No messaging platforms enabled.")
+ logger.info("Gateway will continue running for cron job execution.")
+
+ # Update delivery router with adapters
+ if await self._abort_startup_if_shutdown_requested():
+ return True
+ self.delivery_router.adapters = self.adapters
+ self._wire_teams_pipeline_runtime()
- Each profile's adapters are created and connected under that profile's
- HERMES_HOME + secret scope (``_profile_runtime_scope``), stored in
- ``self._profile_adapters[profile]``, and given a message handler that
- stamps ``source.profile`` before delegating to the shared
- ``_handle_message`` — so the agent turn resolves that profile's config,
- skills, and credentials. Same-platform credential collisions (two
- profiles polling the same bot token) are detected and refused here, the
- only point that sees every profile's resolved credentials together.
- """
- if not getattr(self.config, "multiplex_profiles", False):
- return 0
+ self._running = True
+ self._update_runtime_status("running")
+ # Loop-liveness heartbeat (#66892): an asyncio task so a frozen loop
+ # stops refreshing ``state/gateway.heartbeat``. Cancelled with the
+ # other background tasks during stop(). Best-effort — a liveness probe
+ # must never be able to abort startup.
try:
- from hermes_cli.profiles import profiles_to_serve, get_active_profile_name
+ _existing_hb = getattr(self, "_loop_heartbeat_task", None)
+ if _existing_hb is None or _existing_hb.done():
+ self._loop_heartbeat_task = asyncio.create_task(
+ loop_heartbeat_forever(
+ interval_s=DEFAULT_HEARTBEAT_INTERVAL_S,
+ start_time=getattr(self, "_gateway_started_at", 0.0),
+ )
+ )
+ _bg = getattr(self, "_background_tasks", None)
+ if _bg is not None:
+ _bg.add(self._loop_heartbeat_task)
+ self._loop_heartbeat_task.add_done_callback(_bg.discard)
except Exception:
- return 0
+ logger.debug("Failed to start gateway loop heartbeat", exc_info=True)
- active = get_active_profile_name() or "default"
- connected = 0
- # Resource claim -> profile that owns it. Credential claims prevent two
- # profiles polling the same account; listener claims prevent sidecars
- # with distinct credentials from binding the same endpoint.
- claimed: Dict[tuple, str] = {}
- for _plat, _ad in self.adapters.items():
- fp = self._adapter_credential_fingerprint(_ad)
- if fp is not None:
- claimed[(_plat, fp)] = active
- listener_claim = self._adapter_listener_claim(_plat, _ad)
- if listener_claim is not None:
- claimed[listener_claim] = active
- # A retryable primary still owns its configured credential and listener.
- # Reserve both while it is queued so a secondary cannot take the endpoint
- # before the reconnect watcher retries the primary adapter.
- for retry_info in getattr(self, "_failed_platforms", {}).values():
- for claim_name in ("credential_claim", "listener_claim"):
- retry_claim = retry_info.get(claim_name)
- if isinstance(retry_claim, tuple):
- claimed[retry_claim] = active
+ # Emit gateway:startup hook
+ hook_count = len(self.hooks.loaded_hooks)
+ if hook_count:
+ logger.info("%s hook(s) loaded", hook_count)
+ await self.hooks.emit("gateway:startup", {
+ "platforms": [p.value for p in self.adapters.keys()],
+ })
+
+ if connected_count > 0:
+ logger.info("Gateway running with %s platform(s)", connected_count)
+
+ # Build initial channel directory for send_message name resolution
+ try:
+ from gateway.channel_directory import build_channel_directory
+ directory = await build_channel_directory(self.adapters)
+ ch_count = sum(len(chs) for chs in directory.get("platforms", {}).values())
+ logger.info("Channel directory built: %d target(s)", ch_count)
+ except Exception as e:
+ logger.warning("Channel directory build failed: %s", e)
+
+ # Check if we're restarting after a /update command. If the update is
+ # still running, keep watching so we notify once it actually finishes.
+ notified = await self._send_update_notification()
+ if not notified and any(
+ path.exists()
+ for path in (
+ _hermes_home / ".update_pending.json",
+ _hermes_home / ".update_pending.claimed.json",
+ )
+ ):
+ self._schedule_update_notification_watch()
- for profile_name, profile_home in profiles_to_serve(multiplex=True):
- if profile_name == active:
- continue # handled by the primary startup loop
+ # Give freshly connected platform adapters a brief moment to settle
+ # before sending restart/startup lifecycle messages. In practice this
+ # helps Discord thread deliveries right after reconnect.
+ if connected_count > 0:
+ await asyncio.sleep(1.0)
+
+ # Notify the chat that initiated /restart that the gateway is back.
+ chat_restart_notification_pending = _restart_notification_pending()
+ planned_restart_notification_pending = _planned_restart_notification_pending()
+ # Capture, before _send_restart_notification() unlinks the marker,
+ # whether this process booted from a chat-originated /restart. Used as
+ # a one-shot signal by the /restart redelivery guard so a missing
+ # dedup marker only suppresses a /restart when we KNOW we just came out
+ # of a restart cycle (see _is_stale_restart_redelivery).
+ if chat_restart_notification_pending:
+ self._booted_from_restart = True
+ await self._send_restart_notification()
+
+ # Broadcast a lightweight "gateway is back" message to configured home
+ # channels only for non-chat planned restarts (terminal/SIGUSR1/service
+ # paths). Chat-originated /restart already has a precise reply target
+ # in .restart_notify.json, so keep that lifecycle in the originating
+ # chat/topic instead of also leaking it to the configured home channel.
+ if planned_restart_notification_pending:
try:
- connected += await self._start_one_profile_adapters(
- profile_name, profile_home, claimed
- )
- except SecondaryPortBindingConfigError as e:
- logger.warning(
- "Skipping secondary profile '%s' due to port-binding config error: %s",
- profile_name,
- e,
- )
- except MultiplexConfigError:
- raise
- except Exception as e:
- logger.error(
- "Failed to start adapters for profile '%s': %s",
- profile_name, e, exc_info=True,
+ await self._send_home_channel_startup_notifications(
+ skip_targets=None,
)
+ finally:
+ _clear_planned_restart_notification()
- # Record served profiles in runtime status for `hermes status`.
- try:
- from gateway.status import write_runtime_status
- from gateway.pairing import PairingStore
- served = [active] + sorted(self._profile_adapters.keys())
- # Per-profile PairingStores so authz_mixin can route pairing
- # checks to the right whitelist. The active profile gets a store
- # at its HERMES_HOME; additional served profiles get one under
- # profiles/<name>/pairing/. See gateway.pairing.PairingStore.
- for name in served:
- if name and name not in self.pairing_stores:
- self.pairing_stores[name] = PairingStore(profile=name)
- write_runtime_status(served_profiles=served)
- except Exception:
- logger.debug("could not record served_profiles", exc_info=True)
+ # Automatically continue fresh sessions that were interrupted by the
+ # previous gateway restart/shutdown. The resume_pending flag is cleared
+ # by the normal successful-turn path, so a failed auto-resume remains
+ # visible for manual recovery on the next user message.
+ #
+ # Delivery-obligation redelivery runs FIRST: a session whose final
+ # response was generated but never confirmed-delivered has its answer
+ # in the ledger — redelivering it (and clearing resume_pending for
+ # that session) is strictly cheaper and more correct than re-running
+ # the whole turn.
+ await self._redeliver_pending_obligations()
+ self._schedule_resume_pending_sessions()
+ await self._finish_startup_restore()
- return connected
+ # Drain any recovered process watchers (from crash recovery checkpoint)
+ try:
+ from tools.process_registry import process_registry
+ # Detach the current batch atomically: reassigning to a fresh list
+ # takes ownership of exactly the watchers present now, so any watcher
+ # appended concurrently during the yield below isn't silently dropped
+ # by a clear() on the shared list.
+ watchers = process_registry.pending_watchers
+ process_registry.pending_watchers = []
+ # Process in batches of 100 with event-loop yield points to avoid
+ # O(n^2) event-loop blocking when recovering thousands of watchers.
+ for i, watcher in enumerate(watchers):
+ self._spawn_supervised(
+ lambda w=watcher: self._run_process_watcher(w),
+ f"process_watcher:{watcher.get('session_id')}",
+ restart=False,
+ )
+ logger.info("Resumed watcher for recovered process %s", watcher.get("session_id"))
+ if i % 100 == 99:
+ await asyncio.sleep(0)
+ except Exception as e:
+ logger.error("Recovered watcher setup error: %s", e)
- async def _start_one_profile_adapters(
- self, profile_name: str, profile_home: "Path", claimed: Dict[tuple, str]
- ) -> int:
- """Create+connect one profile's adapters under its runtime scope."""
- from gateway.config import load_gateway_config
+ # Start background session expiry watcher to finalize expired sessions
+ self._spawn_supervised(self._session_expiry_watcher, "session_expiry_watcher")
- with _profile_runtime_scope(profile_home):
- profile_cfg = load_gateway_config()
- violation = _own_policy_open_startup_violation(profile_cfg)
- if violation:
- raise MultiplexConfigError(
- f"Profile '{profile_name}' enables {violation}. "
- "Enable GATEWAY_ALLOW_ALL_USERS or the platform allow-all flag "
- "for that profile, or change dm_policy/group_policy away from "
- "'open'."
- )
+ # Start background kanban notifier — delivers `completed`, `blocked`,
+ # `spawn_auto_blocked`, and `crashed` events to gateway subscribers
+ # so human-in-the-loop workflows hear back without polling.
+ self._spawn_supervised(self._kanban_notifier_watcher, "kanban_notifier_watcher")
- port_binding_platforms = sorted(
- platform.value
- for platform, platform_config in profile_cfg.platforms.items()
- if platform_config.enabled
- and _platform_binds_port(platform.value, platform_config.extra)
- )
- if port_binding_platforms:
- joined = ", ".join(port_binding_platforms)
- raise SecondaryPortBindingConfigError(
- f"Profile '{profile_name}' enables port-binding platform(s) "
- f"{joined}, but gateway.multiplex_profiles is on. The default "
- f"profile owns the single shared HTTP listener and serves every "
- f"profile through the /p/{profile_name}/ URL prefix. Remove "
- f"these platform entries from profile '{profile_name}'s config.yaml "
- f"or configure them only on the default profile."
+ # Start background kanban dispatcher — spawns workers for ready
+ # tasks. Gated by `kanban.dispatch_in_gateway` (default True).
+ # When false, users run `hermes kanban daemon` externally or
+ # simply don't use kanban; this loop becomes a no-op.
+ self._spawn_supervised(self._kanban_dispatcher_watcher, "kanban_dispatcher_watcher")
+
+ # Start background reconnection watcher for platforms that failed at startup
+ if self._failed_platforms:
+ logger.info(
+ "Starting reconnection watcher for %d failed platform(s): %s",
+ len(self._failed_platforms),
+ ", ".join(p.value for p in self._failed_platforms),
)
+ # Track the reconnect watcher task so _ensure_reconnect_watcher_running
+ # can detect if it dies and respawn it (#70344). Spawned via
+ # _spawn_supervised (not a bare asyncio.create_task) so an exception
+ # escaping the watcher's OUTER while-loop -- not just the per-platform
+ # inner try/except -- is caught, logged, and auto-restarted with
+ # backoff instead of silently killing the watcher forever. Without
+ # this, a platform already queued in _failed_platforms when the
+ # watcher dies stays stranded indefinitely: _ensure_reconnect_watcher_running()
+ # only gets called from a NEW fatal-error arrival, so if no other
+ # platform ever fails afterward, nothing ever notices the watcher is
+ # dead (#71758 -- reported as 17.5h of silent downtime for a platform
+ # whose transient upstream outage had long since recovered).
+ # ``on_spawn`` keeps ``_reconnect_watcher_task`` pointed at the CURRENT
+ # live task even when _spawn_supervised's own backoff respawns it — so
+ # _ensure_reconnect_watcher_running never mistakes a superseded handle
+ # for a dead watcher and spawns a duplicate.
+ self._reconnect_watcher_task = self._spawn_supervised(
+ self._platform_reconnect_watcher,
+ "platform_reconnect_watcher",
+ on_spawn=lambda t: setattr(self, "_reconnect_watcher_task", t),
+ )
- profile_map = self._profile_adapters.setdefault(profile_name, {})
- connected = 0
- for platform, platform_config in profile_cfg.platforms.items():
- if not platform_config.enabled:
- continue
- # Relay is shared process-level ingress in multiplex mode. The
- # active profile owns the one connection; connector-stamped
- # source.profile routes inbound turns to secondary profiles.
- if (
- getattr(self.config, "multiplex_profiles", False)
- and platform is Platform.RELAY
- ):
- continue
- try:
- with _profile_runtime_scope(profile_home):
- adapter = self._create_adapter(platform, platform_config)
- except Exception as e:
- logger.error(
- "[MULTIPLEX] Profile '%s': _create_adapter('%s') raised %s",
- profile_name,
- platform.value,
- e,
- exc_info=True,
- )
- continue
- if not adapter:
- logger.warning(
- "[MULTIPLEX] Profile '%s': skipping platform '%s' - adapter creation returned None",
- profile_name,
- platform.value,
- )
- continue
+ # Start background handoff watcher — picks up CLI sessions marked
+ # handoff_state='pending' in state.db and re-binds them to the
+ # destination platform's home channel, then forges a synthetic user
+ # turn so the agent kicks off the new chat.
+ self._spawn_supervised(self._handoff_watcher, "handoff_watcher")
- # Same-token conflict detection — refuse a duplicate poll.
- credential_claim = self._adapter_credential_claim(platform, adapter)
- if credential_claim is not None:
- owner = claimed.get(credential_claim)
- if owner is not None:
- logger.error(
- "Profile '%s' and '%s' both configure %s with the same "
- "credential — refusing to start the duplicate (one "
- "credential cannot be consumed twice). Give each profile "
- "its own %s credential.",
- owner, profile_name, platform.value, platform.value,
- )
- # This adapter has not connected and therefore owns no
- # resources to clean up. Calling disconnect here can mutate
- # the shared platform state and, for a same-credential Photon
- # adapter, shut down the primary profile's live sidecar.
- continue
+ # Start background async-delegation watcher — drains completion events
+ # from delegate_task(background=true) subagents and injects each
+ # result back into its originating session as a new turn, covering the
+ # idle case where the subagent finishes with no agent turn running.
+ self._spawn_supervised(self._async_delegation_watcher, "async_delegation_watcher")
- listener_claim = self._adapter_listener_claim(platform, adapter)
- if listener_claim is not None:
- owner = claimed.get(listener_claim)
- if owner is not None:
- bind, port = listener_claim[-2:]
- logger.error(
- "Profile '%s' and '%s' both configure %s sidecars on "
- "%s:%s — refusing to start the duplicate listener. "
- "Set platforms.%s.extra.sidecar_port to a distinct port "
- "for profile '%s'.",
- owner,
- profile_name,
- platform.value,
- bind,
- port,
- platform.value,
- profile_name,
- )
- # Like credential conflicts, this adapter never connected
- # and owns no resources that should be disconnected.
- continue
+ # Start the scale-to-zero idle watcher ONLY when this instance is opted
+ # in (the NAS "Labs" HERMES_SCALE_TO_ZERO stamp), messaging is
+ # relay-only/absent, and a wakeUrl is registered (decisions.md D1/D11/
+ # §3.4(1)). A non-opted instance never starts it, so behaviour is exactly
+ # as today. When armed, the watcher drives the relay dormant on sustained
+ # idle so the platform (Fly autostop:"suspend") can suspend the machine.
+ try:
+ if self._scale_to_zero_should_arm():
+ logger.info(
+ "scale-to-zero: armed (idle timeout %.0fs) — watching for idle",
+ self._scale_to_zero_idle_timeout_seconds(),
+ )
+ self._spawn_supervised(self._scale_to_zero_watcher, "scale_to_zero_watcher")
+ else:
+ # Surface WHY an OPTED-IN instance didn't arm (a non-opted instance
+ # not arming is normal — stay silent there). Without this, a failed
+ # arm is invisible and "why won't it suspend/wake?" needs a box-dive.
+ self._log_scale_to_zero_not_armed_reason()
+ except Exception: # noqa: BLE001 - arming must never block startup
+ logger.debug("scale-to-zero: arm check failed at startup", exc_info=True)
- self._configure_profile_adapter(adapter, profile_name, platform)
+ # Start background drain-control watcher — reconciles the gateway's
+ # new-turn accept-state with the external ``.drain_request.json`` marker
+ # the dashboard begin/cancel-drain endpoint writes (Phase 2). A marker
+ # left behind by a prior instantiation (durable-volume restart, NS-570)
+ # is ignored via its instantiation epoch; only a current-epoch marker
+ # engages drain on the first tick.
+ self._spawn_supervised(self._drain_control_watcher, "drain_control_watcher")
- try:
- with _profile_runtime_scope(profile_home):
- success = await self._connect_initial_adapter_with_timeout(
- adapter, platform
- )
- if success:
- profile_map[platform] = adapter
- if credential_claim is not None:
- claimed[credential_claim] = profile_name
- if listener_claim is not None:
- claimed[listener_claim] = profile_name
- connected += 1
- logger.info("✓ %s connected (profile: %s)", platform.value, profile_name)
- else:
- logger.warning("✗ %s failed to connect (profile: %s)", platform.value, profile_name)
- await self._safe_adapter_disconnect(adapter, platform)
- except Exception as e:
- logger.error("✗ %s error (profile: %s): %s", platform.value, profile_name, e)
- await self._safe_adapter_disconnect(adapter, platform)
- return connected
+ logger.info("Press Ctrl+C to stop")
+
+ return True
- def _configure_profile_adapter(
- self,
- adapter: BasePlatformAdapter,
- profile_name: str,
- platform: Platform,
- ) -> None:
- """Install the profile-scoped handlers shared by startup and reconnect."""
- adapter.set_message_handler(self._make_profile_message_handler(profile_name))
- adapter.set_fatal_error_handler(
- self._make_profile_fatal_error_handler(profile_name, platform)
- )
- adapter.set_session_store(self.session_store)
- adapter.set_busy_session_handler(self._handle_active_session_busy_message)
- _set_reaction = getattr(adapter, "set_reaction_handler", None)
- if callable(_set_reaction):
- _set_reaction(self._handle_reaction_event)
- adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
- adapter.set_authorization_check(
- self._make_adapter_auth_check(platform, profile_name=profile_name)
- )
- adapter._busy_text_mode = self._busy_text_mode
+ _MAX_SUPERVISED_RESTARTS = 5
+ # A task that ran at least this long before crashing is treated as having
+ # been HEALTHY — its crash is a fresh, isolated failure rather than part of
+ # a rapid crash-loop, so the consecutive-restart counter resets to 0. Only
+ # crashes that happen within this window of a (re)spawn accumulate toward
+ # ``_MAX_SUPERVISED_RESTARTS``. Without this, a long-lived launchd daemon
+ # whose watcher crashes a handful of times over days would hit the cap and
+ # be permanently abandoned (NS: silent loss of platform-reconnect / kanban /
+ # handoff for the rest of the process life).
+ _SUPERVISED_HEALTHY_SECS = 300
- async def _run_secondary_profile_reconnect(
- self, profile_name: str, platform: Platform
- ) -> None:
- """Reconnect a retryable secondary adapter under its own profile scope."""
- attempts = 0
- current_task = asyncio.current_task()
- try:
- while self._running:
- adapter = None
- try:
- from hermes_cli.profiles import get_profile_dir
- from gateway.config import load_gateway_config
+ def _spawn_supervised(self, coro_factory, name, *, restart=True, _attempt=0, on_spawn=None):
+ """Launch a long-lived background task with task-level supervision.
- profile_home = get_profile_dir(profile_name)
- with _profile_runtime_scope(profile_home):
- profile_config = load_gateway_config().platforms.get(platform)
- if profile_config is None or not profile_config.enabled:
- return
- adapter = self._create_adapter(platform, profile_config)
- if adapter is None:
- logger.warning(
- "Secondary %s reconnect skipped: adapter unavailable (profile: %s)",
- platform.value,
- profile_name,
- )
- return
- self._configure_profile_adapter(
- adapter, profile_name, platform
- )
- success = await self._connect_adapter_with_timeout(
- adapter, platform, is_reconnect=True
- )
+ Complements upstream's per-iteration inner-loop try/except (which only
+ guards a single loop-body) by covering what that CANNOT: an exception
+ raised in the watcher's OUTER ``while self._running:`` loop or its
+ pre-try setup region, plus task-level death generally. A bare
+ ``asyncio.create_task`` drops such an exception on the floor — no log,
+ no restart, the watcher silently gone. This retains the handle in
+ ``self._background_tasks``, logs any crash, and restarts with capped
+ exponential backoff up to ``_MAX_SUPERVISED_RESTARTS`` failures in rapid
+ succession (each within ``_SUPERVISED_HEALTHY_SECS`` of its restart).
+ The counter resets after any run that stayed healthy for at least
+ ``_SUPERVISED_HEALTHY_SECS`` — so a long-lived daemon that crashes
+ occasionally over days is never permanently abandoned.
- if success and self._running:
- profile_map = self._profile_adapters.setdefault(profile_name, {})
- if platform not in profile_map:
- profile_map[platform] = adapter
- self._sync_voice_mode_state_to_adapter(adapter)
- logger.info(
- "✓ %s reconnected (profile: %s)",
- platform.value,
- profile_name,
- )
- return
- # A newer reconnect already won the slot while this
- # attempt was awaiting connect; do not replace it.
- await self._safe_adapter_disconnect(adapter, platform)
- return
+ ``on_spawn`` (optional) is invoked with the freshly-created task on
+ every spawn, INCLUDING internal backoff respawns. Callers that also
+ track the live handle elsewhere (e.g. ``self._reconnect_watcher_task``
+ for ``_ensure_reconnect_watcher_running``) MUST pass it — otherwise the
+ supervisor's own respawn creates a new task without updating that
+ external handle, so ``_ensure_...`` later sees the stale/done handle
+ and spawns a SECOND concurrent watcher (double reconnect attempts).
+ """
+ if getattr(self, "_background_tasks", None) is None:
+ self._background_tasks = set()
- # Shutdown can begin while connect() is in flight. Do not
- # republish a newly connected adapter after the registry has
- # been drained; release its partial resources instead.
- if success:
- await self._safe_adapter_disconnect(adapter, platform)
- return
+ # Monotonic spawn timestamp captured per spawn: the ``_done`` callback
+ # uses it to distinguish a rapid crash-loop from a healthy-run-then-crash.
+ _started = time.monotonic()
- await self._safe_adapter_disconnect(adapter, platform)
- if (
- getattr(adapter, "has_fatal_error", False)
- and not getattr(adapter, "fatal_error_retryable", True)
- ):
- return
- except asyncio.CancelledError:
- if adapter is not None:
- await self._safe_adapter_disconnect(adapter, platform)
- raise
- except Exception:
- if adapter is not None:
- await self._safe_adapter_disconnect(adapter, platform)
- logger.debug(
- "Secondary %s reconnect attempt failed (profile: %s)",
- platform.value,
- profile_name,
- exc_info=True,
- )
+ # Deliberately do NOT pass name= to create_task — some test doubles mock
+ # create_task with a signature that rejects the name kwarg.
+ task = asyncio.create_task(coro_factory())
+ self._background_tasks.add(task)
+ if on_spawn is not None:
+ # Record the live handle NOW so an external tracker (e.g.
+ # _reconnect_watcher_task) always points at the current task, not a
+ # dead one left behind by a prior supervised respawn.
+ try:
+ on_spawn(task)
+ except Exception: # pragma: no cover - defensive; a tracker must never kill the spawn
+ logger.debug("on_spawn callback for %s raised", name, exc_info=True)
- if not self._running:
+ def _done(t):
+ self._background_tasks.discard(t)
+ if t.cancelled():
+ return
+ exc = t.exception()
+ if exc is None:
+ # Clean return == deliberate shutdown or a self-disabling watcher
+ # (e.g. a gated no-op that returns synchronously). Respawning here
+ # would busy-spin such a watcher — so NEVER restart on clean exit.
+ return
+ logger.error("Supervised task %s died: %r", name, exc, exc_info=exc)
+ if restart and self._running:
+ ran_for = time.monotonic() - _started
+ if ran_for >= self._SUPERVISED_HEALTHY_SECS:
+ # Ran healthily for a while before crashing — this is a
+ # FRESH failure, not part of a rapid crash-loop. Reset the
+ # consecutive counter so a daemon that crashes a handful of
+ # times over days is never permanently abandoned.
+ effective_attempt = 0
+ else:
+ effective_attempt = _attempt
+ if effective_attempt >= self._MAX_SUPERVISED_RESTARTS:
+ logger.error(
+ "Supervised task %s died %d times in rapid succession "
+ "(each within %ds of restart) — giving up restarts",
+ name,
+ effective_attempt,
+ self._SUPERVISED_HEALTHY_SECS,
+ )
return
- attempts += 1
- backoff = _reconnect_backoff(attempts)
- logger.info(
- "Secondary %s reconnect retry in %ds (profile: %s)",
- platform.value,
- backoff,
- profile_name,
- )
- await asyncio.sleep(backoff)
- finally:
- pending = self._profile_failed_platforms
- if isinstance(pending, dict):
- profile_pending = pending.get(profile_name)
- task = profile_pending.get(platform) if isinstance(profile_pending, dict) else None
- if not isinstance(task, asyncio.Task) or task is current_task:
- if isinstance(profile_pending, dict):
- profile_pending.pop(platform, None)
- if not profile_pending:
- pending.pop(profile_name, None)
+ backoff = min(60, 2 ** min(effective_attempt, 6))
- def _schedule_secondary_profile_reconnect(
- self, profile_name: str, platform: Platform, adapter: BasePlatformAdapter
- ) -> None:
- """Schedule one runner-owned reconnect without sharing primary secrets."""
- if not self._running or not adapter.fatal_error_retryable:
- return
- pending = self._profile_failed_platforms
- if not isinstance(pending, dict):
- pending = {}
- self._profile_failed_platforms = pending
- profile_pending = pending.setdefault(profile_name, {})
- if platform in profile_pending:
- return
- task = asyncio.create_task(
- self._run_secondary_profile_reconnect(profile_name, platform),
- name=f"secondary-reconnect:{profile_name}:{platform.value}",
- )
- profile_pending[platform] = task
- background_tasks = getattr(self, "_background_tasks", None)
- if not isinstance(background_tasks, set):
- background_tasks = set()
- self._background_tasks = background_tasks
- background_tasks.add(task)
- task.add_done_callback(background_tasks.discard)
+ async def _respawn():
+ await asyncio.sleep(backoff)
+ if self._running:
+ self._spawn_supervised(
+ coro_factory,
+ name,
+ restart=restart,
+ _attempt=effective_attempt + 1,
+ on_spawn=on_spawn,
+ )
- def _make_profile_fatal_error_handler(
- self, profile_name: str, platform: Platform
- ) -> Callable[[BasePlatformAdapter], Awaitable[None]]:
- """Route a secondary-profile fatal error to that profile's reconnect slot."""
- async def _handler(adapter: BasePlatformAdapter) -> None:
- await self._handle_profile_adapter_fatal_error(profile_name, platform, adapter)
+ respawn_task = asyncio.create_task(_respawn())
+ self._background_tasks.add(respawn_task)
+ respawn_task.add_done_callback(self._background_tasks.discard)
- return _handler
+ task.add_done_callback(_done)
+ return task
- async def _handle_profile_adapter_fatal_error(
- self,
- profile_name: str,
- platform: Platform,
- adapter: BasePlatformAdapter,
- ) -> None:
- """Remove a failed multiplexed adapter without touching the primary slot.
+ async def _handoff_watcher(self, interval: float = 2.0) -> None:
+ """Background task that processes pending CLI→gateway session handoffs.
- Secondary adapters are owned by ``_profile_adapters`` rather than
- ``self.adapters``. The primary-only fatal handler intentionally ignores
- them; without this route, a fatal secondary Discord client stayed live
- forever after its liveness sampler stopped.
- """
- profile_map = getattr(self, "_profile_adapters", {}).get(profile_name)
- if not isinstance(profile_map, dict) or profile_map.get(platform) is not adapter:
- logger.debug(
- "Ignoring stale fatal error from secondary %s adapter (profile: %s)",
- platform.value,
- profile_name,
- )
- return
- profile_map.pop(platform, None)
- await self._safe_adapter_disconnect(adapter, platform)
- if not self._running:
- return
- self._schedule_secondary_profile_reconnect(profile_name, platform, adapter)
- logger.error(
- "Fatal %s adapter error for multiplexed profile %s (%s)",
- platform.value,
- profile_name,
- adapter.fatal_error_code or "unknown",
- )
- # Reconnect is scoped to the profile's own config and secret mapping;
- # never rebuild a secondary adapter with the default profile's credentials.
+ Polls ``state.db`` for sessions in ``handoff_state='pending'`` and,
+ for each one:
- def _make_profile_message_handler(self, profile_name: str):
- """Return a message handler that stamps source.profile then delegates.
+ 1. Atomically claims it (pending → running).
+ 2. Resolves the destination platform's configured home channel.
+ 3. Re-binds the gateway's session_key for that home channel to the
+ CLI's existing session_id via ``session_store.switch_session`` so
+ the full role-aware transcript replays on the next agent turn.
+ 4. Forges a synthetic ``MessageEvent`` (``internal=True``) with a
+ handoff-notice text and dispatches through the normal gateway
+ message pipeline so the agent runs and replies on the platform.
+ 5. Marks the row ``completed`` (or ``failed`` with ``handoff_error``).
- Auth runs inside ``_handle_message`` *before* the agent-turn scope is
- installed. For secondary profiles under multiplex, wrap the whole
- handler in ``_profile_runtime_scope`` so allowlists/tokens from that
- profile's ``.env`` are visible to ``get_secret`` / authz.
+ The CLI process is poll-blocked on the row's terminal state and
+ prints the result to the user.
"""
- from hermes_cli.profiles import get_profile_dir
-
- try:
- profile_home = get_profile_dir(profile_name)
- except Exception:
- profile_home = None
-
- async def _handler(event):
+ # Initial delay so the gateway is fully connected to its platforms
+ # before we try to dispatch handoffs through them.
+ await asyncio.sleep(5)
+ while self._running:
try:
- if getattr(event, "source", None) is not None and not event.source.profile:
- event.source.profile = profile_name
- except Exception:
- pass
- if profile_home is not None:
- with _profile_runtime_scope(profile_home):
- return await self._handle_message(event)
- return await self._handle_message(event)
-
- return _handler
+ if self._session_db is None:
+ await asyncio.sleep(interval)
+ continue
+ pending = await self._session_db.list_pending_handoffs()
+ for row in pending:
+ session_id = row.get("id")
+ if not session_id:
+ continue
+ if not await self._session_db.claim_handoff(session_id):
+ # Another tick or another gateway already claimed it.
+ continue
+ try:
+ await self._process_handoff(row)
+ await self._session_db.complete_handoff(session_id)
+ except Exception as exc:
+ logger.warning(
+ "Handoff for session %s failed: %s",
+ session_id, exc, exc_info=True,
+ )
+ await self._session_db.fail_handoff(session_id, str(exc))
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ logger.debug("Handoff watcher tick error: %s", exc, exc_info=True)
+ await asyncio.sleep(interval)
- @staticmethod
- def _adapter_credential_claim(
- platform: Platform, adapter: Any
- ) -> Optional[tuple]:
- """Return the exclusive credential resource claimed by an adapter."""
- fingerprint = GatewayRunner._adapter_credential_fingerprint(adapter)
- if fingerprint is None:
- return None
- return (platform, fingerprint)
+ async def _process_handoff(self, row: Dict[str, Any]) -> None:
+ """Execute one handoff row. Raises on failure (caller marks failed)."""
+ from gateway.config import Platform
+ from gateway.session import SessionSource, build_session_key
+ from gateway.platforms.base import MessageEvent
- @staticmethod
- def _adapter_listener_claim(platform: Platform, adapter: Any) -> Optional[tuple]:
- """Return the exclusive listener resource claimed by an adapter.
+ cli_session_id = row["id"]
+ platform_name = (row.get("handoff_platform") or "").strip().lower()
+ if not platform_name:
+ raise RuntimeError("handoff_platform is empty")
- Photon sidecars are per-profile processes. Even when two profiles use
- different project credentials, their sidecars cannot share a bind and
- port. Represent that endpoint as a claim so multiplex startup rejects
- the later adapter before either ``connect()`` or ``disconnect()`` can
- disturb the first profile.
- """
- if getattr(platform, "value", None) != "photon":
- return None
- bind = getattr(adapter, "_sidecar_bind", None)
- port = getattr(adapter, "_sidecar_port", None)
- if not isinstance(bind, str) or not bind.strip():
- return None
+ # Resolve platform enum
try:
- port = int(port)
- except (TypeError, ValueError):
- return None
- return ("listener", "photon", bind.strip().lower(), port)
+ platform = Platform(platform_name)
+ except (ValueError, KeyError):
+ raise RuntimeError(f"unknown platform '{platform_name}'")
- @staticmethod
- def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]:
- """Return a stable, log-safe fingerprint of an adapter's credential.
+ # Adapter must be live. A relay-fronted gateway registers ONE adapter
+ # under Platform.RELAY that fronts N logical platforms — so a literal
+ # adapters.get(discord) misses even though "discord" is deliverable.
+ # resolve_delivery_transport is the shared alias-aware resolver (native
+ # adapter wins; relay eligible only when its authenticated transport
+ # advertises it fronts the logical platform).
+ transport = resolve_delivery_transport(platform, self.config, self.adapters)
+ if not transport:
+ raise RuntimeError(
+ f"platform '{platform_name}' is not active in this gateway"
+ )
+ adapter = transport.adapter
- Used only to detect two profiles claiming the same platform credential.
- Returns a salted hash (never the credential itself) of the adapter's
- primary credential, or None when no credential is discoverable (in
- which case we don't attempt conflict detection for it).
- """
- token = None
- for attr in (
- "token",
- "bot_token",
- "_token",
- "api_token",
- "_bot_token",
- # Photon/Spectrum authenticates with project credentials instead
- # of a bot token. Including its secret keeps multiplexed profiles
- # from spawning competing sidecars for the same account and port.
- "_project_secret",
- ):
- val = getattr(adapter, attr, None)
- if isinstance(val, str) and val.strip():
- token = val.strip()
- break
- # Many adapters (e.g. Discord) store the token on their `config`
- # sub-object rather than directly on the adapter. Without this lookup
- # those adapters all return None here, the same-token conflict check
- # is silently skipped, and every profile's adapter for that platform
- # starts polling the same bot token — producing a per-message race
- # for which adapter answers. See test_reads_config_token.
- if not token:
- cfg = getattr(adapter, "config", None)
- if cfg is not None:
- for attr in ("token", "bot_token"):
- val = getattr(cfg, attr, None)
- if isinstance(val, str) and val.strip():
- token = val.strip()
- break
- if not token:
- config = getattr(adapter, "config", None)
- val = getattr(config, "token", None)
- if isinstance(val, str) and val.strip():
- token = val.strip()
- if not token:
- return None
- import hashlib
- return hashlib.sha256(("hermes-mux:" + token).encode("utf-8")).hexdigest()[:16]
+ # Home channel must be configured
+ home = self.config.get_home_channel(platform)
+ if not home or not home.chat_id:
+ raise RuntimeError(
+ f"no home channel configured for {platform_name}; "
+ f"run /sethome on the desired chat first"
+ )
- def _create_adapter(
- self,
- platform: Platform,
- config: Any
- ) -> Optional[BasePlatformAdapter]:
- """Create the appropriate adapter for a platform.
+ cli_title = row.get("title") or cli_session_id[:8]
- Checks the platform_registry first (plugin adapters), then falls
- through to the built-in if/elif chain for core platforms.
- """
- if hasattr(config, "extra") and isinstance(config.extra, dict):
- config.extra.setdefault(
- "group_sessions_per_user",
- self.config.group_sessions_per_user,
+ # Try to create a fresh thread on the destination so the handoff
+ # has its own scrollback. Adapter returns None if threading isn't
+ # supported (Matrix/WhatsApp/Signal/SMS) or if creation failed
+ # (no permission, topics-mode off, parent is a DM, etc.). When
+ # None we fall through to using the home channel directly — the
+ # synthetic turn still lands; just without thread isolation.
+ thread_name = f"Hermes — {cli_title}"
+ try:
+ new_thread_id = await adapter.create_handoff_thread(
+ str(home.chat_id), thread_name,
)
- config.extra.setdefault(
- "thread_sessions_per_user",
- getattr(self.config, "thread_sessions_per_user", False),
+ except Exception as exc:
+ logger.debug(
+ "Handoff: create_handoff_thread raised on %s: %s",
+ platform_name, exc, exc_info=True,
)
+ new_thread_id = None
- # ── Plugin-registered platforms (checked first) ───────────────────
- try:
- from gateway.platform_registry import platform_registry
- if platform_registry.is_registered(platform.value):
- adapter = platform_registry.create_adapter(platform.value, config)
- if adapter is not None:
- # Inject a back-reference to the gateway runner so every
- # adapter can (a) deliver cross-platform admin alerts and
- # (b) resolve inbound profile routing through
- # ``runner._profile_name_for_source``. Unconditional:
- # ``BasePlatformAdapter`` declares ``gateway_runner``, so
- # this reaches ALL platforms (not just the ones that
- # pre-declared it), making profile routing platform-generic.
- adapter.gateway_runner = self
- return adapter
- # Registered but failed to instantiate — don't silently fall
- # through to built-ins (there are none for plugin platforms).
- logger.error(
- "Platform '%s' is registered but adapter creation failed "
- "(check dependencies and config)",
- platform.value,
- )
- return None
- except Exception as e:
- logger.debug("Platform registry lookup for '%s' failed: %s", platform.value, e)
- # Fall through to built-in adapters below
+ # Use the new thread if the adapter created one; otherwise fall
+ # back to whatever thread (if any) the home channel was configured
+ # with.
+ effective_thread_id = new_thread_id or (
+ str(home.thread_id) if home.thread_id else None
+ )
- if platform == Platform.WHATSAPP_CLOUD:
- from gateway.platforms.whatsapp_cloud import (
- WhatsAppCloudAdapter,
- check_whatsapp_cloud_requirements,
- )
- if not check_whatsapp_cloud_requirements():
- logger.warning(
- "WhatsApp Cloud: aiohttp/httpx missing — reinstall hermes-agent"
- )
- return None
- return WhatsAppCloudAdapter(config)
-
- elif platform == Platform.SIGNAL:
- from gateway.platforms.signal import (
- SignalAdapter,
- check_signal_requirements,
- validate_signal_config,
- )
- if not check_signal_requirements():
- logger.warning("Signal: runtime requirements not met")
- return None
- if not validate_signal_config(config):
- logger.warning("Signal: SIGNAL_HTTP_URL or SIGNAL_ACCOUNT not configured")
- return None
- return SignalAdapter(config)
-
- elif platform == Platform.WEIXIN:
- from gateway.platforms.weixin import WeixinAdapter, check_weixin_requirements
- if not check_weixin_requirements():
- logger.warning("Weixin: aiohttp/cryptography not installed")
- return None
- return WeixinAdapter(config)
-
- elif platform == Platform.API_SERVER:
- from gateway.platforms.api_server import APIServerAdapter, check_api_server_requirements
- if not check_api_server_requirements():
- logger.warning("API Server: aiohttp not installed")
- return None
- adapter = APIServerAdapter(config)
- adapter.gateway_runner = self
- return adapter
-
- elif platform == Platform.WEBHOOK:
- from gateway.platforms.webhook import WebhookAdapter, check_webhook_requirements
- if not check_webhook_requirements():
- logger.warning("Webhook: aiohttp not installed")
- return None
- adapter = WebhookAdapter(config)
- adapter.gateway_runner = self # For cross-platform delivery
- return adapter
-
- elif platform == Platform.MSGRAPH_WEBHOOK:
- from gateway.platforms.msgraph_webhook import (
- MSGraphWebhookAdapter,
- check_msgraph_webhook_requirements,
- )
- if not check_msgraph_webhook_requirements():
- logger.warning("MSGraph webhook: aiohttp not installed")
- return None
- return MSGraphWebhookAdapter(config)
-
- elif platform == Platform.BLUEBUBBLES:
- from gateway.platforms.bluebubbles import BlueBubblesAdapter, check_bluebubbles_requirements
- if not check_bluebubbles_requirements():
- logger.warning("BlueBubbles: aiohttp/httpx missing or BLUEBUBBLES_SERVER_URL/BLUEBUBBLES_PASSWORD not configured")
- return None
- return BlueBubblesAdapter(config)
-
- elif platform == Platform.QQBOT:
- from gateway.platforms.qqbot import QQAdapter, check_qq_requirements
- if not check_qq_requirements():
- logger.warning("QQBot: aiohttp/httpx missing or QQ_APP_ID/QQ_CLIENT_SECRET not configured")
- return None
- return QQAdapter(config)
-
- elif platform == Platform.YUANBAO:
- from gateway.platforms.yuanbao import YuanbaoAdapter, WEBSOCKETS_AVAILABLE
- if not WEBSOCKETS_AVAILABLE:
- logger.warning("Yuanbao: websockets not installed. Run: pip install websockets")
- return None
- return YuanbaoAdapter(config)
+ # Determine chat_type/user_id for the destination source.
+ #
+ # Telegram private-chat DM topics are represented differently from
+ # group/forum threads by the inbound adapter. A handoff-created topic
+ # in a positive Telegram chat_id must therefore use the same DM-topic
+ # source shape as the user's next real message; otherwise the synthetic
+ # handoff turn binds a generic `thread` session key while real replies
+ # arrive on a `dm` session key.
+ home_chat_id = str(home.chat_id)
+ is_telegram_private_chat = (
+ platform == Platform.TELEGRAM
+ and looks_like_telegram_private_chat_id(home_chat_id)
+ )
- return None
+ if new_thread_id and not is_telegram_private_chat:
+ dest_chat_type = "thread"
+ dest_user_id = "system:handoff"
+ else:
+ # No thread — assume DM-style for the home channel. For Telegram
+ # private-chat topics, use the real user id (same as chat_id) so
+ # topic-mode checks and binding persistence see the same identity as
+ # subsequent inbound user messages.
+ dest_chat_type = "dm"
+ dest_user_id = home_chat_id if is_telegram_private_chat else "system:handoff"
- def _make_adapter_auth_check(
- self,
- platform: Platform,
- profile_name: Optional[str] = None,
- ) -> Callable[[str, Optional[str], Optional[str]], bool]:
- """Build a platform-bound auth callback for adapter use.
+ dest_source = SessionSource(
+ platform=platform,
+ chat_id=home_chat_id,
+ chat_name=home.name,
+ chat_type=dest_chat_type,
+ user_id=dest_user_id,
+ user_name="Handoff",
+ thread_id=effective_thread_id,
+ )
- Adapters that fetch external context (e.g. Slack
- ``conversations.replies``) call this through
- ``BasePlatformAdapter._is_sender_authorized`` to mark non-allowlisted
- senders as unverified in LLM context, mitigating indirect prompt
- injection from third parties in shared threads/channels.
+ # Compute the gateway's session_key for that destination using the
+ # same rules its adapters use, so switch_session targets the right
+ # entry. For thread destinations build_session_key keys without
+ # user_id (thread_sessions_per_user defaults to False) — so the
+ # next real user message in the thread shares this same session.
+ platform_cfg = self.config.platforms.get(platform)
+ extra = platform_cfg.extra if platform_cfg else {}
+ session_key = build_session_key(
+ dest_source,
+ group_sessions_per_user=extra.get("group_sessions_per_user", True),
+ thread_sessions_per_user=extra.get("thread_sessions_per_user", False),
+ )
- The returned callback delegates to :meth:`_is_user_authorized` so the
- full auth chain — platform allowlists, group allowlists, pairing
- store, allow-all flags — stays the single source of truth.
+ # Make sure there's an entry in the session_store for this key. If
+ # the home channel has never been used, get_or_create_session
+ # creates one; switch_session then re-points it.
+ await self.async_session_store.get_or_create_session(dest_source)
- ``profile_name`` binds the callback to the secondary adapter's own
- multiplex profile, so its ``SessionSource`` resolves that profile's
- secret scope instead of falling back to the active profile.
- """
- def check(
- user_id: str,
- chat_type: Optional[str] = None,
- chat_id: Optional[str] = None,
- ) -> bool:
- if not user_id:
- return False
- source = SessionSource(
- platform=platform,
- chat_id=chat_id or "",
- chat_type=chat_type or "group",
- user_id=user_id,
- profile=profile_name,
+ # Re-bind the destination key to the CLI session_id. switch_session
+ # ends the prior session in SQLite and reopens the CLI session under
+ # the new key. The CLI's transcript becomes the active one for the
+ # gateway from this moment on.
+ switched = await self.async_session_store.switch_session(session_key, cli_session_id)
+ if switched is None:
+ raise RuntimeError(
+ f"could not switch session key {session_key} → {cli_session_id}"
)
- return self._is_user_authorized(source)
- return check
+ # Evict any cached AIAgent for this session_key so the next dispatch
+ # rebuilds it against the CLI session_id (mirrors /resume / /branch).
+ self._evict_cached_agent(session_key)
+ # Cancel any in-flight running-agent state for the destination key
+ # so the synthetic turn isn't queued behind a stale running flag.
+ self._release_running_agent_state(session_key)
+ synthetic_text = (
+ f"[Session was just handed off from CLI (\"{cli_title}\") to this "
+ f"channel. The full prior conversation history is loaded above. "
+ f"Briefly confirm you're working here and summarize what we were "
+ f"working on, so the user can continue from this device.]"
+ )
+ synthetic_event = MessageEvent(
+ text=synthetic_text,
+ source=dest_source,
+ internal=True,
+ )
+ logger.info(
+ "Handoff: dispatching synthetic turn for CLI session %s → %s "
+ "(home=%s, thread=%s, session_key=%s)",
+ cli_session_id, platform_name, home.chat_id, effective_thread_id,
+ session_key,
+ )
- async def _deliver_platform_notice(self, source, content: str) -> None:
- """Deliver a setup/operational notice using platform-specific privacy rules."""
- adapter = self._adapter_for_source(source)
- if not adapter:
+ # Dispatch through the runner directly. Going through
+ # adapter.handle_message would spawn a background task and we'd
+ # lose synchronous error visibility; calling _handle_message inline
+ # keeps the success/failure path observable for the watcher.
+ response_text = await self._handle_message(synthetic_event)
+ if not response_text:
+ # Streaming may have already delivered the response inline.
+ # Either way, agent ran without raising — count as success.
return
- config = getattr(self, "config", None)
- if (
- config
- and getattr(source, "platform", None) == Platform.SLACK
- and _is_slack_ignored_channel(config, getattr(source, "chat_id", None))
- ):
- logger.info(
- "Skipping Slack platform notice for configured ignored channel %s",
- getattr(source, "chat_id", None),
+ # Send the agent's reply to the destination. Route to the new
+ # thread if we created one; otherwise the configured home channel
+ # (which may itself carry a thread_id). Send through the resolved
+ # transport (not adapter.send directly) so a relay-fronted logical
+ # platform is stamped on the outbound frame (send_for_platform).
+ send_metadata: Dict[str, Any] = {}
+ if effective_thread_id:
+ send_metadata["thread_id"] = effective_thread_id
+ try:
+ result = await transport.send(
+ platform,
+ str(home.chat_id),
+ response_text,
+ send_metadata or None,
)
- return
-
- notice_delivery = "public"
- if config and hasattr(config, "get_notice_delivery"):
- notice_delivery = config.get_notice_delivery(source.platform)
-
- metadata = self._thread_metadata_for_source(source)
- if notice_delivery == "private" and getattr(source, "user_id", None):
- try:
- result = await adapter.send_private_notice(
- source.chat_id,
- source.user_id,
- content,
- metadata=metadata,
- )
- if getattr(result, "success", False):
- return
- except Exception:
- logger.debug(
- "[%s] send_private_notice failed, falling back to public",
- getattr(source, "platform", "?"),
- exc_info=True,
- )
+ except Exception as exc:
+ raise RuntimeError(f"adapter.send failed: {exc}") from exc
- await adapter.send(source.chat_id, content, metadata=metadata)
+ if not getattr(result, "success", True):
+ err = getattr(result, "error", "send returned success=False")
+ raise RuntimeError(f"adapter.send failed: {err}")
- async def _resolve_async_delegation_session(
- self,
- session_entry: SessionEntry,
- pinned_session_id: str,
- ) -> Optional[SessionEntry]:
- """Resolve an async completion to its verified owning gateway session.
+ async def _session_expiry_watcher(self, interval: int = 300):
+ """Background task that finalizes expired sessions.
- A compression rotation ends the physical parent row while continuing
- the same logical conversation in a child. Follow that lineage, but
- never let a late completion override an unrelated /new or restored
- route. Unknown ownership remains fail-closed; the result is still
- available in the delegation records.
+ Runs every ``interval`` seconds (default 5 min). For each session
+ whose reset policy has expired, invokes ``on_session_finalize``
+ hooks, cleans up the cached AIAgent's tool resources, evicts the
+ cache entry so it can be garbage-collected, and marks the session
+ so it won't be finalized again.
"""
- session_db = cast(Any, self._session_db)
- if session_db is None:
- logger.warning(
- "Async-delegation completion has no session database; "
- "dropping injection (#55578 fail-closed)."
- )
- return None
-
- pinned_row = None
- try:
- pinned_row = await session_db.get_session(pinned_session_id)
- except Exception:
- logger.debug(
- "Async-delegation parent lookup failed for %s",
- pinned_session_id,
- exc_info=True,
- )
-
- if pinned_row is None:
- logger.warning(
- "Async-delegation completion has unknown spawning session %s; "
- "dropping injection (#55578 fail-closed).",
- pinned_session_id,
- )
- return None
-
- target_session_id = pinned_session_id
- follows_compression = False
- if pinned_row.get("ended_at"):
- if pinned_row.get("end_reason") != "compression":
- logger.warning(
- "Async-delegation completion pinned to ended session %s "
- "(end_reason=%r); dropping injection instead of resurrecting it "
- "(#55578 fail-closed).",
- pinned_session_id,
- pinned_row.get("end_reason"),
- )
- return None
-
- follows_compression = True
+ await asyncio.sleep(60) # initial delay — let the gateway fully start
+ _finalize_failures: dict[str, int] = {} # session_id -> consecutive failure count
+ _MAX_FINALIZE_RETRIES = 3
+ while self._running:
try:
- target_session_id = await session_db.get_compression_tip(
- pinned_session_id
- )
- except Exception:
- logger.debug(
- "Async-delegation compression-tip lookup failed for %s",
- pinned_session_id,
- exc_info=True,
- )
- target_session_id = None
+ await self.async_session_store._ensure_loaded()
+ # Collect expired sessions first, then log a single summary.
+ _expired_entries = []
+ for key, entry in list(self.session_store._entries.items()):
+ if entry.expiry_finalized:
+ continue
+ if not await self.async_session_store._is_session_expired(entry):
+ continue
+ _expired_entries.append((key, entry))
- if not target_session_id or target_session_id == pinned_session_id:
- logger.warning(
- "Async-delegation completion pinned to compressed session %s "
- "without a continuation; dropping injection.",
- pinned_session_id,
- )
- return None
+ if _expired_entries:
+ # Extract platform names from session keys for a compact summary.
+ # Keys look like "agent:main:telegram:dm:12345" — platform is field [2].
+ _platforms: dict[str, int] = {}
+ for _k, _e in _expired_entries:
+ _parts = _k.split(":")
+ _plat = _parts[2] if len(_parts) > 2 else "unknown"
+ _platforms[_plat] = _platforms.get(_plat, 0) + 1
+ _plat_summary = ", ".join(
+ f"{p}:{c}" for p, c in sorted(_platforms.items())
+ )
+ logger.info(
+ "Session expiry: %d sessions to finalize (%s)",
+ len(_expired_entries), _plat_summary,
+ )
- try:
- tip_row = await session_db.get_session(target_session_id)
- except Exception:
- tip_row = None
- if tip_row is None or tip_row.get("ended_at"):
- logger.warning(
- "Async-delegation compression continuation %s is %s; "
- "dropping injection.",
- target_session_id,
- "unknown" if tip_row is None else "ended",
- )
- return None
+ for key, entry in _expired_entries:
+ try:
+ try:
+ from hermes_cli.lifecycle import finalize_session
+ _parts = key.split(":")
+ _platform = _parts[2] if len(_parts) > 2 else ""
+ finalize_session(
+ session_id=entry.session_id,
+ platform=_platform,
+ reason="session_expired",
+ )
+ except Exception:
+ pass
+ # Shut down memory provider and close tool resources
+ # on the cached agent. Idle agents live in
+ # _agent_cache (not _running_agents), so look there.
+ _cached_agent = None
+ _cache_lock = getattr(self, "_agent_cache_lock", None)
+ if _cache_lock is not None:
+ with _cache_lock:
+ _cached = self._agent_cache.get(key)
+ _cached_agent = _cached[0] if isinstance(_cached, tuple) else _cached if _cached else None
+ # Fall back to _running_agents in case the agent is
+ # still mid-turn when the expiry fires.
+ if _cached_agent is None:
+ _exp_state = self._peek_session_state(key)
+ _cached_agent = _exp_state.turn.agent if _exp_state else None
+ if _cached_agent and _cached_agent is not _AGENT_PENDING_SENTINEL:
+ await self._cleanup_agent_resources_off_loop(
+ _cached_agent, context="session expiry"
+ )
+ # Drop the cache entry so the AIAgent (and its LLM
+ # clients, tool schemas, memory provider refs) can
+ # be garbage-collected. Otherwise the cache grows
+ # unbounded across the gateway's lifetime.
+ self._evict_cached_agent(key)
+ # Permanently finalizing this session — one funnel
+ # call drops every conversation-scoped dict AND the
+ # boundary security state (approvals, update
+ # prompts, slash-confirm) so the dicts don't grow
+ # unbounded across the gateway's lifetime. (Idle
+ # agent-cache eviction must NOT do this: the
+ # session is still alive and a resumed turn rebuilds
+ # its agent from these overrides. Only true session
+ # finalization, /new, and /reset clear them.) See
+ # _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(
+ key, reason="expiry_finalized"
+ )
+ # Persist the finalized flag to sessions.json AND
+ # state.db (single write-path, #9006) — also drops
+ # the persisted /model override, since finalization
+ # is a conversation boundary.
+ await self.async_session_store.set_expiry_finalized(entry)
+ logger.debug(
+ "Session expiry finalized for %s",
+ entry.session_id,
+ )
+ _finalize_failures.pop(entry.session_id, None)
+ except Exception as e:
+ failures = _finalize_failures.get(entry.session_id, 0) + 1
+ _finalize_failures[entry.session_id] = failures
+ if failures >= _MAX_FINALIZE_RETRIES:
+ logger.warning(
+ "Session finalize gave up after %d attempts for %s: %s. "
+ "Marking as finalized to prevent infinite retry loop.",
+ failures, entry.session_id, e,
+ )
+ await self.async_session_store.set_expiry_finalized(
+ entry, clear_model_override=False
+ )
+ _finalize_failures.pop(entry.session_id, None)
+ else:
+ logger.debug(
+ "Session finalize failed (%d/%d) for %s: %s",
+ failures, _MAX_FINALIZE_RETRIES, entry.session_id, e,
+ )
- route_owns_lineage = session_entry.session_id in {
- pinned_session_id,
- target_session_id,
- }
- if not route_owns_lineage:
- # A long-running delegation may survive multiple compression
- # rotations. Accept an intermediate stale route only when its
- # own verified compression tip is the same live target.
- try:
- route_row = await session_db.get_session(session_entry.session_id)
- route_tip = (
- await session_db.get_compression_tip(session_entry.session_id)
- if route_row is not None
- and route_row.get("ended_at")
- and route_row.get("end_reason") == "compression"
- else None
+ if _expired_entries:
+ _done = sum(
+ 1 for _, e in _expired_entries if e.expiry_finalized
)
- except Exception:
- route_tip = None
- route_owns_lineage = route_tip == target_session_id
-
- if not route_owns_lineage:
- logger.warning(
- "Async-delegation completion for compression lineage %s -> %s "
- "does not own current route %s; dropping injection.",
- pinned_session_id,
- target_session_id,
- session_entry.session_id,
- )
- return None
+ _failed = len(_expired_entries) - _done
+ if _failed:
+ logger.info(
+ "Session expiry done: %d finalized, %d pending retry",
+ _done, _failed,
+ )
+ else:
+ logger.info(
+ "Session expiry done: %d finalized", _done,
+ )
- if target_session_id == session_entry.session_id:
- return session_entry
+ # Sweep agents that have been idle beyond the TTL regardless
+ # of session reset policy. This catches sessions with very
+ # long / "never" reset windows, whose cached AIAgents would
+ # otherwise pin memory for the gateway's entire lifetime.
+ try:
+ _idle_evicted = self._sweep_idle_cached_agents()
+ if _idle_evicted:
+ logger.info(
+ "Agent cache idle sweep: evicted %d agent(s)",
+ _idle_evicted,
+ )
+ except Exception as _e:
+ logger.debug("Idle agent sweep failed: %s", _e)
- prior_session_id = session_entry.session_id
- if follows_compression:
- switched = await self.async_session_store.advance_compression_session(
- session_entry.session_key,
- prior_session_id,
- target_session_id,
- )
- else:
- switched = await self.async_session_store.switch_session(
- session_entry.session_key,
- target_session_id,
- )
- if switched is None:
- logger.warning(
- "Async-delegation completion could not bind routing key %s to "
- "owning session %s; dropping injection.",
- session_entry.session_key,
- target_session_id,
- )
- return None
-
- logger.info(
- "Pinned async-delegation completion to owning session %s "
- "(was %s) for routing key %s (#57498)",
- target_session_id,
- prior_session_id,
- session_entry.session_key,
- )
- return switched
+ # Periodically prune stale SessionStore entries. The
+ # in-memory dict (and sessions.json) would otherwise grow
+ # unbounded in gateways serving many rotating chats /
+ # threads / users over long time windows. Pruning is
+ # invisible to users — a resumed session just gets a
+ # fresh session_id, exactly as if the reset policy fired.
+ _last_prune_ts = getattr(self, "_last_session_store_prune_ts", 0.0)
+ _prune_interval = 3600.0 # once per hour
+ if time.time() - _last_prune_ts > _prune_interval:
+ try:
+ _max_age = int(
+ getattr(self.config, "session_store_max_age_days", 0) or 0
+ )
+ if _max_age > 0:
+ _pruned = await self.async_session_store.prune_old_entries(_max_age)
+ if _pruned:
+ logger.info(
+ "SessionStore prune: dropped %d stale entries",
+ _pruned,
+ )
+ except Exception as _e:
+ logger.debug("SessionStore prune failed: %s", _e)
+ self._last_session_store_prune_ts = time.time()
+ except Exception as e:
+ logger.debug("Session expiry watcher error: %s", e)
+ # Sleep in small increments so we can stop quickly
+ for _ in range(interval):
+ if not self._running:
+ break
+ await asyncio.sleep(1)
- # ------------------------------------------------------------------
- # Mid-run (busy-session) slash command dispatch — "Guard 2".
- #
- # Replaces the historical hand-written per-command if-chain: each
- # command's mid-run behavior is declared on its CommandDef
- # (busy_policy / busy_handler in hermes_cli/commands.py) and resolved
- # here through a single handler table. Reply strings are byte-identical
- # to the old chain.
- # ------------------------------------------------------------------
+ def _active_profile_name(self) -> str:
+ """Return the profile name this gateway represents."""
+ try:
+ from hermes_cli.profiles import get_active_profile_name
+ return get_active_profile_name() or "default"
+ except Exception:
+ return "default"
- # Command-specific mid-run reject texts (busy_policy == "reject" with a
- # busy_handler naming an entry here). All other rejected commands get
- # the generic catch-all text in _dispatch_busy_slash_command.
- _BUSY_REJECT_TEXT: Dict[str, str] = {
- "model": "Agent is running — wait or /stop first, then switch models.",
- "codex-runtime": ("Agent is running — wait or /stop first, then "
- "change runtime."),
- "moa": "Agent is running — wait or /stop first, then run /moa.",
- }
+ # ── Kanban board watchers ───────────────────────────────────────────
+ # The kanban notifier/dispatcher watcher loops + their helpers live in
+ # GatewayKanbanWatchersMixin (gateway/kanban_watchers.py). They use only
+ # self state, so inheriting the mixin keeps every self._kanban_* call site
+ # working unchanged while lifting ~1,000 LOC out of this file.
- async def _dispatch_busy_slash_command(
- self, event: MessageEvent, cmd_def, quick_key: str, source,
- ):
- """Dispatch a recognized slash command while an agent is running.
+ def _ensure_reconnect_watcher_running(self) -> None:
+ """Ensure the platform reconnect watcher background task is alive.
- Resolution order:
- 1. ``busy_handler`` — special mid-run variant (e.g. /goal's
- control-verb whitelist, /queue's FIFO enqueue, /model's
- custom reject text).
- 2. ``busy_policy == "dispatch"`` — the command's normal handler.
- 3. Catch-all busy-reject text. Rejecting is required rather than
- falling through to interrupt + discard: commands like /model,
- /reasoning, /voice, /insights, /title, /resume, /retry,
- /undo, /compress, /usage, /reload-mcp, /sethome, /reset (all
- registered as Discord slash commands) would interrupt the
- agent AND get silently discarded by the slash-command safety
- net, producing a zero-char response. See #5057, #6252, #10370.
+ If the tracked reconnect watcher task has died (e.g. from exhausting
+ its restart budget, or a terminal exception that _spawn_supervised
+ could not recover), respawns it so platforms queued for reconnection
+ are not permanently stranded. Called after queueing a retryable fatal
+ error in _handle_adapter_fatal_error (#70344).
"""
- name = cmd_def.name
- policy = getattr(cmd_def, "busy_policy", "reject")
- handler_key = getattr(cmd_def, "busy_handler", None)
+ if not getattr(self, "_running", False):
+ return
+ task = getattr(self, "_reconnect_watcher_task", None)
+ if task is not None and not task.done():
+ return # already alive
+ logger.warning(
+ "Reconnect watcher task is dead (done=%s) — respawning",
+ task.done() if task is not None else "N/A",
+ )
+ self._reconnect_watcher_task = self._spawn_supervised(
+ self._platform_reconnect_watcher,
+ "platform_reconnect_watcher",
+ on_spawn=lambda t: setattr(self, "_reconnect_watcher_task", t),
+ )
- if handler_key:
- special = {
- "start": self._busy_start_command,
- "stop": self._busy_stop_command,
- "new": self._busy_new_command,
- "queue": self._busy_queue_command,
- "steer": self._busy_steer_command,
- "egress": self._busy_egress_command,
- "goal": self._busy_goal_command,
- }.get(handler_key)
- if special is not None:
- return await special(event, quick_key, source)
- reject_text = self._BUSY_REJECT_TEXT.get(handler_key)
- if reject_text is not None:
- return reject_text
+ async def _platform_reconnect_watcher(self) -> None:
+ """Background task that periodically retries connecting failed platforms.
- if policy in ("dispatch", "interrupt_then_dispatch"):
- plain = {
- "status": self._handle_status_command,
- "context": self._handle_context_command,
- "restart": self._handle_restart_command,
- "approve": self._handle_approve_command,
- "deny": self._handle_deny_command,
- "agents": self._handle_agents_command,
- "background": self._handle_background_command,
- "kanban": self._handle_kanban_command,
- "subgoal": self._handle_subgoal_command,
- "yolo": self._handle_yolo_command,
- "verbose": self._handle_verbose_command,
- "footer": self._handle_footer_command,
- "help": self._handle_help_command,
- "commands": self._handle_commands_command,
- "profile": self._handle_profile_command,
- "update": self._handle_update_command,
- "version": self._handle_version_command,
- }.get(name)
- if plain is not None:
- return await plain(event)
- logger.warning(
- "busy_policy=%s for /%s has no mid-run handler — "
- "falling back to busy-reject", policy, name,
- )
+ Uses exponential backoff: 30s → 60s → 120s → 240s → 300s (cap).
+ Retryable failures (network/DNS blips) keep retrying at the backoff
+ cap indefinitely — they self-heal once connectivity returns, so a
+ transient outage never requires manual intervention. Non-retryable
+ failures (bad auth, etc.) drop out of the queue immediately. The
+ circuit breaker (``_pause_failed_platform`` / ``/platform pause``)
+ remains available for manual operator control via ``/platform list``
+ and ``/platform resume <name>``, but is no longer triggered
+ automatically — auto-pausing a recovered platform was the cause of
+ bots silently staying dead after a transient DNS failure.
+ """
+ await asyncio.sleep(10) # initial delay — let startup finish
+ while self._running:
+ if not self._failed_platforms:
+ # Nothing to reconnect — sleep and check again
+ for _ in range(30):
+ if not self._running:
+ return
+ if self._failed_platforms:
+ break
+ await asyncio.sleep(1)
+ continue
- # Catch-all: any other recognized slash command reached the
- # running-agent guard. Reject gracefully rather than falling
- # through to interrupt + discard.
- return (
- f"⏳ Agent is running — `/{name}` can't run "
- f"mid-turn. Wait for the current response or `/stop` first."
- )
+ now = time.monotonic()
+ for platform in list(self._failed_platforms.keys()):
+ if not self._running:
+ return
+ info = self._failed_platforms.get(platform)
+ if info is None:
+ # Removed concurrently (e.g. a manual /platform resume,
+ # or a reconnect that succeeded via a different path)
+ # between the snapshot above and this lookup. Not an
+ # error -- just nothing to do for it this pass.
+ continue
+ # Skip paused platforms entirely — they need explicit
+ # /platform resume to come back.
+ if info.get("paused"):
+ continue
+ if now < info["next_retry"]:
+ continue # not time yet
- async def _busy_start_command(self, event: MessageEvent, quick_key: str, source):
- # Telegram sends /start for bot launches/deep-links. Treat it as a
- # platform ping, not a user command: no help dump, no agent
- # interrupt, no queued text.
- logger.info("Ignoring /start platform ping for active session %s", quick_key)
- return ""
+ platform_config = info["config"]
+ attempt = info["attempts"] + 1
+ # Empty-token primary configs can never reconnect; drop them so
+ # multiplex setups where a secondary profile owns the bot do
+ # not spin forever (#64674).
+ if not _platform_has_bot_credential(platform, platform_config):
+ logger.warning(
+ "Reconnect %s: no bot credential on queued config, "
+ "removing from retry queue",
+ platform.value,
+ )
+ del self._failed_platforms[platform]
+ continue
+ logger.info(
+ "Reconnecting %s (attempt %d)...",
+ platform.value, attempt,
+ )
- async def _busy_egress_command(self, event: MessageEvent, quick_key: str, source):
- from hermes_cli.proxy_cli import format_status_text
+ adapter = None
+ try:
+ adapter = self._create_adapter(platform, platform_config)
+ if not adapter:
+ logger.warning(
+ "Reconnect %s: adapter creation returned None, removing from retry queue",
+ platform.value,
+ )
+ del self._failed_platforms[platform]
+ continue
- return format_status_text()
+ adapter.set_message_handler(self._handle_message)
+ adapter.set_fatal_error_handler(self._handle_adapter_fatal_error)
+ adapter.set_session_store(self.session_store)
+ adapter.set_busy_session_handler(self._handle_active_session_busy_message)
+ _set_reaction = getattr(adapter, "set_reaction_handler", None)
+ if callable(_set_reaction):
+ _set_reaction(self._handle_reaction_event)
+ adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
+ adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))
+ adapter._busy_text_mode = self._busy_text_mode
- async def _busy_stop_command(self, event: MessageEvent, quick_key: str, source):
- # /stop must hard-kill the session when an agent is running.
- # A soft interrupt (agent.interrupt()) doesn't help when the agent
- # is truly hung — the executor thread is blocked and never checks
- # _interrupt_requested. Force-clean _running_agents so the session
- # is unlocked and subsequent messages are processed normally.
- await self._interrupt_and_clear_session(
- quick_key,
- source,
- interrupt_reason=_INTERRUPT_REASON_STOP,
- invalidation_reason="stop_command",
- )
- logger.info("STOP for session %s — agent interrupted, session lock released", quick_key)
- return EphemeralReply(t("gateway.stop.stopped"))
+ # Reconnect after an outage: preserve the platform's
+ # server-side update queue so messages sent while the bot
+ # was offline are delivered rather than dropped (#46621).
+ success = await self._connect_adapter_with_timeout(
+ adapter, platform, is_reconnect=True
+ )
+ if success:
+ self.adapters[platform] = adapter
+ self._sync_voice_mode_state_to_adapter(adapter)
+ # Wire voice input callback on reconnect as well (#60623).
+ if hasattr(adapter, "_voice_input_callback"):
+ adapter._voice_input_callback = self._handle_voice_channel_input
+ self.delivery_router.adapters = self.adapters
+ del self._failed_platforms[platform]
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="connected",
+ error_code=None,
+ error_message=None,
+ )
+ logger.info("✓ %s reconnected successfully", platform.value)
- async def _busy_new_command(self, event: MessageEvent, quick_key: str, source):
- # /reset and /new must bypass the running-agent guard so they
- # actually dispatch as commands instead of being queued as user
- # text (which would be fed back to the agent with the same
- # broken history — #2170). Interrupt the agent first, then
- # clear the adapter's pending queue so the stale "/reset" text
- # doesn't get re-processed as a user message after the
- # interrupt completes.
- # Clear any pending messages so the old text doesn't replay
- await self._interrupt_and_clear_session(
- quick_key,
- source,
- interrupt_reason=_INTERRUPT_REASON_RESET,
- invalidation_reason="new_command",
- )
- # Clean up the running agent entry so the reset handler
- # doesn't think an agent is still active.
- return await self._handle_reset_command(event)
+ # Rebuild channel directory with the new adapter
+ try:
+ from gateway.channel_directory import build_channel_directory
+ await build_channel_directory(self.adapters)
+ except Exception:
+ pass
- async def _busy_queue_command(self, event: MessageEvent, quick_key: str, source):
- # /queue <prompt> — queue without interrupting.
- # Semantics: each /queue invocation produces its own full agent
- # turn, processed in FIFO order after the current run (and any
- # earlier /queue items) finishes. Messages are NOT merged.
- queued_text = event.get_command_args().strip()
- # Preserve media/reply payloads: a /queue carrying a photo,
- # document, or reply context is valid even with no prompt text
- # (e.g. "/queue" as the caption of an image). Dropping these
- # fields silently lost the attachment when the queued turn ran.
- has_media = bool(getattr(event, "media_urls", None))
- if not queued_text and not has_media:
- return "Usage: /queue <prompt>"
- adapter = self._adapter_for_source(source)
- if adapter:
- queued_event = MessageEvent(
- text=queued_text,
- message_type=event.message_type if has_media else MessageType.TEXT,
- source=event.source,
- raw_message=event.raw_message,
- message_id=event.message_id,
- media_urls=list(getattr(event, "media_urls", []) or []),
- media_types=list(getattr(event, "media_types", []) or []),
- reply_to_message_id=event.reply_to_message_id,
- reply_to_text=event.reply_to_text,
- reply_to_author_id=event.reply_to_author_id,
- reply_to_author_name=event.reply_to_author_name,
- reply_to_is_own_message=event.reply_to_is_own_message,
- auto_skill=event.auto_skill,
- channel_prompt=event.channel_prompt,
- channel_context=event.channel_context,
- internal=event.internal,
- timestamp=event.timestamp,
- )
- self._enqueue_fifo(quick_key, queued_event, adapter)
- depth = self._queue_depth(quick_key, adapter=self._adapter_for_source(source))
- if depth <= 1:
- return "Queued for the next turn."
- return f"Queued for the next turn. ({depth} queued)"
+ # A platform that was offline at gateway startup never
+ # got its restart-interrupted sessions auto-resumed —
+ # the startup pass skips sessions whose adapter isn't
+ # connected yet. Now that it's back, retry the
+ # auto-resume scoped to this platform so recovery
+ # doesn't silently wait for a manual user message.
+ try:
+ self._schedule_resume_pending_sessions(platform=platform)
+ except Exception:
+ logger.debug(
+ "resume-pending reschedule after %s reconnect failed",
+ platform.value,
+ exc_info=True,
+ )
+ # Check if the failure is non-retryable
+ elif adapter.has_fatal_error and not adapter.fatal_error_retryable:
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="fatal",
+ error_code=adapter.fatal_error_code,
+ error_message=adapter.fatal_error_message,
+ )
+ logger.warning(
+ "Reconnect %s: non-retryable error (%s), removing from retry queue",
+ platform.value, adapter.fatal_error_message,
+ )
+ # The adapter is about to be dropped from the queue
+ # without ever being installed on self.adapters, so
+ # nothing else will call disconnect() on it. We must
+ # dispose it here, otherwise the resource owners it
+ # constructed in __init__ (ResponseStore for
+ # APIServerAdapter, etc.) leak 2 fds each. The
+ # gateway hits the 2560-fd limit after ~12h of
+ # failed reconnects at the 300s backoff cap (#37011).
+ await _dispose_unused_adapter(adapter)
+ del self._failed_platforms[platform]
+ else:
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="retrying",
+ error_code=adapter.fatal_error_code,
+ error_message=adapter.fatal_error_message or "failed to reconnect",
+ )
+ backoff = _reconnect_backoff(attempt)
+ info["attempts"] = attempt
+ info["next_retry"] = time.monotonic() + backoff
+ logger.info(
+ "Reconnect %s failed, next retry in %ds",
+ platform.value, backoff,
+ )
+ # Same fd-leak concern as the non-retryable branch
+ # above: the adapter failed to connect and is being
+ # thrown away. Without an explicit dispose call, the
+ # resources it opened in __init__ stay open until
+ # the next GC pass — and aiohttp/SQLite handles
+ # don't get GC'd promptly, so 2 fds/retry leak at
+ # 300s backoff cap = ~12 fds/hour (#37011).
+ await _dispose_unused_adapter(adapter)
+ # Retryable failures (network/DNS blips) keep retrying
+ # at the backoff cap indefinitely — they self-heal once
+ # connectivity returns. We do NOT auto-pause them: a
+ # transient outage must never require manual `/platform
+ # resume` to recover. Non-retryable failures (bad auth,
+ # etc.) already drop out of the queue via the
+ # `not fatal_error_retryable` branch above, so anything
+ # reaching here is by definition retryable.
+ except Exception as e:
+ if adapter is not None:
+ # An exception escaping the connect call path
+ # (DNS timeout, aiohttp server.start() crash, etc.)
+ # leaves the adapter in the same unowned state as
+ # the two branches above. Dispose so __init__
+ # resources don't accumulate while the watcher
+ # keeps retrying.
+ await _dispose_unused_adapter(adapter)
+ self._update_platform_runtime_status(
+ platform.value,
+ platform_state="retrying",
+ error_code=None,
+ error_message=str(e),
+ )
+ backoff = _reconnect_backoff(attempt)
+ info["attempts"] = attempt
+ info["next_retry"] = time.monotonic() + backoff
+ logger.warning(
+ "Reconnect %s error: %s, next retry in %ds",
+ platform.value, e, backoff,
+ )
+ # A raised exception during reconnect (connect timeout, DNS
+ # resolution failure, etc.) is inherently transient — keep
+ # retrying at the backoff cap rather than auto-pausing.
- async def _busy_steer_command(self, event: MessageEvent, quick_key: str, source):
- # /steer <prompt> — inject mid-run after the next tool call.
- # Unlike /queue (turn boundary), /steer lands BETWEEN tool-call
- # iterations inside the same agent run, by appending to the
- # last tool result's content. No interrupt, no new user turn,
- # no role-alternation violation.
- steer_text = event.get_command_args().strip()
- if not steer_text:
- return "Usage: /steer <prompt>"
- _steer_state = self._peek_session_state(quick_key)
- running_agent = _steer_state.turn.agent if _steer_state else None
- if running_agent is _AGENT_PENDING_SENTINEL:
- # Agent hasn't started yet — queue as turn-boundary fallback.
- adapter = self._adapter_for_source(source)
- if adapter:
- queued_event = MessageEvent(
- text=steer_text,
- message_type=MessageType.TEXT,
- source=event.source,
- message_id=event.message_id,
- channel_prompt=event.channel_prompt,
- channel_context=event.channel_context,
- )
- adapter._pending_messages[quick_key] = queued_event
- return "Agent still starting — /steer queued for the next turn."
- if running_agent and hasattr(running_agent, "steer"):
- try:
- accepted = running_agent.steer(steer_text)
- except Exception as exc:
- logger.warning("Steer failed for session %s: %s", quick_key, exc)
- return f"⚠️ Steer failed: {exc}"
- if accepted:
- preview = steer_text[:60] + ("..." if len(steer_text) > 60 else "")
- return f"⏩ Steer queued — arrives after the next tool call: '{preview}'"
- return "Steer rejected (empty payload)."
- # Running agent is missing or lacks steer() — fall back to queue.
- adapter = self._adapter_for_source(source)
- if adapter:
- queued_event = MessageEvent(
- text=steer_text,
- message_type=MessageType.TEXT,
- source=event.source,
- message_id=event.message_id,
- channel_prompt=event.channel_prompt,
- channel_context=event.channel_context,
- )
- adapter._pending_messages[quick_key] = queued_event
- return "No active agent — /steer queued for the next turn."
+ # Check every 10 seconds for platforms that need reconnection
+ for _ in range(10):
+ if not self._running:
+ return
+ await asyncio.sleep(1)
- async def _busy_goal_command(self, event: MessageEvent, quick_key: str, source):
- # /goal is safe mid-run for status/pause/clear/wait (inspection
- # and control-plane only — doesn't interrupt the running turn).
- # Setting a new goal text mid-run is rejected with the same
- # "wait or /stop" message as /model so we don't race a second
- # continuation prompt against the current turn.
- _goal_arg = (event.get_command_args() or "").strip().lower()
- _goal_verb = _goal_arg.split(None, 1)[0] if _goal_arg else ""
- # Exact-match control verbs (unchanged semantics), plus the
- # wait/unwait barrier verbs which take a pid argument.
- _is_control = (
- not _goal_arg
- or _goal_arg in {"status", "pause", "resume", "clear", "stop", "done", "unwait"}
- or _goal_verb == "wait"
- )
- if _is_control:
- return await self._handle_goal_command(event)
- return "Agent is running — use /goal status / pause / clear / wait mid-run, or /stop before setting a new goal."
+ async def _cancel_secondary_profile_reconnect_tasks(self) -> None:
+ """Cancel profile-scoped reconnects before tearing down their registry.
- async def _handle_message(self, event: MessageEvent) -> Optional[str]:
- """
- Handle an incoming message from any platform.
-
- This is the core message processing pipeline:
- 1. Check user authorization
- 2. Check for commands (/new, /reset, etc.)
- 3. Check for running agent and interrupt if needed
- 4. Get or create session
- 5. Build context for agent
- 6. Run agent conversation
- 7. Return response
+ A reconnect can be waiting in adapter setup while shutdown begins. It
+ must not republish an adapter after the secondary registry is drained.
+ Waiting is bounded by the same adapter-cleanup budget; if a task does
+ not finish in time, the stopped runner state still prevents it from
+ installing an adapter when it eventually resumes.
"""
- source = event.source
+ pending = self._profile_failed_platforms
+ if not isinstance(pending, dict):
+ return
+ current = asyncio.current_task()
+ tasks: list[asyncio.Task] = []
+ for profile_pending in pending.values():
+ if not isinstance(profile_pending, dict):
+ continue
+ for task in profile_pending.values():
+ if isinstance(task, asyncio.Task) and task is not current and not task.done():
+ tasks.append(task)
+ for task in tasks:
+ task.cancel()
+ timeout = self._adapter_disconnect_timeout_secs()
+ if tasks and timeout > 0:
+ _done, unfinished = await asyncio.wait(tasks, timeout=timeout)
+ if unfinished:
+ logger.warning(
+ "Timed out waiting for %d secondary profile reconnect task(s) during shutdown",
+ len(unfinished),
+ )
+ pending.clear()
- # 🔴 Cross-session leak guard. This handler runs inside a per-message
- # asyncio task created via create_task(), which snapshots the spawning
- # context with copy_context(). If a *concurrent* message had already
- # bound its session via set_session_vars() when this task was created,
- # we inherited ITS HERMES_SESSION_* ContextVars. Until we bind our own
- # (a few steps down, in _set_session_env), any subprocess spawned here
- # would read the foreign session's identity via the subprocess-env
- # bridge — the _UNSET-strip guard there can't help because the vars are
- # set-to-foreign, not _UNSET. Reset to _UNSET now so that window strips
- # safe (no session) instead of leaking the sibling's. See
- # gateway/session_context.reset_session_vars + the inheritance test.
- try:
- from gateway.session_context import reset_session_vars
- reset_session_vars()
- except Exception:
- logger.debug("reset_session_vars failed at handler entry", exc_info=True)
+ def _start_systemd_watchdog(self) -> bool:
+ """Start sd_notify only after a configured gateway is truly running."""
+ if not self._running or self.config.systemd_watchdog_seconds <= 0:
+ return False
+ if self._systemd_watchdog is not None:
+ return True
- # Internal events (e.g. background-process completion notifications)
- # are system-generated and must skip user authorization.
- is_internal = bool(getattr(event, "internal", False))
+ from gateway.systemd_notify import SystemdWatchdog
- # Ignored-channel guard runs FIRST — before startup-restore queueing,
- # plugin hooks, auth, and session setup — so a configured ignored
- # channel can never reach pairing/auth/session state (#51899).
- # getattr: bare test runners construct GatewayRunner via
- # object.__new__ without config (see AGENTS.md pitfall on
- # object.__new__ test pattern).
- if (
- not is_internal
- and getattr(source, "platform", None) == Platform.SLACK
- and _is_slack_ignored_channel(
- getattr(self, "config", None), getattr(source, "chat_id", None)
- )
- ):
- logger.info(
- "Dropping Slack message from configured ignored channel %s",
- getattr(source, "chat_id", None),
- )
- return None
+ watchdog = SystemdWatchdog(config_enabled=True)
+ if not watchdog.start():
+ return False
+ self._systemd_watchdog = watchdog
+ watchdog.ready("Hermes Gateway running")
+ return True
- if (
- getattr(self, "_startup_restore_in_progress", False)
- and not is_internal
- and not getattr(event, "_hermes_startup_restore_replay", False)
- ):
- self._queue_startup_restore_event(event)
- return None
+ async def _stop_systemd_watchdog(self) -> None:
+ """Stop heartbeats before any potentially long shutdown drain."""
+ watchdog = self._systemd_watchdog
+ if watchdog is None:
+ return
+ self._systemd_watchdog = None
+ await watchdog.stop()
- # scale-to-zero (Phase 0, 0.B/F13): stamp the gateway-scoped last-inbound
- # clock for real (user-originated) inbound only. Internal/system events
- # (background-process completions, startup-restore replays) are NOT
- # traffic — counting them would keep a genuinely idle gateway awake. This
- # clock is what the idle predicate (gateway/scale_to_zero.is_idle) reads.
- if not is_internal:
- self._scale_to_zero_note_real_inbound()
+ async def stop(
+ self,
+ *,
+ restart: bool = False,
+ detached_restart: bool = False,
+ service_restart: bool = False,
+ ) -> None:
+ """Stop the gateway and disconnect all adapters."""
+ # getattr-guard: shutdown-path tests build bare runners via
+ # object.__new__ that lack the liveness-guard machinery.
+ _stop_guards = getattr(self, "_stop_loop_liveness_guards", None)
+ if callable(_stop_guards):
+ _stop_guards()
+ if restart:
+ self._restart_requested = True
+ self._restart_detached = detached_restart
+ self._restart_via_service = service_restart
+ if self._stop_task is not None:
+ await self._stop_task
+ return
- # Fire pre_gateway_dispatch plugin hook for user-originated messages.
- # Plugins receive the MessageEvent and may return a dict influencing flow:
- # {"action": "skip", "reason": ...} -> drop (no reply, plugin handled)
- # {"action": "rewrite", "text": ...} -> replace event.text, continue
- # {"action": "allow"} / None -> normal dispatch
- # Hook runs BEFORE auth so plugins can handle unauthorized senders
- # (e.g. customer handover ingest) without triggering the pairing flow.
- if not is_internal:
- try:
- from hermes_cli.lifecycle import invoke_hook as _invoke_hook
- _hook_results = _invoke_hook(
- "pre_gateway_dispatch",
- event=event,
- gateway=self,
- # getattr: bare-runner tests build GatewayRunner via
- # object.__new__ without __init__ (pitfall #17), and the
- # hook must not fail dispatch over a missing attribute.
- session_store=getattr(self, "session_store", None),
- )
- except Exception as _hook_exc:
- logger.warning("pre_gateway_dispatch invocation failed: %s", _hook_exc)
- _hook_results = []
+ async def _stop_impl() -> None:
+ def _kill_tool_subprocesses(phase: str) -> None:
+ """Kill tool subprocesses + tear down terminal envs + browsers.
- for _result in _hook_results:
- if not isinstance(_result, dict):
- continue
- _action = _result.get("action")
- if _action == "skip":
- logger.info(
- "pre_gateway_dispatch skip: reason=%s platform=%s chat=%s",
- _result.get("reason"),
- source.platform.value if source.platform else "unknown",
- source.chat_id or "unknown",
- )
- return None
- if _action == "rewrite":
- _new_text = _result.get("text")
- if isinstance(_new_text, str):
- event = dataclasses.replace(event, text=_new_text)
- source = event.source
- break
- if _action == "allow":
- break
+ Called twice in the shutdown path: once eagerly after a
+ drain timeout forces agent interrupt (so we reclaim bash/
+ sleep children before systemd TimeoutStopSec escalates to
+ SIGKILL on the cgroup — #8202), and once as a final
+ catch-all at the end of _stop_impl() for the graceful
+ path or anything respawned mid-teardown.
- if is_internal:
- pass
- elif source.user_id is None:
- # Messages with no user identity (Telegram service messages,
- # channel forwards, anonymous admin posts, sender_chat) can't
- # be paired, but they can still be authorized via a
- # chat-scoped allowlist (e.g. TELEGRAM_GROUP_ALLOWED_CHATS
- # authorizes every member of the listed chat regardless of
- # sender). Defer to _is_user_authorized so that path runs.
- if not self._is_user_authorized(source):
- logger.debug("Ignoring message with no user_id from %s", source.platform.value)
- return None
- elif not self._is_user_authorized(source):
- logger.warning("Unauthorized user: %s (%s) on %s", source.user_id, source.user_name, source.platform.value)
- # In DMs: offer pairing code. In groups: silently ignore.
- if (
- source.chat_type == "dm"
- and self._get_unauthorized_dm_behavior(
- source.platform,
- profile=source.profile,
- )
- == "pair"
- ):
- platform_name = source.platform.value if source.platform else "unknown"
- # Rate-limit ALL pairing responses (code or rejection) to
- # prevent spamming the user with repeated messages when
- # multiple DMs arrive in quick succession.
- if self.pairing_store._is_rate_limited(platform_name, source.user_id):
- return None
- code = self.pairing_store.generate_code(
- platform_name, source.user_id, source.user_name or ""
- )
- if code:
- adapter = self._adapter_for_source(source)
- if adapter:
- await adapter.send(
- source.chat_id,
- f"Hi~ I don't recognize you yet!\n\n"
- f"Here's your pairing code: `{code}`\n\n"
- f"Ask the bot owner to run:\n"
- f"`hermes pairing approve {platform_name} {code}`"
- )
- else:
- adapter = self._adapter_for_source(source)
- if adapter:
- await adapter.send(
- source.chat_id,
- "Too many pairing requests right now~ "
- "Please try again later!"
+ All steps are best-effort; exceptions are swallowed so
+ one subsystem's failure doesn't block the rest.
+ """
+ try:
+ from tools.process_registry import process_registry
+ _killed = process_registry.kill_all()
+ if _killed:
+ logger.info(
+ "Shutdown (%s): killed %d tool subprocess(es)",
+ phase, _killed,
)
- # Record rate limit so subsequent messages are silently ignored
- self.pairing_store._record_rate_limit(platform_name, source.user_id)
- return None
-
- # 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
- # .update_response so the update process can continue.
- #
- # IMPORTANT: recognized slash commands must bypass this interception.
- # Otherwise control/session commands like /new or /help get silently
- # consumed as update answers instead of being dispatched normally.
- _quick_key = self._session_key_for_source(source)
- _up_state = self._peek_session_state(_quick_key)
- if _up_state is not None and _up_state.persistent.update_prompt_pending:
- raw = (event.text or "").strip()
- # Accept /approve and /deny as shorthand for yes/no
- cmd = event.get_command()
- if cmd in {"approve", "yes"}:
- response_text = "y"
- elif cmd in {"deny", "no"}:
- response_text = "n"
- else:
- _recognized_cmd = None
- if cmd:
- try:
- from hermes_cli.commands import resolve_command as _resolve_update_cmd
- except Exception:
- _resolve_update_cmd = None
- if _resolve_update_cmd is not None:
- try:
- _cmd_def = _resolve_update_cmd(cmd)
- _recognized_cmd = _cmd_def.name if _cmd_def else None
- except Exception:
- _recognized_cmd = None
- if _recognized_cmd:
- response_text = ""
- else:
- response_text = raw
- if response_text:
- response_path = _hermes_home / ".update_response"
- prompt_path = _hermes_home / ".update_prompt.json"
- try:
- tmp = response_path.with_suffix(".tmp")
- tmp.write_text(response_text, encoding="utf-8")
- tmp.replace(response_path)
- prompt_path.unlink(missing_ok=True)
- except OSError as e:
- logger.warning("Failed to write update response: %s", e)
- return f"✗ Failed to send response to update process: {e}"
- _up_state.persistent.update_prompt_pending = False
- label = response_text if len(response_text) <= 20 else response_text[:20] + "…"
- return f"✓ Sent `{label}` to the update process."
- # Recognized slash command during a pending update prompt:
- # unblock the detached update subprocess by writing a blank
- # response so ``_gateway_prompt`` returns the prompt's default
- # (typically a safe "n" / skip) and exits cleanly instead of
- # blocking on stdin until the 30-minute watcher timeout.
- # The slash command then falls through to normal dispatch.
- if _recognized_cmd:
- response_path = _hermes_home / ".update_response"
- prompt_path = _hermes_home / ".update_prompt.json"
+ except Exception as _e:
+ logger.debug("process_registry.kill_all (%s) error: %s", phase, _e)
try:
- tmp = response_path.with_suffix(".tmp")
- tmp.write_text("", encoding="utf-8")
- tmp.replace(response_path)
- prompt_path.unlink(missing_ok=True)
- logger.info(
- "Recognized /%s during pending update prompt for %s; "
- "cancelled prompt with default and dispatching command",
- _recognized_cmd,
- _quick_key,
- )
- except OSError as e:
- logger.warning(
- "Failed to write cancel response for pending update prompt: %s",
- e,
+ # Any cron job still dispatched at this instant just had
+ # its tool subprocess killed above (kill_all() has no
+ # per-job-ID targeting — it's a global sweep). Its agent
+ # thread is still alive in this process and may go on to
+ # produce a plausible-looking final response from the
+ # now-truncated tool output; mark the run interrupted so
+ # the scheduler can never report that as success (#60432).
+ # No-op when no cron job is in flight.
+ from cron.scheduler import mark_running_jobs_interrupted
+ _interrupted = mark_running_jobs_interrupted(
+ f"Gateway shutdown ({phase}) killed the job's tool "
+ "subprocess before the run finished."
)
- _up_state.persistent.update_prompt_pending = False
+ if _interrupted:
+ logger.warning(
+ "Shutdown (%s): marked %d in-flight cron job(s) interrupted: %s",
+ phase, len(_interrupted), ", ".join(_interrupted),
+ )
+ except Exception as _e:
+ logger.debug("mark_running_jobs_interrupted (%s) error: %s", phase, _e)
+ try:
+ from tools.async_delegation import interrupt_all as _interrupt_async
+ _async_n = _interrupt_async(reason=f"gateway shutdown ({phase})")
+ if _async_n:
+ logger.info(
+ "Shutdown (%s): interrupted %d background delegation(s)",
+ phase, _async_n,
+ )
+ except Exception as _e:
+ logger.debug("async interrupt_all (%s) error: %s", phase, _e)
+ try:
+ from tools.terminal_tool import cleanup_all_environments
+ cleanup_all_environments()
+ except Exception as _e:
+ logger.debug("cleanup_all_environments (%s) error: %s", phase, _e)
+ try:
+ from tools.browser_tool import cleanup_all_browsers
+ cleanup_all_browsers()
+ except Exception as _e:
+ logger.debug("cleanup_all_browsers (%s) error: %s", phase, _e)
- # Intercept messages that are responses to a pending clarify.
- # Open-ended prompts and "Other" responses are captured as free text;
- # direct replies to multi-choice prompts are accepted too ("2" maps
- # to the second option, arbitrary text becomes a custom answer). Slash
- # commands still bypass this path so /stop and friends keep working.
- _clarify_mod = None
- try:
- from tools import clarify_gateway as _clarify_mod
- _pending_clarify = _clarify_mod.get_pending_for_session(
- _quick_key, include_choice_prompts=True,
- )
- except Exception:
- _pending_clarify = None
- if _pending_clarify is not None and _clarify_mod is not None:
- _clarify_has_audio = bool(self._pending_event_audio_paths(event))
- _raw_clarify_reply = await self._prepare_clarify_reply_text(event)
- if _clarify_has_audio and not _raw_clarify_reply:
- logger.info(
- "Gateway retained pending clarify after voice transcription "
- "produced no usable text (session=%s, id=%s)",
- _quick_key,
- _pending_clarify.clarify_id,
- )
- return ""
- # Skip slash commands — the user clearly wanted to issue a
- # command, not answer the clarify. Leave the clarify pending
- # so the user can retry; if it times out, the agent unblocks
- # with an empty response.
- if _raw_clarify_reply and not _raw_clarify_reply.startswith("/"):
- _resolved = _clarify_mod.resolve_text_response_for_session(
- _quick_key, _raw_clarify_reply,
- )
- if _resolved:
- logger.info(
- "Gateway intercepted clarify text response (session=%s, id=%s)",
- _quick_key, _pending_clarify.clarify_id,
- )
- # The clarify callback pauses the platform typing/status
- # indicator while waiting so Slack users can type their
- # answer. The active agent resumes as soon as this reply
- # resolves the wait, so re-enable its indicator here too.
- # Without this, Slack stays silent until the independent
- # long-running heartbeat fires (three minutes by default).
- _clarify_adapter = self._adapter_for_source(source)
- if _clarify_adapter:
- try:
- _clarify_adapter.resume_typing_for_chat(source.chat_id)
- except Exception:
- logger.debug(
- "Failed to resume typing after clarify response",
- exc_info=True,
- )
- # Acknowledge with empty string so adapters that emit
- # the agent's response don't double-post. The agent
- # itself will produce the next user-facing message.
- return ""
+ # Thread-based shutdown watchdog (#66892): asyncio timeouts cannot
+ # recover a frozen loop. Arm a plain OS thread at the start of
+ # stop(); if teardown never finishes within drain+grace it dumps
+ # faulthandler stacks and os._exit so KeepAlive/systemd can revive.
+ # Skip under pytest so stop()-driving unit tests don't get a
+ # delayed hard-exit in the worker.
+ _watchdog_done = threading.Event()
+ self._shutdown_watchdog_done = _watchdog_done
+ _stop_started_at_box: dict[str, float] = {}
- # Intercept messages that are responses to a pending /reload-mcp
- # (or future) slash-confirm prompt. Recognized confirm replies are
- # /approve, /always, /cancel (plus short aliases). Anything else
- # falls through to normal dispatch — a stale pending confirm does
- # NOT block other commands.
- #
- # Important: if a dangerous-command approval is ALSO pending (agent
- # blocked inside tools/approval.py), the tool approval takes
- # precedence — /approve there unblocks the waiting tool thread.
- # Slash-confirm only catches /approve when no tool approval is live.
- from tools import slash_confirm as _slash_confirm_mod
- _pending_confirm = _slash_confirm_mod.get_pending(_quick_key)
- _tool_approval_live = False
- try:
- from tools.approval import has_blocking_approval
- _tool_approval_live = has_blocking_approval(_quick_key)
- except Exception:
- _tool_approval_live = False
- if _pending_confirm and not _tool_approval_live:
- _raw_reply = (event.text or "").strip()
- # Accept bang-prefixed replies (`!always`, `!cancel`) verbatim.
- # Slack/Matrix instruction text shows the `!` prefix (typed `/`
- # is blocked in Slack threads), but the adapters only rewrite
- # `!<known-command>` — `always`/`cancel` are confirm keywords,
- # not registered commands, so the `!` survives to here.
- _norm_reply = _raw_reply.lstrip("!/").lower()
- _cmd_reply = event.get_command()
- _confirm_choice = None
- if _cmd_reply in {"approve", "yes", "ok", "confirm"}:
- _confirm_choice = "once"
- elif _cmd_reply in {"always", "remember"}:
- _confirm_choice = "always"
- elif _cmd_reply in {"cancel", "no", "deny", "nevermind"}:
- _confirm_choice = "cancel"
- elif _norm_reply in {"approve", "approve once", "once"}:
- _confirm_choice = "once"
- elif _norm_reply in {"always", "always approve"}:
- _confirm_choice = "always"
- elif _norm_reply in {"cancel", "nevermind", "no"}:
- _confirm_choice = "cancel"
- if _confirm_choice is not None:
- _resolved = await _slash_confirm_mod.resolve(
- _quick_key, _pending_confirm.get("confirm_id"), _confirm_choice,
+ def _shutdown_watchdog_snapshot() -> dict:
+ started = _stop_started_at_box.get("t")
+ return {
+ "restart_requested": bool(self._restart_requested),
+ "draining": bool(self._draining),
+ "running": bool(self._running),
+ "active_agents": self._running_agent_count(),
+ "active_cron_jobs": self._active_cron_job_count(),
+ "active_api_runs": self._active_api_run_count(),
+ "restart_drain_timeout": self._restart_drain_timeout,
+ "watchdog_delay_s": resolve_shutdown_watchdog_delay(
+ self._restart_drain_timeout
+ ),
+ "phase_elapsed_s": (
+ time.monotonic() - started if started is not None else None
+ ),
+ }
+
+ if not os.environ.get("PYTEST_CURRENT_TEST"):
+ arm_shutdown_watchdog(
+ resolve_shutdown_watchdog_delay(self._restart_drain_timeout),
+ done_event=_watchdog_done,
+ snapshot_fn=_shutdown_watchdog_snapshot,
+ exit_code=1,
)
- return _resolved or ""
- # Stale pending + unrelated command: drop the pending state so
- # the confirm doesn't block normal usage indefinitely. The user
- # clearly moved on.
- _slash_confirm_mod.clear_if_stale(_quick_key)
- # PRIORITY handling when an agent is already running for this session.
- # Default behavior is to interrupt immediately so user text/stop messages
- # are handled with minimal latency.
- #
- # Special case: Telegram/photo bursts often arrive as multiple near-
- # simultaneous updates. Do NOT interrupt for photo-only follow-ups here;
- # let the adapter-level batching/queueing logic absorb them.
+ try:
+ await _stop_impl_body(
+ _kill_tool_subprocesses,
+ _stop_started_at_box,
+ )
+ finally:
+ _watchdog_done.set()
- # Staleness eviction: detect leaked locks from hung/crashed handlers.
- # With inactivity-based timeout, active tasks can run for hours, so
- # wall-clock age alone isn't sufficient. Evict only when the agent
- # has been *idle* beyond the inactivity threshold (or when the agent
- # object has no activity tracker and wall-clock age is extreme).
- _raw_stale_timeout = _float_env("HERMES_AGENT_TIMEOUT", 1800)
- _quick_state = self._peek_session_state(_quick_key)
- _stale_ts = _quick_state.turn.started_ts if _quick_state else 0
- if _quick_state is not None and _quick_state.turn.agent is not None and _stale_ts:
- _stale_age = time.time() - _stale_ts
- _stale_agent = _quick_state.turn.agent
- # Never evict the pending sentinel — it was just placed moments
- # ago during the async setup phase before the real agent is
- # created. Sentinels have no get_activity_summary(), so the
- # idle check below would always evaluate to inf >= timeout and
- # immediately evict them, racing with the setup path.
- _stale_idle = float("inf") # assume idle if we can't check
- _stale_detail = ""
- if _stale_agent and hasattr(_stale_agent, "get_activity_summary"):
+ async def _stop_impl_body(_kill_tool_subprocesses, _stop_started_at_box) -> None:
+ logger.info(
+ "Stopping gateway%s...",
+ " for restart" if self._restart_requested else "",
+ )
+ _stop_started_at = time.monotonic()
+ _stop_started_at_box["t"] = _stop_started_at
+
+ def _phase_elapsed() -> float:
+ return time.monotonic() - _stop_started_at
+
+ self._running = False
+ self._draining = True
+
+ stop_watchdog = getattr(self, "_stop_systemd_watchdog", None)
+ if callable(stop_watchdog):
+ await stop_watchdog()
+
+ await self._cancel_secondary_profile_reconnect_tasks()
+
+ # Notify all chats with active agents BEFORE draining.
+ # Adapters are still connected here, so messages can be sent.
+ await self._notify_active_sessions_of_shutdown()
+ logger.info(
+ "Shutdown phase: notify_active_sessions done at +%.2fs",
+ _phase_elapsed(),
+ )
+
+ timeout = self._restart_drain_timeout
+
+ # Pre-mark sessions as resume_pending BEFORE the drain wait.
+ # If the process is killed by the service manager during the
+ # drain, the durable marker is already written so the next
+ # gateway boot can recover in-flight sessions (#27856).
+ _pre_drain_keys: list[str] = []
+ for _sk, _agent in list(self._running_agents.items()):
+ if _agent is _AGENT_PENDING_SENTINEL:
+ continue
try:
- _sa = _stale_agent.get_activity_summary()
- _stale_idle = _sa.get("seconds_since_activity", float("inf"))
- _stale_detail = (
- f" | last_activity={_sa.get('last_activity_desc', 'unknown')} "
- f"({_stale_idle:.0f}s ago) "
- f"| iteration={_sa.get('api_call_count', 0)}/{_sa.get('max_iterations', 0)}"
+ await self.async_session_store.mark_resume_pending(
+ _sk,
+ "restart_timeout" if self._restart_requested else "shutdown_timeout",
)
- except Exception:
- pass
- # Evict if: agent is idle beyond timeout, OR wall-clock age is
- # extreme (10x timeout or 2h, whichever is larger — catches
- # cases where the agent object was garbage-collected).
- _wall_ttl = max(_raw_stale_timeout * 10, 7200) if _raw_stale_timeout > 0 else float("inf")
- _should_evict = (
- _stale_agent is not _AGENT_PENDING_SENTINEL
- and (
- (_raw_stale_timeout > 0 and _stale_idle >= _raw_stale_timeout)
- or _stale_age > _wall_ttl
- )
+ _pre_drain_keys.append(_sk)
+ except Exception as _e:
+ logger.debug("pre-drain mark_resume_pending failed for %s: %s", _sk, _e)
+
+ _cron_at_start = self._active_cron_job_count()
+ _api_at_start = self._active_api_run_count()
+ _drain_started_at = time.monotonic()
+ active_agents, timed_out = await self._drain_active_agents(timeout)
+ logger.info(
+ "Shutdown phase: drain done at +%.2fs (drain took %.2fs, "
+ "timed_out=%s, active_at_start=%d, active_now=%d, "
+ "cron_at_start=%d, cron_now=%d, "
+ "api_at_start=%d, api_now=%d)",
+ _phase_elapsed(),
+ time.monotonic() - _drain_started_at,
+ timed_out,
+ len(active_agents),
+ self._running_agent_count(),
+ _cron_at_start,
+ self._active_cron_job_count(),
+ _api_at_start,
+ self._active_api_run_count(),
)
- if _should_evict:
+
+ if not timed_out:
+ # Drain completed gracefully — all running sessions finished.
+ # Clear the pre-drain resume_pending markers so sessions that
+ # completed during the drain window don't carry a stale flag.
+ for _sk in _pre_drain_keys:
+ if _sk not in self._running_agents:
+ try:
+ await self.async_session_store.clear_resume_pending(_sk)
+ except Exception as _e:
+ logger.debug(
+ "clear_resume_pending after drain failed for %s: %s",
+ _sk, _e,
+ )
+
+ if timed_out:
logger.warning(
- "Evicting stale _running_agents entry for %s "
- "(age: %.0fs, idle: %.0fs, timeout: %.0fs)%s",
- _quick_key, _stale_age, _stale_idle,
- _raw_stale_timeout, _stale_detail,
+ "Gateway drain timed out after %.1fs with %d active agent(s), "
+ "%d in-flight cron job(s), and %d api_server run(s); "
+ "interrupting remaining work.",
+ timeout,
+ self._running_agent_count(),
+ self._active_cron_job_count(),
+ self._active_api_run_count(),
)
- self._invalidate_session_run_generation(
- _quick_key,
- reason="stale_running_agent_eviction",
+ # Mark forcibly-interrupted sessions as resume_pending BEFORE
+ # interrupting the agents. This preserves each session's
+ # session_id + transcript so the next message on the same
+ # session_key auto-resumes from the existing conversation
+ # instead of getting routed through suspend_recently_active()
+ # and converted into a fresh session. Terminal escalation
+ # for genuinely stuck sessions still flows through the
+ # existing ``.restart_failure_counts`` stuck-loop counter
+ # (incremented below, threshold 3), which sets
+ # ``suspended=True`` and overrides resume_pending.
+ #
+ # Iterate self._running_agents (current) rather than the
+ # drain-start ``active_agents`` snapshot — the snapshot
+ # may include sessions that finished gracefully during
+ # the drain window, and marking those falsely would give
+ # them a stray restart-interruption system note on their
+ # next turn even though their previous turn completed
+ # cleanly. Skip pending sentinels for the same reason
+ # _interrupt_running_agents() does: their agent hasn't
+ # started yet, there's nothing to interrupt, and the
+ # session shouldn't carry a misleading resume flag.
+ _resume_reason = (
+ "restart_timeout" if self._restart_requested else "shutdown_timeout"
)
- self._release_running_agent_state(_quick_key)
+ for _sk, _agent in list(self._running_agents.items()):
+ if _agent is _AGENT_PENDING_SENTINEL:
+ continue
+ try:
+ await self.async_session_store.mark_resume_pending(_sk, _resume_reason)
+ except Exception as _e:
+ logger.debug(
+ "mark_resume_pending failed for %s: %s",
+ _sk, _e,
+ )
+ self._interrupt_running_agents(
+ _INTERRUPT_REASON_GATEWAY_RESTART if self._restart_requested else _INTERRUPT_REASON_GATEWAY_SHUTDOWN
+ )
+ interrupt_deadline = asyncio.get_running_loop().time() + 5.0
+ while self._running_agents and asyncio.get_running_loop().time() < interrupt_deadline:
+ self._update_runtime_status("draining")
+ await asyncio.sleep(0.1)
- if self._is_session_running(_quick_key):
- # Resolve the command once; every command's mid-run behavior is
- # declared on its CommandDef (busy_policy / busy_handler in
- # hermes_cli/commands.py) and dispatched through the single
- # resolver _dispatch_busy_slash_command below — no per-command
- # if-chain here.
- from hermes_cli.commands import resolve_command as _resolve_cmd_inner
- _evt_cmd = event.get_command()
- _cmd_def_inner = _resolve_cmd_inner(_evt_cmd) if _evt_cmd else None
+ # Kill lingering tool subprocesses NOW, before we spend more
+ # budget on adapter disconnect / session DB close. Under
+ # systemd (TimeoutStopSec bounded by drain_timeout+headroom),
+ # deferring this to the end of stop() risks systemd escalating
+ # to SIGKILL on the cgroup first — at which point bash/sleep
+ # children left behind by an interrupted terminal tool get
+ # killed by systemd instead of us (issue #8202). The final
+ # catch-all cleanup below still runs for the graceful path.
+ _kill_tool_subprocesses("post-interrupt")
+ logger.info(
+ "Shutdown phase: post-interrupt tool kill done at +%.2fs",
+ _phase_elapsed(),
+ )
- # /status and /context are intentionally pre-gate so users
- # always see session state.
- if _cmd_def_inner and _cmd_def_inner.name == "status":
- return await self._handle_status_command(event)
- if _cmd_def_inner and _cmd_def_inner.name == "context":
- return await self._handle_context_command(event)
+ if self._restart_requested and self._restart_detached:
+ try:
+ await self._launch_detached_restart_command()
+ except Exception as e:
+ logger.error("Failed to launch detached gateway restart: %s", e)
- # Slash command access control on the running-agent fast-path.
- # Mirrors the cold-path gate further below so non-admin users
- # can't bypass gating just because an agent happens to be busy.
- # /status above is intentionally pre-gate so users always see
- # session state. /help and /whoami fall under the always-allowed
- # floor inside _check_slash_access.
- if _evt_cmd and _cmd_def_inner is not None:
- _denied = self._check_slash_access(source, _cmd_def_inner.name)
- if _denied is not None:
- return _denied
+ await self._finalize_shutdown_agents(active_agents)
- # Any recognized slash command: dispatch according to its
- # declared busy_policy (dispatch / interrupt_then_dispatch /
- # reject). Unrecognized commands and plain text fall through
- # to the interrupt/queue logic below.
- if _cmd_def_inner:
- return await self._dispatch_busy_slash_command(
- event, _cmd_def_inner, _quick_key, source,
- )
+ # Also shut down memory providers on idle cached agents.
+ # _finalize_shutdown_agents only handles agents that were
+ # mid-turn at drain time; the _agent_cache may still hold
+ # idle agents whose MemoryProviders never received
+ # on_session_end().
+ _cache_lock = getattr(self, "_agent_cache_lock", None)
+ _cache = getattr(self, "_agent_cache", None)
+ if _cache_lock is not None and _cache is not None:
+ with _cache_lock:
+ _idle_agents = list(_cache.values())
+ _cache.clear()
+ for _entry in _idle_agents:
+ _agent = (
+ _entry[0] if isinstance(_entry, tuple) else _entry
+ )
+ # Bounded + off-loop so a wedged memory provider on one
+ # idle agent can't hang shutdown indefinitely — that path
+ # is why SIGTERM failed to kill the process (#53175).
+ await self._cleanup_agent_resources_off_loop(
+ _agent, context="shutdown idle-cache"
+ )
- if event.message_type == MessageType.PHOTO:
- logger.debug("PRIORITY photo follow-up for session %s — queueing without interrupt", _quick_key)
- adapter = self._adapter_for_source(source)
- if adapter:
- merge_pending_message_event(adapter._pending_messages, _quick_key, event)
- return None
+ for platform, adapter in list(self.adapters.items()):
+ await self._bounded_adapter_teardown(adapter, platform)
- _telegram_followup_grace = float(
- os.getenv("HERMES_TELEGRAM_FOLLOWUP_GRACE_SECONDS", "3.0")
- )
- _grace_state = self._peek_session_state(_quick_key)
- _started_at = _grace_state.turn.started_ts if _grace_state else 0
- if (
- source.platform == Platform.TELEGRAM
- and event.message_type == MessageType.TEXT
- and _telegram_followup_grace > 0
- and _started_at
- and (time.time() - _started_at) <= _telegram_followup_grace
- ):
- logger.debug(
- "Telegram follow-up arrived %.2fs after run start for %s — queueing without interrupt",
- time.time() - _started_at,
- _quick_key,
- )
- adapter = self._adapter_for_source(source)
- if adapter:
- if self._busy_input_mode == "queue":
- self._enqueue_fifo(_quick_key, event, adapter)
- else:
- merge_pending_message_event(
- adapter._pending_messages,
- _quick_key,
- event,
- merge_text=True,
- )
- return None
-
- _ra_state = self._peek_session_state(_quick_key)
- running_agent = _ra_state.turn.agent if _ra_state else None
- if running_agent is _AGENT_PENDING_SENTINEL:
- # Agent is being set up but not ready yet.
- if event.get_command() == "stop":
- # Force-clean the sentinel so the session is unlocked.
- self._release_running_agent_state(_quick_key)
- logger.info("HARD STOP (pending) for session %s — sentinel cleared", _quick_key)
- return EphemeralReply("⚡ Force-stopped. The agent was still starting — session unlocked.")
- # Queue the message so it will be picked up after the
- # agent starts.
- adapter = self._adapter_for_source(source)
- if adapter:
- merge_pending_message_event(
- adapter._pending_messages,
- _quick_key,
- event,
- merge_text=True,
- )
- return None
- if self._draining:
- if self._queue_during_drain_enabled():
- self._queue_or_replace_pending_event(_quick_key, event)
- return (
- f"⏳ Gateway {self._status_action_gerund()} — queued for the next turn after it comes back."
- if self._queue_during_drain_enabled()
- else f"⏳ Gateway is {self._status_action_gerund()} and is not accepting another turn right now."
- )
- if self._busy_input_mode == "queue":
- logger.debug("PRIORITY queue follow-up for session %s", _quick_key)
- self._queue_or_replace_pending_event(_quick_key, event)
- return None
- if self._busy_input_mode == "steer":
- # Steer mode: inject text into the running agent mid-run via
- # agent.steer(). Falls back to queue semantics if the payload
- # is empty, the agent lacks steer(), or steer() rejects.
- steer_text = (event.text or "").strip()
- steered = False
- if (
- event.message_type == MessageType.TEXT
- and not event.media_urls
- and not event.media_types
- and steer_text
- and hasattr(running_agent, "steer")
- ):
- try:
- steered = bool(running_agent.steer(steer_text))
- except Exception as exc:
- logger.warning("PRIORITY steer failed for session %s: %s", _quick_key, exc)
- steered = False
- if steered:
- logger.debug("PRIORITY steer for session %s", _quick_key)
- return None
- logger.debug("PRIORITY steer-fallback-to-queue for session %s", _quick_key)
- self._queue_or_replace_pending_event(_quick_key, event)
- return None
- # #30170 — Subagent protection (PRIORITY path). Same rationale
- # as ``_handle_active_session_busy_message``: an interrupt
- # cascades through ``_active_children`` and aborts in-flight
- # delegate_task work. Demote to queue semantics when the
- # parent is currently driving subagents so a conversational
- # follow-up doesn't destroy minutes of subagent progress.
- # /stop reaches its dedicated handler above, so the operator
- # still has a clean escape hatch.
- if self._agent_has_active_subagents(running_agent):
- logger.info(
- "PRIORITY interrupt demoted to queue for session %s "
- "because the running agent has active subagents (#30170)",
- _quick_key,
- )
- self._queue_or_replace_pending_event(_quick_key, event)
- return None
- # #56391 — Compression protection (PRIORITY path). Same
- # rationale as ``_handle_active_session_busy_message``: context
- # compression is interrupt-protected (#23975), but an interrupt
- # here starts a new turn against the pre-rotation parent
- # session while the still-running compression later rotates
- # the id out from under it, forking orphaned compression
- # siblings. Demote to queue semantics so the follow-up waits
- # for the in-flight compression + rotation to land.
- if await self._session_has_compression_in_flight(_quick_key):
- logger.info(
- "PRIORITY interrupt demoted to queue for session %s "
- "because context compression is in flight (#56391)",
- _quick_key,
- )
- self._queue_or_replace_pending_event(_quick_key, event)
- return None
- # Text-only corrections redirect the live turn (preserving
- # displayed context) when the runtime supports it; media/voice and
- # older runtimes fall back to the proven interrupt path below.
- if (
- event.message_type == MessageType.TEXT
- and not event.media_urls
- and not event.media_types
- and getattr(running_agent, "_supports_active_turn_redirect", False)
- is True
- and hasattr(running_agent, "redirect")
- ):
- try:
- if running_agent.redirect((event.text or "").strip()):
- logger.debug("PRIORITY redirect for session %s", _quick_key)
- return None
- except Exception as exc:
- logger.warning(
- "PRIORITY redirect failed for session %s: %s",
- _quick_key,
- exc,
+ # Disconnect secondary-profile adapters (multiplex mode).
+ for _prof, _amap in list(getattr(self, "_profile_adapters", {}).items()):
+ for platform, adapter in list(_amap.items()):
+ await self._bounded_adapter_teardown(
+ adapter, platform, profile=_prof
)
- logger.debug("PRIORITY interrupt for session %s", _quick_key)
- _interrupt_text = event.text
- _media_urls = getattr(event, "media_urls", None) or []
- if self._pending_event_audio_paths(event):
- _interrupt_text, _ = await self._transcribe_and_echo_pending_voice(
- event,
- self._adapter_for_source(source),
- source,
- event.text or "",
- log_context="Voice-priority-interrupt",
- )
- elif not _interrupt_text and _media_urls:
- _interrupt_text = _build_media_placeholder(event)
- running_agent.interrupt(_interrupt_text)
- # NOTE: self._pending_messages was write-only (never consumed).
- # The actual interrupt message is delivered via adapter._pending_messages
- # which is read by _run_agent. Removed to prevent unbounded growth.
- return None
+ _amap.clear()
+ if hasattr(self, "_profile_adapters"):
+ self._profile_adapters.clear()
+ logger.info(
+ "Shutdown phase: all adapters disconnected at +%.2fs",
+ _phase_elapsed(),
+ )
- # Check for commands
- command = event.get_command()
+ for _task in list(self._background_tasks):
+ if _task is self._stop_task:
+ continue
+ if _task is self._restart_task:
+ # The restart orchestration task is awaiting _stop_task
+ # right now; cancelling it would propagate CancelledError
+ # into this _stop_impl and skip _shutdown_event.set() /
+ # _exit_code = 75 (#12875). It self-terminates anyway.
+ continue
+ _task.cancel()
+ self._background_tasks.clear()
- from hermes_cli.commands import (
- GATEWAY_KNOWN_COMMANDS,
- is_gateway_known_command,
- resolve_command as _resolve_cmd,
- )
+ self.adapters.clear()
+ for _session_key in list(self._running_agents):
+ self._release_running_agent_state(_session_key)
+ # Flush pending messages to disk before clearing (#72680).
+ # When FTS5 corruption prevents message persistence, the
+ # in-memory pending text is the only surviving copy. Clearing
+ # without flushing causes permanent data loss.
+ try:
+ from gateway.shutdown_flush import flush_pending_to_file
+ flush_pending_to_file(dict(self._pending_messages), reason="shutdown")
+ except Exception:
+ pass
+ # On the real runner these are live SessionState views whose
+ # clear() resets one field per session — never a wholesale dict
+ # swap, so a concurrent writer on another session can't lose its
+ # entry. Test fakes borrowing _stop_impl keep plain dicts.
+ self._running_agents.clear()
+ self._running_agents_ts.clear()
+ if hasattr(self, "_active_session_leases"):
+ self._active_session_leases.clear()
+ self._pending_messages.clear()
+ self._pending_approvals.clear()
+ if hasattr(self, '_busy_ack_ts'):
+ self._busy_ack_ts.clear()
+ self._shutdown_event.set()
- # Resolve aliases to canonical name so dispatch and hook names
- # don't depend on the exact alias the user typed.
- _cmd_def = _resolve_cmd(command) if command else None
- canonical = _cmd_def.name if _cmd_def else command
+ # Global cleanup: kill any remaining tool subprocesses not tied
+ # to a specific agent (catch-all for zombie prevention). On the
+ # drain-timeout path we already did this earlier after agent
+ # interrupt — this second call catches (a) the graceful path
+ # where drain succeeded without interrupt, and (b) anything
+ # that got respawned between the earlier call and adapter
+ # disconnect (defense in depth; safe to call repeatedly).
+ _kill_tool_subprocesses("final-cleanup")
+ logger.info(
+ "Shutdown phase: final-cleanup tool kill done at +%.2fs",
+ _phase_elapsed(),
+ )
- # Expand alias quick commands before built-in dispatch so targets like
- # /model openai/gpt-5.5 --provider openrouter reach the /model handler.
- # Preserve built-in precedence; aliases only need early handling when
- # the typed command is not already known.
- if command and _cmd_def is None:
- if isinstance(self.config, dict):
- quick_commands = self.config.get("quick_commands", {}) or {}
- else:
- quick_commands = getattr(self.config, "quick_commands", {}) or {}
- if isinstance(quick_commands, dict) and command in quick_commands:
- qcmd = quick_commands[command]
- if qcmd.get("type") == "alias":
- target = (qcmd.get("target") or "").strip()
- if target:
- target = target if target.startswith("/") else f"/{target}"
- target_command = target.lstrip("/")
- user_args = event.get_command_args().strip()
- event.text = f"{target} {user_args}".strip()
- command = target_command.split()[0] if target_command else target_command
- _cmd_def = _resolve_cmd(command) if command else None
- canonical = _cmd_def.name if _cmd_def else command
+ # Reap the process-global auxiliary-client cache once at the very
+ # end of teardown. Per-turn cleanup runs in _cleanup_agent_resources
+ # for each active agent, but clients bound to worker-thread loops
+ # that died with their ThreadPoolExecutor (notably cron ticks) only
+ # get swept here. Without this, long-running gateways accumulate
+ # async httpx transports until they hit EMFILE on macOS's default
+ # RLIMIT_NOFILE=256. See #14210.
+ try:
+ from agent.auxiliary_client import shutdown_cached_clients
+ shutdown_cached_clients()
+ except Exception as _e:
+ logger.debug("shutdown_cached_clients error: %s", _e)
- # Per-platform slash command access control. Only kicks in when the
- # operator has set ``allow_admin_from`` for the source's scope (DM
- # vs group). When unset → backward-compat: every allowed user can
- # run every command. When set → non-admins can run only commands in
- # ``user_allowed_commands`` (plus the always-allowed floor: /help,
- # /whoami). Plain chat is unaffected — only slash commands gate.
- if command and canonical and is_gateway_known_command(canonical):
- _denied = self._check_slash_access(source, canonical)
- if _denied is not None:
- return _denied
-
- # Fire the ``command:<canonical>`` hook for any recognized slash
- # command — built-in OR plugin-registered. Handlers can return a
- # dict with ``{"decision": "deny" | "handled" | "rewrite", ...}``
- # to intercept dispatch before core handling runs. This replaces
- # the previous fire-and-forget emit(): return values are now
- # honored, but handlers that return nothing behave exactly as
- # before (telemetry-style hooks keep working).
- if command and is_gateway_known_command(canonical):
- raw_args = event.get_command_args().strip()
- hook_ctx = {
- "platform": source.platform.value if source.platform else "",
- "user_id": source.user_id,
- "command": canonical,
- "raw_command": command,
- "args": raw_args,
- "raw_args": raw_args,
- }
- try:
- hook_results = await self.hooks.emit_collect(
- f"command:{canonical}", hook_ctx
- )
- except Exception as _hook_err:
- logger.debug(
- "command:%s hook dispatch failed (non-fatal): %s",
- canonical, _hook_err,
- )
- hook_results = []
-
- for hook_result in hook_results:
- if not isinstance(hook_result, dict):
- continue
- decision = str(hook_result.get("decision", "")).strip().lower()
- if not decision or decision == "allow":
+ # Close SQLite session DBs so the WAL write lock is released.
+ # Without this, --replace and similar restart flows leave the
+ # old gateway's connection holding the WAL lock until Python
+ # actually exits — causing 'database is locked' errors when
+ # the new gateway tries to open the same file.
+ # ``self`` holds the DB at ``_session_db`` (an AsyncSessionDB facade);
+ # unwrap to the sync handle. ``session_store`` holds it at ``_db``.
+ _self_db = getattr(self, "_session_db", None)
+ _self_db = getattr(_self_db, "_db", _self_db)
+ for _db in (_self_db, getattr(getattr(self, "session_store", None), "_db", None)):
+ if _db is None or not hasattr(_db, "close"):
continue
- if decision == "deny":
- message = hook_result.get("message")
- if isinstance(message, str) and message:
- return message
- return f"Command `/{command}` was blocked by a hook."
- if decision == "handled":
- message = hook_result.get("message")
- return message if isinstance(message, str) and message else None
- if decision == "rewrite":
- new_command = str(
- hook_result.get("command_name", "")
- ).strip().lstrip("/")
- if not new_command:
- continue
- new_args = str(hook_result.get("raw_args", "")).strip()
- event.text = f"/{new_command} {new_args}".strip()
- command = event.get_command()
- _cmd_def = _resolve_cmd(command) if command else None
- canonical = _cmd_def.name if _cmd_def else command
- break
-
- if canonical == "new":
- if await asyncio.to_thread(self._is_telegram_topic_root_lobby, source):
- return self._telegram_topic_root_new_message()
- async def _do_reset():
- return await self._handle_reset_command(event)
- return await self._maybe_confirm_destructive_slash(
- event=event,
- command="new",
- title="/new",
- detail=(
- "This starts a fresh session and discards the current "
- "conversation history."
- ),
- execute=_do_reset,
+ try:
+ _db.close()
+ except Exception as _e:
+ logger.debug("SessionDB close error: %s", _e)
+ GatewayRunner._shutdown_executor(self)
+ logger.info(
+ "Shutdown phase: SessionDB close done at +%.2fs",
+ _phase_elapsed(),
)
- if canonical == "topic":
- return await self._handle_topic_command(event)
-
- if canonical == "help":
- return await self._handle_help_command(event)
-
- if canonical == "start":
- logger.info("Ignoring /start platform ping for session %s", _quick_key)
- return ""
+ from gateway.status import remove_pid_file, release_gateway_runtime_lock
+ remove_pid_file()
+ release_gateway_runtime_lock()
- if canonical == "commands":
- return await self._handle_commands_command(event)
-
- if canonical == "profile":
- return await self._handle_profile_command(event)
+ # Write a clean-shutdown marker so the next startup knows this
+ # wasn't a crash. suspend_recently_active() only needs to run
+ # after unexpected exits. However, if the drain timed out and
+ # agents were force-interrupted, their sessions may be in an
+ # incomplete state (trailing tool response, no final assistant
+ # message). Skip the marker in that case so the next startup
+ # suspends those sessions — giving users a clean slate instead
+ # of resuming a half-finished tool loop.
+ if not timed_out:
+ try:
+ (_hermes_home / ".clean_shutdown").touch()
+ except Exception:
+ pass
+ else:
+ logger.info(
+ "Skipping .clean_shutdown marker — drain timed out with "
+ "interrupted agents; next startup will suspend recently "
+ "active sessions."
+ )
- if canonical == "whoami":
- return await self._handle_whoami_command(event)
+ # Track sessions that were active at shutdown for stuck-loop
+ # detection (#7536). On each restart, the counter increments
+ # for sessions that were running. If a session hits the
+ # threshold (3 consecutive restarts while active), the next
+ # startup auto-suspends it — breaking the loop.
+ if active_agents:
+ self._increment_restart_failure_counts(set(active_agents.keys()))
- if canonical == "status":
- return await self._handle_status_command(event)
+ if self._restart_requested and self._restart_command_source is None:
+ try:
+ atomic_json_write(
+ _planned_restart_notification_path(),
+ {
+ "requested_at": time.time(),
+ "via_service": bool(self._restart_via_service),
+ "detached": bool(self._restart_detached),
+ },
+ indent=None,
+ )
+ except Exception as e:
+ logger.debug("Failed to write planned restart notification marker: %s", e)
- if canonical == "egress":
- from hermes_cli.proxy_cli import format_status_text
+ if self._restart_requested and self._restart_via_service:
+ self._launch_systemd_restart_shortcut()
+ # Always exit with TEMPFAIL (75) on service-managed
+ # restarts. The shortcut helper above is best-effort and
+ # commonly fails on real deployments: non-root gateway
+ # units hit Polkit denials when invoking ``systemd-run
+ # --system``, headless boxes have no user bus for
+ # ``--user``, and operator-managed unit files may use
+ # ``Restart=on-failure`` rather than ``Restart=always``.
+ # Exit 75 paired with ``RestartForceExitStatus=75`` makes
+ # systemd treat the planned restart as a controlled
+ # failure and revive the unit via ``Restart=on-failure``,
+ # regardless of whether the helper survived. Without
+ # this, a clean exit (0) on Linux left the gateway dead
+ # until someone rebooted the host. Only the planned code
+ # (75) is whitelisted via ``RestartForceExitStatus``; a
+ # genuine crash exits non-zero-but-not-75, so real crash
+ # loops are still governed by the unit's normal
+ # ``Restart=``/``RestartSec`` (and any StartLimit the
+ # operator sets) rather than force-restarted here.
+ self._exit_code = GATEWAY_SERVICE_RESTART_EXIT_CODE
+ self._exit_reason = self._exit_reason or "Gateway restart requested"
- return format_status_text()
+ self._draining = False
+ # Persist the terminal gateway_state. The default is "stopped",
+ # but when this teardown was triggered by an UNEXPECTED external
+ # signal (container/s6 SIGTERM on `docker restart` or image
+ # upgrade, OOM-killer, bare `kill`) we instead persist "running"
+ # to preserve the operator's run-intent across the restart.
+ #
+ # On Docker (s6-overlay), container_boot.py reads gateway_state
+ # on the next boot and only auto-starts gateways whose last
+ # state was "running" (_AUTOSTART_STATES). Persisting "stopped"
+ # — or leaving the mid-shutdown "draining" marker in place — for
+ # a routine `docker compose up --force-recreate` permanently
+ # suppresses auto-start, so the messaging channels silently stay
+ # dark until the operator manually restarts (issue #42675).
+ #
+ # An operator-initiated stop (`hermes gateway stop`,
+ # systemd/launchd ExecStop, the s6 stop path, Ctrl+C) writes a
+ # planned-stop marker BEFORE signalling, so it is classified as
+ # a planned stop (not signal-initiated) and correctly persists
+ # "stopped" — respecting the explicit intent. A restart also
+ # persists "stopped" here; the restarting process brings the
+ # gateway back up itself.
+ if getattr(self, "_signal_initiated_shutdown", False) and not self._restart_requested:
+ logger.info(
+ "Gateway stopped by an unexpected signal — persisting "
+ "gateway_state=running so container_boot auto-starts on "
+ "the next boot (issue #42675)"
+ )
+ self._update_runtime_status("running", self._exit_reason)
+ else:
+ self._update_runtime_status("stopped", self._exit_reason)
+ _shutdown_gateway_health_export(self)
+ logger.info("Gateway stopped (total teardown %.2fs)", _phase_elapsed())
- if canonical == "context":
- return await self._handle_context_command(event)
+ self._stop_task = asyncio.create_task(_stop_impl())
+ await self._stop_task
- if canonical == "agents":
- return await self._handle_agents_command(event)
+ async def wait_for_shutdown(self) -> None:
+ """Wait for shutdown signal."""
+ await self._shutdown_event.wait()
- if canonical == "platform":
- return await self._handle_platform_command(event)
+ async def _start_secondary_profile_adapters(self) -> int:
+ """Bring up adapters for every non-active profile this gateway serves.
- if canonical == "restart":
- return await self._handle_restart_command(event)
-
- if canonical == "stop":
- return await self._handle_stop_command(event)
-
- if canonical == "reasoning":
- return await self._handle_reasoning_command(event)
+ Returns the number of secondary adapters that connected. No-op (returns
+ 0) unless ``gateway.multiplex_profiles`` is on.
- if canonical == "memory":
- return await self._handle_memory_command(event)
+ Each profile's adapters are created and connected under that profile's
+ HERMES_HOME + secret scope (``_profile_runtime_scope``), stored in
+ ``self._profile_adapters[profile]``, and given a message handler that
+ stamps ``source.profile`` before delegating to the shared
+ ``_handle_message`` — so the agent turn resolves that profile's config,
+ skills, and credentials. Same-platform credential collisions (two
+ profiles polling the same bot token) are detected and refused here, the
+ only point that sees every profile's resolved credentials together.
+ """
+ if not getattr(self.config, "multiplex_profiles", False):
+ return 0
- if canonical == "skills":
- return await self._handle_skills_command(event)
+ try:
+ from hermes_cli.profiles import profiles_to_serve, get_active_profile_name
+ except Exception:
+ return 0
- if canonical == "learn":
- # Open-ended: rewrite the turn to a standards-guided prompt and fall
- # through to normal agent processing. The live agent gathers the
- # sources the user described (dirs via read_file, URLs via
- # web_extract, this conversation, pasted text) and authors the skill
- # via skill_manage. Mirrors the /blueprint fall-through so role
- # alternation is preserved. No engine, works on any backend.
- from agent.learn_prompt import build_learn_prompt
-
- _learn_req = event.get_command_args().strip()
- _ack = (
- "Learning a skill from what you described…"
- if _learn_req
- else "Learning a skill from this conversation…"
- )
- try:
- adapter = self._adapter_for_source(source)
- if adapter:
- _ack_meta = self._thread_metadata_for_source(source)
- await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta)
- except Exception:
- logger.debug("learn ack send failed", exc_info=True)
- try:
- event.text = build_learn_prompt(_learn_req)
- # fall through to agent processing
- except Exception:
- return "Could not start /learn — please try again."
-
- if canonical == "init":
- # /init: rewrite the turn to a guidance-laden prompt and fall
- # through to normal agent processing (same fall-through as /learn
- # so role alternation is preserved). The live agent scans the
- # project with its own read-only tools and writes/updates
- # AGENTS.md via write_file. No engine, works on any backend.
- from hermes_cli.init_command import build_init_prompt_for_cwd
+ active = get_active_profile_name() or "default"
+ connected = 0
+ # Resource claim -> profile that owns it. Credential claims prevent two
+ # profiles polling the same account; listener claims prevent sidecars
+ # with distinct credentials from binding the same endpoint.
+ claimed: Dict[tuple, str] = {}
+ for _plat, _ad in self.adapters.items():
+ fp = self._adapter_credential_fingerprint(_ad)
+ if fp is not None:
+ claimed[(_plat, fp)] = active
+ listener_claim = self._adapter_listener_claim(_plat, _ad)
+ if listener_claim is not None:
+ claimed[listener_claim] = active
+ # A retryable primary still owns its configured credential and listener.
+ # Reserve both while it is queued so a secondary cannot take the endpoint
+ # before the reconnect watcher retries the primary adapter.
+ for retry_info in getattr(self, "_failed_platforms", {}).values():
+ for claim_name in ("credential_claim", "listener_claim"):
+ retry_claim = retry_info.get(claim_name)
+ if isinstance(retry_claim, tuple):
+ claimed[retry_claim] = active
- _init_notes = event.get_command_args().strip()
- try:
- _init_prompt = build_init_prompt_for_cwd(extra=_init_notes)
- except Exception:
- return "Could not start /init — please try again."
- _ack = (
- "Updating AGENTS.md from a project scan…"
- if "UPDATE the existing AGENTS.md" in _init_prompt
- else "Generating AGENTS.md from a project scan…"
- )
+ for profile_name, profile_home in profiles_to_serve(multiplex=True):
+ if profile_name == active:
+ continue # handled by the primary startup loop
try:
- adapter = self._adapter_for_source(source)
- if adapter:
- _ack_meta = self._thread_metadata_for_source(source)
- await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta)
- except Exception:
- logger.debug("init ack send failed", exc_info=True)
- event.text = _init_prompt
- # fall through to agent processing
+ connected += await self._start_one_profile_adapters(
+ profile_name, profile_home, claimed
+ )
+ except SecondaryPortBindingConfigError as e:
+ logger.warning(
+ "Skipping secondary profile '%s' due to port-binding config error: %s",
+ profile_name,
+ e,
+ )
+ except MultiplexConfigError:
+ raise
+ except Exception as e:
+ logger.error(
+ "Failed to start adapters for profile '%s': %s",
+ profile_name, e, exc_info=True,
+ )
- if canonical == "fast":
- return await self._handle_fast_command(event)
+ # Record served profiles in runtime status for `hermes status`.
+ try:
+ from gateway.status import write_runtime_status
+ from gateway.pairing import PairingStore
+ served = [active] + sorted(self._profile_adapters.keys())
+ # Per-profile PairingStores so authz_mixin can route pairing
+ # checks to the right whitelist. The active profile gets a store
+ # at its HERMES_HOME; additional served profiles get one under
+ # profiles/<name>/pairing/. See gateway.pairing.PairingStore.
+ for name in served:
+ if name and name not in self.pairing_stores:
+ self.pairing_stores[name] = PairingStore(profile=name)
+ write_runtime_status(served_profiles=served)
+ except Exception:
+ logger.debug("could not record served_profiles", exc_info=True)
- if canonical == "verbose":
- return await self._handle_verbose_command(event)
+ return connected
- if canonical == "footer":
- return await self._handle_footer_command(event)
+ async def _start_one_profile_adapters(
+ self, profile_name: str, profile_home: "Path", claimed: Dict[tuple, str]
+ ) -> int:
+ """Create+connect one profile's adapters under its runtime scope."""
+ from gateway.config import load_gateway_config
- if canonical == "yolo":
- return await self._handle_yolo_command(event)
+ with _profile_runtime_scope(profile_home):
+ profile_cfg = load_gateway_config()
+ violation = _own_policy_open_startup_violation(profile_cfg)
+ if violation:
+ raise MultiplexConfigError(
+ f"Profile '{profile_name}' enables {violation}. "
+ "Enable GATEWAY_ALLOW_ALL_USERS or the platform allow-all flag "
+ "for that profile, or change dm_policy/group_policy away from "
+ "'open'."
+ )
- if canonical == "approvals":
- return await self._handle_approvals_command(event)
+ port_binding_platforms = sorted(
+ platform.value
+ for platform, platform_config in profile_cfg.platforms.items()
+ if platform_config.enabled
+ and _platform_binds_port(platform.value, platform_config.extra)
+ )
+ if port_binding_platforms:
+ joined = ", ".join(port_binding_platforms)
+ raise SecondaryPortBindingConfigError(
+ f"Profile '{profile_name}' enables port-binding platform(s) "
+ f"{joined}, but gateway.multiplex_profiles is on. The default "
+ f"profile owns the single shared HTTP listener and serves every "
+ f"profile through the /p/{profile_name}/ URL prefix. Remove "
+ f"these platform entries from profile '{profile_name}'s config.yaml "
+ f"or configure them only on the default profile."
+ )
- if canonical == "model":
- return await self._handle_model_command(event)
+ profile_map = self._profile_adapters.setdefault(profile_name, {})
+ connected = 0
+ for platform, platform_config in profile_cfg.platforms.items():
+ if not platform_config.enabled:
+ continue
+ # Relay is shared process-level ingress in multiplex mode. The
+ # active profile owns the one connection; connector-stamped
+ # source.profile routes inbound turns to secondary profiles.
+ if (
+ getattr(self.config, "multiplex_profiles", False)
+ and platform is Platform.RELAY
+ ):
+ continue
+ try:
+ with _profile_runtime_scope(profile_home):
+ adapter = self._create_adapter(platform, platform_config)
+ except Exception as e:
+ logger.error(
+ "[MULTIPLEX] Profile '%s': _create_adapter('%s') raised %s",
+ profile_name,
+ platform.value,
+ e,
+ exc_info=True,
+ )
+ continue
+ if not adapter:
+ logger.warning(
+ "[MULTIPLEX] Profile '%s': skipping platform '%s' - adapter creation returned None",
+ profile_name,
+ platform.value,
+ )
+ continue
- if canonical == "codex-runtime":
- return await self._handle_codex_runtime_command(event)
+ # Same-token conflict detection — refuse a duplicate poll.
+ credential_claim = self._adapter_credential_claim(platform, adapter)
+ if credential_claim is not None:
+ owner = claimed.get(credential_claim)
+ if owner is not None:
+ logger.error(
+ "Profile '%s' and '%s' both configure %s with the same "
+ "credential — refusing to start the duplicate (one "
+ "credential cannot be consumed twice). Give each profile "
+ "its own %s credential.",
+ owner, profile_name, platform.value, platform.value,
+ )
+ # This adapter has not connected and therefore owns no
+ # resources to clean up. Calling disconnect here can mutate
+ # the shared platform state and, for a same-credential Photon
+ # adapter, shut down the primary profile's live sidecar.
+ continue
- if canonical == "personality":
- return await self._handle_personality_command(event)
+ listener_claim = self._adapter_listener_claim(platform, adapter)
+ if listener_claim is not None:
+ owner = claimed.get(listener_claim)
+ if owner is not None:
+ bind, port = listener_claim[-2:]
+ logger.error(
+ "Profile '%s' and '%s' both configure %s sidecars on "
+ "%s:%s — refusing to start the duplicate listener. "
+ "Set platforms.%s.extra.sidecar_port to a distinct port "
+ "for profile '%s'.",
+ owner,
+ profile_name,
+ platform.value,
+ bind,
+ port,
+ platform.value,
+ profile_name,
+ )
+ # Like credential conflicts, this adapter never connected
+ # and owns no resources that should be disconnected.
+ continue
- if canonical == "kanban":
- return await self._handle_kanban_command(event)
+ self._configure_profile_adapter(adapter, profile_name, platform)
- if canonical == "suggestions":
- return await self._handle_suggestions_command(event)
+ try:
+ with _profile_runtime_scope(profile_home):
+ success = await self._connect_initial_adapter_with_timeout(
+ adapter, platform
+ )
+ if success:
+ profile_map[platform] = adapter
+ if credential_claim is not None:
+ claimed[credential_claim] = profile_name
+ if listener_claim is not None:
+ claimed[listener_claim] = profile_name
+ connected += 1
+ logger.info("✓ %s connected (profile: %s)", platform.value, profile_name)
+ else:
+ logger.warning("✗ %s failed to connect (profile: %s)", platform.value, profile_name)
+ await self._safe_adapter_disconnect(adapter, platform)
+ except Exception as e:
+ logger.error("✗ %s error (profile: %s): %s", platform.value, profile_name, e)
+ await self._safe_adapter_disconnect(adapter, platform)
+ return connected
- if canonical == "blueprint":
- _blueprint_result = await self._handle_blueprint_command(event)
- _blueprint_seed = getattr(_blueprint_result, "agent_seed", None)
- if _blueprint_seed:
- # Blueprint matched — rewrite the turn to the seed and fall
- # through to _handle_message_with_agent so the agent asks the
- # user for each slot value conversationally and then calls the
- # cronjob tool (the /steer fall-through pattern). The seed
- # enters as a normal user turn, preserving role alternation.
- # Send the "Setting up X…" ack first so the user gets the same
- # immediate feedback CLI users see, instead of silence until
- # the agent's first question.
- _ack = getattr(_blueprint_result, "text", "") or ""
- if _ack:
- try:
- adapter = self._adapter_for_source(source)
- if adapter:
- _ack_meta = self._thread_metadata_for_source(source)
- await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta)
- except Exception:
- logger.debug("blueprint ack send failed", exc_info=True)
- try:
- event.text = _blueprint_seed
- except Exception:
- return getattr(_blueprint_result, "text", "") or None
- else:
- return getattr(_blueprint_result, "text", "") or None
+ def _configure_profile_adapter(
+ self,
+ adapter: BasePlatformAdapter,
+ profile_name: str,
+ platform: Platform,
+ ) -> None:
+ """Install the profile-scoped handlers shared by startup and reconnect."""
+ adapter.set_message_handler(self._make_profile_message_handler(profile_name))
+ adapter.set_fatal_error_handler(
+ self._make_profile_fatal_error_handler(profile_name, platform)
+ )
+ adapter.set_session_store(self.session_store)
+ adapter.set_busy_session_handler(self._handle_active_session_busy_message)
+ _set_reaction = getattr(adapter, "set_reaction_handler", None)
+ if callable(_set_reaction):
+ _set_reaction(self._handle_reaction_event)
+ adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
+ adapter.set_authorization_check(
+ self._make_adapter_auth_check(platform, profile_name=profile_name)
+ )
+ adapter._busy_text_mode = self._busy_text_mode
- if canonical == "retry":
- return await self._handle_retry_command(event)
-
- if canonical == "undo":
- async def _do_undo():
- return await self._handle_undo_command(event)
- _undo_n = 1
- _undo_raw = event.get_command_args().strip()
- if _undo_raw:
+ async def _run_secondary_profile_reconnect(
+ self, profile_name: str, platform: Platform
+ ) -> None:
+ """Reconnect a retryable secondary adapter under its own profile scope."""
+ attempts = 0
+ current_task = asyncio.current_task()
+ try:
+ while self._running:
+ adapter = None
try:
- _undo_n = max(1, int(_undo_raw.split()[0]))
- except (ValueError, IndexError):
- _undo_n = 1
- _undo_detail = (
- "This removes the last user/assistant exchange from history."
- if _undo_n == 1
- else f"This removes the last {_undo_n} user turns from history."
- )
- return await self._maybe_confirm_destructive_slash(
- event=event,
- command="undo",
- title="/undo",
- detail=_undo_detail,
- execute=_do_undo,
- )
-
- if canonical == "sethome":
- return await self._handle_set_home_command(event)
-
- if canonical == "compress":
- return await self._handle_compress_command(event)
-
- if canonical == "usage":
- return await self._handle_usage_command(event)
+ from hermes_cli.profiles import get_profile_dir
+ from gateway.config import load_gateway_config
- if canonical == "topup":
- return await self._handle_topup_command(event)
+ profile_home = get_profile_dir(profile_name)
+ with _profile_runtime_scope(profile_home):
+ profile_config = load_gateway_config().platforms.get(platform)
+ if profile_config is None or not profile_config.enabled:
+ return
+ adapter = self._create_adapter(platform, profile_config)
+ if adapter is None:
+ logger.warning(
+ "Secondary %s reconnect skipped: adapter unavailable (profile: %s)",
+ platform.value,
+ profile_name,
+ )
+ return
+ self._configure_profile_adapter(
+ adapter, profile_name, platform
+ )
+ success = await self._connect_adapter_with_timeout(
+ adapter, platform, is_reconnect=True
+ )
- if canonical == "insights":
- return await self._handle_insights_command(event)
+ if success and self._running:
+ profile_map = self._profile_adapters.setdefault(profile_name, {})
+ if platform not in profile_map:
+ profile_map[platform] = adapter
+ self._sync_voice_mode_state_to_adapter(adapter)
+ logger.info(
+ "✓ %s reconnected (profile: %s)",
+ platform.value,
+ profile_name,
+ )
+ return
+ # A newer reconnect already won the slot while this
+ # attempt was awaiting connect; do not replace it.
+ await self._safe_adapter_disconnect(adapter, platform)
+ return
- if canonical == "reload-mcp":
- return await self._handle_reload_mcp_command(event)
+ # Shutdown can begin while connect() is in flight. Do not
+ # republish a newly connected adapter after the registry has
+ # been drained; release its partial resources instead.
+ if success:
+ await self._safe_adapter_disconnect(adapter, platform)
+ return
- if canonical == "reload-skills":
- return await self._handle_reload_skills_command(event)
+ await self._safe_adapter_disconnect(adapter, platform)
+ if (
+ getattr(adapter, "has_fatal_error", False)
+ and not getattr(adapter, "fatal_error_retryable", True)
+ ):
+ return
+ except asyncio.CancelledError:
+ if adapter is not None:
+ await self._safe_adapter_disconnect(adapter, platform)
+ raise
+ except Exception:
+ if adapter is not None:
+ await self._safe_adapter_disconnect(adapter, platform)
+ logger.debug(
+ "Secondary %s reconnect attempt failed (profile: %s)",
+ platform.value,
+ profile_name,
+ exc_info=True,
+ )
- if canonical == "bundles":
- return await self._handle_bundles_command(event)
+ if not self._running:
+ return
+ attempts += 1
+ backoff = _reconnect_backoff(attempts)
+ logger.info(
+ "Secondary %s reconnect retry in %ds (profile: %s)",
+ platform.value,
+ backoff,
+ profile_name,
+ )
+ await asyncio.sleep(backoff)
+ finally:
+ pending = self._profile_failed_platforms
+ if isinstance(pending, dict):
+ profile_pending = pending.get(profile_name)
+ task = profile_pending.get(platform) if isinstance(profile_pending, dict) else None
+ if not isinstance(task, asyncio.Task) or task is current_task:
+ if isinstance(profile_pending, dict):
+ profile_pending.pop(platform, None)
+ if not profile_pending:
+ pending.pop(profile_name, None)
- if canonical == "approve":
- return await self._handle_approve_command(event)
+ def _schedule_secondary_profile_reconnect(
+ self, profile_name: str, platform: Platform, adapter: BasePlatformAdapter
+ ) -> None:
+ """Schedule one runner-owned reconnect without sharing primary secrets."""
+ if not self._running or not adapter.fatal_error_retryable:
+ return
+ pending = self._profile_failed_platforms
+ if not isinstance(pending, dict):
+ pending = {}
+ self._profile_failed_platforms = pending
+ profile_pending = pending.setdefault(profile_name, {})
+ if platform in profile_pending:
+ return
+ task = asyncio.create_task(
+ self._run_secondary_profile_reconnect(profile_name, platform),
+ name=f"secondary-reconnect:{profile_name}:{platform.value}",
+ )
+ profile_pending[platform] = task
+ background_tasks = getattr(self, "_background_tasks", None)
+ if not isinstance(background_tasks, set):
+ background_tasks = set()
+ self._background_tasks = background_tasks
+ background_tasks.add(task)
+ task.add_done_callback(background_tasks.discard)
- if canonical == "deny":
- return await self._handle_deny_command(event)
+ def _make_profile_fatal_error_handler(
+ self, profile_name: str, platform: Platform
+ ) -> Callable[[BasePlatformAdapter], Awaitable[None]]:
+ """Route a secondary-profile fatal error to that profile's reconnect slot."""
+ async def _handler(adapter: BasePlatformAdapter) -> None:
+ await self._handle_profile_adapter_fatal_error(profile_name, platform, adapter)
- if canonical == "update":
- return await self._handle_update_command(event)
+ return _handler
- if canonical == "version":
- return await self._handle_version_command(event)
+ async def _handle_profile_adapter_fatal_error(
+ self,
+ profile_name: str,
+ platform: Platform,
+ adapter: BasePlatformAdapter,
+ ) -> None:
+ """Remove a failed multiplexed adapter without touching the primary slot.
- if canonical == "debug":
- return await self._handle_debug_command(event)
+ Secondary adapters are owned by ``_profile_adapters`` rather than
+ ``self.adapters``. The primary-only fatal handler intentionally ignores
+ them; without this route, a fatal secondary Discord client stayed live
+ forever after its liveness sampler stopped.
+ """
+ profile_map = getattr(self, "_profile_adapters", {}).get(profile_name)
+ if not isinstance(profile_map, dict) or profile_map.get(platform) is not adapter:
+ logger.debug(
+ "Ignoring stale fatal error from secondary %s adapter (profile: %s)",
+ platform.value,
+ profile_name,
+ )
+ return
+ profile_map.pop(platform, None)
+ await self._safe_adapter_disconnect(adapter, platform)
+ if not self._running:
+ return
+ self._schedule_secondary_profile_reconnect(profile_name, platform, adapter)
+ logger.error(
+ "Fatal %s adapter error for multiplexed profile %s (%s)",
+ platform.value,
+ profile_name,
+ adapter.fatal_error_code or "unknown",
+ )
+ # Reconnect is scoped to the profile's own config and secret mapping;
+ # never rebuild a secondary adapter with the default profile's credentials.
- if canonical == "title":
- return await self._handle_title_command(event)
+ def _make_profile_message_handler(self, profile_name: str):
+ """Return a message handler that stamps source.profile then delegates.
- if canonical == "resume":
- return await self._handle_resume_command(event)
+ Auth runs inside ``_handle_message`` *before* the agent-turn scope is
+ installed. For secondary profiles under multiplex, wrap the whole
+ handler in ``_profile_runtime_scope`` so allowlists/tokens from that
+ profile's ``.env`` are visible to ``get_secret`` / authz.
+ """
+ from hermes_cli.profiles import get_profile_dir
- if canonical == "sessions":
- return await self._handle_sessions_command(event)
+ try:
+ profile_home = get_profile_dir(profile_name)
+ except Exception:
+ profile_home = None
- if canonical == "branch":
- return await self._handle_branch_command(event)
+ async def _handler(event):
+ try:
+ if getattr(event, "source", None) is not None and not event.source.profile:
+ event.source.profile = profile_name
+ except Exception:
+ pass
+ if profile_home is not None:
+ with _profile_runtime_scope(profile_home):
+ return await self._handle_message(event)
+ return await self._handle_message(event)
- if canonical == "rollback":
- return await self._handle_rollback_command(event)
+ return _handler
- if canonical == "diff":
- return await self._handle_diff_command(event)
+ @staticmethod
+ def _adapter_credential_claim(
+ platform: Platform, adapter: Any
+ ) -> Optional[tuple]:
+ """Return the exclusive credential resource claimed by an adapter."""
+ fingerprint = GatewayRunner._adapter_credential_fingerprint(adapter)
+ if fingerprint is None:
+ return None
+ return (platform, fingerprint)
- if canonical == "background":
- return await self._handle_background_command(event)
+ @staticmethod
+ def _adapter_listener_claim(platform: Platform, adapter: Any) -> Optional[tuple]:
+ """Return the exclusive listener resource claimed by an adapter.
- if canonical == "queue":
- queue_payload = event.get_command_args().strip()
- if not queue_payload:
- return "Usage: /queue <prompt>"
- try:
- event.text = queue_payload
- except Exception:
- pass
+ Photon sidecars are per-profile processes. Even when two profiles use
+ different project credentials, their sidecars cannot share a bind and
+ port. Represent that endpoint as a claim so multiplex startup rejects
+ the later adapter before either ``connect()`` or ``disconnect()`` can
+ disturb the first profile.
+ """
+ if getattr(platform, "value", None) != "photon":
+ return None
+ bind = getattr(adapter, "_sidecar_bind", None)
+ port = getattr(adapter, "_sidecar_port", None)
+ if not isinstance(bind, str) or not bind.strip():
+ return None
+ try:
+ port = int(port)
+ except (TypeError, ValueError):
+ return None
+ return ("listener", "photon", bind.strip().lower(), port)
- if canonical == "steer":
- # No active agent — /steer has no tool call to inject into.
- # Strip the prefix so downstream treats it as a normal user
- # message. If the payload is empty, surface the usage hint.
- steer_payload = event.get_command_args().strip()
- if not steer_payload:
- return "Usage: /steer <prompt> (no agent is running; sending as a normal message)"
- try:
- event.text = steer_payload
- except Exception:
- pass
- # Do NOT return — fall through to _handle_message_with_agent
- # at the end of this function so the rewritten text is sent
- # to the agent as a regular user turn.
+ @staticmethod
+ def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]:
+ """Return a stable, log-safe fingerprint of an adapter's credential.
- if canonical == "goal":
- return await self._handle_goal_command(event)
+ Used only to detect two profiles claiming the same platform credential.
+ Returns a salted hash (never the credential itself) of the adapter's
+ primary credential, or None when no credential is discoverable (in
+ which case we don't attempt conflict detection for it).
+ """
+ token = None
+ for attr in (
+ "token",
+ "bot_token",
+ "_token",
+ "api_token",
+ "_bot_token",
+ # Photon/Spectrum authenticates with project credentials instead
+ # of a bot token. Including its secret keeps multiplexed profiles
+ # from spawning competing sidecars for the same account and port.
+ "_project_secret",
+ ):
+ val = getattr(adapter, attr, None)
+ if isinstance(val, str) and val.strip():
+ token = val.strip()
+ break
+ # Many adapters (e.g. Discord) store the token on their `config`
+ # sub-object rather than directly on the adapter. Without this lookup
+ # those adapters all return None here, the same-token conflict check
+ # is silently skipped, and every profile's adapter for that platform
+ # starts polling the same bot token — producing a per-message race
+ # for which adapter answers. See test_reads_config_token.
+ if not token:
+ cfg = getattr(adapter, "config", None)
+ if cfg is not None:
+ for attr in ("token", "bot_token"):
+ val = getattr(cfg, attr, None)
+ if isinstance(val, str) and val.strip():
+ token = val.strip()
+ break
+ if not token:
+ config = getattr(adapter, "config", None)
+ val = getattr(config, "token", None)
+ if isinstance(val, str) and val.strip():
+ token = val.strip()
+ if not token:
+ return None
+ import hashlib
+ return hashlib.sha256(("hermes-mux:" + token).encode("utf-8")).hexdigest()[:16]
- if canonical == "moa":
- # /moa is one-shot sugar only: run a single prompt through the
- # default MoA preset, then restore the prior model. To *switch* to a
- # MoA preset for the session, pick it from the model picker (MoA
- # presets surface as a virtual "Mixture of Agents" provider).
- from hermes_cli.moa_config import (
- moa_usage,
- normalize_moa_config,
+ def _create_adapter(
+ self,
+ platform: Platform,
+ config: Any
+ ) -> Optional[BasePlatformAdapter]:
+ """Create the appropriate adapter for a platform.
+
+ Checks the platform_registry first (plugin adapters), then falls
+ through to the built-in if/elif chain for core platforms.
+ """
+ if hasattr(config, "extra") and isinstance(config.extra, dict):
+ config.extra.setdefault(
+ "group_sessions_per_user",
+ self.config.group_sessions_per_user,
+ )
+ config.extra.setdefault(
+ "thread_sessions_per_user",
+ getattr(self.config, "thread_sessions_per_user", False),
)
- from hermes_cli.config import load_config
- moa_payload = event.get_command_args().strip()
- if not moa_payload:
- return moa_usage()
- try:
- cfg = load_config()
- moa_cfg = normalize_moa_config(cfg.get("moa") if isinstance(cfg, dict) else {})
- except Exception:
- moa_cfg = normalize_moa_config({})
- preset = moa_cfg["default_preset"]
- try:
- event.text = moa_payload
- _moa_state = self._session_state(_quick_key)
- event._moa_restore_override = _moa_state.conversation.model_override
- _moa_state.conversation.model_override = {
- "provider": "moa",
- "model": preset,
- "base_url": "moa://local",
- "api_key": "moa-virtual-provider",
- "api_mode": "chat_completions",
- }
- self._evict_cached_agent(_quick_key)
- event._moa_disable_after_turn = True
- except Exception:
- return "Failed to prepare MoA turn."
+ # ── Plugin-registered platforms (checked first) ───────────────────
+ try:
+ from gateway.platform_registry import platform_registry
+ if platform_registry.is_registered(platform.value):
+ adapter = platform_registry.create_adapter(platform.value, config)
+ if adapter is not None:
+ # Inject a back-reference to the gateway runner so every
+ # adapter can (a) deliver cross-platform admin alerts and
+ # (b) resolve inbound profile routing through
+ # ``runner._profile_name_for_source``. Unconditional:
+ # ``BasePlatformAdapter`` declares ``gateway_runner``, so
+ # this reaches ALL platforms (not just the ones that
+ # pre-declared it), making profile routing platform-generic.
+ adapter.gateway_runner = self
+ return adapter
+ # Registered but failed to instantiate — don't silently fall
+ # through to built-ins (there are none for plugin platforms).
+ logger.error(
+ "Platform '%s' is registered but adapter creation failed "
+ "(check dependencies and config)",
+ platform.value,
+ )
+ return None
+ except Exception as e:
+ logger.debug("Platform registry lookup for '%s' failed: %s", platform.value, e)
+ # Fall through to built-in adapters below
- if canonical == "subgoal":
- return await self._handle_subgoal_command(event)
+ if platform == Platform.WHATSAPP_CLOUD:
+ from gateway.platforms.whatsapp_cloud import (
+ WhatsAppCloudAdapter,
+ check_whatsapp_cloud_requirements,
+ )
+ if not check_whatsapp_cloud_requirements():
+ logger.warning(
+ "WhatsApp Cloud: aiohttp/httpx missing — reinstall hermes-agent"
+ )
+ return None
+ return WhatsAppCloudAdapter(config)
+
+ elif platform == Platform.SIGNAL:
+ from gateway.platforms.signal import (
+ SignalAdapter,
+ check_signal_requirements,
+ validate_signal_config,
+ )
+ if not check_signal_requirements():
+ logger.warning("Signal: runtime requirements not met")
+ return None
+ if not validate_signal_config(config):
+ logger.warning("Signal: SIGNAL_HTTP_URL or SIGNAL_ACCOUNT not configured")
+ return None
+ return SignalAdapter(config)
- if canonical == "voice":
- return await self._handle_voice_command(event)
+ elif platform == Platform.WEIXIN:
+ from gateway.platforms.weixin import WeixinAdapter, check_weixin_requirements
+ if not check_weixin_requirements():
+ logger.warning("Weixin: aiohttp/cryptography not installed")
+ return None
+ return WeixinAdapter(config)
- if self._draining:
- return f"⏳ Gateway is {self._status_action_gerund()} and is not accepting new work right now."
+ elif platform == Platform.API_SERVER:
+ from gateway.platforms.api_server import APIServerAdapter, check_api_server_requirements
+ if not check_api_server_requirements():
+ logger.warning("API Server: aiohttp not installed")
+ return None
+ adapter = APIServerAdapter(config)
+ adapter.gateway_runner = self
+ return adapter
- # User-defined quick commands (bypass agent loop, no LLM call)
- if command:
- if isinstance(self.config, dict):
- quick_commands = self.config.get("quick_commands", {}) or {}
- else:
- quick_commands = getattr(self.config, "quick_commands", {}) or {}
- if not isinstance(quick_commands, dict):
- quick_commands = {}
- if command in quick_commands:
- # Quick commands are slash capabilities too — and type:exec
- # ones run a shell command in the gateway process. The early
- # gate above only fires for registry-known commands, so quick
- # commands (never in the registry) would otherwise reach this
- # dispatch sink unchecked. Apply the same admin/user policy to
- # the raw typed name here so non-admins can't invoke admin-only
- # quick commands. (#44727)
- _denied = self._check_slash_access(source, command)
- if _denied is not None:
- return _denied
- qcmd = quick_commands[command]
- if qcmd.get("type") == "exec":
- exec_cmd = qcmd.get("command", "")
- if exec_cmd:
- try:
- # Sanitize env to prevent credential leakage —
- # quick commands run in the gateway process which
- # has all API keys in os.environ.
- from tools.environments.local import build_subprocess_env
- sanitized_env = build_subprocess_env()
- proc = await asyncio.create_subprocess_shell(
- exec_cmd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- env=sanitized_env,
- )
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
- output = (stdout or stderr).decode().strip()
- # Redact any remaining sensitive patterns in output
- if output:
- from agent.redact import redact_sensitive_text
- output = redact_sensitive_text(output)
- return output if output else "Command returned no output."
- except asyncio.TimeoutError:
- return "Quick command timed out (30s)."
- except Exception as e:
- return f"Quick command error: {e}"
- else:
- return f"Quick command '/{command}' has no command defined."
- elif qcmd.get("type") == "alias":
- target = (qcmd.get("target") or "").strip()
- if target:
- target = target if target.startswith("/") else f"/{target}"
- target_command = target.lstrip("/")
- user_args = event.get_command_args().strip()
- event.text = f"{target} {user_args}".strip()
- command = target_command.split()[0] if target_command else target_command
- # Fall through to normal command dispatch below
- else:
- return f"Quick command '/{command}' has no target defined."
- else:
- return f"Quick command '/{command}' has unsupported type (supported: 'exec', 'alias')."
+ elif platform == Platform.WEBHOOK:
+ from gateway.platforms.webhook import WebhookAdapter, check_webhook_requirements
+ if not check_webhook_requirements():
+ logger.warning("Webhook: aiohttp not installed")
+ return None
+ adapter = WebhookAdapter(config)
+ adapter.gateway_runner = self # For cross-platform delivery
+ return adapter
- # Plugin-registered slash commands
- if command:
- try:
- from hermes_cli.plugins import get_plugin_command_handler
- # Normalize underscores to hyphens so Telegram's underscored
- # autocomplete form matches plugin commands registered with
- # hyphens. See hermes_cli/commands.py:_build_telegram_menu.
- plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
- if plugin_handler:
- user_args = event.get_command_args().strip()
- result = plugin_handler(user_args)
- if asyncio.iscoroutine(result):
- result = await result
- return str(result) if result else None
- except Exception as e:
- logger.warning("Plugin command dispatch failed: %s", e)
+ elif platform == Platform.MSGRAPH_WEBHOOK:
+ from gateway.platforms.msgraph_webhook import (
+ MSGraphWebhookAdapter,
+ check_msgraph_webhook_requirements,
+ )
+ if not check_msgraph_webhook_requirements():
+ logger.warning("MSGraph webhook: aiohttp not installed")
+ return None
+ return MSGraphWebhookAdapter(config)
- # Skill slash commands: /skill-name loads the skill and sends to agent.
- # resolve_skill_command_key() handles the Telegram underscore/hyphen
- # round-trip so /claude_code from Telegram autocomplete still resolves
- # to the claude-code skill.
- if command:
- # Skill bundles take precedence over individual skill commands —
- # /<bundle> loads multiple skills at once. Mirrors CLI dispatch.
- _bundle_handled = False
- try:
- from agent.skill_bundles import (
- build_bundle_invocation_message,
- resolve_bundle_command_key,
- )
- bundle_key = resolve_bundle_command_key(command)
- if bundle_key is not None:
- user_instruction = event.get_command_args().strip()
- # Pass the platform explicitly: bundle skill loading
- # bypasses get_skill_commands()' scan-time disabled
- # filter, and the gateway serves multiple platforms in
- # one process, so env-var platform resolution can't be
- # trusted here. Mirrors the stacked-skill gate (#58888).
- _bundle_plat = source.platform.value if source.platform else None
- bundle_result = build_bundle_invocation_message(
- bundle_key, user_instruction, task_id=_quick_key,
- platform=_bundle_plat,
- )
- if bundle_result:
- msg, _loaded, missing = bundle_result
- event.text = msg
- _bundle_handled = True
- if missing:
- logger.info(
- "Bundle %s skipped missing skills: %s",
- bundle_key, ", ".join(missing),
- )
- # Fall through to normal message processing with bundle content
- except Exception as exc:
- logger.warning("Bundle dispatch failed: %s", exc)
+ elif platform == Platform.BLUEBUBBLES:
+ from gateway.platforms.bluebubbles import BlueBubblesAdapter, check_bluebubbles_requirements
+ if not check_bluebubbles_requirements():
+ logger.warning("BlueBubbles: aiohttp/httpx missing or BLUEBUBBLES_SERVER_URL/BLUEBUBBLES_PASSWORD not configured")
+ return None
+ return BlueBubblesAdapter(config)
- if command and not locals().get("_bundle_handled", False):
+ elif platform == Platform.QQBOT:
+ from gateway.platforms.qqbot import QQAdapter, check_qq_requirements
+ if not check_qq_requirements():
+ logger.warning("QQBot: aiohttp/httpx missing or QQ_APP_ID/QQ_CLIENT_SECRET not configured")
+ return None
+ return QQAdapter(config)
+
+ elif platform == Platform.YUANBAO:
+ from gateway.platforms.yuanbao import YuanbaoAdapter, WEBSOCKETS_AVAILABLE
+ if not WEBSOCKETS_AVAILABLE:
+ logger.warning("Yuanbao: websockets not installed. Run: pip install websockets")
+ return None
+ return YuanbaoAdapter(config)
+
+ return None
+
+ def _make_adapter_auth_check(
+ self,
+ platform: Platform,
+ profile_name: Optional[str] = None,
+ ) -> Callable[[str, Optional[str], Optional[str]], bool]:
+ """Build a platform-bound auth callback for adapter use.
+
+ Adapters that fetch external context (e.g. Slack
+ ``conversations.replies``) call this through
+ ``BasePlatformAdapter._is_sender_authorized`` to mark non-allowlisted
+ senders as unverified in LLM context, mitigating indirect prompt
+ injection from third parties in shared threads/channels.
+
+ The returned callback delegates to :meth:`_is_user_authorized` so the
+ full auth chain — platform allowlists, group allowlists, pairing
+ store, allow-all flags — stays the single source of truth.
+
+ ``profile_name`` binds the callback to the secondary adapter's own
+ multiplex profile, so its ``SessionSource`` resolves that profile's
+ secret scope instead of falling back to the active profile.
+ """
+ def check(
+ user_id: str,
+ chat_type: Optional[str] = None,
+ chat_id: Optional[str] = None,
+ ) -> bool:
+ if not user_id:
+ return False
+ source = SessionSource(
+ platform=platform,
+ chat_id=chat_id or "",
+ chat_type=chat_type or "group",
+ user_id=user_id,
+ profile=profile_name,
+ )
+ return self._is_user_authorized(source)
+ return check
+
+
+
+
+
+
+ async def _deliver_platform_notice(self, source, content: str) -> None:
+ """Deliver a setup/operational notice using platform-specific privacy rules."""
+ adapter = self._adapter_for_source(source)
+ if not adapter:
+ return
+
+ config = getattr(self, "config", None)
+ if (
+ config
+ and getattr(source, "platform", None) == Platform.SLACK
+ and _is_slack_ignored_channel(config, getattr(source, "chat_id", None))
+ ):
+ logger.info(
+ "Skipping Slack platform notice for configured ignored channel %s",
+ getattr(source, "chat_id", None),
+ )
+ return
+
+ notice_delivery = "public"
+ if config and hasattr(config, "get_notice_delivery"):
+ notice_delivery = config.get_notice_delivery(source.platform)
+
+ metadata = self._thread_metadata_for_source(source)
+ if notice_delivery == "private" and getattr(source, "user_id", None):
try:
- from agent.skill_commands import (
- get_skill_commands,
- build_skill_invocation_message,
- resolve_skill_command_key,
+ result = await adapter.send_private_notice(
+ source.chat_id,
+ source.user_id,
+ content,
+ metadata=metadata,
+ )
+ if getattr(result, "success", False):
+ return
+ except Exception:
+ logger.debug(
+ "[%s] send_private_notice failed, falling back to public",
+ getattr(source, "platform", "?"),
+ exc_info=True,
)
- skill_cmds = get_skill_commands()
- cmd_key = resolve_skill_command_key(command)
- if cmd_key is not None:
- # Check per-platform disabled status before executing.
- # get_skill_commands() only applies the *global* disabled
- # list at scan time; per-platform overrides need checking
- # here because the cache is process-global across platforms.
- _skill_name = skill_cmds[cmd_key].get("name", "")
- _plat = source.platform.value if source.platform else None
- if _plat and _skill_name:
- from agent.skill_utils import get_disabled_skill_names as _get_plat_disabled
- if _skill_name in _get_plat_disabled(platform=_plat):
- return (
- f"The **{_skill_name}** skill is disabled for {_plat}.\n"
- f"Enable it with: `hermes skills config`"
- )
- user_instruction = event.get_command_args().strip()
- # Stacked slash-skill invocations: `/skill-a /skill-b do
- # XYZ` loads every leading skill (up to 5), not just the
- # first. Inspired by Claude Code v2.1.199. Mirrors CLI.
- try:
- from agent.skill_commands import (
- build_stacked_skill_invocation_message as _build_stacked,
- split_stacked_skill_commands,
- )
- extra_keys, stacked_instruction = (
- split_stacked_skill_commands(user_instruction)
- )
- except Exception:
- _build_stacked = None
- extra_keys, stacked_instruction = [], user_instruction
- if extra_keys and _plat:
- # split_stacked_skill_commands() only resolves that
- # each extra token is a KNOWN skill command — like
- # get_skill_commands() itself, it has no per-platform
- # view. Re-check every stacked skill (not just the
- # leading one above) against the same disabled list,
- # or a skill an operator disabled for this platform
- # still gets its full content loaded via the stack.
- from agent.skill_utils import get_disabled_skill_names as _get_plat_disabled
- _plat_disabled = _get_plat_disabled(platform=_plat)
- _disabled_extra = [
- skill_cmds.get(k, {}).get("name", "")
- for k in extra_keys
- if skill_cmds.get(k, {}).get("name", "") in _plat_disabled
- ]
- if _disabled_extra:
- return (
- f"The **{', '.join(_disabled_extra)}** skill(s) in this "
- f"stacked invocation are disabled for {_plat}.\n"
- f"Enable them with: `hermes skills config`"
- )
- if extra_keys and _build_stacked is not None:
- stacked_result = _build_stacked(
- [cmd_key, *extra_keys],
- stacked_instruction,
- task_id=_quick_key,
- )
- if stacked_result:
- msg, _loaded, _missing = stacked_result
- event.text = msg
- # Fall through to normal message processing
- else:
- return f"Failed to load stacked skills for /{command}."
- else:
- msg = build_skill_invocation_message(
- cmd_key, user_instruction, task_id=_quick_key
- )
- if msg:
- event.text = msg
- # Fall through to normal message processing with skill content
- else:
- # Not an active skill — check if it's a known-but-disabled or
- # uninstalled skill and give actionable guidance.
- _unavail_msg = _check_unavailable_skill(command)
- if _unavail_msg:
- return _unavail_msg
- # Genuinely unrecognized /command: not a built-in, not a
- # plugin, not a skill, not a known-inactive skill. Warn
- # the user instead of silently forwarding it to the LLM
- # as free text (which leads to silent-failure behavior
- # like the model inventing a delegate_task call).
- # Normalize to hyphenated form before checking known
- # built-ins (command may be an alias target set by the
- # quick-command block above, so _cmd_def can be stale).
- if command.replace("_", "-") not in GATEWAY_KNOWN_COMMANDS:
- logger.warning(
- "Unrecognized slash command /%s from %s — "
- "replying with unknown-command notice",
- command,
- source.platform.value if source.platform else "?",
- )
- return (
- f"Unknown command `/{command}`. "
- f"Type /commands to see what's available, "
- f"or resend without the leading slash to send "
- f"as a regular message."
- )
- except Exception as e:
- logger.debug("Skill command check failed (non-fatal): %s", e)
-
- # Pending exec approvals are handled by /approve and /deny commands above.
- # No bare text matching — "yes" in normal conversation must not trigger
- # execution of a dangerous command.
- if not is_internal and await asyncio.to_thread(
- self._is_telegram_topic_root_lobby, source
- ):
- # Debounce the lobby reminder so a user who forgets about
- # topic mode and fires ten prompts doesn't get ten copies.
- if self._should_send_telegram_lobby_reminder(source):
- return self._telegram_topic_root_lobby_message()
- return None
+ await adapter.send(source.chat_id, content, metadata=metadata)
- # ── External-drain new-turn gate (Phase 2) ────────────────────
- # When NAS has engaged an external drain (.drain_request.json present,
- # observed by _drain_control_watcher), refuse to START a new turn so
- # the in-flight set can only fall to zero — eliminating the TOCTOU race
- # (D4a: stop accepting new turns FIRST, then NAS polls until
- # active_agents==0). In-flight turns are untouched; this only blocks the
- # claim of a NEW session slot. Internal/system events (restart-recovery
- # replays, background-process completions) bypass the gate — they are
- # not user-initiated new work and must still flow during a drain.
- # Reversible: once the marker is removed the gate opens again.
- if self._external_drain_active and not is_internal:
- logger.info(
- "Refusing new turn for session %s — external drain active.",
- _quick_key,
+ async def _resolve_async_delegation_session(
+ self,
+ session_entry: SessionEntry,
+ pinned_session_id: str,
+ ) -> Optional[SessionEntry]:
+ """Resolve an async completion to its verified owning gateway session.
+
+ A compression rotation ends the physical parent row while continuing
+ the same logical conversation in a child. Follow that lineage, but
+ never let a late completion override an unrelated /new or restored
+ route. Unknown ownership remains fail-closed; the result is still
+ available in the delegation records.
+ """
+ session_db = cast(Any, self._session_db)
+ if session_db is None:
+ logger.warning(
+ "Async-delegation completion has no session database; "
+ "dropping injection (#55578 fail-closed)."
)
- return (
- "⏳ This agent is draining for a maintenance action and isn't "
- "accepting new turns right now. It'll be back in a moment — "
- "please resend shortly."
+ return None
+
+ pinned_row = None
+ try:
+ pinned_row = await session_db.get_session(pinned_session_id)
+ except Exception:
+ logger.debug(
+ "Async-delegation parent lookup failed for %s",
+ pinned_session_id,
+ exc_info=True,
)
- # ── Claim this session before any await ───────────────────────
- # Between here and _run_agent registering the real AIAgent, there
- # are numerous await points (hooks, vision enrichment, STT,
- # session hygiene compression). Without this sentinel a second
- # message arriving during any of those yields would pass the
- # "already running" guard and spin up a duplicate agent for the
- # same session — corrupting the transcript.
- _active_session_lease, _limit_message = self._claim_active_session_slot(
- _quick_key,
- source,
- )
- if _limit_message is not None:
- logger.info(
- "Rejecting new active session %s: max_concurrent_sessions reached",
- _quick_key,
+ if pinned_row is None:
+ logger.warning(
+ "Async-delegation completion has unknown spawning session %s; "
+ "dropping injection (#55578 fail-closed).",
+ pinned_session_id,
)
- return _limit_message
- _claim_state = self._session_state(_quick_key)
- if _active_session_lease is not None:
- _claim_state.turn.lease = _active_session_lease
- _claim_state.turn.agent = _AGENT_PENDING_SENTINEL
- _claim_state.turn.started_ts = time.time()
- self._persist_active_agents()
- _run_generation = self._begin_session_run_generation(_quick_key)
+ return None
- try:
- _agent_result = await self._handle_message_with_agent(event, source, _quick_key, _run_generation)
- # Goal continuation: after the agent returns a final response
- # for this turn, check any standing /goal — the judge will
- # either mark it done, pause it (budget), or enqueue a
- # continuation prompt back through the adapter FIFO so the
- # next turn makes more progress. Wrapped in try/except so a
- # broken judge never breaks normal message handling.
+ target_session_id = pinned_session_id
+ follows_compression = False
+ if pinned_row.get("ended_at"):
+ if pinned_row.get("end_reason") != "compression":
+ logger.warning(
+ "Async-delegation completion pinned to ended session %s "
+ "(end_reason=%r); dropping injection instead of resurrecting it "
+ "(#55578 fail-closed).",
+ pinned_session_id,
+ pinned_row.get("end_reason"),
+ )
+ return None
+
+ follows_compression = True
try:
- _final_text = ""
- if isinstance(_agent_result, dict):
- _final_text = str(_agent_result.get("final_response") or "")
- elif isinstance(_agent_result, str):
- _final_text = _agent_result
- # Skip for empty responses (interrupted / errored) — the
- # judge would almost always say "continue" and we'd loop
- # on error. Let the user drive the next turn.
- if _final_text.strip():
- try:
- session_entry = await self.async_session_store.get_or_create_session(source)
- except Exception:
- session_entry = None
- if session_entry is not None:
- await self._post_turn_goal_continuation(
- session_entry=session_entry,
- source=source,
- final_response=_final_text,
- )
- except Exception as _goal_exc:
- logger.debug("goal continuation hook failed: %s", _goal_exc)
- return _agent_result
- finally:
- # MoA one-shot restore must run on EVERY exit path, not just
- # success. The restore data lives on the per-turn event object
- # (_moa_restore_override), which is discarded once the event goes
- # out of scope — so if _handle_message_with_agent raises, a restore
- # in the try block would be skipped and the MoA override would leak
- # permanently (every later message silently fans out through MoA).
- # Putting it in finally guarantees the revert on success, exception,
- # and interrupt alike.
- self._restore_moa_one_shot(event, _quick_key)
- self._restore_pending_one_turn_model_override(_quick_key)
- # Unconditional release covers every exit path. _release_running_agent_state
- # is idempotent (pop-on-absent is harmless) and, called without a
- # run_generation guard, always clears the slot regardless of which
- # generation it holds. This evicts the zombie left when session_reset
- # bumps the generation (N -> N+1) mid-flight: gen-N's guarded release
- # inside _run_agent returns False, and the old sentinel-only check here
- # missed the leftover real agent — locking the session out forever (#28686).
- self._release_running_agent_state(_quick_key)
- # Turn lease (#64934): release THIS turn's lease token — keyed by
- # (routing key, run generation) so this unwind can only ever free
- # the lease its own turn acquired, never a newer turn's.
- self._release_turn_lease(_quick_key, _run_generation)
+ target_session_id = await session_db.get_compression_tip(
+ pinned_session_id
+ )
+ except Exception:
+ logger.debug(
+ "Async-delegation compression-tip lookup failed for %s",
+ pinned_session_id,
+ exc_info=True,
+ )
+ target_session_id = None
- def _restore_moa_one_shot(self, event: "MessageEvent", quick_key: str) -> None:
- """Revert a ``/moa <prompt>`` one-shot model override after its turn.
+ if not target_session_id or target_session_id == pinned_session_id:
+ logger.warning(
+ "Async-delegation completion pinned to compressed session %s "
+ "without a continuation; dropping injection.",
+ pinned_session_id,
+ )
+ return None
- Called from the ``finally`` of the message-handling path so the revert
- fires whether the turn succeeded, raised, or was interrupted. A no-op
- unless ``event._moa_disable_after_turn`` is set. ``_moa_restore_override``
- carries the prior per-session override (``None`` means the user had no
- override, so the MoA override is cleared outright).
- """
- if not getattr(event, "_moa_disable_after_turn", False):
- return
- try:
- _restore = getattr(event, "_moa_restore_override", None)
- self._session_state(quick_key).conversation.model_override = _restore
- self._evict_cached_agent(quick_key)
- except Exception:
- pass
+ try:
+ tip_row = await session_db.get_session(target_session_id)
+ except Exception:
+ tip_row = None
+ if tip_row is None or tip_row.get("ended_at"):
+ logger.warning(
+ "Async-delegation compression continuation %s is %s; "
+ "dropping injection.",
+ target_session_id,
+ "unknown" if tip_row is None else "ended",
+ )
+ return None
- def _restore_pending_one_turn_model_override(self, session_key: str) -> None:
- """Restore a per-session model override after ``/model --once`` runs."""
- if not session_key:
- return
- try:
- _otr_state = self._peek_session_state(session_key)
- snapshot = _otr_state.conversation.one_turn_restore if _otr_state else None
- if _otr_state is not None:
- _otr_state.conversation.one_turn_restore = None
- if not snapshot:
- return
- self._restore_session_model_override(session_key, snapshot)
- except Exception:
- logger.debug("Failed to restore one-turn model override", exc_info=True)
+ route_owns_lineage = session_entry.session_id in {
+ pinned_session_id,
+ target_session_id,
+ }
+ if not route_owns_lineage:
+ # A long-running delegation may survive multiple compression
+ # rotations. Accept an intermediate stale route only when its
+ # own verified compression tip is the same live target.
+ try:
+ route_row = await session_db.get_session(session_entry.session_id)
+ route_tip = (
+ await session_db.get_compression_tip(session_entry.session_id)
+ if route_row is not None
+ and route_row.get("ended_at")
+ and route_row.get("end_reason") == "compression"
+ else None
+ )
+ except Exception:
+ route_tip = None
+ route_owns_lineage = route_tip == target_session_id
- async def _prepare_inbound_message_text(
- self,
- *,
- event: MessageEvent,
- source: SessionSource,
- history: List[Dict[str, Any]],
- session_key: Optional[str] = None,
- ) -> Optional[str]:
- """Prepare inbound event text for the agent.
+ if not route_owns_lineage:
+ logger.warning(
+ "Async-delegation completion for compression lineage %s -> %s "
+ "does not own current route %s; dropping injection.",
+ pinned_session_id,
+ target_session_id,
+ session_entry.session_id,
+ )
+ return None
- Keep the normal inbound path and the queued follow-up path on the same
- preprocessing pipeline so sender attribution, image enrichment, STT,
- document notes, reply context, and @ references all behave the same.
+ if target_session_id == session_entry.session_id:
+ return session_entry
- Side effect: buffers per-session native image paths when the active
- model supports native vision AND the user has images attached. The
- caller consumes and clears that session-scoped buffer at the
- ``run_conversation`` site to build a multimodal user turn. When the
- list is empty, the ``_enrich_message_with_vision`` text path has
- already run and images are represented in-text.
- """
- history = history or []
- _pending_stt_prepared = hasattr(event, "_gateway_pending_stt_text")
- message_text = (
- getattr(event, "_gateway_pending_stt_text", None)
- if _pending_stt_prepared
- else event.text
- ) or ""
- _group_sessions_per_user = getattr(self.config, "group_sessions_per_user", True)
- _thread_sessions_per_user = getattr(self.config, "thread_sessions_per_user", False)
- # Prefer the already resolved session key from the caller so this write
- # key matches the consume key at the run_conversation site. Fall back
- # to deriving it here for tests and legacy standalone callers.
- session_key = session_key or self._session_key_for_source(source)
- # Reset only this session's per-call buffer; other sessions may be
- # concurrently preparing multimodal turns on the same runner.
- self._consume_pending_native_image_paths(session_key)
+ prior_session_id = session_entry.session_id
+ if follows_compression:
+ switched = await self.async_session_store.advance_compression_session(
+ session_entry.session_key,
+ prior_session_id,
+ target_session_id,
+ )
+ else:
+ switched = await self.async_session_store.switch_session(
+ session_entry.session_key,
+ target_session_id,
+ )
+ if switched is None:
+ logger.warning(
+ "Async-delegation completion could not bind routing key %s to "
+ "owning session %s; dropping injection.",
+ session_entry.session_key,
+ target_session_id,
+ )
+ return None
- _is_shared_multi_user = is_shared_multi_user_session(
- source,
- group_sessions_per_user=_group_sessions_per_user,
- thread_sessions_per_user=_thread_sessions_per_user,
+ logger.info(
+ "Pinned async-delegation completion to owning session %s "
+ "(was %s) for routing key %s (#57498)",
+ target_session_id,
+ prior_session_id,
+ session_entry.session_key,
)
- if _is_shared_multi_user and source.user_name:
- # source.user_name is the platform display name — attacker-
- # influenceable on any platform that lets participants set their
- # own name. Neutralize embedded newlines/control chars before
- # interpolating it into every message in the shared session, or
- # a hostile name can masquerade as a fake markdown section
- # (mirrors the same field's treatment in
- # build_session_context_prompt via _format_untrusted_prompt_value).
- _safe_user_name = neutralize_untrusted_inline_text(source.user_name)
- # On Slack, expose the current author's verifiable user ID next to
- # the display name (#17916): "mention me again" requests need a
- # trusted `<@U...>` target for the CURRENT speaker — display names
- # are ambiguous and historical mentions may point at someone else.
- # The user_id comes from the Slack event envelope (not
- # user-editable text), so it does not need neutralization.
- if source.platform == Platform.SLACK and source.user_id:
- _safe_user_name = (
- f"{_safe_user_name} | Slack user <@{source.user_id}>"
- )
- message_text = f"[{_safe_user_name}] {message_text}"
-
- # Prepend channel context from history backfill (if any). This
- # happens after sender-prefix so the prefix only applies to the
- # trigger message, not the backfill block.
- if getattr(event, "channel_context", None):
- message_text = f"{event.channel_context}\n\n[New message]\n{message_text}"
-
- # Declare at outer scope so the audio-file-paths handling block below
- # remains safe when ``event.media_urls`` is empty (no inner block runs).
- audio_file_paths: list[str] = []
- video_paths: list[str] = []
+ return switched
- if event.media_urls:
- image_paths = []
- audio_paths = []
- for i, path in enumerate(event.media_urls):
- mtype = event.media_types[i] if i < len(event.media_types) else ""
- # Classify images per-attachment: trust this attachment's own
- # MIME, and only honour the message-level PHOTO type when the
- # per-attachment MIME is unknown. Otherwise a document (or any
- # non-image) sent alongside an image in the same message gets
- # mis-routed here as an image and the provider 400s.
- if _event_media_is_image(event, i):
- image_paths.append(path)
- # MessageType.AUDIO = audio file attachment (e.g. .mp3, .m4a) — never STT
- # MessageType.VOICE = voice message (Opus/OGG) — always STT
- if event.message_type == MessageType.AUDIO:
- audio_file_paths.append(path)
- elif not _pending_stt_prepared and _event_media_is_stt_input(event, i):
- audio_paths.append(path)
- if mtype.startswith("video/") or (not mtype and event.message_type == MessageType.VIDEO):
- video_paths.append(path)
+ # ------------------------------------------------------------------
+ # Mid-run (busy-session) slash command dispatch — "Guard 2".
+ #
+ # Replaces the historical hand-written per-command if-chain: each
+ # command's mid-run behavior is declared on its CommandDef
+ # (busy_policy / busy_handler in hermes_cli/commands.py) and resolved
+ # here through a single handler table. Reply strings are byte-identical
+ # to the old chain.
+ # ------------------------------------------------------------------
- if image_paths:
- # Decide routing: native (attach pixels) vs text (vision_analyze
- # pre-run + prepend description). See agent/image_routing.py.
- # Offload to a worker thread: the decision does blocking network
- # I/O — a models.dev fetch on cache miss, and the Ollama
- # ``/api/show`` capability probe for local servers — whose
- # request timeout would otherwise stall the whole gateway event
- # loop (every session) while a single image is routed.
- _img_mode = await asyncio.to_thread(
- self._decide_image_input_mode,
- source=source,
- session_key=session_key,
- )
- if _img_mode == "native":
- # Defer attachment to the run_conversation call site.
- self._session_state(
- session_key
- ).persistent.native_image_paths = list(image_paths)
- logger.info(
- "Image routing: native (model supports vision). %d image(s) will be attached inline.",
- len(image_paths),
- )
- else:
- logger.info(
- "Image routing: text (mode=%s). Pre-analyzing %d image(s) via vision_analyze.",
- _img_mode, len(image_paths),
- )
- # Vision enrichment runs before AIAgent.run_conversation(),
- # so bind this session's resolved runtime explicitly rather
- # than consulting process-global compatibility mirrors.
- vision_runtime = None
- try:
- turn_model, runtime_kwargs = self._resolve_session_agent_runtime(
- source=source,
- session_key=session_key,
- )
- vision_runtime = dict(runtime_kwargs or {})
- vision_runtime["model"] = turn_model
- except Exception:
- logger.debug(
- "vision enrichment: session runtime resolution failed",
- exc_info=True,
- )
+ # Command-specific mid-run reject texts (busy_policy == "reject" with a
+ # busy_handler naming an entry here). All other rejected commands get
+ # the generic catch-all text in _dispatch_busy_slash_command.
+ _BUSY_REJECT_TEXT: Dict[str, str] = {
+ "model": "Agent is running — wait or /stop first, then switch models.",
+ "codex-runtime": ("Agent is running — wait or /stop first, then "
+ "change runtime."),
+ "moa": "Agent is running — wait or /stop first, then run /moa.",
+ }
- from agent.auxiliary_client import scoped_runtime_main
+ async def _dispatch_busy_slash_command(
+ self, event: MessageEvent, cmd_def, quick_key: str, source,
+ ):
+ """Dispatch a recognized slash command while an agent is running.
- with scoped_runtime_main(vision_runtime):
- message_text = await self._enrich_message_with_vision(
- message_text,
- image_paths,
- )
-
- if audio_paths:
- message_text, _successful_transcripts = await self._enrich_message_with_transcription(
- message_text,
- audio_paths,
- )
- # Echo each successful transcript back to the user immediately
- # when configured. Lets users verify STT quality in real-time,
- # while allowing quiet STT for users who only want the agent to
- # receive the transcription.
- if _successful_transcripts and self._should_echo_stt_transcripts():
- _echo_adapter = self._adapter_for_source(source)
- _echo_meta = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
- if _echo_adapter:
- for _tx in _successful_transcripts:
- try:
- await _echo_adapter.send(
- source.chat_id,
- f'🎙️ "{_tx}"',
- metadata=_echo_meta,
- )
- except Exception as _echo_exc:
- logger.debug(
- "Transcript echo failed (non-fatal): %s", _echo_exc,
- )
- # NOTE: Previously, when transcription failed (e.g. no STT
- # provider configured), the gateway also emitted a hardcoded
- # English notice via `_stt_adapter.send()`. That bypassed the
- # LLM and produced two replies — one pre-canned English clip
- # (which TTS then spoke aloud, in the wrong language) and one
- # correct, localized LLM reply from the enriched message text.
- # The enrichment step now leaves a single neutral marker in the
- # prompt, so the LLM produces one coherent reply in the user's
- # language. The hardcoded send has therefore been removed.
-
- if audio_file_paths:
- from tools.credential_files import to_agent_visible_cache_path as _to_agent_path
- for _apath in audio_file_paths:
- _basename = os.path.basename(_apath)
- _parts = _basename.split("_", 2)
- _display = _parts[2] if len(_parts) >= 3 else _basename
- _display = re.sub(r'[^\w.\- ]', '_', _display)
- _agent_path = _to_agent_path(_apath)
- _note = (
- f"[The user sent an audio file attachment: '{_display}'. "
- f"It is saved at: {_agent_path}. "
- f"Its content is not inlined here. If the user's request involves "
- f"what the audio contains, transcribe or process it yourself — for "
- f"example by passing the path to a transcription or media tool — "
- f"instead of asking the user to describe it. Only ask what to do "
- f"with it if their intent is genuinely unclear.]"
- )
- message_text = f"{_note}\n\n{message_text}"
+ Resolution order:
+ 1. ``busy_handler`` — special mid-run variant (e.g. /goal's
+ control-verb whitelist, /queue's FIFO enqueue, /model's
+ custom reject text).
+ 2. ``busy_policy == "dispatch"`` — the command's normal handler.
+ 3. Catch-all busy-reject text. Rejecting is required rather than
+ falling through to interrupt + discard: commands like /model,
+ /reasoning, /voice, /insights, /title, /resume, /retry,
+ /undo, /compress, /usage, /reload-mcp, /sethome, /reset (all
+ registered as Discord slash commands) would interrupt the
+ agent AND get silently discarded by the slash-command safety
+ net, producing a zero-char response. See #5057, #6252, #10370.
+ """
+ name = cmd_def.name
+ policy = getattr(cmd_def, "busy_policy", "reject")
+ handler_key = getattr(cmd_def, "busy_handler", None)
- if video_paths:
- from tools.credential_files import to_agent_visible_cache_path as _to_agent_path
- for _vpath in video_paths:
- _basename = os.path.basename(_vpath)
- _parts = _basename.split("_", 2)
- _display = _parts[2] if len(_parts) >= 3 else _basename
- _display = re.sub(r'[^\w.\- ]', '_', _display)
- _agent_path = _to_agent_path(_vpath)
- _note = (
- f"[The user sent a video attachment: '{_display}'. "
- f"It is saved at: {_agent_path}. "
- f"Its content is not inlined here. If the user's request involves "
- f"what the video contains, inspect or process it yourself — for "
- f"example by passing the path to a video analysis or media tool — "
- f"instead of asking the user to describe it. Only ask what to do "
- f"with it if their intent is genuinely unclear.]"
- )
- message_text = f"{_note}\n\n{message_text}"
+ if handler_key:
+ special = {
+ "start": self._busy_start_command,
+ "stop": self._busy_stop_command,
+ "new": self._busy_new_command,
+ "queue": self._busy_queue_command,
+ "steer": self._busy_steer_command,
+ "egress": self._busy_egress_command,
+ "goal": self._busy_goal_command,
+ }.get(handler_key)
+ if special is not None:
+ return await special(event, quick_key, source)
+ reject_text = self._BUSY_REJECT_TEXT.get(handler_key)
+ if reject_text is not None:
+ return reject_text
- if event.media_urls:
- import mimetypes as _mimetypes
- from tools.credential_files import to_agent_visible_cache_path
+ if policy in ("dispatch", "interrupt_then_dispatch"):
+ plain = {
+ "status": self._handle_status_command,
+ "context": self._handle_context_command,
+ "restart": self._handle_restart_command,
+ "approve": self._handle_approve_command,
+ "deny": self._handle_deny_command,
+ "agents": self._handle_agents_command,
+ "background": self._handle_background_command,
+ "kanban": self._handle_kanban_command,
+ "subgoal": self._handle_subgoal_command,
+ "yolo": self._handle_yolo_command,
+ "verbose": self._handle_verbose_command,
+ "footer": self._handle_footer_command,
+ "help": self._handle_help_command,
+ "commands": self._handle_commands_command,
+ "profile": self._handle_profile_command,
+ "update": self._handle_update_command,
+ "version": self._handle_version_command,
+ }.get(name)
+ if plain is not None:
+ return await plain(event)
+ logger.warning(
+ "busy_policy=%s for /%s has no mid-run handler — "
+ "falling back to busy-reject", policy, name,
+ )
- _TEXT_EXTENSIONS = {".txt", ".md", ".csv", ".log", ".json", ".xml", ".yaml", ".yml", ".toml", ".ini", ".cfg"}
- for i, path in enumerate(event.media_urls):
- # Per-attachment document handling. Skip anything already routed
- # as image / audio / video by the buckets above — only genuine
- # non-media files get a path-pointing context note. This makes a
- # document mixed into a PHOTO/VOICE message (whole-message type
- # != DOCUMENT) still reach the agent as a readable cached file,
- # instead of being silently dropped because the message-level
- # type wasn't DOCUMENT.
- if (
- _event_media_is_image(event, i)
- or _event_media_is_audio(event, i)
- or _event_media_is_video(event, i)
- ):
- continue
- mtype = event.media_types[i] if i < len(event.media_types) else ""
- if mtype in {"", "application/octet-stream"}:
- _ext = os.path.splitext(path)[1].lower()
- if _ext in _TEXT_EXTENSIONS:
- mtype = "text/plain"
- else:
- guessed, _ = _mimetypes.guess_type(path)
- if guessed:
- mtype = guessed
- else:
- mtype = "application/octet-stream"
- # Any accepted file gets a path-pointing context note — we accept
- # all file types now, so a non-text/non-application MIME (font/*,
- # model/*, etc.) must still tell the agent the file exists.
+ # Catch-all: any other recognized slash command reached the
+ # running-agent guard. Reject gracefully rather than falling
+ # through to interrupt + discard.
+ return (
+ f"⏳ Agent is running — `/{name}` can't run "
+ f"mid-turn. Wait for the current response or `/stop` first."
+ )
- basename = os.path.basename(path)
- parts = basename.split("_", 2)
- display_name = parts[2] if len(parts) >= 3 else basename
- display_name = re.sub(r'[^\w.\- ]', '_', display_name)
+ async def _busy_start_command(self, event: MessageEvent, quick_key: str, source):
+ # Telegram sends /start for bot launches/deep-links. Treat it as a
+ # platform ping, not a user command: no help dump, no agent
+ # interrupt, no queued text.
+ logger.info("Ignoring /start platform ping for active session %s", quick_key)
+ return ""
- # Translate host cache path to in-container path if running under Docker backend.
- # This ensures the agent receives a path it can open inside its sandbox, as the
- # cache directories are auto-mounted at /root/.hermes/cache/* by get_cache_directory_mounts().
- agent_path = to_agent_visible_cache_path(path)
+ async def _busy_egress_command(self, event: MessageEvent, quick_key: str, source):
+ from hermes_cli.proxy_cli import format_status_text
- context_note = _build_document_context_note(display_name, agent_path, mtype)
- message_text = f"{context_note}\n\n{message_text}"
+ return format_status_text()
- # Discord: surface the triggering message id per-turn on the user
- # message rather than in the cached system prompt. message_id changes
- # every turn, so baking it into build_session_context_prompt() would
- # bust the agent-cache signature and rebuild the AIAgent every message
- # (destroying prompt caching). The static IDs block points the agent
- # here; the volatile id rides the per-turn user content.
- if (
- source is not None
- and getattr(source, "platform", None) == Platform.DISCORD
- and getattr(event, "message_id", None)
- ):
- from gateway.session import _discord_tools_loaded as _disc_tools_loaded
- if _disc_tools_loaded():
- message_text = (
- f"[Triggering message id: `{event.message_id}` — use as "
- f"`message_id` for reply/react/pin via the discord tools.]\n\n"
- f"{message_text}"
- )
+ async def _busy_stop_command(self, event: MessageEvent, quick_key: str, source):
+ # /stop must hard-kill the session when an agent is running.
+ # A soft interrupt (agent.interrupt()) doesn't help when the agent
+ # is truly hung — the executor thread is blocked and never checks
+ # _interrupt_requested. Force-clean _running_agents so the session
+ # is unlocked and subsequent messages are processed normally.
+ await self._interrupt_and_clear_session(
+ quick_key,
+ source,
+ interrupt_reason=_INTERRUPT_REASON_STOP,
+ invalidation_reason="stop_command",
+ )
+ logger.info("STOP for session %s — agent interrupted, session lock released", quick_key)
+ return EphemeralReply(t("gateway.stop.stopped"))
- if getattr(event, "reply_to_text", None) and event.reply_to_message_id:
- # Always inject the reply-to pointer — even when the quoted text
- # already appears in history. The prefix isn't deduplication, it's
- # disambiguation: it tells the agent *which* prior message the user
- # is referencing. History can contain the same or similar text
- # multiple times, and without an explicit pointer the agent has to
- # guess (or answer for both subjects). Token overhead is minimal.
- reply_snippet = event.reply_to_text[:500]
- if getattr(event, "reply_to_is_own_message", False):
- message_text = (
- f'[Replying to your previous message: "{reply_snippet}"]\n\n'
- f"{message_text}"
- )
- else:
- message_text = f'[Replying to: "{reply_snippet}"]\n\n{message_text}'
+ async def _busy_new_command(self, event: MessageEvent, quick_key: str, source):
+ # /reset and /new must bypass the running-agent guard so they
+ # actually dispatch as commands instead of being queued as user
+ # text (which would be fed back to the agent with the same
+ # broken history — #2170). Interrupt the agent first, then
+ # clear the adapter's pending queue so the stale "/reset" text
+ # doesn't get re-processed as a user message after the
+ # interrupt completes.
+ # Clear any pending messages so the old text doesn't replay
+ await self._interrupt_and_clear_session(
+ quick_key,
+ source,
+ interrupt_reason=_INTERRUPT_REASON_RESET,
+ invalidation_reason="new_command",
+ )
+ # Clean up the running agent entry so the reset handler
+ # doesn't think an agent is still active.
+ return await self._handle_reset_command(event)
- if "@" in message_text:
- try:
- from agent.context_references import preprocess_context_references_async
- from agent.model_metadata import get_model_context_length_async
-
- _msg_cwd = os.environ.get("TERMINAL_CWD", os.path.expanduser("~"))
- _msg_config_ctx = None
- _msg_cfg = None
- _msg_model_cfg = {}
- _msg_custom_providers = []
- try:
- _msg_cfg = _load_gateway_config()
- _msg_model_cfg = _msg_cfg.get("model", {})
- if isinstance(_msg_model_cfg, dict):
- _msg_raw_ctx = _msg_model_cfg.get("context_length")
- if _msg_raw_ctx is not None:
- _msg_config_ctx = int(_msg_raw_ctx)
- try:
- from hermes_cli.config import get_compatible_custom_providers
-
- _msg_custom_providers = get_compatible_custom_providers(_msg_cfg)
- except Exception:
- _msg_custom_providers = _msg_cfg.get("custom_providers") or []
- except Exception:
- pass
- # Resolve the session's actual model/provider/base_url the
- # same way the hygiene compression block does (~11080).
- # GatewayRunner has no self._model/self._base_url attrs
- # (that was copy-pasted from HermesCLI, which does carry
- # self.model/self.base_url), so using them here always raised
- # AttributeError, silently caught below, meaning this feature
- # never ran.
- _msg_model, _msg_runtime = self._resolve_session_agent_runtime(
- source=source,
- session_key=session_key,
- user_config=_msg_cfg,
- )
- _msg_base_url = _msg_runtime.get("base_url") or ""
- # A global model.context_length belongs to the configured
- # model, not a session /model or channel override. Prefer a
- # matching per-custom-provider model limit when available.
- _msg_configured_model = (
- _msg_model_cfg.get("default") or _msg_model_cfg.get("model")
- if isinstance(_msg_model_cfg, dict)
- else _msg_model_cfg
- )
- if _msg_model != _msg_configured_model:
- _msg_config_ctx = None
- if _msg_config_ctx is not None and isinstance(_msg_model_cfg, dict):
- try:
- from hermes_cli.route_identity import should_clear_context_pin_async
-
- if await should_clear_context_pin_async(
- None, # model match already checked above
- None,
- _msg_model_cfg.get("base_url"),
- _msg_base_url,
- _msg_model_cfg.get("provider"),
- _msg_runtime.get("provider"),
- ):
- _msg_config_ctx = None
- except Exception:
- _msg_config_ctx = None
- if _msg_custom_providers and _msg_base_url:
- try:
- from hermes_cli.config import get_custom_provider_context_length
+ async def _busy_queue_command(self, event: MessageEvent, quick_key: str, source):
+ # /queue <prompt> — queue without interrupting.
+ # Semantics: each /queue invocation produces its own full agent
+ # turn, processed in FIFO order after the current run (and any
+ # earlier /queue items) finishes. Messages are NOT merged.
+ queued_text = event.get_command_args().strip()
+ # Preserve media/reply payloads: a /queue carrying a photo,
+ # document, or reply context is valid even with no prompt text
+ # (e.g. "/queue" as the caption of an image). Dropping these
+ # fields silently lost the attachment when the queued turn ran.
+ has_media = bool(getattr(event, "media_urls", None))
+ if not queued_text and not has_media:
+ return "Usage: /queue <prompt>"
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ queued_event = MessageEvent(
+ text=queued_text,
+ message_type=event.message_type if has_media else MessageType.TEXT,
+ source=event.source,
+ raw_message=event.raw_message,
+ message_id=event.message_id,
+ media_urls=list(getattr(event, "media_urls", []) or []),
+ media_types=list(getattr(event, "media_types", []) or []),
+ reply_to_message_id=event.reply_to_message_id,
+ reply_to_text=event.reply_to_text,
+ reply_to_author_id=event.reply_to_author_id,
+ reply_to_author_name=event.reply_to_author_name,
+ reply_to_is_own_message=event.reply_to_is_own_message,
+ auto_skill=event.auto_skill,
+ channel_prompt=event.channel_prompt,
+ channel_context=event.channel_context,
+ internal=event.internal,
+ timestamp=event.timestamp,
+ )
+ self._enqueue_fifo(quick_key, queued_event, adapter)
+ depth = self._queue_depth(quick_key, adapter=self._adapter_for_source(source))
+ if depth <= 1:
+ return "Queued for the next turn."
+ return f"Queued for the next turn. ({depth} queued)"
- _msg_custom_ctx = get_custom_provider_context_length(
- model=_msg_model,
- base_url=_msg_base_url,
- custom_providers=_msg_custom_providers,
- )
- if _msg_custom_ctx:
- _msg_config_ctx = _msg_custom_ctx
- except Exception:
- pass
- _msg_ctx_len = await get_model_context_length_async(
- _msg_model,
- base_url=_msg_base_url,
- api_key=_msg_runtime.get("api_key") or "",
- config_context_length=_msg_config_ctx,
- provider=_msg_runtime.get("provider") or "",
- custom_providers=_msg_custom_providers,
- )
- _ctx_result = await preprocess_context_references_async(
- message_text,
- cwd=_msg_cwd,
- context_length=_msg_ctx_len,
- allowed_root=_msg_cwd,
+ async def _busy_steer_command(self, event: MessageEvent, quick_key: str, source):
+ # /steer <prompt> — inject mid-run after the next tool call.
+ # Unlike /queue (turn boundary), /steer lands BETWEEN tool-call
+ # iterations inside the same agent run, by appending to the
+ # last tool result's content. No interrupt, no new user turn,
+ # no role-alternation violation.
+ steer_text = event.get_command_args().strip()
+ if not steer_text:
+ return "Usage: /steer <prompt>"
+ _steer_state = self._peek_session_state(quick_key)
+ running_agent = _steer_state.turn.agent if _steer_state else None
+ if running_agent is _AGENT_PENDING_SENTINEL:
+ # Agent hasn't started yet — queue as turn-boundary fallback.
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ queued_event = MessageEvent(
+ text=steer_text,
+ message_type=MessageType.TEXT,
+ source=event.source,
+ message_id=event.message_id,
+ channel_prompt=event.channel_prompt,
+ channel_context=event.channel_context,
)
- if _ctx_result.blocked:
- _adapter = self._adapter_for_source(source)
- if _adapter:
- await _adapter.send(
- source.chat_id,
- "\n".join(_ctx_result.warnings) or "Context injection refused.",
- )
- return None
- if _ctx_result.expanded:
- message_text = _ctx_result.message
+ adapter._pending_messages[quick_key] = queued_event
+ return "Agent still starting — /steer queued for the next turn."
+ if running_agent and hasattr(running_agent, "steer"):
+ try:
+ accepted = running_agent.steer(steer_text)
except Exception as exc:
- logger.warning("@ context reference expansion failed: %s", exc)
- logger.debug("@ context reference expansion failure detail", exc_info=True)
-
- return message_text
+ logger.warning("Steer failed for session %s: %s", quick_key, exc)
+ return f"⚠️ Steer failed: {exc}"
+ if accepted:
+ preview = steer_text[:60] + ("..." if len(steer_text) > 60 else "")
+ return f"⏩ Steer queued — arrives after the next tool call: '{preview}'"
+ return "Steer rejected (empty payload)."
+ # Running agent is missing or lacks steer() — fall back to queue.
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ queued_event = MessageEvent(
+ text=steer_text,
+ message_type=MessageType.TEXT,
+ source=event.source,
+ message_id=event.message_id,
+ channel_prompt=event.channel_prompt,
+ channel_context=event.channel_context,
+ )
+ adapter._pending_messages[quick_key] = queued_event
+ return "No active agent — /steer queued for the next turn."
- async def _prepare_profile_scoped_inbound_message_text(
- self,
- *,
- event: MessageEvent,
- source: SessionSource,
- history: List[Dict[str, Any]],
- session_key: Optional[str] = None,
- ) -> Optional[str]:
- """Run inbound preprocessing under the routed profile when multiplexed."""
- if getattr(getattr(self, "config", None), "multiplex_profiles", False):
- with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):
- return await self._prepare_inbound_message_text(
- event=event,
- source=source,
- history=history,
- session_key=session_key,
- )
- return await self._prepare_inbound_message_text(
- event=event,
- source=source,
- history=history,
- session_key=session_key,
+ async def _busy_goal_command(self, event: MessageEvent, quick_key: str, source):
+ # /goal is safe mid-run for status/pause/clear/wait (inspection
+ # and control-plane only — doesn't interrupt the running turn).
+ # Setting a new goal text mid-run is rejected with the same
+ # "wait or /stop" message as /model so we don't race a second
+ # continuation prompt against the current turn.
+ _goal_arg = (event.get_command_args() or "").strip().lower()
+ _goal_verb = _goal_arg.split(None, 1)[0] if _goal_arg else ""
+ # Exact-match control verbs (unchanged semantics), plus the
+ # wait/unwait barrier verbs which take a pid argument.
+ _is_control = (
+ not _goal_arg
+ or _goal_arg in {"status", "pause", "resume", "clear", "stop", "done", "unwait"}
+ or _goal_verb == "wait"
)
+ if _is_control:
+ return await self._handle_goal_command(event)
+ return "Agent is running — use /goal status / pause / clear / wait mid-run, or /stop before setting a new goal."
- async def _prepare_clarify_reply_text(self, event) -> str:
- """Return raw text or successful voice transcripts for a clarify reply."""
- if not self._pending_event_audio_paths(event):
- return (event.text or "").strip()
-
- _, successful_transcripts = await self._transcribe_pending_audio_event_once(
- event, "",
- )
- return "\n\n".join(
- transcript.strip()
- for transcript in successful_transcripts
- if transcript.strip()
- )
+ async def _handle_message(self, event: MessageEvent) -> Optional[str]:
+ """
+ Handle an incoming message from any platform.
+
+ This is the core message processing pipeline:
+ 1. Check user authorization
+ 2. Check for commands (/new, /reset, etc.)
+ 3. Check for running agent and interrupt if needed
+ 4. Get or create session
+ 5. Build context for agent
+ 6. Run agent conversation
+ 7. Return response
+ """
+ source = event.source
- def _consume_pending_native_image_paths(self, session_key: str) -> List[str]:
- state = self._peek_session_state(session_key)
- if state is None or not state.persistent.native_image_paths:
- return []
- paths = list(state.persistent.native_image_paths)
- state.persistent.native_image_paths = []
- return paths
-
- def _cache_session_source(self, session_key: str, source) -> None:
- if not session_key or source is None:
- return
- cached_sources = getattr(self, "_session_sources", None)
- if cached_sources is None:
- cached_sources = OrderedDict()
- self._session_sources = cached_sources
- try:
- cached_sources[session_key] = dataclasses.replace(source)
- except Exception:
- logger.debug("Failed to cache live session source for %s", session_key, exc_info=True)
- return
- # LRU: mark as most-recently-used and trim to max size.
+ # 🔴 Cross-session leak guard. This handler runs inside a per-message
+ # asyncio task created via create_task(), which snapshots the spawning
+ # context with copy_context(). If a *concurrent* message had already
+ # bound its session via set_session_vars() when this task was created,
+ # we inherited ITS HERMES_SESSION_* ContextVars. Until we bind our own
+ # (a few steps down, in _set_session_env), any subprocess spawned here
+ # would read the foreign session's identity via the subprocess-env
+ # bridge — the _UNSET-strip guard there can't help because the vars are
+ # set-to-foreign, not _UNSET. Reset to _UNSET now so that window strips
+ # safe (no session) instead of leaking the sibling's. See
+ # gateway/session_context.reset_session_vars + the inheritance test.
try:
- cached_sources.move_to_end(session_key)
- max_size = getattr(self, "_session_sources_max", 512)
- while len(cached_sources) > max_size:
- cached_sources.popitem(last=False)
+ from gateway.session_context import reset_session_vars
+ reset_session_vars()
except Exception:
- pass
+ logger.debug("reset_session_vars failed at handler entry", exc_info=True)
- @property
- def async_session_store(self) -> AsyncSessionStore:
- """Return the single async facade for this runner's SessionStore."""
- facade = getattr(self, "_async_session_store", None)
- if facade is None or facade._store is not self.session_store:
- facade = AsyncSessionStore(self.session_store)
- self._async_session_store = facade
- return facade
+ # Internal events (e.g. background-process completion notifications)
+ # are system-generated and must skip user authorization.
+ is_internal = bool(getattr(event, "internal", False))
- def _get_cached_session_source(self, session_key: str):
- if not session_key:
+ # Ignored-channel guard runs FIRST — before startup-restore queueing,
+ # plugin hooks, auth, and session setup — so a configured ignored
+ # channel can never reach pairing/auth/session state (#51899).
+ # getattr: bare test runners construct GatewayRunner via
+ # object.__new__ without config (see AGENTS.md pitfall on
+ # object.__new__ test pattern).
+ if (
+ not is_internal
+ and getattr(source, "platform", None) == Platform.SLACK
+ and _is_slack_ignored_channel(
+ getattr(self, "config", None), getattr(source, "chat_id", None)
+ )
+ ):
+ logger.info(
+ "Dropping Slack message from configured ignored channel %s",
+ getattr(source, "chat_id", None),
+ )
return None
- cached_sources = getattr(self, "_session_sources", None)
- if not cached_sources:
+
+ if (
+ getattr(self, "_startup_restore_in_progress", False)
+ and not is_internal
+ and not getattr(event, "_hermes_startup_restore_replay", False)
+ ):
+ self._queue_startup_restore_event(event)
return None
- source = cached_sources.get(session_key)
- if source is not None:
- try:
- cached_sources.move_to_end(session_key)
- except Exception:
- pass
- return source
- async def _handle_message_with_agent(self, event, source, _quick_key: str, run_generation: int):
- """Inner handler that runs under the _running_agents sentinel guard."""
- _msg_start_time = time.time()
- _platform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform)
- _msg_preview = (event.text or "")[:80].replace("\n", " ")
- _reply_id = getattr(event, "reply_to_message_id", None)
- _reply_txt = (getattr(event, "reply_to_text", None) or "")[:80].replace("\n", " ")
- logger.info(
- "inbound message: platform=%s user=%s chat=%s msg=%r reply_to_id=%s reply_to_text=%r",
- _platform_name, source.user_name or source.user_id or "unknown",
- source.chat_id or "unknown", _msg_preview, _reply_id, _reply_txt,
- )
+ # scale-to-zero (Phase 0, 0.B/F13): stamp the gateway-scoped last-inbound
+ # clock for real (user-originated) inbound only. Internal/system events
+ # (background-process completions, startup-restore replays) are NOT
+ # traffic — counting them would keep a genuinely idle gateway awake. This
+ # clock is what the idle predicate (gateway/scale_to_zero.is_idle) reads.
+ if not is_internal:
+ self._scale_to_zero_note_real_inbound()
- # Get or create session
- # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's
- # last-active topic so a cross-topic Reply or stripped plain reply
- # doesn't fragment the conversation across sessions.
- recovered = await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
- if recovered is not None:
- logger.info(
- "telegram topic recovery: chat=%s user=%s %r -> %s",
- source.chat_id, source.user_id, source.thread_id, recovered,
- )
- source = dataclasses.replace(source, thread_id=recovered)
+ # Fire pre_gateway_dispatch plugin hook for user-originated messages.
+ # Plugins receive the MessageEvent and may return a dict influencing flow:
+ # {"action": "skip", "reason": ...} -> drop (no reply, plugin handled)
+ # {"action": "rewrite", "text": ...} -> replace event.text, continue
+ # {"action": "allow"} / None -> normal dispatch
+ # Hook runs BEFORE auth so plugins can handle unauthorized senders
+ # (e.g. customer handover ingest) without triggering the pairing flow.
+ if not is_internal:
try:
- event.source = source
- except Exception:
- pass
+ from hermes_cli.lifecycle import invoke_hook as _invoke_hook
+ _hook_results = _invoke_hook(
+ "pre_gateway_dispatch",
+ event=event,
+ gateway=self,
+ # getattr: bare-runner tests build GatewayRunner via
+ # object.__new__ without __init__ (pitfall #17), and the
+ # hook must not fail dispatch over a missing attribute.
+ session_store=getattr(self, "session_store", None),
+ )
+ except Exception as _hook_exc:
+ logger.warning("pre_gateway_dispatch invocation failed: %s", _hook_exc)
+ _hook_results = []
- session_entry = await self.async_session_store.get_or_create_session(source)
- session_key = session_entry.session_key
- pinned_session_id = str(
- (getattr(event, "metadata", None) or {}).get("gateway_session_id") or ""
- ).strip()
- if pinned_session_id:
- resolved_entry = await self._resolve_async_delegation_session(
- session_entry,
- pinned_session_id,
- )
- if resolved_entry is None:
- return
- session_entry = resolved_entry
- self._cache_session_source(session_key, source)
- if await asyncio.to_thread(self._is_telegram_topic_lane, source):
- try:
- binding = (await self._session_db.get_telegram_topic_binding(
- chat_id=str(source.chat_id),
- thread_id=str(source.thread_id),
- )) if self._session_db else None
- except Exception:
- logger.debug("Failed to read Telegram topic binding", exc_info=True)
- binding = None
- if binding:
- bound_session_id = str(binding.get("session_id") or "")
- # Heal bindings that point at a pre-compression parent: walk
- # the compression-continuation chain forward to its tip so the
- # next message resumes the compressed child instead of
- # reloading the oversized parent transcript (#20470/#29712/
- # #33414). Returns the input unchanged when the session isn't
- # a compression parent, so this is cheap and safe.
- if bound_session_id and self._session_db is not None:
- try:
- canonical_session_id = await self._session_db.get_compression_tip(
- bound_session_id,
+ for _result in _hook_results:
+ if not isinstance(_result, dict):
+ continue
+ _action = _result.get("action")
+ if _action == "skip":
+ logger.info(
+ "pre_gateway_dispatch skip: reason=%s platform=%s chat=%s",
+ _result.get("reason"),
+ source.platform.value if source.platform else "unknown",
+ source.chat_id or "unknown",
+ )
+ return None
+ if _action == "rewrite":
+ _new_text = _result.get("text")
+ if isinstance(_new_text, str):
+ event = dataclasses.replace(event, text=_new_text)
+ source = event.source
+ break
+ if _action == "allow":
+ break
+
+ if is_internal:
+ pass
+ elif source.user_id is None:
+ # Messages with no user identity (Telegram service messages,
+ # channel forwards, anonymous admin posts, sender_chat) can't
+ # be paired, but they can still be authorized via a
+ # chat-scoped allowlist (e.g. TELEGRAM_GROUP_ALLOWED_CHATS
+ # authorizes every member of the listed chat regardless of
+ # sender). Defer to _is_user_authorized so that path runs.
+ if not self._is_user_authorized(source):
+ logger.debug("Ignoring message with no user_id from %s", source.platform.value)
+ return None
+ elif not self._is_user_authorized(source):
+ logger.warning("Unauthorized user: %s (%s) on %s", source.user_id, source.user_name, source.platform.value)
+ # In DMs: offer pairing code. In groups: silently ignore.
+ if (
+ source.chat_type == "dm"
+ and self._get_unauthorized_dm_behavior(
+ source.platform,
+ profile=source.profile,
+ )
+ == "pair"
+ ):
+ platform_name = source.platform.value if source.platform else "unknown"
+ # Rate-limit ALL pairing responses (code or rejection) to
+ # prevent spamming the user with repeated messages when
+ # multiple DMs arrive in quick succession.
+ if self.pairing_store._is_rate_limited(platform_name, source.user_id):
+ return None
+ code = self.pairing_store.generate_code(
+ platform_name, source.user_id, source.user_name or ""
+ )
+ if code:
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ await adapter.send(
+ source.chat_id,
+ f"Hi~ I don't recognize you yet!\n\n"
+ f"Here's your pairing code: `{code}`\n\n"
+ f"Ask the bot owner to run:\n"
+ f"`hermes pairing approve {platform_name} {code}`"
)
- except Exception:
- logger.debug(
- "compression-tip lookup failed for %s",
- bound_session_id, exc_info=True,
+ else:
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ await adapter.send(
+ source.chat_id,
+ "Too many pairing requests right now~ "
+ "Please try again later!"
)
- canonical_session_id = bound_session_id
- if (
- canonical_session_id
- and canonical_session_id != bound_session_id
- ):
- bound_session_id = canonical_session_id
- if bound_session_id and bound_session_id != session_entry.session_id:
- # Route the override through SessionStore so the session_key
- # → session_id mapping is persisted to disk and the previous
- # lane session is ended cleanly. Mutating session_entry in
- # place here created a split-brain state where the JSON
- # index pointed at one id but code downstream used another.
- switched = await self.async_session_store.switch_session(session_key, bound_session_id)
- if switched is not None:
- session_entry = switched
- # If the stored binding pointed at a parent, rewrite it to the
- # canonical descendant now that we've followed the chain.
- if (
- bound_session_id
- and bound_session_id != str(binding.get("session_id") or "")
- ):
- await asyncio.to_thread(
- self._sync_telegram_topic_binding,
- source, session_entry, reason="compression-tip-walk",
- )
+ # Record rate limit so subsequent messages are silently ignored
+ self.pairing_store._record_rate_limit(platform_name, source.user_id)
+ return None
+
+ # 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
+ # .update_response so the update process can continue.
+ #
+ # IMPORTANT: recognized slash commands must bypass this interception.
+ # Otherwise control/session commands like /new or /help get silently
+ # consumed as update answers instead of being dispatched normally.
+ _quick_key = self._session_key_for_source(source)
+ _up_state = self._peek_session_state(_quick_key)
+ if _up_state is not None and _up_state.persistent.update_prompt_pending:
+ raw = (event.text or "").strip()
+ # Accept /approve and /deny as shorthand for yes/no
+ cmd = event.get_command()
+ if cmd in {"approve", "yes"}:
+ response_text = "y"
+ elif cmd in {"deny", "no"}:
+ response_text = "n"
else:
+ _recognized_cmd = None
+ if cmd:
+ try:
+ from hermes_cli.commands import resolve_command as _resolve_update_cmd
+ except Exception:
+ _resolve_update_cmd = None
+ if _resolve_update_cmd is not None:
+ try:
+ _cmd_def = _resolve_update_cmd(cmd)
+ _recognized_cmd = _cmd_def.name if _cmd_def else None
+ except Exception:
+ _recognized_cmd = None
+ if _recognized_cmd:
+ response_text = ""
+ else:
+ response_text = raw
+ if response_text:
+ response_path = _hermes_home / ".update_response"
+ prompt_path = _hermes_home / ".update_prompt.json"
try:
- await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)
- except Exception:
- logger.debug("Failed to record Telegram topic binding", exc_info=True)
- # Capture and immediately consume was_auto_reset so it does not
- # re-fire on subsequent messages — preventing the cleanup from
- # wiping model/reasoning overrides set between turns (Closes #48031).
- _was_auto_reset = getattr(session_entry, "was_auto_reset", False)
- if _was_auto_reset:
- # Treat auto-reset as a full conversation boundary — clear every
- # conversation-scoped per-session dict in one funnel call so the
- # fresh session does not inherit the previous conversation's
- # model/reasoning overrides, a queued "/model switched" note, or
- # a stale resolved-model cache (#48031, #58403). See
- # _CONVERSATION_SCOPED_STATE.
- self._clear_conversation_scope(session_key, reason="auto_reset")
- # Evict the cached agent so the fresh session does not inherit the
- # previous conversation's context_compressor._previous_summary —
- # the cache is keyed on the stable session_key, so an auto-reset
- # otherwise reuses the old agent and leaks prior history into new
- # compaction summaries. Mirrors /reset and the compression-exhausted
- # path (#9893). Covers daily/idle/suspended auto-reset.
- self._evict_cached_agent(session_key)
- session_entry.was_auto_reset = False
-
- # Emit session:start for new or auto-reset sessions
- _is_new_session = (
- session_entry.created_at == session_entry.updated_at
- or _was_auto_reset
- or getattr(session_entry, "is_fresh_reset", False)
- )
- # Consume the is_fresh_reset flag immediately so it doesn't leak
- # onto subsequent messages in the same session (issue #6508).
- if getattr(session_entry, "is_fresh_reset", False):
- session_entry.is_fresh_reset = False
- if _is_new_session:
- await self.hooks.emit("session:start", {
- "platform": source.platform.value if source.platform else "",
- "user_id": source.user_id,
- "session_id": session_entry.session_id,
- "session_key": session_key,
- })
-
- # Build session context
- context = build_session_context(source, self.config, session_entry)
-
- # Set session context variables for tools (task-local, concurrency-safe)
- _session_env_tokens = self._set_session_env(context)
-
- # Read privacy.redact_pii from config (re-read per message)
- _redact_pii = False
- persist_user_message = None
- persist_user_timestamp = None
+ tmp = response_path.with_suffix(".tmp")
+ tmp.write_text(response_text, encoding="utf-8")
+ tmp.replace(response_path)
+ prompt_path.unlink(missing_ok=True)
+ except OSError as e:
+ logger.warning("Failed to write update response: %s", e)
+ return f"✗ Failed to send response to update process: {e}"
+ _up_state.persistent.update_prompt_pending = False
+ label = response_text if len(response_text) <= 20 else response_text[:20] + "…"
+ return f"✓ Sent `{label}` to the update process."
+ # Recognized slash command during a pending update prompt:
+ # unblock the detached update subprocess by writing a blank
+ # response so ``_gateway_prompt`` returns the prompt's default
+ # (typically a safe "n" / skip) and exits cleanly instead of
+ # blocking on stdin until the 30-minute watcher timeout.
+ # The slash command then falls through to normal dispatch.
+ if _recognized_cmd:
+ response_path = _hermes_home / ".update_response"
+ prompt_path = _hermes_home / ".update_prompt.json"
+ try:
+ tmp = response_path.with_suffix(".tmp")
+ tmp.write_text("", encoding="utf-8")
+ tmp.replace(response_path)
+ prompt_path.unlink(missing_ok=True)
+ logger.info(
+ "Recognized /%s during pending update prompt for %s; "
+ "cancelled prompt with default and dispatching command",
+ _recognized_cmd,
+ _quick_key,
+ )
+ except OSError as e:
+ logger.warning(
+ "Failed to write cancel response for pending update prompt: %s",
+ e,
+ )
+ _up_state.persistent.update_prompt_pending = False
+
+ # Intercept messages that are responses to a pending clarify.
+ # Open-ended prompts and "Other" responses are captured as free text;
+ # direct replies to multi-choice prompts are accepted too ("2" maps
+ # to the second option, arbitrary text becomes a custom answer). Slash
+ # commands still bypass this path so /stop and friends keep working.
+ _clarify_mod = None
try:
- _pcfg = _load_gateway_config()
- _redact_pii = bool((_pcfg.get("privacy") or {}).get("redact_pii", False))
+ from tools import clarify_gateway as _clarify_mod
+ _pending_clarify = _clarify_mod.get_pending_for_session(
+ _quick_key, include_choice_prompts=True,
+ )
except Exception:
- pass
-
- # Build the context prompt to inject. The render is pinned per
- # session, keyed by a hash of the exact renderer inputs
- # (_ephemeral_change_key). A key hit reuses the pinned bytes verbatim
- # so the composed system prompt cannot drift turn-over-turn; a key
- # miss (thread rename, /sethome, redact_pii flip, ...) re-renders
- # once — the only legitimate cache busts.
- context_prompt = self._pinned_session_context_prompt(
- context, _redact_pii, session_key
- )
-
- # Per-turn must-deliver notes. These used to be appended to
- # context_prompt (the ephemeral system prompt), which guaranteed a
- # turn1→turn2 system-prompt diff and a full agent rebuild. They now
- # ride the current user message via the api_content sidecar instead
- # (staged below, consumed in run_sync → build_turn_context).
- turn_sidecar_notes: List[str] = []
-
- # If the previous session expired and was auto-reset, deliver a notice
- # so the agent knows this is a fresh conversation (not an intentional /reset).
- if _was_auto_reset:
- reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'idle'
- if reset_reason == "suspended":
- context_note = "[System note: The user's previous session was stopped and suspended. This is a fresh conversation with no prior context.]"
- elif reset_reason == "daily":
- context_note = "[System note: The user's session was automatically reset by the daily schedule. This is a fresh conversation with no prior context.]"
- elif reset_reason == "resume_pending_expired":
- context_note = "[System note: The previous gateway session could not be recovered after a restart (API recovery timed out). This is a fresh conversation — use /resume to restore history if needed.]"
- else:
- context_note = "[System note: The user's previous session expired due to inactivity. This is a fresh conversation with no prior context.]"
- # Slack/Discord channels/threads are long-lived: point the agent at
- # the specific prior same-channel session so it recalls that context
- # via session_search instead of an unrelated recent session. Returns
- # None (appends nothing) for other platforms or when there's no prior
- # activity to recall. Deterministic — no extra API/DB calls (#36220).
- try:
- continuity_note = build_channel_continuity_note(session_entry, source)
- except Exception:
- continuity_note = None
- if continuity_note:
- context_note = context_note + "\n\n" + continuity_note
- turn_sidecar_notes.append(context_note)
-
- # Send a user-facing notification explaining the reset, unless:
- # - notifications are disabled in config
- # - the platform is excluded (e.g. api_server, webhook)
- # - the expired session had no activity (nothing was cleared)
- try:
- policy = self.session_store.config.get_reset_policy(
- platform=source.platform,
- session_type=getattr(source, 'chat_type', 'dm'),
+ _pending_clarify = None
+ if _pending_clarify is not None and _clarify_mod is not None:
+ _clarify_has_audio = bool(self._pending_event_audio_paths(event))
+ _raw_clarify_reply = await self._prepare_clarify_reply_text(event)
+ if _clarify_has_audio and not _raw_clarify_reply:
+ logger.info(
+ "Gateway retained pending clarify after voice transcription "
+ "produced no usable text (session=%s, id=%s)",
+ _quick_key,
+ _pending_clarify.clarify_id,
)
- platform_name = source.platform.value if source.platform else ""
- had_activity = getattr(session_entry, 'reset_had_activity', False)
- # Suspended and restart-recovery-expired sessions always notify
- # regardless of policy.notify — the user had an active session
- # that was silently replaced, so they need to know they can
- # /resume it. Idle/daily resets respect the policy flag.
- should_notify = reset_reason in {"suspended", "resume_pending_expired"} or (
- policy.notify
- and had_activity
- and platform_name not in policy.notify_exclude_platforms
+ return ""
+ # Skip slash commands — the user clearly wanted to issue a
+ # command, not answer the clarify. Leave the clarify pending
+ # so the user can retry; if it times out, the agent unblocks
+ # with an empty response.
+ if _raw_clarify_reply and not _raw_clarify_reply.startswith("/"):
+ _resolved = _clarify_mod.resolve_text_response_for_session(
+ _quick_key, _raw_clarify_reply,
)
- if should_notify:
- adapter = self._adapter_for_source(source)
- if adapter:
- if reset_reason == "suspended":
- reason_text = "previous session was stopped or interrupted"
- elif reset_reason == "resume_pending_expired":
- reason_text = "gateway restart recovery timed out"
- elif reset_reason == "daily":
- reason_text = f"daily schedule at {policy.at_hour}:00"
- else:
- hours = policy.idle_minutes // 60
- mins = policy.idle_minutes % 60
- duration = f"{hours}h" if not mins else f"{hours}h {mins}m" if hours else f"{mins}m"
- reason_text = f"inactive for {duration}"
- notice = (
- f"◐ Session automatically reset ({reason_text}). "
- f"Conversation history cleared.\n"
- f"Use /resume to browse and restore a previous session.\n"
- f"Adjust reset timing in config.yaml under session_reset."
- )
- try:
- session_info = await asyncio.to_thread(
- self._reset_notice_session_info, source
- )
- if session_info:
- notice = f"{notice}\n\n{session_info}"
- except Exception:
- pass
- await adapter.send(
- source.chat_id, notice,
- metadata=self._thread_metadata_for_source(source),
- )
- except Exception as e:
- logger.debug("Auto-reset notification failed (non-fatal): %s", e)
-
- # was_auto_reset is already consumed in the cleanup block above
- # (single source of truth); only the reset reason needs clearing here.
- session_entry.auto_reset_reason = None
-
- # Auto-load skill(s) for topic/channel bindings (Telegram DM Topics,
- # Discord channel_skill_bindings). Supports a single name or ordered list.
- # Only inject on NEW sessions — ongoing conversations already have the
- # skill content in their conversation history from the first message.
- _auto = getattr(event, "auto_skill", None)
- if _is_new_session and _auto:
- _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)
- try:
- from agent.skill_commands import _load_skill_payload, _build_skill_message
- _combined_parts: list[str] = []
- _loaded_names: list[str] = []
- for _sname in _skill_names:
- _loaded = _load_skill_payload(_sname, task_id=_quick_key)
- if _loaded:
- _loaded_skill, _skill_dir, _display_name = _loaded
- _note = (
- f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '
- f"Follow its instructions for this session.]"
- )
- _part = _build_skill_message(_loaded_skill, _skill_dir, _note)
- if _part:
- _combined_parts.append(_part)
- _loaded_names.append(_sname)
- else:
- logger.warning("[Gateway] Auto-skill '%s' not found", _sname)
- if _combined_parts:
- # Append the user's original text after all skill payloads
- _combined_parts.append(event.text)
- event.text = "\n\n".join(_combined_parts)
+ if _resolved:
logger.info(
- "[Gateway] Auto-loaded skill(s) %s for session %s",
- _loaded_names, session_key,
+ "Gateway intercepted clarify text response (session=%s, id=%s)",
+ _quick_key, _pending_clarify.clarify_id,
)
- except Exception as e:
- logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)
-
- # ── Turn lease (#64934) ────────────────────────────────────────
- # Session resolution is FINAL here (get_or_create → async-delegation
- # pinning → topic tip-walk switch_session are all above). Serialize
- # the [load history → run → flush] region per resolved SESSION_ID:
- # when a second routing key is mapped to this same session_id, its
- # turn waits here for the previous turn's flush instead of loading a
- # stale history base and interleaving transcript writes. Same-key
- # messages never reach this point mid-turn (adapter + runner guards
- # hold them), so the lock is uncontended outside the alias-key route.
- # Fail-open: on timeout the token comes back degraded and the turn
- # proceeds unserialized (never a wedged session). Released in
- # _handle_message's finally via _release_turn_lease — granted per
- # (routing key, run generation) so a stale unwind can't release a
- # newer turn's lease.
- _lease_registry = getattr(self, "_turn_leases", None)
- if _lease_registry is not None:
- _lease_token = await _lease_registry.acquire(
- session_entry.session_id,
- owner_key=_quick_key,
- generation=run_generation,
- timeout=_float_env("HERMES_AGENT_TIMEOUT", 1800),
- )
- if _lease_token is not None:
- _lease_state = self._session_state(_quick_key).turn
- _lease_state.lease_token = _lease_token
- _lease_state.lease_generation = run_generation
+ # The clarify callback pauses the platform typing/status
+ # indicator while waiting so Slack users can type their
+ # answer. The active agent resumes as soon as this reply
+ # resolves the wait, so re-enable its indicator here too.
+ # Without this, Slack stays silent until the independent
+ # long-running heartbeat fires (three minutes by default).
+ _clarify_adapter = self._adapter_for_source(source)
+ if _clarify_adapter:
+ try:
+ _clarify_adapter.resume_typing_for_chat(source.chat_id)
+ except Exception:
+ logger.debug(
+ "Failed to resume typing after clarify response",
+ exc_info=True,
+ )
+ # Acknowledge with empty string so adapters that emit
+ # the agent's response don't double-post. The agent
+ # itself will produce the next user-facing message.
+ return ""
- # Load conversation history from transcript
- history = await self.async_session_store.load_transcript(session_entry.session_id)
-
- # -----------------------------------------------------------------
- # Session hygiene: auto-compress pathologically large transcripts
+ # Intercept messages that are responses to a pending /reload-mcp
+ # (or future) slash-confirm prompt. Recognized confirm replies are
+ # /approve, /always, /cancel (plus short aliases). Anything else
+ # falls through to normal dispatch — a stale pending confirm does
+ # NOT block other commands.
#
- # Long-lived gateway sessions can accumulate enough history that
- # every new message rehydrates an oversized transcript, causing
- # repeated truncation/context failures. Detect this early and
- # compress proactively — before the agent even starts. (#628)
+ # Important: if a dangerous-command approval is ALSO pending (agent
+ # blocked inside tools/approval.py), the tool approval takes
+ # precedence — /approve there unblocks the waiting tool thread.
+ # Slash-confirm only catches /approve when no tool approval is live.
+ from tools import slash_confirm as _slash_confirm_mod
+ _pending_confirm = _slash_confirm_mod.get_pending(_quick_key)
+ _tool_approval_live = False
+ try:
+ from tools.approval import has_blocking_approval
+ _tool_approval_live = has_blocking_approval(_quick_key)
+ except Exception:
+ _tool_approval_live = False
+ if _pending_confirm and not _tool_approval_live:
+ _raw_reply = (event.text or "").strip()
+ # Accept bang-prefixed replies (`!always`, `!cancel`) verbatim.
+ # Slack/Matrix instruction text shows the `!` prefix (typed `/`
+ # is blocked in Slack threads), but the adapters only rewrite
+ # `!<known-command>` — `always`/`cancel` are confirm keywords,
+ # not registered commands, so the `!` survives to here.
+ _norm_reply = _raw_reply.lstrip("!/").lower()
+ _cmd_reply = event.get_command()
+ _confirm_choice = None
+ if _cmd_reply in {"approve", "yes", "ok", "confirm"}:
+ _confirm_choice = "once"
+ elif _cmd_reply in {"always", "remember"}:
+ _confirm_choice = "always"
+ elif _cmd_reply in {"cancel", "no", "deny", "nevermind"}:
+ _confirm_choice = "cancel"
+ elif _norm_reply in {"approve", "approve once", "once"}:
+ _confirm_choice = "once"
+ elif _norm_reply in {"always", "always approve"}:
+ _confirm_choice = "always"
+ elif _norm_reply in {"cancel", "nevermind", "no"}:
+ _confirm_choice = "cancel"
+ if _confirm_choice is not None:
+ _resolved = await _slash_confirm_mod.resolve(
+ _quick_key, _pending_confirm.get("confirm_id"), _confirm_choice,
+ )
+ return _resolved or ""
+ # Stale pending + unrelated command: drop the pending state so
+ # the confirm doesn't block normal usage indefinitely. The user
+ # clearly moved on.
+ _slash_confirm_mod.clear_if_stale(_quick_key)
+
+ # PRIORITY handling when an agent is already running for this session.
+ # Default behavior is to interrupt immediately so user text/stop messages
+ # are handled with minimal latency.
#
- # Token source priority:
- # 1. Actual API-reported prompt_tokens from the last turn
- # (stored in session_entry.last_prompt_tokens)
- # 2. Rough char-based estimate (str(msg)//4). Overestimates
- # by 30-50% on code/JSON-heavy sessions, but that just
- # means hygiene fires a bit early — safe and harmless.
- # -----------------------------------------------------------------
- if history and len(history) >= 4:
- from agent.model_metadata import (
- estimate_messages_tokens_rough,
- get_model_context_length_async,
+ # Special case: Telegram/photo bursts often arrive as multiple near-
+ # simultaneous updates. Do NOT interrupt for photo-only follow-ups here;
+ # let the adapter-level batching/queueing logic absorb them.
+
+ # Staleness eviction: detect leaked locks from hung/crashed handlers.
+ # With inactivity-based timeout, active tasks can run for hours, so
+ # wall-clock age alone isn't sufficient. Evict only when the agent
+ # has been *idle* beyond the inactivity threshold (or when the agent
+ # object has no activity tracker and wall-clock age is extreme).
+ _raw_stale_timeout = _float_env("HERMES_AGENT_TIMEOUT", 1800)
+ _quick_state = self._peek_session_state(_quick_key)
+ _stale_ts = _quick_state.turn.started_ts if _quick_state else 0
+ if _quick_state is not None and _quick_state.turn.agent is not None and _stale_ts:
+ _stale_age = time.time() - _stale_ts
+ _stale_agent = _quick_state.turn.agent
+ # Never evict the pending sentinel — it was just placed moments
+ # ago during the async setup phase before the real agent is
+ # created. Sentinels have no get_activity_summary(), so the
+ # idle check below would always evaluate to inf >= timeout and
+ # immediately evict them, racing with the setup path.
+ _stale_idle = float("inf") # assume idle if we can't check
+ _stale_detail = ""
+ if _stale_agent and hasattr(_stale_agent, "get_activity_summary"):
+ try:
+ _sa = _stale_agent.get_activity_summary()
+ _stale_idle = _sa.get("seconds_since_activity", float("inf"))
+ _stale_detail = (
+ f" | last_activity={_sa.get('last_activity_desc', 'unknown')} "
+ f"({_stale_idle:.0f}s ago) "
+ f"| iteration={_sa.get('api_call_count', 0)}/{_sa.get('max_iterations', 0)}"
+ )
+ except Exception:
+ pass
+ # Evict if: agent is idle beyond timeout, OR wall-clock age is
+ # extreme (10x timeout or 2h, whichever is larger — catches
+ # cases where the agent object was garbage-collected).
+ _wall_ttl = max(_raw_stale_timeout * 10, 7200) if _raw_stale_timeout > 0 else float("inf")
+ _should_evict = (
+ _stale_agent is not _AGENT_PENDING_SENTINEL
+ and (
+ (_raw_stale_timeout > 0 and _stale_idle >= _raw_stale_timeout)
+ or _stale_age > _wall_ttl
+ )
)
+ if _should_evict:
+ logger.warning(
+ "Evicting stale _running_agents entry for %s "
+ "(age: %.0fs, idle: %.0fs, timeout: %.0fs)%s",
+ _quick_key, _stale_age, _stale_idle,
+ _raw_stale_timeout, _stale_detail,
+ )
+ self._invalidate_session_run_generation(
+ _quick_key,
+ reason="stale_running_agent_eviction",
+ )
+ self._release_running_agent_state(_quick_key)
- # Read model + compression config from config.yaml.
- # NOTE: hygiene threshold is intentionally HIGHER than the agent's
- # own compressor (0.85 vs 0.50). Hygiene is a safety net for
- # sessions that grew too large between turns — it fires pre-agent
- # to prevent API failures. The agent's own compressor handles
- # normal context management during its tool loop with accurate
- # real token counts. Having hygiene at 0.50 caused premature
- # compression on every turn in long gateway sessions.
- _hyg_model = "anthropic/claude-sonnet-4.6"
- _hyg_threshold_pct = 0.85
- _hyg_compression_enabled = True
- _hyg_hard_msg_limit = 5000
- _hyg_timeout_seconds = 30.0
- _hyg_total_ceiling_seconds = 600.0
- _hyg_failure_cooldown_seconds = 300.0
- _hyg_config_context_length = None
- _hyg_provider = None
- _hyg_base_url = None
- _hyg_api_key = None
- _hyg_configured_model = None
- _hyg_configured_provider = None
- _hyg_configured_base_url = None
- _hyg_data = {}
- try:
- _hyg_data = _load_gateway_config()
- if _hyg_data:
- # Resolve model name (same logic as run_sync)
- _model_cfg = _hyg_data.get("model", {})
- if isinstance(_model_cfg, str):
- _hyg_model = _model_cfg
- elif isinstance(_model_cfg, dict):
- _hyg_model = _model_cfg.get("default") or _model_cfg.get("model") or _hyg_model
- # Read explicit context_length override from model config
- # (same as run_agent.py lines 995-1005)
- _raw_ctx = _model_cfg.get("context_length")
- if _raw_ctx is not None:
- try:
- _hyg_config_context_length = int(_raw_ctx)
- except (TypeError, ValueError):
- pass
- # Read provider for accurate context detection
- _hyg_provider = _model_cfg.get("provider") or None
- _hyg_base_url = _model_cfg.get("base_url") or None
-
- # Read compression settings — only use enabled flag.
- # The threshold is intentionally separate from the agent's
- # compression.threshold (hygiene runs higher).
- _comp_cfg = _hyg_data.get("compression", {})
- if isinstance(_comp_cfg, dict):
- _hyg_compression_enabled = str(
- _comp_cfg.get("enabled", True)
- ).lower() in {"true", "1", "yes"}
- _raw_hard_limit = _comp_cfg.get("hygiene_hard_message_limit")
- if _raw_hard_limit is not None:
- try:
- _parsed = int(_raw_hard_limit)
- if _parsed > 0:
- _hyg_hard_msg_limit = _parsed
- except (TypeError, ValueError):
- pass
- _raw_timeout = _comp_cfg.get("hygiene_timeout_seconds")
- if _raw_timeout is not None:
- try:
- _parsed = float(_raw_timeout)
- if _parsed > 0:
- _hyg_timeout_seconds = _parsed
- except (TypeError, ValueError):
- pass
- _raw_ceiling = _comp_cfg.get("hygiene_total_ceiling_seconds")
- if _raw_ceiling is not None:
- try:
- _parsed = float(_raw_ceiling)
- if _parsed > 0:
- _hyg_total_ceiling_seconds = _parsed
- except (TypeError, ValueError):
- pass
- # The ceiling can never be tighter than one idle
- # window, or the extension loop would be dead code.
- _hyg_total_ceiling_seconds = max(
- _hyg_total_ceiling_seconds, _hyg_timeout_seconds,
- )
- _raw_cooldown = _comp_cfg.get("hygiene_failure_cooldown_seconds")
- if _raw_cooldown is not None:
- try:
- _parsed = float(_raw_cooldown)
- if _parsed >= 0:
- _hyg_failure_cooldown_seconds = _parsed
- except (TypeError, ValueError):
- pass
-
- _hyg_configured_model = _hyg_model
- _hyg_configured_provider = _hyg_provider
- _hyg_configured_base_url = _hyg_base_url
-
- try:
- _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(
- source=source,
- session_key=session_key,
- user_config=_hyg_data if isinstance(_hyg_data, dict) else None,
- )
- _hyg_provider = _hyg_runtime.get("provider") or _hyg_provider
- _hyg_base_url = _hyg_runtime.get("base_url") or _hyg_base_url
- _hyg_api_key = _hyg_runtime.get("api_key") or _hyg_api_key
- except Exception:
- pass
-
- if _hyg_config_context_length is not None:
- try:
- from hermes_cli.route_identity import should_clear_context_pin_async
+ if self._is_session_running(_quick_key):
+ # Resolve the command once; every command's mid-run behavior is
+ # declared on its CommandDef (busy_policy / busy_handler in
+ # hermes_cli/commands.py) and dispatched through the single
+ # resolver _dispatch_busy_slash_command below — no per-command
+ # if-chain here.
+ from hermes_cli.commands import resolve_command as _resolve_cmd_inner
+ _evt_cmd = event.get_command()
+ _cmd_def_inner = _resolve_cmd_inner(_evt_cmd) if _evt_cmd else None
- if await should_clear_context_pin_async(
- _hyg_configured_model,
- _hyg_model,
- _hyg_configured_base_url,
- _hyg_base_url,
- _hyg_configured_provider,
- _hyg_provider,
- ):
- _hyg_config_context_length = None
- except Exception:
- _hyg_config_context_length = None
+ # /status and /context are intentionally pre-gate so users
+ # always see session state.
+ if _cmd_def_inner and _cmd_def_inner.name == "status":
+ return await self._handle_status_command(event)
+ if _cmd_def_inner and _cmd_def_inner.name == "context":
+ return await self._handle_context_command(event)
- # Check custom_providers per-model context_length
- # (same fallback as run_agent.py lines 1171-1189).
- # Must run after runtime resolution so _hyg_base_url is set.
- if _hyg_config_context_length is None and _hyg_base_url:
- try:
- try:
- from hermes_cli.config import (
- get_compatible_custom_providers as _gw_gcp,
- get_custom_provider_context_length as _gw_gccl,
- )
- _hyg_custom_providers = _gw_gcp(_hyg_data)
- except Exception:
- _hyg_custom_providers = _hyg_data.get("custom_providers")
- if not isinstance(_hyg_custom_providers, list):
- _hyg_custom_providers = []
- _hyg_custom_ctx = _gw_gccl(
- model=_hyg_model,
- base_url=_hyg_base_url,
- custom_providers=_hyg_custom_providers,
- )
- if _hyg_custom_ctx:
- _hyg_config_context_length = int(_hyg_custom_ctx)
- except (TypeError, ValueError):
- pass
- except Exception:
- pass
+ # Slash command access control on the running-agent fast-path.
+ # Mirrors the cold-path gate further below so non-admin users
+ # can't bypass gating just because an agent happens to be busy.
+ # /status above is intentionally pre-gate so users always see
+ # session state. /help and /whoami fall under the always-allowed
+ # floor inside _check_slash_access.
+ if _evt_cmd and _cmd_def_inner is not None:
+ _denied = self._check_slash_access(source, _cmd_def_inner.name)
+ if _denied is not None:
+ return _denied
- if _hyg_compression_enabled:
- _hyg_context_length = await get_model_context_length_async(
- _hyg_model,
- base_url=_hyg_base_url or "",
- api_key=_hyg_api_key or "",
- config_context_length=_hyg_config_context_length,
- provider=_hyg_provider or "",
- )
- _compress_token_threshold = int(
- _hyg_context_length * _hyg_threshold_pct
+ # Any recognized slash command: dispatch according to its
+ # declared busy_policy (dispatch / interrupt_then_dispatch /
+ # reject). Unrecognized commands and plain text fall through
+ # to the interrupt/queue logic below.
+ if _cmd_def_inner:
+ return await self._dispatch_busy_slash_command(
+ event, _cmd_def_inner, _quick_key, source,
)
- _warn_token_threshold = int(_hyg_context_length * 0.95)
-
- _msg_count = len(history)
- # Prefer actual API-reported tokens from the last turn
- # (stored in session entry) over the rough char-based estimate.
- _stored_tokens = session_entry.last_prompt_tokens
- if _stored_tokens > 0:
- _approx_tokens = _stored_tokens
- _token_source = "actual"
- else:
- _approx_tokens = estimate_messages_tokens_rough(history)
- _token_source = "estimated"
- # Note: rough estimates overestimate by 30-50% for code/JSON-heavy
- # sessions, but that just means hygiene fires a bit early — which
- # is safe and harmless. The 85% threshold already provides ample
- # headroom (agent's own compressor runs at 50%). A previous 1.4x
- # multiplier tried to compensate by inflating the threshold, but
- # 85% * 1.4 = 119% of context — which exceeds the model's limit
- # and prevented hygiene from ever firing for ~200K models (GLM-5).
+ if event.message_type == MessageType.PHOTO:
+ logger.debug("PRIORITY photo follow-up for session %s — queueing without interrupt", _quick_key)
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ merge_pending_message_event(adapter._pending_messages, _quick_key, event)
+ return None
- # Hard safety valve: force compression if message count is
- # extreme, regardless of token estimates. This breaks the
- # death spiral where API disconnects prevent token data
- # collection, which prevents compression, which causes more
- # disconnects. 5000 messages is far above any normal session
- # but catches truly runaway growth before it becomes
- # unrecoverable. Set well clear of legitimate large-context
- # (1M+) sessions doing thousands of short turns — those
- # compress on the token threshold, not this count-based floor.
- # Threshold is configurable via
- # compression.hygiene_hard_message_limit.
- # (#2153)
- _HARD_MSG_LIMIT = _hyg_hard_msg_limit
- _needs_compress = (
- _approx_tokens >= _compress_token_threshold
- or _msg_count >= _HARD_MSG_LIMIT
+ _telegram_followup_grace = float(
+ os.getenv("HERMES_TELEGRAM_FOLLOWUP_GRACE_SECONDS", "3.0")
+ )
+ _grace_state = self._peek_session_state(_quick_key)
+ _started_at = _grace_state.turn.started_ts if _grace_state else 0
+ if (
+ source.platform == Platform.TELEGRAM
+ and event.message_type == MessageType.TEXT
+ and _telegram_followup_grace > 0
+ and _started_at
+ and (time.time() - _started_at) <= _telegram_followup_grace
+ ):
+ logger.debug(
+ "Telegram follow-up arrived %.2fs after run start for %s — queueing without interrupt",
+ time.time() - _started_at,
+ _quick_key,
)
-
- if _needs_compress:
- _cooldowns = getattr(self, "_hygiene_compression_failure_cooldowns", None)
- if _cooldowns is None:
- _cooldowns = {}
- self._hygiene_compression_failure_cooldowns = _cooldowns
- _cooldown_key = session_entry.session_id
- _cooldown_until = float(_cooldowns.get(_cooldown_key) or 0.0)
- if _cooldown_until > time.time():
- logger.info(
- "Session hygiene: skipping compression for %s; "
- "previous failure cooldown active for %.1fs",
- _cooldown_key,
- max(0.0, _cooldown_until - time.time()),
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ if self._busy_input_mode == "queue":
+ self._enqueue_fifo(_quick_key, event, adapter)
+ else:
+ merge_pending_message_event(
+ adapter._pending_messages,
+ _quick_key,
+ event,
+ merge_text=True,
)
- _needs_compress = False
-
- if _needs_compress:
- logger.info(
- "Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing "
- "(threshold: %s%% of %s = %s tokens)",
- _msg_count, f"{_approx_tokens:,}", _token_source,
- int(_hyg_threshold_pct * 100),
- f"{_hyg_context_length:,}",
- f"{_compress_token_threshold:,}",
- )
-
- _hyg_meta = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
-
- try:
- from agent.conversation_compression import CompressionCommitFence
- from run_agent import AIAgent
+ return None
- _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(
- source=source,
- session_key=session_key,
- user_config=_hyg_data if isinstance(_hyg_data, dict) else None,
- )
- if _hyg_runtime.get("api_key"):
- # Pass the FULL transcript (tool results included).
- # Filtering to user/assistant-only starved the
- # compressor: tool results are usually the bulk of
- # the context, _prune_old_tool_results never saw
- # them, and short filtered histories tripped the
- # protect-first/last early-return so nothing was
- # compressed at all (#3854). The agent loop passes
- # its full message list to _compress_context — the
- # gateway now matches.
- _hyg_msgs = [
- m for m in history
- if m.get("role") in {"user", "assistant", "tool"}
- ]
-
- if len(_hyg_msgs) >= 4:
- try:
- _hyg_session_row = await self._session_db.get_session(
- session_entry.session_id
- )
- except Exception as exc:
- _hyg_session_row = None
- logger.warning(
- "Session hygiene could not restore the system "
- "prompt for session %s: %s. Preserving an empty "
- "prompt so the live turn rebuilds it with its "
- "configured providers.",
- session_entry.session_id,
- exc,
- exc_info=True,
- )
- _hyg_session_db = getattr(self._session_db, "_db", self._session_db)
- _hyg_agent = AIAgent(
- **_hyg_runtime,
- model=_hyg_model,
- max_iterations=4,
- quiet_mode=True,
- skip_memory=True,
- enabled_toolsets=["memory"],
- session_id=session_entry.session_id,
- session_db=_hyg_session_db,
- )
- _seed_hygiene_system_prompt(
- _hyg_agent,
- _hyg_session_row,
- )
- # If compression must rebuild instead of retaining
- # the cached prompt, make the persisted result
- # deliberately stale for every real gateway surface.
- _hyg_agent.platform = _GATEWAY_HYGIENE_PLATFORM
- _hyg_cleanup_deferred = False
- try:
- # Gateway hygiene runs before the user turn
- # starts and already owns the session binding.
- # Prefer in-place compaction here: it archives
- # old rows under the same session id instead of
- # minting a continuation child that then has to
- # be published back to SessionStore/topic
- # bindings. If no SessionDB is available,
- # compress_context leaves this flag false and
- # the guard below preserves the transcript.
- _hyg_agent.compression_in_place = True
- _bind_hyg_state = getattr(
- getattr(_hyg_agent, "context_compressor", None),
- "bind_session_state",
- None,
- )
- if callable(_bind_hyg_state):
- _bind_hyg_state(
- _hyg_session_db,
- session_entry.session_id,
- )
- # It must never finalize on close() — close()
- # would end the live gateway session row.
- _hyg_agent._end_session_on_close = False
- _hyg_agent._print_fn = lambda *a, **kw: None
-
- loop = asyncio.get_running_loop()
- _hyg_commit_fence = CompressionCommitFence()
- _hyg_future = loop.run_in_executor(
- None,
- lambda: _hyg_agent._compress_context(
- _hyg_msgs, "",
- approx_tokens=_approx_tokens,
- commit_fence=_hyg_commit_fence,
- ),
- )
- try:
- # Progress-aware wait: the timeout is an
- # INACTIVITY budget, not a total one. The
- # compression worker streams its summary
- # call and ticks the fence per token
- # (CompressionCommitFence.touch_progress),
- # so a slow reasoning model that is still
- # generating keeps extending the deadline;
- # only a genuinely silent worker times out.
- # A hard ceiling bounds the total wait so
- # a degenerate trickle stream can't hold
- # the turn forever.
- _hyg_wait_started = time.monotonic()
- while True:
- try:
- _compressed, _ = await asyncio.wait_for(
- asyncio.shield(_hyg_future),
- timeout=_hyg_timeout_seconds,
- )
- break
- except asyncio.TimeoutError:
- _hyg_waited = time.monotonic() - _hyg_wait_started
- _idle = _hyg_commit_fence.seconds_since_progress()
- if (
- _idle < _hyg_timeout_seconds
- and _hyg_waited < _hyg_total_ceiling_seconds
- ):
- logger.info(
- "Session hygiene compression for "
- "session %s still streaming after "
- "%.0fs (last progress %.1fs ago) — "
- "extending wait (ceiling %.0fs)",
- session_entry.session_id,
- _hyg_waited, _idle,
- _hyg_total_ceiling_seconds,
- )
- continue
- raise
- except asyncio.TimeoutError:
- _cancelled = None
- while _cancelled is None:
- _cancelled = (
- _hyg_commit_fence.try_cancel_before_commit()
- )
- if _cancelled is None:
- await asyncio.sleep(0.001)
- if not _cancelled:
- # The worker crossed the commit boundary just
- # before the timeout. The fence poll waited for
- # that boundary to finish, so consume the
- # completed result instead of treating a
- # successful compaction as a timeout.
- _compressed, _ = await _hyg_future
- else:
- self._defer_agent_cleanup_until_future_done(
- _hyg_future,
- _hyg_agent,
- context="session hygiene timeout",
- )
- _hyg_cleanup_deferred = True
- if _hyg_failure_cooldown_seconds >= 0:
- self._hygiene_compression_failure_cooldowns[
- session_entry.session_id
- ] = time.time() + _hyg_failure_cooldown_seconds
- logger.warning(
- "Session hygiene compression for session %s "
- "made no progress for %.1fs "
- "(total wait %.1fs, ceiling %.1fs); "
- "continuing without compression",
- session_entry.session_id,
- _hyg_commit_fence.seconds_since_progress(),
- time.monotonic() - _hyg_wait_started,
- _hyg_total_ceiling_seconds,
- )
- _timeout_msg = (
- "⚠️ Context compression timed out "
- f"after {_hyg_timeout_seconds:.1f}s "
- "with no output from the summary model. "
- "No messages were dropped — continuing without "
- "compression. Run /compress to retry, /reset for "
- "a clean session, or check your "
- "auxiliary.compression model configuration."
- )
- try:
- _adapter = self._adapter_for_source(source)
- if _adapter and source.chat_id:
- await _adapter.send(
- source.chat_id,
- _timeout_msg,
- metadata=_hyg_meta,
- )
- except Exception as _werr:
- logger.warning(
- "Failed to deliver compression-timeout "
- "warning to user: %s",
- _werr,
- )
- raise
-
- # _compress_context ends the old session and creates
- # a new session_id. Write compressed messages into
- # the NEW session so the old transcript stays intact
- # and searchable via session_search.
- _hyg_new_sid = _hyg_agent.session_id
- _hyg_rotated = _hyg_new_sid != session_entry.session_id
- _hyg_in_place = bool(
- getattr(_hyg_agent, "_last_compaction_in_place", False)
- )
- # Only rewrite the transcript when rotation produced
- # a NEW session id. In-place compaction does NOT
- # need a rewrite: archive_and_compact() has already
- # soft-archived the previous active rows and inserted
- # the compacted messages as the new active set inside
- # _compress_context(). Calling rewrite_transcript()
- # after in-place compaction would invoke
- # replace_messages(active_only=False) which DELETEs
- # ALL rows — including the archived turns that
- # archive_and_compact() deliberately preserved
- # (silent data loss, #61145).
- #
- # The danger this guards against (mirrors the
- # /compress fix #44794/#39704): if _compress_context
- # returns a summary but neither rotates nor completes
- # archive_and_compact(), the session_id is unchanged
- # for a FAILURE reason, and an unconditional
- # rewrite_transcript() would DELETE the original
- # messages and replace them with only the compressed
- # summary (permanent data loss, #21301).
- #
- # Write-before-repoint (mirrors manual /compress):
- # if we repointed session_entry onto the child SID
- # and rewrite_transcript then failed (lock/ENOSPC),
- # the live entry would already reference a brand-new
- # empty session while the turn continues — the
- # conversation silently vanishes. Persist the child
- # transcript first; only then rebind the live entry.
- if _hyg_rotated:
- if not await self.async_session_store.rewrite_transcript(
- _hyg_new_sid, _compressed
- ):
- logger.error(
- "Session hygiene: failed to persist "
- "compressed transcript for rotated "
- "session %s → %s; keeping the live "
- "entry on the original session so the "
- "conversation is not dropped",
- session_entry.session_id,
- _hyg_new_sid,
- )
- # Fail closed: treat like no rotation.
- _hyg_rotated = False
- _hyg_in_place = False
- else:
- session_entry.session_id = _hyg_new_sid
- # The held turn lease follows the
- # rotation so an alias key resolving
- # the fresh child still serializes
- # against this turn (#64934).
- self._rebind_turn_lease(
- _quick_key, run_generation, _hyg_new_sid
- )
- await self.async_session_store._save()
- await asyncio.to_thread(
- self._sync_telegram_topic_binding,
- source, session_entry,
- reason="hygiene-compression",
- )
-
- if _hyg_rotated:
- # Reset stored token count — transcript rewritten
- session_entry.last_prompt_tokens = 0
- history = _compressed
- _new_count = len(_compressed)
- _new_tokens = estimate_messages_tokens_rough(
- _compressed
- )
- elif _hyg_in_place:
- # archive_and_compact() already persisted the
- # compacted transcript inside _compress_context.
- # Reset counts to match the new active set.
- session_entry.last_prompt_tokens = 0
- history = _compressed
- _new_count = len(_compressed)
- _new_tokens = estimate_messages_tokens_rough(
- _compressed
- )
- else:
- # No rewrite happened — transcript preserved
- # unchanged, so the post-compression counts equal
- # the pre-compression ones.
- _new_count = _msg_count
- _new_tokens = _approx_tokens
- logger.warning(
- "Gateway hygiene compression for session %s "
- "did not rotate or compact in place "
- "(no session_db on the hygiene agent) — "
- "preserving the original transcript instead "
- "of overwriting it with the summary (#21301).",
- session_entry.session_id,
- )
-
- logger.info(
- "Session hygiene: compressed %s → %s msgs, "
- "~%s → ~%s tokens",
- _msg_count, _new_count,
- f"{_approx_tokens:,}", f"{_new_tokens:,}",
- )
-
- if _new_tokens >= _warn_token_threshold:
- logger.warning(
- "Session hygiene: still ~%s tokens after "
- "compression",
- f"{_new_tokens:,}",
- )
-
- # If summary generation failed, the
- # compressor aborts entirely and returns
- # messages unchanged — nothing is dropped.
- # Surface a visible warning to the gateway
- # user — agent.log alone is invisible on
- # TG/Discord/etc. — so they know the chat
- # is "frozen" at the current size and can
- # /compress to retry or /reset to start
- # fresh.
- _comp = getattr(_hyg_agent, "context_compressor", None)
- if _comp is not None and getattr(_comp, "_last_compress_aborted", False):
- if _hyg_failure_cooldown_seconds >= 0:
- self._hygiene_compression_failure_cooldowns[
- session_entry.session_id
- ] = time.time() + _hyg_failure_cooldown_seconds
- _err = getattr(_comp, "_last_summary_error", None) or "unknown error"
- # Force-redact: provider exception text
- # may contain credentials; this message
- # reaches gateway users directly.
- from agent.redact import redact_sensitive_text
- _err = redact_sensitive_text(_err, force=True)
- _warn_msg = (
- "⚠️ Context compression aborted "
- f"({_err}). No messages were dropped — "
- "conversation is unchanged. Run /compress "
- "to retry, /reset for a clean session, or "
- "check your auxiliary.compression model "
- "configuration."
- )
- try:
- _adapter = self._adapter_for_source(source)
- if _adapter and source.chat_id:
- await _adapter.send(source.chat_id, _warn_msg, metadata=_hyg_meta)
- except Exception as _werr:
- logger.warning(
- "Failed to deliver compression-failure warning to user: %s",
- _werr,
- )
- # Separately: if the user's CONFIGURED aux
- # model failed and we recovered by falling
- # back to the main model, tell them — a
- # misconfigured auxiliary.compression.model
- # is something only they can fix, and
- # silent recovery would hide it.
- elif _comp is not None and getattr(_comp, "_last_aux_model_failure_model", None):
- _aux_model = getattr(_comp, "_last_aux_model_failure_model", "")
- _aux_err = getattr(_comp, "_last_aux_model_failure_error", None) or "unknown error"
- _aux_msg = (
- f"ℹ️ Configured compression model `{_aux_model}` "
- f"failed ({_aux_err}). Recovered using your main "
- "model — context is intact — but you may want to "
- "check `auxiliary.compression.model` in config.yaml."
- )
- try:
- _adapter = self._adapter_for_source(source)
- if _adapter and source.chat_id:
- await _adapter.send(source.chat_id, _aux_msg, metadata=_hyg_meta)
- except Exception as _werr:
- logger.warning(
- "Failed to deliver aux-model-fallback notice to user: %s",
- _werr,
- )
- finally:
- # Evict the cached agent so the next turn
- # rebuilds its system prompt from current
- # SOUL.md, memory, and skills.
- self._evict_cached_agent(session_key)
- if not _hyg_cleanup_deferred:
- await self._cleanup_agent_resources_off_loop(
- _hyg_agent, context="session hygiene"
- )
-
- except Exception as e:
- logger.warning(
- "Session hygiene auto-compress failed: %s", e
- )
-
- # First-message onboarding -- only on the very first interaction ever.
- # Delivered on the current user message (sidecar), NOT the ephemeral
- # system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed
- # system-prompt diff and agent rebuild.
- if not history and not await self.async_session_store.has_any_sessions():
- # Default first-contact note: a brief self-introduction.
- _intro_note = (
- "[System note: This is the user's very first message ever. "
- "Briefly introduce yourself and mention that /help shows available commands. "
- "Keep the introduction concise -- one or two sentences max.]"
- )
- # Opt-in structured profile-build path. When enabled (default
- # "ask") and not yet offered on this install, swap the plain intro
- # for a consent-gated directive that offers to build a user
- # profile and persists confirmed facts via memory(target="user").
- # The offer fires at most once (onboarding.seen flag); set
- # onboarding.profile_build: off in config.yaml to disable.
- try:
- from agent.onboarding import (
- PROFILE_BUILD_FLAG,
- is_seen,
- mark_seen,
- profile_build_directive,
- profile_build_mode,
+ _ra_state = self._peek_session_state(_quick_key)
+ running_agent = _ra_state.turn.agent if _ra_state else None
+ if running_agent is _AGENT_PENDING_SENTINEL:
+ # Agent is being set up but not ready yet.
+ if event.get_command() == "stop":
+ # Force-clean the sentinel so the session is unlocked.
+ self._release_running_agent_state(_quick_key)
+ logger.info("HARD STOP (pending) for session %s — sentinel cleared", _quick_key)
+ return EphemeralReply("⚡ Force-stopped. The agent was still starting — session unlocked.")
+ # Queue the message so it will be picked up after the
+ # agent starts.
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ merge_pending_message_event(
+ adapter._pending_messages,
+ _quick_key,
+ event,
+ merge_text=True,
+ )
+ return None
+ if self._draining:
+ if self._queue_during_drain_enabled():
+ self._queue_or_replace_pending_event(_quick_key, event)
+ return (
+ f"⏳ Gateway {self._status_action_gerund()} — queued for the next turn after it comes back."
+ if self._queue_during_drain_enabled()
+ else f"⏳ Gateway is {self._status_action_gerund()} and is not accepting another turn right now."
)
- _onb_cfg = _load_gateway_config()
+ if self._busy_input_mode == "queue":
+ logger.debug("PRIORITY queue follow-up for session %s", _quick_key)
+ self._queue_or_replace_pending_event(_quick_key, event)
+ return None
+ if self._busy_input_mode == "steer":
+ # Steer mode: inject text into the running agent mid-run via
+ # agent.steer(). Falls back to queue semantics if the payload
+ # is empty, the agent lacks steer(), or steer() rejects.
+ steer_text = (event.text or "").strip()
+ steered = False
if (
- profile_build_mode(_onb_cfg) == "ask"
- and not is_seen(_onb_cfg, PROFILE_BUILD_FLAG)
+ event.message_type == MessageType.TEXT
+ and not event.media_urls
+ and not event.media_types
+ and steer_text
+ and hasattr(running_agent, "steer")
):
- turn_sidecar_notes.append(profile_build_directive().strip())
- mark_seen(_hermes_home / "config.yaml", PROFILE_BUILD_FLAG)
- else:
- turn_sidecar_notes.append(_intro_note)
- except Exception as _pb_err:
- logger.debug(
- "Profile-build onboarding directive failed, using plain intro: %s",
- _pb_err,
- )
- turn_sidecar_notes.append(_intro_note)
-
- # One-time prompt if no home channel is set for this platform
- # Skip for webhooks - they deliver directly to configured targets (github_comment, etc.)
- if not history and source.platform and source.platform != Platform.LOCAL and source.platform != Platform.WEBHOOK:
- platform_name = source.platform.value
- env_key = _home_target_env_var(platform_name)
- # Multiplex: home channel may live only in the profile secret
- # scope / PlatformConfig, not process os.environ.
- home_env = ""
- try:
- from agent.secret_scope import get_secret
-
- home_env = (get_secret(env_key) or "").strip() if env_key else ""
- except Exception:
- home_env = ""
- if not home_env:
- home_env = (os.getenv(env_key) or "").strip() if env_key else ""
- # Also honor in-memory / yaml home_channel on this platform.
- try:
- if not home_env and self.config.get_home_channel(source.platform):
- home_env = "set"
- except Exception:
- pass
- # Secondary-profile platforms (e.g. Slack on yolo) may only exist
- # under that profile's loaded config — check after scope install.
- if not home_env:
- try:
- from gateway.config import load_gateway_config as _lgc
- prof = (getattr(source, "profile", None) or "").strip()
- if prof and prof != "default":
- # Already inside profile scope for secondary handlers;
- # re-read live config for home_channel.
- _pcfg = _lgc()
- if _pcfg.get_home_channel(source.platform):
- home_env = "set"
- except Exception:
- pass
- if not home_env:
- # Slack dispatches all Hermes commands through a single
- # parent slash command `/hermes`; bare `/sethome` is not
- # registered and would fail with "app did not respond".
- sethome_cmd = (
- "/hermes sethome"
- if source.platform == Platform.SLACK
- else "/sethome"
- )
- notice = (
- f"📬 No home channel is set for {platform_name.title()}. "
- f"A home channel is where Hermes delivers cron job results "
- f"and cross-platform messages.\n\n"
- f"Type {sethome_cmd} to make this chat your home channel, "
- f"or ignore to skip."
+ try:
+ steered = bool(running_agent.steer(steer_text))
+ except Exception as exc:
+ logger.warning("PRIORITY steer failed for session %s: %s", _quick_key, exc)
+ steered = False
+ if steered:
+ logger.debug("PRIORITY steer for session %s", _quick_key)
+ return None
+ logger.debug("PRIORITY steer-fallback-to-queue for session %s", _quick_key)
+ self._queue_or_replace_pending_event(_quick_key, event)
+ return None
+ # #30170 — Subagent protection (PRIORITY path). Same rationale
+ # as ``_handle_active_session_busy_message``: an interrupt
+ # cascades through ``_active_children`` and aborts in-flight
+ # delegate_task work. Demote to queue semantics when the
+ # parent is currently driving subagents so a conversational
+ # follow-up doesn't destroy minutes of subagent progress.
+ # /stop reaches its dedicated handler above, so the operator
+ # still has a clean escape hatch.
+ if self._agent_has_active_subagents(running_agent):
+ logger.info(
+ "PRIORITY interrupt demoted to queue for session %s "
+ "because the running agent has active subagents (#30170)",
+ _quick_key,
)
- await self._deliver_platform_notice(source, notice)
-
- # -----------------------------------------------------------------
- # Voice channel awareness — deliver current voice channel state so
- # the agent knows who is in the channel and who is speaking, without
- # needing a separate tool call. Delivered on the current user
- # message and ONLY when it changed since the previous turn: the
- # member/speaking serialization differs essentially every turn, and
- # appending it to the ephemeral system prompt forced a full agent
- # rebuild + prompt-cache re-key per message. The system prompt
- # carries a static pointer line instead (gateway/session.py).
- # -----------------------------------------------------------------
- _vc_note = self._voice_channel_sidecar_note(event, source, session_key)
- if _vc_note:
- turn_sidecar_notes.append(_vc_note)
-
- # -----------------------------------------------------------------
- # Auto-analyze images sent by the user
- #
- # If the user attached image(s), we run the vision tool eagerly so
- # the conversation model always receives a text description. The
- # local file path is also included so the model can re-examine the
- # image later with a more targeted question via vision_analyze.
- #
- # We filter to image paths only (by media_type) so that non-image
- # attachments (documents, audio, etc.) are not sent to the vision
- # tool even when they appear in the same message.
- # -----------------------------------------------------------------
- message_text = await self._prepare_profile_scoped_inbound_message_text(
- event=event,
- source=source,
- history=history,
- session_key=session_key,
- )
- if message_text is None:
- return
-
- # Capture the platform event time as message metadata and keep the
- # persisted transcript clean (strip any leading timestamp prefix).
- # This runs regardless of the toggle so storage stays clean and the
- # send-time is preserved. Only the in-context RENDER (prepending the
- # human-readable prefix the model sees) is gated behind
- # gateway.message_timestamps.enabled — default OFF.
- try:
- from hermes_time import get_timezone as _get_evt_tz
- from gateway.message_timestamps import (
- coerce_message_timestamp as _coerce_msg_ts,
- render_user_content_with_timestamp as _render_msg_ts,
- strip_leading_message_timestamps as _strip_msg_ts,
- )
- _evt_tz = _get_evt_tz()
- _evt_ts = getattr(event, "timestamp", None)
- if message_text and isinstance(message_text, str):
- _clean_message_text, _embedded_ts = _strip_msg_ts(
- message_text, tz=_evt_tz)
- persist_user_message = _clean_message_text
- _event_epoch = _coerce_msg_ts(_evt_ts, tz=_evt_tz)
- persist_user_timestamp = (
- _event_epoch if _event_epoch is not None else _embedded_ts
+ self._queue_or_replace_pending_event(_quick_key, event)
+ return None
+ # #56391 — Compression protection (PRIORITY path). Same
+ # rationale as ``_handle_active_session_busy_message``: context
+ # compression is interrupt-protected (#23975), but an interrupt
+ # here starts a new turn against the pre-rotation parent
+ # session while the still-running compression later rotates
+ # the id out from under it, forking orphaned compression
+ # siblings. Demote to queue semantics so the follow-up waits
+ # for the in-flight compression + rotation to land.
+ if await self._session_has_compression_in_flight(_quick_key):
+ logger.info(
+ "PRIORITY interrupt demoted to queue for session %s "
+ "because context compression is in flight (#56391)",
+ _quick_key,
)
- if _message_timestamps_enabled(_load_gateway_config()):
- message_text = _render_msg_ts(
- _clean_message_text,
- persist_user_timestamp,
- tz=_evt_tz,
+ self._queue_or_replace_pending_event(_quick_key, event)
+ return None
+ # Text-only corrections redirect the live turn (preserving
+ # displayed context) when the runtime supports it; media/voice and
+ # older runtimes fall back to the proven interrupt path below.
+ if (
+ event.message_type == MessageType.TEXT
+ and not event.media_urls
+ and not event.media_types
+ and getattr(running_agent, "_supports_active_turn_redirect", False)
+ is True
+ and hasattr(running_agent, "redirect")
+ ):
+ try:
+ if running_agent.redirect((event.text or "").strip()):
+ logger.debug("PRIORITY redirect for session %s", _quick_key)
+ return None
+ except Exception as exc:
+ logger.warning(
+ "PRIORITY redirect failed for session %s: %s",
+ _quick_key,
+ exc,
)
- else:
- # Toggle off: model sees the clean message; the timestamp
- # is still stored as metadata for later opt-in.
- message_text = _clean_message_text
- except Exception as _ts_err:
- logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)
+ logger.debug("PRIORITY interrupt for session %s", _quick_key)
+ _interrupt_text = event.text
+ _media_urls = getattr(event, "media_urls", None) or []
+ if self._pending_event_audio_paths(event):
+ _interrupt_text, _ = await self._transcribe_and_echo_pending_voice(
+ event,
+ self._adapter_for_source(source),
+ source,
+ event.text or "",
+ log_context="Voice-priority-interrupt",
+ )
+ elif not _interrupt_text and _media_urls:
+ _interrupt_text = _build_media_placeholder(event)
+ running_agent.interrupt(_interrupt_text)
+ # NOTE: self._pending_messages was write-only (never consumed).
+ # The actual interrupt message is delivered via adapter._pending_messages
+ # which is read by _run_agent. Removed to prevent unbounded growth.
+ return None
- # Stage the collected must-deliver notes for this turn's agent run
- # (one-shot; consumed in run_sync). Staged AFTER the message_text
- # early-out above so an aborted turn cannot leak its notes into the
- # next turn's user message.
- if turn_sidecar_notes and session_key:
- self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)
+ # Check for commands
+ command = event.get_command()
- # Bind this gateway run generation to the adapter's active-session
- # event so deferred post-delivery callbacks can be released by the
- # same run that registered them.
- self._bind_adapter_run_generation(
- self._adapter_for_source(source),
- session_key,
- run_generation,
+ from hermes_cli.commands import (
+ GATEWAY_KNOWN_COMMANDS,
+ is_gateway_known_command,
+ resolve_command as _resolve_cmd,
)
- try:
- # Emit agent:start hook
+ # Resolve aliases to canonical name so dispatch and hook names
+ # don't depend on the exact alias the user typed.
+ _cmd_def = _resolve_cmd(command) if command else None
+ canonical = _cmd_def.name if _cmd_def else command
+
+ # Expand alias quick commands before built-in dispatch so targets like
+ # /model openai/gpt-5.5 --provider openrouter reach the /model handler.
+ # Preserve built-in precedence; aliases only need early handling when
+ # the typed command is not already known.
+ if command and _cmd_def is None:
+ if isinstance(self.config, dict):
+ quick_commands = self.config.get("quick_commands", {}) or {}
+ else:
+ quick_commands = getattr(self.config, "quick_commands", {}) or {}
+ if isinstance(quick_commands, dict) and command in quick_commands:
+ qcmd = quick_commands[command]
+ if qcmd.get("type") == "alias":
+ target = (qcmd.get("target") or "").strip()
+ if target:
+ target = target if target.startswith("/") else f"/{target}"
+ target_command = target.lstrip("/")
+ user_args = event.get_command_args().strip()
+ event.text = f"{target} {user_args}".strip()
+ command = target_command.split()[0] if target_command else target_command
+ _cmd_def = _resolve_cmd(command) if command else None
+ canonical = _cmd_def.name if _cmd_def else command
+
+ # Per-platform slash command access control. Only kicks in when the
+ # operator has set ``allow_admin_from`` for the source's scope (DM
+ # vs group). When unset → backward-compat: every allowed user can
+ # run every command. When set → non-admins can run only commands in
+ # ``user_allowed_commands`` (plus the always-allowed floor: /help,
+ # /whoami). Plain chat is unaffected — only slash commands gate.
+ if command and canonical and is_gateway_known_command(canonical):
+ _denied = self._check_slash_access(source, canonical)
+ if _denied is not None:
+ return _denied
+
+ # Fire the ``command:<canonical>`` hook for any recognized slash
+ # command — built-in OR plugin-registered. Handlers can return a
+ # dict with ``{"decision": "deny" | "handled" | "rewrite", ...}``
+ # to intercept dispatch before core handling runs. This replaces
+ # the previous fire-and-forget emit(): return values are now
+ # honored, but handlers that return nothing behave exactly as
+ # before (telemetry-style hooks keep working).
+ if command and is_gateway_known_command(canonical):
+ raw_args = event.get_command_args().strip()
hook_ctx = {
"platform": source.platform.value if source.platform else "",
"user_id": source.user_id,
- "chat_id": source.chat_id or "",
- "thread_id": str(getattr(source, "thread_id", None)) if getattr(source, "thread_id", None) else "",
- "chat_type": getattr(source, "chat_type", "") or "",
- "session_id": session_entry.session_id,
- "message": message_text[:500],
+ "command": canonical,
+ "raw_command": command,
+ "args": raw_args,
+ "raw_args": raw_args,
}
- await self.hooks.emit("agent:start", hook_ctx)
+ try:
+ hook_results = await self.hooks.emit_collect(
+ f"command:{canonical}", hook_ctx
+ )
+ except Exception as _hook_err:
+ logger.debug(
+ "command:%s hook dispatch failed (non-fatal): %s",
+ canonical, _hook_err,
+ )
+ hook_results = []
- # Run the agent. Capture the session id that this run was launched
- # against so post-run compression publication can be identity-guarded
- # below; a /new or another lifecycle transition may move
- # session_entry.session_id while the old run is still unwinding.
- _run_start_session_id = session_entry.session_id
- agent_result = await self._run_agent(
- message=message_text,
- context_prompt=context_prompt,
- history=history,
- source=source,
- session_id=_run_start_session_id,
- session_key=session_key,
- run_generation=run_generation,
- event_message_id=self._reply_anchor_for_event(event),
- channel_prompt=event.channel_prompt,
- moa_config=getattr(event, "_moa_config", None),
- persist_user_message=persist_user_message,
- persist_user_timestamp=persist_user_timestamp,
- message_type=event.message_type,
+ for hook_result in hook_results:
+ if not isinstance(hook_result, dict):
+ continue
+ decision = str(hook_result.get("decision", "")).strip().lower()
+ if not decision or decision == "allow":
+ continue
+ if decision == "deny":
+ message = hook_result.get("message")
+ if isinstance(message, str) and message:
+ return message
+ return f"Command `/{command}` was blocked by a hook."
+ if decision == "handled":
+ message = hook_result.get("message")
+ return message if isinstance(message, str) and message else None
+ if decision == "rewrite":
+ new_command = str(
+ hook_result.get("command_name", "")
+ ).strip().lstrip("/")
+ if not new_command:
+ continue
+ new_args = str(hook_result.get("raw_args", "")).strip()
+ event.text = f"/{new_command} {new_args}".strip()
+ command = event.get_command()
+ _cmd_def = _resolve_cmd(command) if command else None
+ canonical = _cmd_def.name if _cmd_def else command
+ break
+
+ if canonical == "new":
+ if await asyncio.to_thread(self._is_telegram_topic_root_lobby, source):
+ return self._telegram_topic_root_new_message()
+ async def _do_reset():
+ return await self._handle_reset_command(event)
+ return await self._maybe_confirm_destructive_slash(
+ event=event,
+ command="new",
+ title="/new",
+ detail=(
+ "This starts a fresh session and discards the current "
+ "conversation history."
+ ),
+ execute=_do_reset,
)
- # Stop persistent typing indicator now that the agent is done.
- # Slack AI status is scoped to a thread/workspace, so preserve the
- # same routing metadata used by the response delivery path.
- try:
- _typing_adapter = self._adapter_for_source(source)
- _stop_with_metadata = getattr(
- type(_typing_adapter), "_stop_typing_with_metadata", None
- )
- _stop_typing = getattr(type(_typing_adapter), "stop_typing", None)
- if _typing_adapter and callable(_stop_with_metadata):
- await _typing_adapter._stop_typing_with_metadata(
- source.chat_id,
- self._thread_metadata_for_source(
- source, self._reply_anchor_for_event(event)
- ),
- )
- elif _typing_adapter and callable(_stop_typing):
- await _typing_adapter.stop_typing(source.chat_id)
- except Exception:
- pass
+ if canonical == "topic":
+ return await self._handle_topic_command(event)
+
+ if canonical == "help":
+ return await self._handle_help_command(event)
- if not self._is_session_run_current(_quick_key, run_generation):
- logger.info(
- "Discarding stale agent result for %s — generation %d is no longer current",
- _quick_key or "?",
- run_generation,
- )
- _stale_adapter = self._adapter_for_source(source)
- if getattr(type(_stale_adapter), "pop_post_delivery_callback", None) is not None:
- _stale_adapter.pop_post_delivery_callback(
- _quick_key,
- generation=run_generation,
- )
- elif _stale_adapter and hasattr(_stale_adapter, "_post_delivery_callbacks"):
- _stale_adapter._post_delivery_callbacks.pop(_quick_key, None)
- return None
+ if canonical == "start":
+ logger.info("Ignoring /start platform ping for session %s", _quick_key)
+ return ""
+
+ if canonical == "commands":
+ return await self._handle_commands_command(event)
+
+ if canonical == "profile":
+ return await self._handle_profile_command(event)
+
+ if canonical == "whoami":
+ return await self._handle_whoami_command(event)
+
+ if canonical == "status":
+ return await self._handle_status_command(event)
- response = agent_result.get("final_response") or ""
- # Hidden-reasoning-only retry exhaustion: the loop's sentinel text
- # ("Codex response remained incomplete after 3 continuation
- # attempts") doubles as final_response, so it would be delivered
- # verbatim into the channel — where peer agents can ingest it as a
- # completed assistant turn (#51628). Blank it here so the normal
- # empty-response handling (and the suppression below) applies.
- if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):
- response = ""
- try:
- from gateway.response_filters import is_intentional_silence_agent_result
- _intentional_silence = is_intentional_silence_agent_result(
- agent_result, response,
- )
- except Exception:
- _intentional_silence = False
+ if canonical == "egress":
+ from hermes_cli.proxy_cli import format_status_text
- # Convert the agent's internal "(empty)" sentinel into a
- # user-friendly message. "(empty)" means the model failed to
- # produce visible content after exhausting all retries (nudge,
- # prefill, empty-retry, fallback). Sending the raw sentinel
- # looks like a bug; a short explanation is more helpful.
- if response == "(empty)" and not _intentional_silence:
- response = (
- "⚠️ The model returned no response after processing tool "
- "results. This can happen with some models — try again or "
- "rephrase your question."
- )
- agent_messages = agent_result.get("messages", [])
- _response_time = time.time() - _msg_start_time
- _api_calls = agent_result.get("api_calls", 0)
- _resp_len = len(response)
- logger.info(
- "response ready: platform=%s chat=%s time=%.1fs api_calls=%d response=%d chars",
- _platform_name, source.chat_id or "unknown",
- _response_time, _api_calls, _resp_len,
- )
+ return format_status_text()
- # NOTE: the cross-process cache-coherence re-baseline
- # (_refresh_agent_cache_message_count) is intentionally deferred
- # until AFTER this turn's transcript persistence block below — it
- # must include the first-turn `session_meta` marker row and the
- # compression session_id swap, both of which happen later. See
- # the call site after the `update_session(...)` write.
+ if canonical == "context":
+ return await self._handle_context_command(event)
- # Successful turn — clear any stuck-loop counter for this session.
- # This ensures the counter only accumulates across CONSECUTIVE
- # restarts where the session was active (never completed).
- #
- # Also clear the resume_pending flag (set by drain-timeout
- # shutdown) — the turn ran to completion, so recovery
- # succeeded and subsequent messages should no longer receive
- # the restart-interruption system note.
- if session_key and _should_clear_resume_pending_after_turn(agent_result):
- self._clear_restart_failure_count(session_key)
- try:
- await self.async_session_store.clear_resume_pending(session_key)
- except Exception as _e:
- logger.debug(
- "clear_resume_pending failed for %s: %s",
- session_key, _e,
- )
+ if canonical == "agents":
+ return await self._handle_agents_command(event)
- # Normalize empty responses: surface errors, partial failures, and
- # the case where agent did work but returned no text. Fix for #18765.
- if not _intentional_silence:
- response = _normalize_empty_agent_response(
- agent_result, response, history_len=len(history),
- )
- response = _sanitize_gateway_final_response(source.platform, response)
+ if canonical == "platform":
+ return await self._handle_platform_command(event)
- # Ordering contract: the agent thread already updated the contextvar
- # in conversation_compression.py; propagate to SessionEntry + _save().
- # If the agent's session_id changed during compression, update
- # session_entry so transcript writes below go to the right session.
- if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:
- if session_entry.session_id == _run_start_session_id:
- session_entry.session_id = agent_result["session_id"]
- # The held turn lease follows the rotation: the transcript
- # persistence below writes to the NEW id, so the
- # serialization boundary must move with it or an alias
- # key resolving the fresh child could interleave (#64934).
- self._rebind_turn_lease(
- _quick_key, run_generation, session_entry.session_id
- )
- await self.async_session_store._save()
- await self.async_session_store._record_gateway_session_peer(
- session_entry.session_id,
- session_key,
- source,
- )
- await asyncio.to_thread(
- self._sync_telegram_topic_binding,
- source, session_entry, reason="agent-result-compression",
- )
- else:
- logger.info(
- "Skipping agent-result session split sync for %s because "
- "the session binding moved from %s to %s before "
- "compression finished",
- session_key or "?",
- _run_start_session_id,
- session_entry.session_id,
- )
+ if canonical == "restart":
+ return await self._handle_restart_command(event)
+
+ if canonical == "stop":
+ return await self._handle_stop_command(event)
+
+ if canonical == "reasoning":
+ return await self._handle_reasoning_command(event)
- # Prepend reasoning/thinking if display is enabled (per-platform).
- # Mattermost requires explicit per-platform opt-in because this is
- # scratch text, not ordinary final-answer content.
+ if canonical == "memory":
+ return await self._handle_memory_command(event)
+
+ if canonical == "skills":
+ return await self._handle_skills_command(event)
+
+ if canonical == "learn":
+ # Open-ended: rewrite the turn to a standards-guided prompt and fall
+ # through to normal agent processing. The live agent gathers the
+ # sources the user described (dirs via read_file, URLs via
+ # web_extract, this conversation, pasted text) and authors the skill
+ # via skill_manage. Mirrors the /blueprint fall-through so role
+ # alternation is preserved. No engine, works on any backend.
+ from agent.learn_prompt import build_learn_prompt
+
+ _learn_req = event.get_command_args().strip()
+ _ack = (
+ "Learning a skill from what you described…"
+ if _learn_req
+ else "Learning a skill from this conversation…"
+ )
try:
- _show_reasoning_effective = _resolve_gateway_display_bool(
- _load_gateway_config(),
- _platform_config_key(source.platform),
- "show_reasoning",
- default=bool(getattr(self, "_show_reasoning", False)),
- platform=source.platform,
- require_platform_override_for={Platform.MATTERMOST},
- )
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ _ack_meta = self._thread_metadata_for_source(source)
+ await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta)
except Exception:
- _show_reasoning_effective = (
- False
- if source.platform == Platform.MATTERMOST
- else getattr(self, "_show_reasoning", False)
- )
- if _show_reasoning_effective and response and not _intentional_silence:
- last_reasoning = agent_result.get("last_reasoning")
- if last_reasoning:
- from gateway.stream_consumer import escape_code_fences_for_display
- # Collapse long reasoning to keep messages readable
- lines = last_reasoning.strip().splitlines()
- if len(lines) > 15:
- display_reasoning = "\n".join(lines[:15])
- display_reasoning += f"\n_... ({len(lines) - 15} more lines)_"
- else:
- display_reasoning = last_reasoning.strip()
- # Render style is per-platform: Discord defaults to "-# "
- # subtext (native small grey metadata text); other
- # platforms keep the fenced code block.
- try:
- from gateway.display_config import resolve_display_setting
- _reasoning_style = resolve_display_setting(
- _load_gateway_config(),
- _platform_config_key(source.platform),
- "reasoning_style",
- "code",
- )
- except Exception:
- _reasoning_style = "code"
- if _reasoning_style == "subtext":
- _quoted = "\n".join(
- f"-# {ln}" if ln else "-#" for ln in display_reasoning.splitlines()
- )
- response = f"-# 💭 Reasoning\n{_quoted}\n\n{response}"
- elif _reasoning_style == "blockquote":
- _quoted = "\n".join(
- f"> {ln}" if ln else ">" for ln in display_reasoning.splitlines()
- )
- response = f"> 💭 **Reasoning:**\n{_quoted}\n\n{response}"
- else:
- # Escape ``` inside reasoning so inner fences don't
- # break the outer code block used to render it.
- display_reasoning = escape_code_fences_for_display(display_reasoning)
- response = f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"
+ logger.debug("learn ack send failed", exc_info=True)
+ try:
+ event.text = build_learn_prompt(_learn_req)
+ # fall through to agent processing
+ except Exception:
+ return "Could not start /learn — please try again."
- # Runtime-metadata footer — only on the FINAL message of the turn.
- # Off by default (display.runtime_footer.enabled=false). When
- # streaming already delivered the body, we can't mutate the sent
- # text, so we fire a separate trailing send below.
- _footer_line = ""
+ if canonical == "init":
+ # /init: rewrite the turn to a guidance-laden prompt and fall
+ # through to normal agent processing (same fall-through as /learn
+ # so role alternation is preserved). The live agent scans the
+ # project with its own read-only tools and writes/updates
+ # AGENTS.md via write_file. No engine, works on any backend.
+ from hermes_cli.init_command import build_init_prompt_for_cwd
+
+ _init_notes = event.get_command_args().strip()
try:
- from gateway.runtime_footer import build_footer_line as _bfl
- _footer_line = _bfl(
- user_config=_load_gateway_config(),
- platform_key=_platform_config_key(source.platform),
- model=agent_result.get("model"),
- context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,
- context_length=agent_result.get("context_length") or None,
- cwd=os.environ.get("TERMINAL_CWD", ""),
- )
- except Exception as _footer_err:
- logger.debug("runtime_footer build failed: %s", _footer_err)
- _footer_line = ""
- if _footer_line and response and not agent_result.get("already_sent") and not _intentional_silence:
- response = f"{response}\n\n{_footer_line}"
+ _init_prompt = build_init_prompt_for_cwd(extra=_init_notes)
+ except Exception:
+ return "Could not start /init — please try again."
+ _ack = (
+ "Updating AGENTS.md from a project scan…"
+ if "UPDATE the existing AGENTS.md" in _init_prompt
+ else "Generating AGENTS.md from a project scan…"
+ )
+ try:
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ _ack_meta = self._thread_metadata_for_source(source)
+ await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta)
+ except Exception:
+ logger.debug("init ack send failed", exc_info=True)
+ event.text = _init_prompt
+ # fall through to agent processing
+
+ if canonical == "fast":
+ return await self._handle_fast_command(event)
+
+ if canonical == "verbose":
+ return await self._handle_verbose_command(event)
+
+ if canonical == "footer":
+ return await self._handle_footer_command(event)
- # Emit agent:end hook
- await self.hooks.emit("agent:end", {
- **hook_ctx,
- "response": (response or "")[:500],
- })
-
- # Check for pending process watchers (check_interval on background processes)
- try:
- from tools.process_registry import process_registry
- # Detach the current batch atomically (see crash-recovery drain
- # above): reassign to a fresh list so a watcher appended by a
- # concurrent session during the yield isn't dropped by clear().
- watchers = process_registry.pending_watchers
- process_registry.pending_watchers = []
- for i, watcher in enumerate(watchers):
- asyncio.create_task(self._run_process_watcher(watcher))
- if i % 100 == 99:
- await asyncio.sleep(0)
- except Exception as e:
- logger.error("Process watcher setup error: %s", e)
+ if canonical == "yolo":
+ return await self._handle_yolo_command(event)
- # Drain watch pattern notifications that arrived during the agent run.
- # Watch events and completions share the same queue; process
- # completions are already handled by the per-process watcher task
- # above, so we only inject watch-type events here.
- #
- # Async-delegation completions ALSO ride this shared queue but are
- # owned by the dedicated _async_delegation_watcher (started at
- # boot), which covers both the idle and post-turn cases with a
- # single consumer — so we leave them on the queue here.
- try:
- from tools.process_registry import process_registry as _pr
- _watch_events = _drain_gateway_watch_events(_pr.completion_queue)
- for evt in _watch_events:
- synth_text = _format_gateway_process_notification(evt)
- if synth_text:
- try:
- await self._inject_watch_notification(synth_text, evt)
- except Exception as e2:
- logger.error("Watch notification injection error: %s", e2)
- except Exception as e:
- logger.debug("Watch queue drain error: %s", e)
+ if canonical == "approvals":
+ return await self._handle_approvals_command(event)
- # NOTE: Dangerous command approvals are now handled inline by the
- # blocking gateway approval mechanism in tools/approval.py. The agent
- # thread blocks until the user responds with /approve or /deny, so by
- # the time we reach here the approval has already been resolved. The
- # old post-loop pop_pending + approval_hint code was removed in favour
- # of the blocking approach that mirrors CLI's synchronous input().
-
- # Save the full conversation to the transcript, including tool calls.
- # This preserves the complete agent loop (tool_calls, tool results,
- # intermediate reasoning) so sessions can be resumed with full context
- # and transcripts are useful for debugging and training data.
- #
- # IMPORTANT: For context-overflow failures (compression exhausted,
- # generic 400 on large sessions) we must NOT persist the user's
- # message — doing so would grow the session further and cause the
- # same failure on the next attempt, an infinite loop. (#1630, #9893)
- #
- # Transient failures (429, timeout, connection error, provider 5xx)
- # are different: the session is not oversized, and silently dropping
- # the user message causes severe context loss on retry — the agent
- # forgets what was just asked. Persist the user turn so the
- # conversation is preserved. (#7100)
- agent_failed_early = bool(agent_result.get("failed"))
- hidden_reasoning_incomplete = _is_gateway_hidden_reasoning_incomplete_turn(
- agent_result
+ if canonical == "model":
+ return await self._handle_model_command(event)
+
+ if canonical == "codex-runtime":
+ return await self._handle_codex_runtime_command(event)
+
+ if canonical == "personality":
+ return await self._handle_personality_command(event)
+
+ if canonical == "kanban":
+ return await self._handle_kanban_command(event)
+
+ if canonical == "suggestions":
+ return await self._handle_suggestions_command(event)
+
+ if canonical == "blueprint":
+ _blueprint_result = await self._handle_blueprint_command(event)
+ _blueprint_seed = getattr(_blueprint_result, "agent_seed", None)
+ if _blueprint_seed:
+ # Blueprint matched — rewrite the turn to the seed and fall
+ # through to _handle_message_with_agent so the agent asks the
+ # user for each slot value conversationally and then calls the
+ # cronjob tool (the /steer fall-through pattern). The seed
+ # enters as a normal user turn, preserving role alternation.
+ # Send the "Setting up X…" ack first so the user gets the same
+ # immediate feedback CLI users see, instead of silence until
+ # the agent's first question.
+ _ack = getattr(_blueprint_result, "text", "") or ""
+ if _ack:
+ try:
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ _ack_meta = self._thread_metadata_for_source(source)
+ await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta)
+ except Exception:
+ logger.debug("blueprint ack send failed", exc_info=True)
+ try:
+ event.text = _blueprint_seed
+ except Exception:
+ return getattr(_blueprint_result, "text", "") or None
+ else:
+ return getattr(_blueprint_result, "text", "") or None
+
+ if canonical == "retry":
+ return await self._handle_retry_command(event)
+
+ if canonical == "undo":
+ async def _do_undo():
+ return await self._handle_undo_command(event)
+ _undo_n = 1
+ _undo_raw = event.get_command_args().strip()
+ if _undo_raw:
+ try:
+ _undo_n = max(1, int(_undo_raw.split()[0]))
+ except (ValueError, IndexError):
+ _undo_n = 1
+ _undo_detail = (
+ "This removes the last user/assistant exchange from history."
+ if _undo_n == 1
+ else f"This removes the last {_undo_n} user turns from history."
)
- _err_str_for_classify = str(agent_result.get("error", "")).lower()
- # Use specific multi-word phrases (not bare "exceed" or "token")
- # to avoid false positives on transient errors like "rate limit
- # exceeded" or "invalid auth token". Matches run_agent.py's
- # own context-length classifier.
- is_context_overflow_failure = agent_failed_early and (
- bool(agent_result.get("compression_exhausted"))
- or any(p in _err_str_for_classify for p in (
- "context length", "context size", "context window",
- "maximum context", "token limit", "too many tokens",
- "reduce the length", "exceeds the limit",
- "request entity too large", "prompt is too long",
- "payload too large", "input is too long",
- ))
- or ("400" in _err_str_for_classify and len(history) > 50)
+ return await self._maybe_confirm_destructive_slash(
+ event=event,
+ command="undo",
+ title="/undo",
+ detail=_undo_detail,
+ execute=_do_undo,
)
- if is_context_overflow_failure:
- logger.info(
- "Skipping transcript persistence for context-overflow "
- "failure in session %s to prevent session growth loop.",
- session_entry.session_id,
- )
- elif agent_failed_early:
- logger.info(
- "Transient agent failure in session %s — persisting user "
- "message so conversation context is preserved on retry.",
- session_entry.session_id,
- )
- elif hidden_reasoning_incomplete:
- logger.warning(
- "Suppressing hidden-reasoning-only incomplete gateway turn "
- "for session %s: %s",
- session_entry.session_id,
- agent_result.get("error", "processing incomplete"),
- )
+
+ if canonical == "sethome":
+ return await self._handle_set_home_command(event)
- # When compression is exhausted, the session is permanently too
- # large to process. Auto-reset it so the next message starts
- # fresh instead of replaying the same oversized context in an
- # infinite fail loop. (#9893)
- #
- # A lock-contended defer is the OPPOSITE case: the session is
- # temporarily uncompressible only because a concurrent path holds
- # the compression lock and is actively shrinking it. Never wipe
- # the session for that — retry-next-message semantics apply
- # (#69870 lock-skip consumer; salvaged from #49874).
- if agent_result.get("compression_deferred"):
- logger.info(
- "Compression deferred for session %s — the compression "
- "lock is held by a concurrent compressor. Keeping the "
- "session intact; the next message retries normally.",
- session_entry.session_id if session_entry else "?",
- )
- elif agent_result.get("compression_exhausted") and session_entry and session_key:
- logger.info(
- "Auto-resetting session %s after compression exhaustion.",
- session_entry.session_id,
- )
- new_entry = await self.async_session_store.reset_session(session_key)
- self._evict_cached_agent(session_key)
- # Conversation boundary: one funnel call clears every
- # conversation-scoped per-session dict (#58403 and siblings).
- # See _CONVERSATION_SCOPED_STATE.
- self._clear_conversation_scope(
- session_key, reason="compression_exhausted_reset"
- )
- if new_entry is not None:
- # Drop the stale reference to the bloated compressed child and
- # re-point the Telegram topic binding at the fresh session.
- # Compression rotated session_entry.session_id to the oversized
- # compressed child earlier this turn (the agent-result sync
- # above), and that _sync also rewrote the (chat_id, thread_id)
- # -> bloated-child binding. reset_session swaps in a clean,
- # parentless session, but without re-syncing the binding the
- # next inbound message in this topic gets switch_session'd back
- # onto the bloated child by the binding-heal walk, reloads the
- # oversized transcript, and re-triggers compression exhaustion
- # forever (#35809 — regression of the #9893/#10063 auto-reset).
- # No-op on non-topic lanes.
- session_entry = new_entry
- await asyncio.to_thread(
- self._sync_telegram_topic_binding,
- source, session_entry, reason="compression-exhausted-reset",
- )
- response = (response or "") + (
- "\n\n🔄 Session auto-reset — the conversation exceeded the "
- "maximum context size and could not be compressed further. "
- "Your next message will start a fresh session."
- )
+ if canonical == "compress":
+ return await self._handle_compress_command(event)
+
+ if canonical == "usage":
+ return await self._handle_usage_command(event)
+
+ if canonical == "topup":
+ return await self._handle_topup_command(event)
+
+ if canonical == "insights":
+ return await self._handle_insights_command(event)
+
+ if canonical == "reload-mcp":
+ return await self._handle_reload_mcp_command(event)
+
+ if canonical == "reload-skills":
+ return await self._handle_reload_skills_command(event)
+
+ if canonical == "bundles":
+ return await self._handle_bundles_command(event)
+
+ if canonical == "approve":
+ return await self._handle_approve_command(event)
+
+ if canonical == "deny":
+ return await self._handle_deny_command(event)
+
+ if canonical == "update":
+ return await self._handle_update_command(event)
- ts = time.time() # Unix epoch float — consistent with DB storage
-
- # If this is a fresh session (no history), write the full tool
- # definitions as the first entry so the transcript is self-describing
- # -- the same list of dicts sent as tools=[...] in the API request.
- if is_context_overflow_failure:
- pass # Skip all transcript writes — don't grow a broken session
- elif not history:
- tool_defs = agent_result.get("tools", [])
- await self.async_session_store.append_to_transcript(
- session_entry.session_id,
- {
- "role": "session_meta",
- "tools": tool_defs or [],
- "model": _resolve_gateway_model(),
- "platform": source.platform.value if source.platform else "",
- "timestamp": ts,
- }
- )
-
- # The agent already persisted these messages to SQLite via
- # _flush_messages_to_session_db(), so skip the DB write here
- # to prevent the duplicate-write bug (#860 / #42039). This holds
- # for the codex app-server runtime too: although it early-returns
- # and bypasses conversation_loop's per-step flushes, it flushes its
- # own projected assistant/tool messages before returning and
- # reports agent_persisted=True (see agent/codex_runtime.py). Reading
- # the flag (default = self._session_db is not None) keeps the
- # persistence contract explicit and lets any future non-persisting
- # runtime opt into a gateway-side write by returning False.
- agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)
+ if canonical == "version":
+ return await self._handle_version_command(event)
- # Find only the NEW messages from this turn (skip history we loaded).
- # Use the filtered history length (history_offset) that was actually
- # passed to the agent, not len(history) which includes session_meta
- # entries that were stripped before the agent saw them.
- if is_context_overflow_failure:
- pass # handled above — skip all transcript writes
- elif agent_failed_early or hidden_reasoning_incomplete:
- # Transient failure (429/timeout/5xx): persist only the user
- # message so the next message can load a transcript that
- # reflects what was said. Skip the assistant error text since
- # it's a gateway-generated hint, not model output. Hidden-
- # reasoning-only incomplete turns follow the same persistence
- # rule so peer-agent channels don't ingest them as completed
- # assistant turns. (#7100, #51628)
- _user_entry = {
- "role": "user",
- "content": (
- persist_user_message
- if persist_user_message is not None
- else message_text
- ),
- "timestamp": (
- persist_user_timestamp
- if persist_user_timestamp is not None
- else ts
- ),
+ if canonical == "debug":
+ return await self._handle_debug_command(event)
+
+ if canonical == "title":
+ return await self._handle_title_command(event)
+
+ if canonical == "resume":
+ return await self._handle_resume_command(event)
+
+ if canonical == "sessions":
+ return await self._handle_sessions_command(event)
+
+ if canonical == "branch":
+ return await self._handle_branch_command(event)
+
+ if canonical == "rollback":
+ return await self._handle_rollback_command(event)
+
+ if canonical == "diff":
+ return await self._handle_diff_command(event)
+
+ if canonical == "background":
+ return await self._handle_background_command(event)
+
+ if canonical == "queue":
+ queue_payload = event.get_command_args().strip()
+ if not queue_payload:
+ return "Usage: /queue <prompt>"
+ try:
+ event.text = queue_payload
+ except Exception:
+ pass
+
+ if canonical == "steer":
+ # No active agent — /steer has no tool call to inject into.
+ # Strip the prefix so downstream treats it as a normal user
+ # message. If the payload is empty, surface the usage hint.
+ steer_payload = event.get_command_args().strip()
+ if not steer_payload:
+ return "Usage: /steer <prompt> (no agent is running; sending as a normal message)"
+ try:
+ event.text = steer_payload
+ except Exception:
+ pass
+ # Do NOT return — fall through to _handle_message_with_agent
+ # at the end of this function so the rewritten text is sent
+ # to the agent as a regular user turn.
+
+ if canonical == "goal":
+ return await self._handle_goal_command(event)
+
+ if canonical == "moa":
+ # /moa is one-shot sugar only: run a single prompt through the
+ # default MoA preset, then restore the prior model. To *switch* to a
+ # MoA preset for the session, pick it from the model picker (MoA
+ # presets surface as a virtual "Mixture of Agents" provider).
+ from hermes_cli.moa_config import (
+ moa_usage,
+ normalize_moa_config,
+ )
+ from hermes_cli.config import load_config
+
+ moa_payload = event.get_command_args().strip()
+ if not moa_payload:
+ return moa_usage()
+ try:
+ cfg = load_config()
+ moa_cfg = normalize_moa_config(cfg.get("moa") if isinstance(cfg, dict) else {})
+ except Exception:
+ moa_cfg = normalize_moa_config({})
+ preset = moa_cfg["default_preset"]
+ try:
+ event.text = moa_payload
+ _moa_state = self._session_state(_quick_key)
+ event._moa_restore_override = _moa_state.conversation.model_override
+ _moa_state.conversation.model_override = {
+ "provider": "moa",
+ "model": preset,
+ "base_url": "moa://local",
+ "api_key": "moa-virtual-provider",
+ "api_mode": "chat_completions",
}
- if event.message_id:
- _user_entry["message_id"] = str(event.message_id)
- # Dedupe: skip if this platform message_id is already in the
- # transcript (prevents duplicate user turns on Telegram retries
- # after transient failures). #47237
- _skip_persist = (
- event.message_id
- and await self.async_session_store.has_platform_message_id(
- session_entry.session_id, str(event.message_id)
- )
- )
- if _skip_persist:
- logger.info(
- "Skipping duplicate user turn "
- "(message_id=%s) in session %s",
- event.message_id, session_entry.session_id,
- )
- else:
- await self.async_session_store.append_to_transcript(
- session_entry.session_id,
- _user_entry,
- skip_db=agent_persisted,
- )
+ self._evict_cached_agent(_quick_key)
+ event._moa_disable_after_turn = True
+ except Exception:
+ return "Failed to prepare MoA turn."
+
+ if canonical == "subgoal":
+ return await self._handle_subgoal_command(event)
+
+ if canonical == "voice":
+ return await self._handle_voice_command(event)
+
+ if self._draining:
+ return f"⏳ Gateway is {self._status_action_gerund()} and is not accepting new work right now."
+
+ # User-defined quick commands (bypass agent loop, no LLM call)
+ if command:
+ if isinstance(self.config, dict):
+ quick_commands = self.config.get("quick_commands", {}) or {}
else:
- history_len = agent_result.get("history_offset", len(history))
- new_messages = agent_messages[history_len:] if len(agent_messages) > history_len else []
+ quick_commands = getattr(self.config, "quick_commands", {}) or {}
+ if not isinstance(quick_commands, dict):
+ quick_commands = {}
+ if command in quick_commands:
+ # Quick commands are slash capabilities too — and type:exec
+ # ones run a shell command in the gateway process. The early
+ # gate above only fires for registry-known commands, so quick
+ # commands (never in the registry) would otherwise reach this
+ # dispatch sink unchecked. Apply the same admin/user policy to
+ # the raw typed name here so non-admins can't invoke admin-only
+ # quick commands. (#44727)
+ _denied = self._check_slash_access(source, command)
+ if _denied is not None:
+ return _denied
+ qcmd = quick_commands[command]
+ if qcmd.get("type") == "exec":
+ exec_cmd = qcmd.get("command", "")
+ if exec_cmd:
+ try:
+ # Sanitize env to prevent credential leakage —
+ # quick commands run in the gateway process which
+ # has all API keys in os.environ.
+ from tools.environments.local import build_subprocess_env
+ sanitized_env = build_subprocess_env()
+ proc = await asyncio.create_subprocess_shell(
+ exec_cmd,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=sanitized_env,
+ )
+ stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
+ output = (stdout or stderr).decode().strip()
+ # Redact any remaining sensitive patterns in output
+ if output:
+ from agent.redact import redact_sensitive_text
+ output = redact_sensitive_text(output)
+ return output if output else "Command returned no output."
+ except asyncio.TimeoutError:
+ return "Quick command timed out (30s)."
+ except Exception as e:
+ return f"Quick command error: {e}"
+ else:
+ return f"Quick command '/{command}' has no command defined."
+ elif qcmd.get("type") == "alias":
+ target = (qcmd.get("target") or "").strip()
+ if target:
+ target = target if target.startswith("/") else f"/{target}"
+ target_command = target.lstrip("/")
+ user_args = event.get_command_args().strip()
+ event.text = f"{target} {user_args}".strip()
+ command = target_command.split()[0] if target_command else target_command
+ # Fall through to normal command dispatch below
+ else:
+ return f"Quick command '/{command}' has no target defined."
+ else:
+ return f"Quick command '/{command}' has unsupported type (supported: 'exec', 'alias')."
+
+ # Plugin-registered slash commands
+ if command:
+ try:
+ from hermes_cli.plugins import get_plugin_command_handler
+ # Normalize underscores to hyphens so Telegram's underscored
+ # autocomplete form matches plugin commands registered with
+ # hyphens. See hermes_cli/commands.py:_build_telegram_menu.
+ plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
+ if plugin_handler:
+ user_args = event.get_command_args().strip()
+ result = plugin_handler(user_args)
+ if asyncio.iscoroutine(result):
+ result = await result
+ return str(result) if result else None
+ except Exception as e:
+ logger.warning("Plugin command dispatch failed: %s", e)
- # If no new messages found (edge case), fall back to simple user/assistant
- if not new_messages:
- _user_entry = {
- "role": "user",
- "content": (
- persist_user_message
- if persist_user_message is not None
- else message_text
- ),
- "timestamp": (
- persist_user_timestamp
- if persist_user_timestamp is not None
- else ts
- ),
- }
- if event.message_id:
- _user_entry["message_id"] = str(event.message_id)
- await self.async_session_store.append_to_transcript(
- session_entry.session_id,
- _user_entry,
- skip_db=agent_persisted,
+ # Skill slash commands: /skill-name loads the skill and sends to agent.
+ # resolve_skill_command_key() handles the Telegram underscore/hyphen
+ # round-trip so /claude_code from Telegram autocomplete still resolves
+ # to the claude-code skill.
+ if command:
+ # Skill bundles take precedence over individual skill commands —
+ # /<bundle> loads multiple skills at once. Mirrors CLI dispatch.
+ _bundle_handled = False
+ try:
+ from agent.skill_bundles import (
+ build_bundle_invocation_message,
+ resolve_bundle_command_key,
+ )
+ bundle_key = resolve_bundle_command_key(command)
+ if bundle_key is not None:
+ user_instruction = event.get_command_args().strip()
+ # Pass the platform explicitly: bundle skill loading
+ # bypasses get_skill_commands()' scan-time disabled
+ # filter, and the gateway serves multiple platforms in
+ # one process, so env-var platform resolution can't be
+ # trusted here. Mirrors the stacked-skill gate (#58888).
+ _bundle_plat = source.platform.value if source.platform else None
+ bundle_result = build_bundle_invocation_message(
+ bundle_key, user_instruction, task_id=_quick_key,
+ platform=_bundle_plat,
)
- if response:
- await self.async_session_store.append_to_transcript(
- session_entry.session_id,
- {"role": "assistant", "content": response, "timestamp": ts},
- skip_db=agent_persisted,
+ if bundle_result:
+ msg, _loaded, missing = bundle_result
+ event.text = msg
+ _bundle_handled = True
+ if missing:
+ logger.info(
+ "Bundle %s skipped missing skills: %s",
+ bundle_key, ", ".join(missing),
+ )
+ # Fall through to normal message processing with bundle content
+ except Exception as exc:
+ logger.warning("Bundle dispatch failed: %s", exc)
+
+ if command and not locals().get("_bundle_handled", False):
+ try:
+ from agent.skill_commands import (
+ get_skill_commands,
+ build_skill_invocation_message,
+ resolve_skill_command_key,
+ )
+ skill_cmds = get_skill_commands()
+ cmd_key = resolve_skill_command_key(command)
+ if cmd_key is not None:
+ # Check per-platform disabled status before executing.
+ # get_skill_commands() only applies the *global* disabled
+ # list at scan time; per-platform overrides need checking
+ # here because the cache is process-global across platforms.
+ _skill_name = skill_cmds[cmd_key].get("name", "")
+ _plat = source.platform.value if source.platform else None
+ if _plat and _skill_name:
+ from agent.skill_utils import get_disabled_skill_names as _get_plat_disabled
+ if _skill_name in _get_plat_disabled(platform=_plat):
+ return (
+ f"The **{_skill_name}** skill is disabled for {_plat}.\n"
+ f"Enable it with: `hermes skills config`"
+ )
+ user_instruction = event.get_command_args().strip()
+ # Stacked slash-skill invocations: `/skill-a /skill-b do
+ # XYZ` loads every leading skill (up to 5), not just the
+ # first. Inspired by Claude Code v2.1.199. Mirrors CLI.
+ try:
+ from agent.skill_commands import (
+ build_stacked_skill_invocation_message as _build_stacked,
+ split_stacked_skill_commands,
+ )
+ extra_keys, stacked_instruction = (
+ split_stacked_skill_commands(user_instruction)
+ )
+ except Exception:
+ _build_stacked = None
+ extra_keys, stacked_instruction = [], user_instruction
+ if extra_keys and _plat:
+ # split_stacked_skill_commands() only resolves that
+ # each extra token is a KNOWN skill command — like
+ # get_skill_commands() itself, it has no per-platform
+ # view. Re-check every stacked skill (not just the
+ # leading one above) against the same disabled list,
+ # or a skill an operator disabled for this platform
+ # still gets its full content loaded via the stack.
+ from agent.skill_utils import get_disabled_skill_names as _get_plat_disabled
+ _plat_disabled = _get_plat_disabled(platform=_plat)
+ _disabled_extra = [
+ skill_cmds.get(k, {}).get("name", "")
+ for k in extra_keys
+ if skill_cmds.get(k, {}).get("name", "") in _plat_disabled
+ ]
+ if _disabled_extra:
+ return (
+ f"The **{', '.join(_disabled_extra)}** skill(s) in this "
+ f"stacked invocation are disabled for {_plat}.\n"
+ f"Enable them with: `hermes skills config`"
+ )
+ if extra_keys and _build_stacked is not None:
+ stacked_result = _build_stacked(
+ [cmd_key, *extra_keys],
+ stacked_instruction,
+ task_id=_quick_key,
)
+ if stacked_result:
+ msg, _loaded, _missing = stacked_result
+ event.text = msg
+ # Fall through to normal message processing
+ else:
+ return f"Failed to load stacked skills for /{command}."
+ else:
+ msg = build_skill_invocation_message(
+ cmd_key, user_instruction, task_id=_quick_key
+ )
+ if msg:
+ event.text = msg
+ # Fall through to normal message processing with skill content
else:
- # Attach the inbound platform message_id to the first user
- # entry written this turn so platform-level quote-resolution
- # (e.g. Yuanbao QuoteContextMiddleware's transcript fallback)
- # can find earlier @bot messages by their original message_id.
- _user_msg_id_attached = False
- for msg in new_messages:
- # Skip system messages (they're rebuilt each run)
- if msg.get("role") == "system":
- continue
- # Add timestamp to each message for debugging
- entry = {**msg, "timestamp": ts}
- if (
- not _user_msg_id_attached
- and msg.get("role") == "user"
- and event.message_id
- and "message_id" not in entry
- ):
- entry["message_id"] = str(event.message_id)
- _user_msg_id_attached = True
- await self.async_session_store.append_to_transcript(
- session_entry.session_id, entry,
- skip_db=agent_persisted,
+ # Not an active skill — check if it's a known-but-disabled or
+ # uninstalled skill and give actionable guidance.
+ _unavail_msg = _check_unavailable_skill(command)
+ if _unavail_msg:
+ return _unavail_msg
+ # Genuinely unrecognized /command: not a built-in, not a
+ # plugin, not a skill, not a known-inactive skill. Warn
+ # the user instead of silently forwarding it to the LLM
+ # as free text (which leads to silent-failure behavior
+ # like the model inventing a delegate_task call).
+ # Normalize to hyphenated form before checking known
+ # built-ins (command may be an alias target set by the
+ # quick-command block above, so _cmd_def can be stale).
+ if command.replace("_", "-") not in GATEWAY_KNOWN_COMMANDS:
+ logger.warning(
+ "Unrecognized slash command /%s from %s — "
+ "replying with unknown-command notice",
+ command,
+ source.platform.value if source.platform else "?",
+ )
+ return (
+ f"Unknown command `/{command}`. "
+ f"Type /commands to see what's available, "
+ f"or resend without the leading slash to send "
+ f"as a regular message."
+ )
+ except Exception as e:
+ logger.debug("Skill command check failed (non-fatal): %s", e)
+
+ # Pending exec approvals are handled by /approve and /deny commands above.
+ # No bare text matching — "yes" in normal conversation must not trigger
+ # execution of a dangerous command.
+
+ if not is_internal and await asyncio.to_thread(
+ self._is_telegram_topic_root_lobby, source
+ ):
+ # Debounce the lobby reminder so a user who forgets about
+ # topic mode and fires ten prompts doesn't get ten copies.
+ if self._should_send_telegram_lobby_reminder(source):
+ return self._telegram_topic_root_lobby_message()
+ return None
+
+ # ── External-drain new-turn gate (Phase 2) ────────────────────
+ # When NAS has engaged an external drain (.drain_request.json present,
+ # observed by _drain_control_watcher), refuse to START a new turn so
+ # the in-flight set can only fall to zero — eliminating the TOCTOU race
+ # (D4a: stop accepting new turns FIRST, then NAS polls until
+ # active_agents==0). In-flight turns are untouched; this only blocks the
+ # claim of a NEW session slot. Internal/system events (restart-recovery
+ # replays, background-process completions) bypass the gate — they are
+ # not user-initiated new work and must still flow during a drain.
+ # Reversible: once the marker is removed the gate opens again.
+ if self._external_drain_active and not is_internal:
+ logger.info(
+ "Refusing new turn for session %s — external drain active.",
+ _quick_key,
+ )
+ return (
+ "⏳ This agent is draining for a maintenance action and isn't "
+ "accepting new turns right now. It'll be back in a moment — "
+ "please resend shortly."
+ )
+
+ # ── Claim this session before any await ───────────────────────
+ # Between here and _run_agent registering the real AIAgent, there
+ # are numerous await points (hooks, vision enrichment, STT,
+ # session hygiene compression). Without this sentinel a second
+ # message arriving during any of those yields would pass the
+ # "already running" guard and spin up a duplicate agent for the
+ # same session — corrupting the transcript.
+ _active_session_lease, _limit_message = self._claim_active_session_slot(
+ _quick_key,
+ source,
+ )
+ if _limit_message is not None:
+ logger.info(
+ "Rejecting new active session %s: max_concurrent_sessions reached",
+ _quick_key,
+ )
+ return _limit_message
+ _claim_state = self._session_state(_quick_key)
+ if _active_session_lease is not None:
+ _claim_state.turn.lease = _active_session_lease
+ _claim_state.turn.agent = _AGENT_PENDING_SENTINEL
+ _claim_state.turn.started_ts = time.time()
+ self._persist_active_agents()
+ _run_generation = self._begin_session_run_generation(_quick_key)
+
+ try:
+ _agent_result = await self._handle_message_with_agent(event, source, _quick_key, _run_generation)
+ # Goal continuation: after the agent returns a final response
+ # for this turn, check any standing /goal — the judge will
+ # either mark it done, pause it (budget), or enqueue a
+ # continuation prompt back through the adapter FIFO so the
+ # next turn makes more progress. Wrapped in try/except so a
+ # broken judge never breaks normal message handling.
+ try:
+ _final_text = ""
+ if isinstance(_agent_result, dict):
+ _final_text = str(_agent_result.get("final_response") or "")
+ elif isinstance(_agent_result, str):
+ _final_text = _agent_result
+ # Skip for empty responses (interrupted / errored) — the
+ # judge would almost always say "continue" and we'd loop
+ # on error. Let the user drive the next turn.
+ if _final_text.strip():
+ try:
+ session_entry = await self.async_session_store.get_or_create_session(source)
+ except Exception:
+ session_entry = None
+ if session_entry is not None:
+ await self._post_turn_goal_continuation(
+ session_entry=session_entry,
+ source=source,
+ final_response=_final_text,
)
-
- # Token counts and model are now persisted by the agent directly.
- # Keep only last_prompt_tokens here for context-window tracking and
- # compression decisions.
- await self.async_session_store.update_session(
- session_entry.session_key,
- last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),
- )
+ except Exception as _goal_exc:
+ logger.debug("goal continuation hook failed: %s", _goal_exc)
+ return _agent_result
+ finally:
+ # MoA one-shot restore must run on EVERY exit path, not just
+ # success. The restore data lives on the per-turn event object
+ # (_moa_restore_override), which is discarded once the event goes
+ # out of scope — so if _handle_message_with_agent raises, a restore
+ # in the try block would be skipped and the MoA override would leak
+ # permanently (every later message silently fans out through MoA).
+ # Putting it in finally guarantees the revert on success, exception,
+ # and interrupt alike.
+ self._restore_moa_one_shot(event, _quick_key)
+ self._restore_pending_one_turn_model_override(_quick_key)
+ # Unconditional release covers every exit path. _release_running_agent_state
+ # is idempotent (pop-on-absent is harmless) and, called without a
+ # run_generation guard, always clears the slot regardless of which
+ # generation it holds. This evicts the zombie left when session_reset
+ # bumps the generation (N -> N+1) mid-flight: gen-N's guarded release
+ # inside _run_agent returns False, and the old sentinel-only check here
+ # missed the leftover real agent — locking the session out forever (#28686).
+ self._release_running_agent_state(_quick_key)
+ # Turn lease (#64934): release THIS turn's lease token — keyed by
+ # (routing key, run generation) so this unwind can only ever free
+ # the lease its own turn acquired, never a newer turn's.
+ self._release_turn_lease(_quick_key, _run_generation)
- # Re-baseline the cached agent's message_count snapshot now that
- # ALL of this turn's transcript writes are done — the agent's
- # flushed user/assistant/tool rows AND the first-turn `session_meta`
- # marker appended above. The cross-process coherence guard (#45966)
- # snapshots the count at agent-BUILD time (before this turn's own
- # writes) and never refreshes it on reuse, so without this the
- # process's own turn grows message_count and the next turn sees a
- # mismatch and rebuilds the agent — destroying prompt caching.
- #
- # This MUST run after the `session_meta` append: that row also
- # increments message_count, so re-baselining before it (the old
- # position) left the snapshot one short and the guard mis-fired on
- # turn 2 of EVERY fresh gateway conversation, rebuilding the cached
- # agent and busting the prompt cache. Running here also uses the
- # compaction-updated session_id (the agent_result session_id swap
- # above), matching this function's documented contract. Refreshing
- # here makes the guard fire only on a DIFFERENT process's writes.
- # Fail-safe inside the helper.
- await self._refresh_agent_cache_message_count(
- session_key, session_entry.session_id
- )
+ def _restore_moa_one_shot(self, event: "MessageEvent", quick_key: str) -> None:
+ """Revert a ``/moa <prompt>`` one-shot model override after its turn.
- # Intentional silence is a delivery decision, not a transcript
- # mutation. The agent's [SILENT]/NO_REPLY assistant turn above is
- # still persisted in session history so later turns keep normal
- # user/assistant alternation; only the outbound chat delivery is
- # suppressed.
- if _intentional_silence:
- logger.info(
- "Suppressing intentional silence marker for session %s",
- session_entry.session_id,
+ Called from the ``finally`` of the message-handling path so the revert
+ fires whether the turn succeeded, raised, or was interrupted. A no-op
+ unless ``event._moa_disable_after_turn`` is set. ``_moa_restore_override``
+ carries the prior per-session override (``None`` means the user had no
+ override, so the MoA override is cleared outright).
+ """
+ if not getattr(event, "_moa_disable_after_turn", False):
+ return
+ try:
+ _restore = getattr(event, "_moa_restore_override", None)
+ self._session_state(quick_key).conversation.model_override = _restore
+ self._evict_cached_agent(quick_key)
+ except Exception:
+ pass
+
+ def _restore_pending_one_turn_model_override(self, session_key: str) -> None:
+ """Restore a per-session model override after ``/model --once`` runs."""
+ if not session_key:
+ return
+ try:
+ _otr_state = self._peek_session_state(session_key)
+ snapshot = _otr_state.conversation.one_turn_restore if _otr_state else None
+ if _otr_state is not None:
+ _otr_state.conversation.one_turn_restore = None
+ if not snapshot:
+ return
+ self._restore_session_model_override(session_key, snapshot)
+ except Exception:
+ logger.debug("Failed to restore one-turn model override", exc_info=True)
+
+ async def _prepare_inbound_message_text(
+ self,
+ *,
+ event: MessageEvent,
+ source: SessionSource,
+ history: List[Dict[str, Any]],
+ session_key: Optional[str] = None,
+ ) -> Optional[str]:
+ """Prepare inbound event text for the agent.
+
+ Keep the normal inbound path and the queued follow-up path on the same
+ preprocessing pipeline so sender attribution, image enrichment, STT,
+ document notes, reply context, and @ references all behave the same.
+
+ Side effect: buffers per-session native image paths when the active
+ model supports native vision AND the user has images attached. The
+ caller consumes and clears that session-scoped buffer at the
+ ``run_conversation`` site to build a multimodal user turn. When the
+ list is empty, the ``_enrich_message_with_vision`` text path has
+ already run and images are represented in-text.
+ """
+ history = history or []
+ _pending_stt_prepared = hasattr(event, "_gateway_pending_stt_text")
+ message_text = (
+ getattr(event, "_gateway_pending_stt_text", None)
+ if _pending_stt_prepared
+ else event.text
+ ) or ""
+ _group_sessions_per_user = getattr(self.config, "group_sessions_per_user", True)
+ _thread_sessions_per_user = getattr(self.config, "thread_sessions_per_user", False)
+ # Prefer the already resolved session key from the caller so this write
+ # key matches the consume key at the run_conversation site. Fall back
+ # to deriving it here for tests and legacy standalone callers.
+ session_key = session_key or self._session_key_for_source(source)
+ # Reset only this session's per-call buffer; other sessions may be
+ # concurrently preparing multimodal turns on the same runner.
+ self._consume_pending_native_image_paths(session_key)
+
+ _is_shared_multi_user = is_shared_multi_user_session(
+ source,
+ group_sessions_per_user=_group_sessions_per_user,
+ thread_sessions_per_user=_thread_sessions_per_user,
+ )
+ if _is_shared_multi_user and source.user_name:
+ # source.user_name is the platform display name — attacker-
+ # influenceable on any platform that lets participants set their
+ # own name. Neutralize embedded newlines/control chars before
+ # interpolating it into every message in the shared session, or
+ # a hostile name can masquerade as a fake markdown section
+ # (mirrors the same field's treatment in
+ # build_session_context_prompt via _format_untrusted_prompt_value).
+ _safe_user_name = neutralize_untrusted_inline_text(source.user_name)
+ # On Slack, expose the current author's verifiable user ID next to
+ # the display name (#17916): "mention me again" requests need a
+ # trusted `<@U...>` target for the CURRENT speaker — display names
+ # are ambiguous and historical mentions may point at someone else.
+ # The user_id comes from the Slack event envelope (not
+ # user-editable text), so it does not need neutralization.
+ if source.platform == Platform.SLACK and source.user_id:
+ _safe_user_name = (
+ f"{_safe_user_name} | Slack user <@{source.user_id}>"
)
- response = ""
+ message_text = f"[{_safe_user_name}] {message_text}"
- # Auto voice reply: send TTS audio before the text response
- _already_sent = bool(agent_result.get("already_sent"))
- # Skip when streaming TTS already delivered audio for this turn (#60671).
- _stts_adapter = self._adapter_for_source(source)
- _streaming_tts_done = (
- _stts_adapter is not None
- and bool(getattr(_stts_adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation))
- )
- if (
- not _streaming_tts_done
- and self._should_send_voice_reply(event, response, agent_messages, already_sent=_already_sent)
- ):
- await self._send_voice_reply(event, response)
+ # Prepend channel context from history backfill (if any). This
+ # happens after sender-prefix so the prefix only applies to the
+ # trigger message, not the backfill block.
+ if getattr(event, "channel_context", None):
+ message_text = f"{event.channel_context}\n\n[New message]\n{message_text}"
- # If streaming already delivered the response, extract and
- # deliver any MEDIA: files before returning None. Streaming
- # sends raw text chunks that include MEDIA: tags — the normal
- # post-processing in _process_message_background is skipped
- # when already_sent is True, so media files would never be
- # delivered without this.
- #
- # Never skip when the agent failed — the error message is new
- # content the user hasn't seen (streaming only sent earlier
- # partial output before the failure). Without this guard,
- # users see the agent "stop responding without explanation."
- if agent_result.get("already_sent") and not agent_result.get("failed"):
- if response:
- _media_adapter = self._adapter_for_source(source)
- if _media_adapter:
- await self._deliver_media_from_response(
- response, event, _media_adapter,
- history_media_paths=_collect_history_media_paths(history),
- )
- # Streaming already delivered the body text, but the footer was
- # intentionally held back (see the `not already_sent` gate above).
- # Send it now as a small trailing message so Telegram/Discord/etc.
- # still surface the runtime metadata on the final reply.
- if _footer_line:
- try:
- _foot_adapter = self._adapter_for_source(source)
- if _foot_adapter:
- await _foot_adapter.send(
- source.chat_id,
- _footer_line,
- metadata=self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)),
- )
- except Exception as _e:
- logger.debug("trailing footer send failed: %s", _e)
- return None
+ # Declare at outer scope so the audio-file-paths handling block below
+ # remains safe when ``event.media_urls`` is empty (no inner block runs).
+ audio_file_paths: list[str] = []
+ video_paths: list[str] = []
+
+ if event.media_urls:
+ image_paths = []
+ audio_paths = []
+ for i, path in enumerate(event.media_urls):
+ mtype = event.media_types[i] if i < len(event.media_types) else ""
+ # Classify images per-attachment: trust this attachment's own
+ # MIME, and only honour the message-level PHOTO type when the
+ # per-attachment MIME is unknown. Otherwise a document (or any
+ # non-image) sent alongside an image in the same message gets
+ # mis-routed here as an image and the provider 400s.
+ if _event_media_is_image(event, i):
+ image_paths.append(path)
+ # MessageType.AUDIO = audio file attachment (e.g. .mp3, .m4a) — never STT
+ # MessageType.VOICE = voice message (Opus/OGG) — always STT
+ if event.message_type == MessageType.AUDIO:
+ audio_file_paths.append(path)
+ elif not _pending_stt_prepared and _event_media_is_stt_input(event, i):
+ audio_paths.append(path)
+ if mtype.startswith("video/") or (not mtype and event.message_type == MessageType.VIDEO):
+ video_paths.append(path)
- return response
-
- except Exception as e:
- # Stop typing indicator on error too, retaining Slack thread/workspace
- # routing so a failed turn cannot leave its status visible.
- try:
- _err_adapter = self._adapter_for_source(source)
- _stop_with_metadata = getattr(
- type(_err_adapter), "_stop_typing_with_metadata", None
+ if image_paths:
+ # Decide routing: native (attach pixels) vs text (vision_analyze
+ # pre-run + prepend description). See agent/image_routing.py.
+ # Offload to a worker thread: the decision does blocking network
+ # I/O — a models.dev fetch on cache miss, and the Ollama
+ # ``/api/show`` capability probe for local servers — whose
+ # request timeout would otherwise stall the whole gateway event
+ # loop (every session) while a single image is routed.
+ _img_mode = await asyncio.to_thread(
+ self._decide_image_input_mode,
+ source=source,
+ session_key=session_key,
)
- _stop_typing = getattr(type(_err_adapter), "stop_typing", None)
- if _err_adapter and callable(_stop_with_metadata):
- await _err_adapter._stop_typing_with_metadata(
- source.chat_id,
- self._thread_metadata_for_source(
- source, self._reply_anchor_for_event(event)
- ),
+ if _img_mode == "native":
+ # Defer attachment to the run_conversation call site.
+ self._session_state(
+ session_key
+ ).persistent.native_image_paths = list(image_paths)
+ logger.info(
+ "Image routing: native (model supports vision). %d image(s) will be attached inline.",
+ len(image_paths),
)
- elif _err_adapter and callable(_stop_typing):
- await _err_adapter.stop_typing(source.chat_id)
- except Exception:
- pass
- logger.exception("Agent error in session %s", session_key)
- # Crash-resilience for failures that happen before AIAgent enters
- # run_conversation() (for example: provider/httpx client init
- # failures). In that path the agent cannot persist the current
- # inbound turn itself, so append the user message here once. If the
- # agent already reached its early turn-start persistence, the latest
- # transcript user row will match and we skip the duplicate.
- try:
- if 'message_text' in locals() and message_text is not None and session_entry is not None:
- _already_persisted = False
+ else:
+ logger.info(
+ "Image routing: text (mode=%s). Pre-analyzing %d image(s) via vision_analyze.",
+ _img_mode, len(image_paths),
+ )
+ # Vision enrichment runs before AIAgent.run_conversation(),
+ # so bind this session's resolved runtime explicitly rather
+ # than consulting process-global compatibility mirrors.
+ vision_runtime = None
try:
- _recent_transcript = await self.async_session_store.load_transcript(session_entry.session_id)
+ turn_model, runtime_kwargs = self._resolve_session_agent_runtime(
+ source=source,
+ session_key=session_key,
+ )
+ vision_runtime = dict(runtime_kwargs or {})
+ vision_runtime["model"] = turn_model
except Exception:
- _recent_transcript = []
- for _msg in reversed(_recent_transcript[-10:]):
- if _msg.get("role") == "user":
- _expected_user_content = (
- persist_user_message
- if persist_user_message is not None
- else message_text
- )
- _already_persisted = (_msg.get("content") == _expected_user_content)
- break
- if not _already_persisted:
- _user_entry = {
- "role": "user",
- "content": (
- persist_user_message
- if persist_user_message is not None
- else message_text
- ),
- "timestamp": (
- persist_user_timestamp
- if persist_user_timestamp is not None
- else time.time()
- ),
- }
- if getattr(event, "message_id", None):
- _user_entry["message_id"] = str(event.message_id)
- await self.async_session_store.append_to_transcript(
- session_entry.session_id,
- _user_entry,
+ logger.debug(
+ "vision enrichment: session runtime resolution failed",
+ exc_info=True,
)
- except Exception:
- logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)
- # Log full details server-side only; never expose raw exception
- # types or messages to end users (info-leakage risk).
- status_hint = ""
- status_code = getattr(e, "status_code", None)
- _hist_len = len(history) if 'history' in locals() else 0
- if status_code == 401:
- status_hint = " Check your API key or run `claude /login` to refresh OAuth credentials."
- elif status_code == 402:
- status_hint = " Your API balance or quota is exhausted. Check your provider dashboard."
- elif status_code == 429:
- # Check if this is a plan usage limit (resets on a schedule) vs a transient rate limit
- _err_body = getattr(e, "response", None)
- _err_json = {}
+
+ from agent.auxiliary_client import scoped_runtime_main
+
+ with scoped_runtime_main(vision_runtime):
+ message_text = await self._enrich_message_with_vision(
+ message_text,
+ image_paths,
+ )
+
+ if audio_paths:
+ message_text, _successful_transcripts = await self._enrich_message_with_transcription(
+ message_text,
+ audio_paths,
+ )
+ # Echo each successful transcript back to the user immediately
+ # when configured. Lets users verify STT quality in real-time,
+ # while allowing quiet STT for users who only want the agent to
+ # receive the transcription.
+ if _successful_transcripts and self._should_echo_stt_transcripts():
+ _echo_adapter = self._adapter_for_source(source)
+ _echo_meta = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
+ if _echo_adapter:
+ for _tx in _successful_transcripts:
+ try:
+ await _echo_adapter.send(
+ source.chat_id,
+ f'🎙️ "{_tx}"',
+ metadata=_echo_meta,
+ )
+ except Exception as _echo_exc:
+ logger.debug(
+ "Transcript echo failed (non-fatal): %s", _echo_exc,
+ )
+ # NOTE: Previously, when transcription failed (e.g. no STT
+ # provider configured), the gateway also emitted a hardcoded
+ # English notice via `_stt_adapter.send()`. That bypassed the
+ # LLM and produced two replies — one pre-canned English clip
+ # (which TTS then spoke aloud, in the wrong language) and one
+ # correct, localized LLM reply from the enriched message text.
+ # The enrichment step now leaves a single neutral marker in the
+ # prompt, so the LLM produces one coherent reply in the user's
+ # language. The hardcoded send has therefore been removed.
+
+ if audio_file_paths:
+ from tools.credential_files import to_agent_visible_cache_path as _to_agent_path
+ for _apath in audio_file_paths:
+ _basename = os.path.basename(_apath)
+ _parts = _basename.split("_", 2)
+ _display = _parts[2] if len(_parts) >= 3 else _basename
+ _display = re.sub(r'[^\w.\- ]', '_', _display)
+ _agent_path = _to_agent_path(_apath)
+ _note = (
+ f"[The user sent an audio file attachment: '{_display}'. "
+ f"It is saved at: {_agent_path}. "
+ f"Its content is not inlined here. If the user's request involves "
+ f"what the audio contains, transcribe or process it yourself — for "
+ f"example by passing the path to a transcription or media tool — "
+ f"instead of asking the user to describe it. Only ask what to do "
+ f"with it if their intent is genuinely unclear.]"
+ )
+ message_text = f"{_note}\n\n{message_text}"
+
+ if video_paths:
+ from tools.credential_files import to_agent_visible_cache_path as _to_agent_path
+ for _vpath in video_paths:
+ _basename = os.path.basename(_vpath)
+ _parts = _basename.split("_", 2)
+ _display = _parts[2] if len(_parts) >= 3 else _basename
+ _display = re.sub(r'[^\w.\- ]', '_', _display)
+ _agent_path = _to_agent_path(_vpath)
+ _note = (
+ f"[The user sent a video attachment: '{_display}'. "
+ f"It is saved at: {_agent_path}. "
+ f"Its content is not inlined here. If the user's request involves "
+ f"what the video contains, inspect or process it yourself — for "
+ f"example by passing the path to a video analysis or media tool — "
+ f"instead of asking the user to describe it. Only ask what to do "
+ f"with it if their intent is genuinely unclear.]"
+ )
+ message_text = f"{_note}\n\n{message_text}"
+
+ if event.media_urls:
+ import mimetypes as _mimetypes
+ from tools.credential_files import to_agent_visible_cache_path
+
+ _TEXT_EXTENSIONS = {".txt", ".md", ".csv", ".log", ".json", ".xml", ".yaml", ".yml", ".toml", ".ini", ".cfg"}
+ for i, path in enumerate(event.media_urls):
+ # Per-attachment document handling. Skip anything already routed
+ # as image / audio / video by the buckets above — only genuine
+ # non-media files get a path-pointing context note. This makes a
+ # document mixed into a PHOTO/VOICE message (whole-message type
+ # != DOCUMENT) still reach the agent as a readable cached file,
+ # instead of being silently dropped because the message-level
+ # type wasn't DOCUMENT.
+ if (
+ _event_media_is_image(event, i)
+ or _event_media_is_audio(event, i)
+ or _event_media_is_video(event, i)
+ ):
+ continue
+ mtype = event.media_types[i] if i < len(event.media_types) else ""
+ if mtype in {"", "application/octet-stream"}:
+ _ext = os.path.splitext(path)[1].lower()
+ if _ext in _TEXT_EXTENSIONS:
+ mtype = "text/plain"
+ else:
+ guessed, _ = _mimetypes.guess_type(path)
+ if guessed:
+ mtype = guessed
+ else:
+ mtype = "application/octet-stream"
+ # Any accepted file gets a path-pointing context note — we accept
+ # all file types now, so a non-text/non-application MIME (font/*,
+ # model/*, etc.) must still tell the agent the file exists.
+
+ basename = os.path.basename(path)
+ parts = basename.split("_", 2)
+ display_name = parts[2] if len(parts) >= 3 else basename
+ display_name = re.sub(r'[^\w.\- ]', '_', display_name)
+
+ # Translate host cache path to in-container path if running under Docker backend.
+ # This ensures the agent receives a path it can open inside its sandbox, as the
+ # cache directories are auto-mounted at /root/.hermes/cache/* by get_cache_directory_mounts().
+ agent_path = to_agent_visible_cache_path(path)
+
+ context_note = _build_document_context_note(display_name, agent_path, mtype)
+ message_text = f"{context_note}\n\n{message_text}"
+
+ # Discord: surface the triggering message id per-turn on the user
+ # message rather than in the cached system prompt. message_id changes
+ # every turn, so baking it into build_session_context_prompt() would
+ # bust the agent-cache signature and rebuild the AIAgent every message
+ # (destroying prompt caching). The static IDs block points the agent
+ # here; the volatile id rides the per-turn user content.
+ if (
+ source is not None
+ and getattr(source, "platform", None) == Platform.DISCORD
+ and getattr(event, "message_id", None)
+ ):
+ from gateway.session import _discord_tools_loaded as _disc_tools_loaded
+ if _disc_tools_loaded():
+ message_text = (
+ f"[Triggering message id: `{event.message_id}` — use as "
+ f"`message_id` for reply/react/pin via the discord tools.]\n\n"
+ f"{message_text}"
+ )
+
+ if getattr(event, "reply_to_text", None) and event.reply_to_message_id:
+ # Always inject the reply-to pointer — even when the quoted text
+ # already appears in history. The prefix isn't deduplication, it's
+ # disambiguation: it tells the agent *which* prior message the user
+ # is referencing. History can contain the same or similar text
+ # multiple times, and without an explicit pointer the agent has to
+ # guess (or answer for both subjects). Token overhead is minimal.
+ reply_snippet = event.reply_to_text[:500]
+ if getattr(event, "reply_to_is_own_message", False):
+ message_text = (
+ f'[Replying to your previous message: "{reply_snippet}"]\n\n'
+ f"{message_text}"
+ )
+ else:
+ message_text = f'[Replying to: "{reply_snippet}"]\n\n{message_text}'
+
+ if "@" in message_text:
+ try:
+ from agent.context_references import preprocess_context_references_async
+ from agent.model_metadata import get_model_context_length_async
+
+ _msg_cwd = os.environ.get("TERMINAL_CWD", os.path.expanduser("~"))
+ _msg_config_ctx = None
+ _msg_cfg = None
+ _msg_model_cfg = {}
+ _msg_custom_providers = []
try:
- if _err_body is not None:
- _err_json = _err_body.json().get("error", {})
- if not isinstance(_err_json, dict):
- _err_json = {}
+ _msg_cfg = _load_gateway_config()
+ _msg_model_cfg = _msg_cfg.get("model", {})
+ if isinstance(_msg_model_cfg, dict):
+ _msg_raw_ctx = _msg_model_cfg.get("context_length")
+ if _msg_raw_ctx is not None:
+ _msg_config_ctx = int(_msg_raw_ctx)
+ try:
+ from hermes_cli.config import get_compatible_custom_providers
+
+ _msg_custom_providers = get_compatible_custom_providers(_msg_cfg)
+ except Exception:
+ _msg_custom_providers = _msg_cfg.get("custom_providers") or []
except Exception:
pass
- if _err_json.get("type") == "usage_limit_reached":
- _resets_in = _err_json.get("resets_in_seconds")
- if _resets_in and _resets_in > 0:
- import math
- _hours = math.ceil(_resets_in / 3600)
- status_hint = f" Your plan's usage limit has been reached. It resets in ~{_hours}h."
- else:
- status_hint = " Your plan's usage limit has been reached. Please wait until it resets."
- else:
- status_hint = " You are being rate-limited. Please wait a moment and try again."
- elif status_code == 529:
- status_hint = " The API is temporarily overloaded. Please try again shortly."
- elif status_code in {400, 500}:
- # 400 with a large session is context overflow.
- # 500 with a large session often means the payload is too large
- # for the API to process — treat it the same way.
- if _hist_len > 50:
- return (
- "⚠️ Session too large for the model's context window.\n"
- "Use /compact to compress the conversation, or "
- "/reset to start fresh."
- )
- elif status_code == 400:
- status_hint = " The request was rejected by the API."
- return (
- f"Sorry, I encountered an unexpected error.{status_hint}\n"
- "Try again or use /reset to start a fresh session."
- )
- finally:
- # Restore session context variables to their pre-handler state
- self._clear_session_env(_session_env_tokens)
+ # Resolve the session's actual model/provider/base_url the
+ # same way the hygiene compression block does (~11080).
+ # GatewayRunner has no self._model/self._base_url attrs
+ # (that was copy-pasted from HermesCLI, which does carry
+ # self.model/self.base_url), so using them here always raised
+ # AttributeError, silently caught below, meaning this feature
+ # never ran.
+ _msg_model, _msg_runtime = self._resolve_session_agent_runtime(
+ source=source,
+ session_key=session_key,
+ user_config=_msg_cfg,
+ )
+ _msg_base_url = _msg_runtime.get("base_url") or ""
+ # A global model.context_length belongs to the configured
+ # model, not a session /model or channel override. Prefer a
+ # matching per-custom-provider model limit when available.
+ _msg_configured_model = (
+ _msg_model_cfg.get("default") or _msg_model_cfg.get("model")
+ if isinstance(_msg_model_cfg, dict)
+ else _msg_model_cfg
+ )
+ if _msg_model != _msg_configured_model:
+ _msg_config_ctx = None
+ if _msg_config_ctx is not None and isinstance(_msg_model_cfg, dict):
+ try:
+ from hermes_cli.route_identity import should_clear_context_pin_async
- def _reset_notice_session_info(self, source: SessionSource) -> str:
- """Session-info block for the auto-reset notice, profile-scoped.
+ if await should_clear_context_pin_async(
+ None, # model match already checked above
+ None,
+ _msg_model_cfg.get("base_url"),
+ _msg_base_url,
+ _msg_model_cfg.get("provider"),
+ _msg_runtime.get("provider"),
+ ):
+ _msg_config_ctx = None
+ except Exception:
+ _msg_config_ctx = None
+ if _msg_custom_providers and _msg_base_url:
+ try:
+ from hermes_cli.config import get_custom_provider_context_length
- When multiplexing, resolve model/provider/context inside the profile
- serving ``source`` — otherwise the banner advertises the base config's
- model while the session actually runs on the profile's (#59003).
- Mirrors ``_run_agent``'s gating so single-profile gateways never
- enter the scope.
+ _msg_custom_ctx = get_custom_provider_context_length(
+ model=_msg_model,
+ base_url=_msg_base_url,
+ custom_providers=_msg_custom_providers,
+ )
+ if _msg_custom_ctx:
+ _msg_config_ctx = _msg_custom_ctx
+ except Exception:
+ pass
+ _msg_ctx_len = await get_model_context_length_async(
+ _msg_model,
+ base_url=_msg_base_url,
+ api_key=_msg_runtime.get("api_key") or "",
+ config_context_length=_msg_config_ctx,
+ provider=_msg_runtime.get("provider") or "",
+ custom_providers=_msg_custom_providers,
+ )
+ _ctx_result = await preprocess_context_references_async(
+ message_text,
+ cwd=_msg_cwd,
+ context_length=_msg_ctx_len,
+ allowed_root=_msg_cwd,
+ )
+ if _ctx_result.blocked:
+ _adapter = self._adapter_for_source(source)
+ if _adapter:
+ await _adapter.send(
+ source.chat_id,
+ "\n".join(_ctx_result.warnings) or "Context injection refused.",
+ )
+ return None
+ if _ctx_result.expanded:
+ message_text = _ctx_result.message
+ except Exception as exc:
+ logger.warning("@ context reference expansion failed: %s", exc)
+ logger.debug("@ context reference expansion failure detail", exc_info=True)
- Call via ``asyncio.to_thread`` from async handlers: under the scope,
- resolution can do blocking work (credential refresh, context-length
- HTTP probes) that must not run on the event loop. The scope is entered
- inside this method, so contextvars behave correctly in the worker
- thread.
- """
+ return message_text
+
+ async def _prepare_profile_scoped_inbound_message_text(
+ self,
+ *,
+ event: MessageEvent,
+ source: SessionSource,
+ history: List[Dict[str, Any]],
+ session_key: Optional[str] = None,
+ ) -> Optional[str]:
+ """Run inbound preprocessing under the routed profile when multiplexed."""
if getattr(getattr(self, "config", None), "multiplex_profiles", False):
with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):
- return self._format_session_info()
- return self._format_session_info()
+ return await self._prepare_inbound_message_text(
+ event=event,
+ source=source,
+ history=history,
+ session_key=session_key,
+ )
+ return await self._prepare_inbound_message_text(
+ event=event,
+ source=source,
+ history=history,
+ session_key=session_key,
+ )
- def _format_session_info(self) -> str:
- """Resolve current model config and return a formatted info block.
+ async def _prepare_clarify_reply_text(self, event) -> str:
+ """Return raw text or successful voice transcripts for a clarify reply."""
+ if not self._pending_event_audio_paths(event):
+ return (event.text or "").strip()
- Surfaces model, provider, context length, and endpoint so gateway
- users can immediately see if context detection went wrong (e.g.
- local models falling to the 128K default).
- """
- from agent.model_metadata import get_model_context_length, DEFAULT_FALLBACK_CONTEXT
+ _, successful_transcripts = await self._transcribe_pending_audio_event_once(
+ event, "",
+ )
+ return "\n\n".join(
+ transcript.strip()
+ for transcript in successful_transcripts
+ if transcript.strip()
+ )
- model = _resolve_gateway_model()
- config_context_length = None
- provider = None
- base_url = None
- api_key = None
- custom_provs = None
- data = None
- configured_model = None
- configured_provider = None
- configured_base_url = None
+ def _consume_pending_native_image_paths(self, session_key: str) -> List[str]:
+ state = self._peek_session_state(session_key)
+ if state is None or not state.persistent.native_image_paths:
+ return []
+ paths = list(state.persistent.native_image_paths)
+ state.persistent.native_image_paths = []
+ return paths
- try:
- data = _load_gateway_config()
- if data:
- model_cfg = data.get("model", {})
- if isinstance(model_cfg, dict):
- configured_model = model_cfg.get("default") or model_cfg.get("model")
- raw_ctx = model_cfg.get("context_length")
- if raw_ctx is not None:
- try:
- config_context_length = int(raw_ctx)
- except (TypeError, ValueError):
- pass
- provider = model_cfg.get("provider") or None
- base_url = model_cfg.get("base_url") or None
- configured_provider = provider
- configured_base_url = base_url
- try:
- from hermes_cli.config import get_compatible_custom_providers
- custom_provs = get_compatible_custom_providers(data)
- except Exception:
- custom_provs = data.get("custom_providers")
+ def _cache_session_source(self, session_key: str, source) -> None:
+ if not session_key or source is None:
+ return
+ cached_sources = getattr(self, "_session_sources", None)
+ if cached_sources is None:
+ cached_sources = OrderedDict()
+ self._session_sources = cached_sources
+ try:
+ cached_sources[session_key] = dataclasses.replace(source)
except Exception:
- pass
-
- # Resolve runtime credentials for probing
+ logger.debug("Failed to cache live session source for %s", session_key, exc_info=True)
+ return
+ # LRU: mark as most-recently-used and trim to max size.
try:
- runtime = _resolve_runtime_agent_kwargs()
- provider = runtime.get("provider") or provider
- base_url = runtime.get("base_url") or base_url
- api_key = runtime.get("api_key")
+ cached_sources.move_to_end(session_key)
+ max_size = getattr(self, "_session_sources_max", 512)
+ while len(cached_sources) > max_size:
+ cached_sources.popitem(last=False)
except Exception:
pass
- if config_context_length is not None:
- try:
- from hermes_cli.route_identity import should_clear_context_pin
-
- if should_clear_context_pin(
- configured_model,
- model,
- configured_base_url,
- base_url,
- configured_provider,
- provider,
- ):
- config_context_length = None
- except Exception:
- config_context_length = None
+ @property
+ def async_session_store(self) -> AsyncSessionStore:
+ """Return the single async facade for this runner's SessionStore."""
+ facade = getattr(self, "_async_session_store", None)
+ if facade is None or facade._store is not self.session_store:
+ facade = AsyncSessionStore(self.session_store)
+ self._async_session_store = facade
+ return facade
- if config_context_length is None and custom_provs and base_url:
+ def _get_cached_session_source(self, session_key: str):
+ if not session_key:
+ return None
+ cached_sources = getattr(self, "_session_sources", None)
+ if not cached_sources:
+ return None
+ source = cached_sources.get(session_key)
+ if source is not None:
try:
- from hermes_cli.config import get_custom_provider_context_length
-
- custom_ctx = get_custom_provider_context_length(
- model=model,
- base_url=base_url,
- custom_providers=custom_provs,
- )
- if custom_ctx:
- config_context_length = custom_ctx
+ cached_sources.move_to_end(session_key)
except Exception:
pass
+ return source
- context_length = get_model_context_length(
- model,
- base_url=base_url or "",
- api_key=api_key or "",
- config_context_length=config_context_length,
- provider=provider or "",
- custom_providers=custom_provs,
+ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_generation: int):
+ """Inner handler that runs under the _running_agents sentinel guard."""
+ _msg_start_time = time.time()
+ _platform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform)
+ _msg_preview = (event.text or "")[:80].replace("\n", " ")
+ _reply_id = getattr(event, "reply_to_message_id", None)
+ _reply_txt = (getattr(event, "reply_to_text", None) or "")[:80].replace("\n", " ")
+ logger.info(
+ "inbound message: platform=%s user=%s chat=%s msg=%r reply_to_id=%s reply_to_text=%r",
+ _platform_name, source.user_name or source.user_id or "unknown",
+ source.chat_id or "unknown", _msg_preview, _reply_id, _reply_txt,
)
- # Format context source hint
- if config_context_length is not None:
- ctx_source = "config"
- elif context_length == DEFAULT_FALLBACK_CONTEXT:
- ctx_source = "default — set model.context_length in config to override"
- else:
- ctx_source = "detected"
-
- # Format context length for display
- if context_length >= 1_000_000:
- ctx_display = f"{context_length / 1_000_000:.1f}M"
- elif context_length >= 1_000:
- ctx_display = f"{context_length // 1_000}K"
- else:
- ctx_display = str(context_length)
-
- lines = [
- f"◆ Model: `{model}`",
- f"◆ Provider: {provider or 'openrouter'}",
- f"◆ Context: {ctx_display} tokens ({ctx_source})",
- ]
-
- # Show endpoint for local/custom setups
- if base_url and ("localhost" in base_url or "127.0.0.1" in base_url or "0.0.0.0" in base_url):
- lines.append(f"◆ Endpoint: {base_url}")
-
- return "\n".join(lines)
-
-
-
-
- def _check_slash_access(
- self, source: SessionSource, canonical_cmd: str
- ) -> Optional[str]:
- """Return a denial message if ``source`` cannot run ``canonical_cmd``,
- else None. Used by both the cold and running-agent dispatch paths
- in ``_handle_message`` so admin/user gating can't be bypassed by
- an in-flight agent.
+ # Get or create session
+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's
+ # last-active topic so a cross-topic Reply or stripped plain reply
+ # doesn't fragment the conversation across sessions.
+ recovered = await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ if recovered is not None:
+ logger.info(
+ "telegram topic recovery: chat=%s user=%s %r -> %s",
+ source.chat_id, source.user_id, source.thread_id, recovered,
+ )
+ source = dataclasses.replace(source, thread_id=recovered)
+ try:
+ event.source = source
+ except Exception:
+ pass
- Backward-compat semantics live in
- :func:`gateway.slash_access.policy_for_source` — when the operator
- hasn't set ``allow_admin_from`` for the scope, the policy returns
- ``enabled=False`` and this method always returns None.
- """
- from gateway.slash_access import policy_for_source as _policy_for_source
+ session_entry = await self.async_session_store.get_or_create_session(source)
+ session_key = session_entry.session_key
+ pinned_session_id = str(
+ (getattr(event, "metadata", None) or {}).get("gateway_session_id") or ""
+ ).strip()
+ if pinned_session_id:
+ resolved_entry = await self._resolve_async_delegation_session(
+ session_entry,
+ pinned_session_id,
+ )
+ if resolved_entry is None:
+ return
+ session_entry = resolved_entry
+ self._cache_session_source(session_key, source)
+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):
+ try:
+ binding = (await self._session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id),
+ thread_id=str(source.thread_id),
+ )) if self._session_db else None
+ except Exception:
+ logger.debug("Failed to read Telegram topic binding", exc_info=True)
+ binding = None
+ if binding:
+ bound_session_id = str(binding.get("session_id") or "")
+ # Heal bindings that point at a pre-compression parent: walk
+ # the compression-continuation chain forward to its tip so the
+ # next message resumes the compressed child instead of
+ # reloading the oversized parent transcript (#20470/#29712/
+ # #33414). Returns the input unchanged when the session isn't
+ # a compression parent, so this is cheap and safe.
+ if bound_session_id and self._session_db is not None:
+ try:
+ canonical_session_id = await self._session_db.get_compression_tip(
+ bound_session_id,
+ )
+ except Exception:
+ logger.debug(
+ "compression-tip lookup failed for %s",
+ bound_session_id, exc_info=True,
+ )
+ canonical_session_id = bound_session_id
+ if (
+ canonical_session_id
+ and canonical_session_id != bound_session_id
+ ):
+ bound_session_id = canonical_session_id
+ if bound_session_id and bound_session_id != session_entry.session_id:
+ # Route the override through SessionStore so the session_key
+ # → session_id mapping is persisted to disk and the previous
+ # lane session is ended cleanly. Mutating session_entry in
+ # place here created a split-brain state where the JSON
+ # index pointed at one id but code downstream used another.
+ switched = await self.async_session_store.switch_session(session_key, bound_session_id)
+ if switched is not None:
+ session_entry = switched
+ # If the stored binding pointed at a parent, rewrite it to the
+ # canonical descendant now that we've followed the chain.
+ if (
+ bound_session_id
+ and bound_session_id != str(binding.get("session_id") or "")
+ ):
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding,
+ source, session_entry, reason="compression-tip-walk",
+ )
+ else:
+ try:
+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)
+ except Exception:
+ logger.debug("Failed to record Telegram topic binding", exc_info=True)
+ # Capture and immediately consume was_auto_reset so it does not
+ # re-fire on subsequent messages — preventing the cleanup from
+ # wiping model/reasoning overrides set between turns (Closes #48031).
+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)
+ if _was_auto_reset:
+ # Treat auto-reset as a full conversation boundary — clear every
+ # conversation-scoped per-session dict in one funnel call so the
+ # fresh session does not inherit the previous conversation's
+ # model/reasoning overrides, a queued "/model switched" note, or
+ # a stale resolved-model cache (#48031, #58403). See
+ # _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(session_key, reason="auto_reset")
+ # Evict the cached agent so the fresh session does not inherit the
+ # previous conversation's context_compressor._previous_summary —
+ # the cache is keyed on the stable session_key, so an auto-reset
+ # otherwise reuses the old agent and leaks prior history into new
+ # compaction summaries. Mirrors /reset and the compression-exhausted
+ # path (#9893). Covers daily/idle/suspended auto-reset.
+ self._evict_cached_agent(session_key)
+ session_entry.was_auto_reset = False
+
+ # Emit session:start for new or auto-reset sessions
+ _is_new_session = (
+ session_entry.created_at == session_entry.updated_at
+ or _was_auto_reset
+ or getattr(session_entry, "is_fresh_reset", False)
+ )
+ # Consume the is_fresh_reset flag immediately so it doesn't leak
+ # onto subsequent messages in the same session (issue #6508).
+ if getattr(session_entry, "is_fresh_reset", False):
+ session_entry.is_fresh_reset = False
+ if _is_new_session:
+ await self.hooks.emit("session:start", {
+ "platform": source.platform.value if source.platform else "",
+ "user_id": source.user_id,
+ "session_id": session_entry.session_id,
+ "session_key": session_key,
+ })
+
+ # Build session context
+ context = build_session_context(source, self.config, session_entry)
+
+ # Set session context variables for tools (task-local, concurrency-safe)
+ _session_env_tokens = self._set_session_env(context)
+
+ # Read privacy.redact_pii from config (re-read per message)
+ _redact_pii = False
+ persist_user_message = None
+ persist_user_timestamp = None
+ try:
+ _pcfg = _load_gateway_config()
+ _redact_pii = bool((_pcfg.get("privacy") or {}).get("redact_pii", False))
+ except Exception:
+ pass
- if not canonical_cmd:
- return None
- policy = _policy_for_source(self.config, source)
- if not policy.enabled or policy.can_run(source.user_id, canonical_cmd):
- return None
- logger.info(
- "Slash command /%s denied for %s:%s (not admin, not in user_allowed_commands)",
- canonical_cmd,
- source.platform.value if source.platform else "?",
- source.user_id,
+ # Build the context prompt to inject. The render is pinned per
+ # session, keyed by a hash of the exact renderer inputs
+ # (_ephemeral_change_key). A key hit reuses the pinned bytes verbatim
+ # so the composed system prompt cannot drift turn-over-turn; a key
+ # miss (thread rename, /sethome, redact_pii flip, ...) re-renders
+ # once — the only legitimate cache busts.
+ context_prompt = self._pinned_session_context_prompt(
+ context, _redact_pii, session_key
)
- allowed_preview = sorted(policy.user_allowed_commands)
- if allowed_preview:
- suffix = (
- "You can run: "
- + ", ".join(f"/{c}" for c in allowed_preview[:12])
- + ("…" if len(allowed_preview) > 12 else "")
- + ". Use /whoami for the full list."
- )
- else:
- suffix = (
- "No slash commands are enabled for non-admins on this "
- "platform. Ask an admin to add you to allow_admin_from "
- "or to set user_allowed_commands."
- )
- return f"⛔ /{canonical_cmd} is admin-only here. {suffix}"
-
-
-
-
+ # Per-turn must-deliver notes. These used to be appended to
+ # context_prompt (the ephemeral system prompt), which guaranteed a
+ # turn1→turn2 system-prompt diff and a full agent rebuild. They now
+ # ride the current user message via the api_content sidecar instead
+ # (staged below, consumed in run_sync → build_turn_context).
+ turn_sidecar_notes: List[str] = []
+ # If the previous session expired and was auto-reset, deliver a notice
+ # so the agent knows this is a fresh conversation (not an intentional /reset).
+ if _was_auto_reset:
+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'idle'
+ if reset_reason == "suspended":
+ context_note = "[System note: The user's previous session was stopped and suspended. This is a fresh conversation with no prior context.]"
+ elif reset_reason == "daily":
+ context_note = "[System note: The user's session was automatically reset by the daily schedule. This is a fresh conversation with no prior context.]"
+ elif reset_reason == "resume_pending_expired":
+ context_note = "[System note: The previous gateway session could not be recovered after a restart (API recovery timed out). This is a fresh conversation — use /resume to restore history if needed.]"
+ else:
+ context_note = "[System note: The user's previous session expired due to inactivity. This is a fresh conversation with no prior context.]"
+ # Slack/Discord channels/threads are long-lived: point the agent at
+ # the specific prior same-channel session so it recalls that context
+ # via session_search instead of an unrelated recent session. Returns
+ # None (appends nothing) for other platforms or when there's no prior
+ # activity to recall. Deterministic — no extra API/DB calls (#36220).
+ try:
+ continuity_note = build_channel_continuity_note(session_entry, source)
+ except Exception:
+ continuity_note = None
+ if continuity_note:
+ context_note = context_note + "\n\n" + continuity_note
+ turn_sidecar_notes.append(context_note)
- def _sibling_thread_run_keys(self, source: SessionSource, own_key: str) -> list:
- """Find running-agent keys for OTHER participants in the same thread.
+ # Send a user-facing notification explaining the reset, unless:
+ # - notifications are disabled in config
+ # - the platform is excluded (e.g. api_server, webhook)
+ # - the expired session had no activity (nothing was cleared)
+ try:
+ policy = self.session_store.config.get_reset_policy(
+ platform=source.platform,
+ session_type=getattr(source, 'chat_type', 'dm'),
+ )
+ platform_name = source.platform.value if source.platform else ""
+ had_activity = getattr(session_entry, 'reset_had_activity', False)
+ # Suspended and restart-recovery-expired sessions always notify
+ # regardless of policy.notify — the user had an active session
+ # that was silently replaced, so they need to know they can
+ # /resume it. Idle/daily resets respect the policy flag.
+ should_notify = reset_reason in {"suspended", "resume_pending_expired"} or (
+ policy.notify
+ and had_activity
+ and platform_name not in policy.notify_exclude_platforms
+ )
+ if should_notify:
+ adapter = self._adapter_for_source(source)
+ if adapter:
+ if reset_reason == "suspended":
+ reason_text = "previous session was stopped or interrupted"
+ elif reset_reason == "resume_pending_expired":
+ reason_text = "gateway restart recovery timed out"
+ elif reset_reason == "daily":
+ reason_text = f"daily schedule at {policy.at_hour}:00"
+ else:
+ hours = policy.idle_minutes // 60
+ mins = policy.idle_minutes % 60
+ duration = f"{hours}h" if not mins else f"{hours}h {mins}m" if hours else f"{mins}m"
+ reason_text = f"inactive for {duration}"
+ notice = (
+ f"◐ Session automatically reset ({reason_text}). "
+ f"Conversation history cleared.\n"
+ f"Use /resume to browse and restore a previous session.\n"
+ f"Adjust reset timing in config.yaml under session_reset."
+ )
+ try:
+ session_info = await asyncio.to_thread(
+ self._reset_notice_session_info, source
+ )
+ if session_info:
+ notice = f"{notice}\n\n{session_info}"
+ except Exception:
+ pass
+ await adapter.send(
+ source.chat_id, notice,
+ metadata=self._thread_metadata_for_source(source),
+ )
+ except Exception as e:
+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)
- Only applies when the message originates in a thread. In per-user
- thread mode (``thread_sessions_per_user=True``) each participant gets
- an isolated session key of the form
- ``agent:main:{platform}:{chat_type}:{chat_id}:{thread_id}:{user_id}``,
- so a run started by another user is invisible to the caller's own
- ``/stop``. This returns the keys of any *actually running* agents
- (not the pending sentinel, not the caller's own key) whose key shares
- the caller's ``{chat_id}:{thread_id}`` prefix.
+ # was_auto_reset is already consumed in the cleanup block above
+ # (single source of truth); only the reset reason needs clearing here.
+ session_entry.auto_reset_reason = None
- Returns an empty list when the source is not in a thread, or when no
- sibling runs exist — callers must still gate on authorization.
- """
- thread_id = getattr(source, "thread_id", None)
- chat_id = getattr(source, "chat_id", None)
- if not thread_id or not chat_id:
- return []
- platform = source.platform.value
- chat_type = getattr(source, "chat_type", None) or ""
- # Prefix that every per-user key in this thread shares, up to and
- # including the thread_id segment. Matching either the exact
- # shared-thread key or any key with a further (user_id) segment
- # (prefix + ":") avoids cross-matching an unrelated thread whose id
- # merely starts with this one.
- prefix = ":".join(
- ["agent:main", platform, chat_type, str(chat_id), str(thread_id)]
- )
- matches = []
- for key, agent in self._running_agent_items():
- if key == own_key:
- continue
- if agent is _AGENT_PENDING_SENTINEL or not agent:
- continue
- if key == prefix or key.startswith(prefix + ":"):
- matches.append(key)
- return matches
+ # Auto-load skill(s) for topic/channel bindings (Telegram DM Topics,
+ # Discord channel_skill_bindings). Supports a single name or ordered list.
+ # Only inject on NEW sessions — ongoing conversations already have the
+ # skill content in their conversation history from the first message.
+ _auto = getattr(event, "auto_skill", None)
+ if _is_new_session and _auto:
+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)
+ try:
+ from agent.skill_commands import _load_skill_payload, _build_skill_message
+ _combined_parts: list[str] = []
+ _loaded_names: list[str] = []
+ for _sname in _skill_names:
+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)
+ if _loaded:
+ _loaded_skill, _skill_dir, _display_name = _loaded
+ _note = (
+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '
+ f"Follow its instructions for this session.]"
+ )
+ _part = _build_skill_message(_loaded_skill, _skill_dir, _note)
+ if _part:
+ _combined_parts.append(_part)
+ _loaded_names.append(_sname)
+ else:
+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)
+ if _combined_parts:
+ # Append the user's original text after all skill payloads
+ _combined_parts.append(event.text)
+ event.text = "\n\n".join(_combined_parts)
+ logger.info(
+ "[Gateway] Auto-loaded skill(s) %s for session %s",
+ _loaded_names, session_key,
+ )
+ except Exception as e:
+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)
+ # ── Turn lease (#64934) ────────────────────────────────────────
+ # Session resolution is FINAL here (get_or_create → async-delegation
+ # pinning → topic tip-walk switch_session are all above). Serialize
+ # the [load history → run → flush] region per resolved SESSION_ID:
+ # when a second routing key is mapped to this same session_id, its
+ # turn waits here for the previous turn's flush instead of loading a
+ # stale history base and interleaving transcript writes. Same-key
+ # messages never reach this point mid-turn (adapter + runner guards
+ # hold them), so the lock is uncontended outside the alias-key route.
+ # Fail-open: on timeout the token comes back degraded and the turn
+ # proceeds unserialized (never a wedged session). Released in
+ # _handle_message's finally via _release_turn_lease — granted per
+ # (routing key, run generation) so a stale unwind can't release a
+ # newer turn's lease.
+ _lease_registry = getattr(self, "_turn_leases", None)
+ if _lease_registry is not None:
+ _lease_token = await _lease_registry.acquire(
+ session_entry.session_id,
+ owner_key=_quick_key,
+ generation=run_generation,
+ timeout=_float_env("HERMES_AGENT_TIMEOUT", 1800),
+ )
+ if _lease_token is not None:
+ _lease_state = self._session_state(_quick_key).turn
+ _lease_state.lease_token = _lease_token
+ _lease_state.lease_generation = run_generation
+ # Load conversation history from transcript
+ history = await self.async_session_store.load_transcript(session_entry.session_id)
+
+ # -----------------------------------------------------------------
+ # Session hygiene: auto-compress pathologically large transcripts
+ #
+ # Long-lived gateway sessions can accumulate enough history that
+ # every new message rehydrates an oversized transcript, causing
+ # repeated truncation/context failures. Detect this early and
+ # compress proactively — before the agent even starts. (#628)
+ #
+ # Token source priority:
+ # 1. Actual API-reported prompt_tokens from the last turn
+ # (stored in session_entry.last_prompt_tokens)
+ # 2. Rough char-based estimate (str(msg)//4). Overestimates
+ # by 30-50% on code/JSON-heavy sessions, but that just
+ # means hygiene fires a bit early — safe and harmless.
+ # -----------------------------------------------------------------
+ if history and len(history) >= 4:
+ from agent.model_metadata import (
+ estimate_messages_tokens_rough,
+ get_model_context_length_async,
+ )
+ # Read model + compression config from config.yaml.
+ # NOTE: hygiene threshold is intentionally HIGHER than the agent's
+ # own compressor (0.85 vs 0.50). Hygiene is a safety net for
+ # sessions that grew too large between turns — it fires pre-agent
+ # to prevent API failures. The agent's own compressor handles
+ # normal context management during its tool loop with accurate
+ # real token counts. Having hygiene at 0.50 caused premature
+ # compression on every turn in long gateway sessions.
+ _hyg_model = "anthropic/claude-sonnet-4.6"
+ _hyg_threshold_pct = 0.85
+ _hyg_compression_enabled = True
+ _hyg_hard_msg_limit = 5000
+ _hyg_timeout_seconds = 30.0
+ _hyg_total_ceiling_seconds = 600.0
+ _hyg_failure_cooldown_seconds = 300.0
+ _hyg_config_context_length = None
+ _hyg_provider = None
+ _hyg_base_url = None
+ _hyg_api_key = None
+ _hyg_configured_model = None
+ _hyg_configured_provider = None
+ _hyg_configured_base_url = None
+ _hyg_data = {}
+ try:
+ _hyg_data = _load_gateway_config()
+ if _hyg_data:
+ # Resolve model name (same logic as run_sync)
+ _model_cfg = _hyg_data.get("model", {})
+ if isinstance(_model_cfg, str):
+ _hyg_model = _model_cfg
+ elif isinstance(_model_cfg, dict):
+ _hyg_model = _model_cfg.get("default") or _model_cfg.get("model") or _hyg_model
+ # Read explicit context_length override from model config
+ # (same as run_agent.py lines 995-1005)
+ _raw_ctx = _model_cfg.get("context_length")
+ if _raw_ctx is not None:
+ try:
+ _hyg_config_context_length = int(_raw_ctx)
+ except (TypeError, ValueError):
+ pass
+ # Read provider for accurate context detection
+ _hyg_provider = _model_cfg.get("provider") or None
+ _hyg_base_url = _model_cfg.get("base_url") or None
- def _is_stale_restart_redelivery(self, event: MessageEvent) -> bool:
- """Return True if this /restart is a Telegram re-delivery we already handled.
+ # Read compression settings — only use enabled flag.
+ # The threshold is intentionally separate from the agent's
+ # compression.threshold (hygiene runs higher).
+ _comp_cfg = _hyg_data.get("compression", {})
+ if isinstance(_comp_cfg, dict):
+ _hyg_compression_enabled = str(
+ _comp_cfg.get("enabled", True)
+ ).lower() in {"true", "1", "yes"}
+ _raw_hard_limit = _comp_cfg.get("hygiene_hard_message_limit")
+ if _raw_hard_limit is not None:
+ try:
+ _parsed = int(_raw_hard_limit)
+ if _parsed > 0:
+ _hyg_hard_msg_limit = _parsed
+ except (TypeError, ValueError):
+ pass
+ _raw_timeout = _comp_cfg.get("hygiene_timeout_seconds")
+ if _raw_timeout is not None:
+ try:
+ _parsed = float(_raw_timeout)
+ if _parsed > 0:
+ _hyg_timeout_seconds = _parsed
+ except (TypeError, ValueError):
+ pass
+ _raw_ceiling = _comp_cfg.get("hygiene_total_ceiling_seconds")
+ if _raw_ceiling is not None:
+ try:
+ _parsed = float(_raw_ceiling)
+ if _parsed > 0:
+ _hyg_total_ceiling_seconds = _parsed
+ except (TypeError, ValueError):
+ pass
+ # The ceiling can never be tighter than one idle
+ # window, or the extension loop would be dead code.
+ _hyg_total_ceiling_seconds = max(
+ _hyg_total_ceiling_seconds, _hyg_timeout_seconds,
+ )
+ _raw_cooldown = _comp_cfg.get("hygiene_failure_cooldown_seconds")
+ if _raw_cooldown is not None:
+ try:
+ _parsed = float(_raw_cooldown)
+ if _parsed >= 0:
+ _hyg_failure_cooldown_seconds = _parsed
+ except (TypeError, ValueError):
+ pass
- The previous gateway wrote ``.restart_last_processed.json`` with the
- triggering platform + update_id when it processed the /restart. If
- we now see a /restart on the same platform with an update_id <= that
- recorded value, it is a redelivery when this process booted from that
- restart. Otherwise the marker must still be recent (< 5 minutes).
+ _hyg_configured_model = _hyg_model
+ _hyg_configured_provider = _hyg_provider
+ _hyg_configured_base_url = _hyg_base_url
- Only applies to Telegram today (the only platform that exposes a
- numeric cross-session update ordering); other platforms return False.
- """
- if event is None or event.source is None:
- return False
- if event.platform_update_id is None:
- return False
- if event.source.platform is None:
- return False
- # Only Telegram populates platform_update_id currently; be explicit
- # so future platforms aren't accidentally gated by this check.
- try:
- platform_value = event.source.platform.value
- except Exception:
- return False
- if platform_value != "telegram":
- return False
+ try:
+ _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(
+ source=source,
+ session_key=session_key,
+ user_config=_hyg_data if isinstance(_hyg_data, dict) else None,
+ )
+ _hyg_provider = _hyg_runtime.get("provider") or _hyg_provider
+ _hyg_base_url = _hyg_runtime.get("base_url") or _hyg_base_url
+ _hyg_api_key = _hyg_runtime.get("api_key") or _hyg_api_key
+ except Exception:
+ pass
- try:
- marker_path = _hermes_home / ".restart_last_processed.json"
- if not marker_path.exists():
- # Belt-and-suspenders for when the dedup marker goes missing
- # (manually cleaned up, or the previous cycle's write failed).
- # Without a marker the update_id comparison below can't run, so
- # a redelivered /restart would sail through and re-restart the
- # gateway — an infinite loop (issue #18528).
- #
- # Suppress ONLY when we can independently confirm we just came
- # out of a restart cycle: this process booted from a
- # chat-originated /restart (_booted_from_restart) AND is still
- # within a short post-boot window. This never swallows a
- # genuine first /restart on a fresh boot (no restart marker on
- # boot → flag stays False). Consume the flag one-shot so a
- # legitimate /restart sent later in the same session is honored.
- if (
- getattr(self, "_booted_from_restart", False)
- and time.time() - getattr(self, "_startup_time", 0.0) < 60
- ):
- self._booted_from_restart = False
- return True
- return False
- data = json.loads(marker_path.read_text(encoding="utf-8"))
- except Exception:
- return False
+ if _hyg_config_context_length is not None:
+ try:
+ from hermes_cli.route_identity import should_clear_context_pin_async
- if data.get("platform") != platform_value:
- return False
- recorded_uid = data.get("update_id")
- if not isinstance(recorded_uid, int):
- return False
- if event.platform_update_id > recorded_uid:
- return False
+ if await should_clear_context_pin_async(
+ _hyg_configured_model,
+ _hyg_model,
+ _hyg_configured_base_url,
+ _hyg_base_url,
+ _hyg_configured_provider,
+ _hyg_provider,
+ ):
+ _hyg_config_context_length = None
+ except Exception:
+ _hyg_config_context_length = None
- # A service-managed restart can legitimately take longer than the
- # marker's normal five-minute trust window while adapters, cron, and
- # in-flight deliveries drain. If this process booted from the recorded
- # chat restart, the first same-or-older update is still that restart's
- # redelivery regardless of elapsed wall time. Consume the boot signal
- # one-shot so a later genuine command is evaluated normally.
- if getattr(self, "_booted_from_restart", False):
- self._booted_from_restart = False
- return True
+ # Check custom_providers per-model context_length
+ # (same fallback as run_agent.py lines 1171-1189).
+ # Must run after runtime resolution so _hyg_base_url is set.
+ if _hyg_config_context_length is None and _hyg_base_url:
+ try:
+ try:
+ from hermes_cli.config import (
+ get_compatible_custom_providers as _gw_gcp,
+ get_custom_provider_context_length as _gw_gccl,
+ )
+ _hyg_custom_providers = _gw_gcp(_hyg_data)
+ except Exception:
+ _hyg_custom_providers = _hyg_data.get("custom_providers")
+ if not isinstance(_hyg_custom_providers, list):
+ _hyg_custom_providers = []
+ _hyg_custom_ctx = _gw_gccl(
+ model=_hyg_model,
+ base_url=_hyg_base_url,
+ custom_providers=_hyg_custom_providers,
+ )
+ if _hyg_custom_ctx:
+ _hyg_config_context_length = int(_hyg_custom_ctx)
+ except (TypeError, ValueError):
+ pass
+ except Exception:
+ pass
- # Staleness guard: ignore markers older than 5 minutes. A legitimately
- # old marker (e.g. crash recovery where notify never fired) should not
- # swallow a fresh /restart from the user.
- requested_at = data.get("requested_at")
- if isinstance(requested_at, (int, float)):
- if time.time() - requested_at > 300:
- return False
- return True
+ if _hyg_compression_enabled:
+ _hyg_context_length = await get_model_context_length_async(
+ _hyg_model,
+ base_url=_hyg_base_url or "",
+ api_key=_hyg_api_key or "",
+ config_context_length=_hyg_config_context_length,
+ provider=_hyg_provider or "",
+ )
+ _compress_token_threshold = int(
+ _hyg_context_length * _hyg_threshold_pct
+ )
+ _warn_token_threshold = int(_hyg_context_length * 0.95)
+ _msg_count = len(history)
+ # Prefer actual API-reported tokens from the last turn
+ # (stored in session entry) over the rough char-based estimate.
+ _stored_tokens = session_entry.last_prompt_tokens
+ if _stored_tokens > 0:
+ _approx_tokens = _stored_tokens
+ _token_source = "actual"
+ else:
+ _approx_tokens = estimate_messages_tokens_rough(history)
+ _token_source = "estimated"
+ # Note: rough estimates overestimate by 30-50% for code/JSON-heavy
+ # sessions, but that just means hygiene fires a bit early — which
+ # is safe and harmless. The 85% threshold already provides ample
+ # headroom (agent's own compressor runs at 50%). A previous 1.4x
+ # multiplier tried to compensate by inflating the threshold, but
+ # 85% * 1.4 = 119% of context — which exceeds the model's limit
+ # and prevented hygiene from ever firing for ~200K models (GLM-5).
+ # Hard safety valve: force compression if message count is
+ # extreme, regardless of token estimates. This breaks the
+ # death spiral where API disconnects prevent token data
+ # collection, which prevents compression, which causes more
+ # disconnects. 5000 messages is far above any normal session
+ # but catches truly runaway growth before it becomes
+ # unrecoverable. Set well clear of legitimate large-context
+ # (1M+) sessions doing thousands of short turns — those
+ # compress on the token threshold, not this count-based floor.
+ # Threshold is configurable via
+ # compression.hygiene_hard_message_limit.
+ # (#2153)
+ _HARD_MSG_LIMIT = _hyg_hard_msg_limit
+ _needs_compress = (
+ _approx_tokens >= _compress_token_threshold
+ or _msg_count >= _HARD_MSG_LIMIT
+ )
+ if _needs_compress:
+ _cooldowns = getattr(self, "_hygiene_compression_failure_cooldowns", None)
+ if _cooldowns is None:
+ _cooldowns = {}
+ self._hygiene_compression_failure_cooldowns = _cooldowns
+ _cooldown_key = session_entry.session_id
+ _cooldown_until = float(_cooldowns.get(_cooldown_key) or 0.0)
+ if _cooldown_until > time.time():
+ logger.info(
+ "Session hygiene: skipping compression for %s; "
+ "previous failure cooldown active for %.1fs",
+ _cooldown_key,
+ max(0.0, _cooldown_until - time.time()),
+ )
+ _needs_compress = False
+ if _needs_compress:
+ logger.info(
+ "Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing "
+ "(threshold: %s%% of %s = %s tokens)",
+ _msg_count, f"{_approx_tokens:,}", _token_source,
+ int(_hyg_threshold_pct * 100),
+ f"{_hyg_context_length:,}",
+ f"{_compress_token_threshold:,}",
+ )
+ _hyg_meta = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
+ try:
+ from agent.conversation_compression import CompressionCommitFence
+ from run_agent import AIAgent
+ _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(
+ source=source,
+ session_key=session_key,
+ user_config=_hyg_data if isinstance(_hyg_data, dict) else None,
+ )
+ if _hyg_runtime.get("api_key"):
+ # Pass the FULL transcript (tool results included).
+ # Filtering to user/assistant-only starved the
+ # compressor: tool results are usually the bulk of
+ # the context, _prune_old_tool_results never saw
+ # them, and short filtered histories tripped the
+ # protect-first/last early-return so nothing was
+ # compressed at all (#3854). The agent loop passes
+ # its full message list to _compress_context — the
+ # gateway now matches.
+ _hyg_msgs = [
+ m for m in history
+ if m.get("role") in {"user", "assistant", "tool"}
+ ]
- async def _handle_suggestions_command(self, event: MessageEvent) -> str:
- """Handle /suggestions in the gateway.
+ if len(_hyg_msgs) >= 4:
+ try:
+ _hyg_session_row = await self._session_db.get_session(
+ session_entry.session_id
+ )
+ except Exception as exc:
+ _hyg_session_row = None
+ logger.warning(
+ "Session hygiene could not restore the system "
+ "prompt for session %s: %s. Preserving an empty "
+ "prompt so the live turn rebuilds it with its "
+ "configured providers.",
+ session_entry.session_id,
+ exc,
+ exc_info=True,
+ )
+ _hyg_session_db = getattr(self._session_db, "_db", self._session_db)
+ _hyg_agent = AIAgent(
+ **_hyg_runtime,
+ model=_hyg_model,
+ max_iterations=4,
+ quiet_mode=True,
+ skip_memory=True,
+ enabled_toolsets=["memory"],
+ session_id=session_entry.session_id,
+ session_db=_hyg_session_db,
+ )
+ _seed_hygiene_system_prompt(
+ _hyg_agent,
+ _hyg_session_row,
+ )
+ # If compression must rebuild instead of retaining
+ # the cached prompt, make the persisted result
+ # deliberately stale for every real gateway surface.
+ _hyg_agent.platform = _GATEWAY_HYGIENE_PLATFORM
+ _hyg_cleanup_deferred = False
+ try:
+ # Gateway hygiene runs before the user turn
+ # starts and already owns the session binding.
+ # Prefer in-place compaction here: it archives
+ # old rows under the same session id instead of
+ # minting a continuation child that then has to
+ # be published back to SessionStore/topic
+ # bindings. If no SessionDB is available,
+ # compress_context leaves this flag false and
+ # the guard below preserves the transcript.
+ _hyg_agent.compression_in_place = True
+ _bind_hyg_state = getattr(
+ getattr(_hyg_agent, "context_compressor", None),
+ "bind_session_state",
+ None,
+ )
+ if callable(_bind_hyg_state):
+ _bind_hyg_state(
+ _hyg_session_db,
+ session_entry.session_id,
+ )
+ # It must never finalize on close() — close()
+ # would end the live gateway session row.
+ _hyg_agent._end_session_on_close = False
+ _hyg_agent._print_fn = lambda *a, **kw: None
- Delegates to the shared handler so CLI and gateway never drift. The
- origin is built from the event source so an accepted suggestion's job
- delivers back to this chat/thread.
- """
- args = (event.get_command_args() or "").strip()
- source = event.source
- origin = None
- try:
- platform = getattr(source.platform, "value", None) or str(getattr(source, "platform", "") or "")
- chat_id = getattr(source, "chat_id", None)
- if platform and chat_id:
- origin = {
- "platform": platform,
- "chat_id": str(chat_id),
- "chat_name": getattr(source, "chat_name", None),
- "thread_id": getattr(source, "thread_id", None),
- }
- except Exception:
- origin = None
- try:
- from hermes_cli.suggestions_cmd import handle_suggestions_command
+ loop = asyncio.get_running_loop()
+ _hyg_commit_fence = CompressionCommitFence()
+ _hyg_future = loop.run_in_executor(
+ None,
+ lambda: _hyg_agent._compress_context(
+ _hyg_msgs, "",
+ approx_tokens=_approx_tokens,
+ commit_fence=_hyg_commit_fence,
+ ),
+ )
+ try:
+ # Progress-aware wait: the timeout is an
+ # INACTIVITY budget, not a total one. The
+ # compression worker streams its summary
+ # call and ticks the fence per token
+ # (CompressionCommitFence.touch_progress),
+ # so a slow reasoning model that is still
+ # generating keeps extending the deadline;
+ # only a genuinely silent worker times out.
+ # A hard ceiling bounds the total wait so
+ # a degenerate trickle stream can't hold
+ # the turn forever.
+ _hyg_wait_started = time.monotonic()
+ while True:
+ try:
+ _compressed, _ = await asyncio.wait_for(
+ asyncio.shield(_hyg_future),
+ timeout=_hyg_timeout_seconds,
+ )
+ break
+ except asyncio.TimeoutError:
+ _hyg_waited = time.monotonic() - _hyg_wait_started
+ _idle = _hyg_commit_fence.seconds_since_progress()
+ if (
+ _idle < _hyg_timeout_seconds
+ and _hyg_waited < _hyg_total_ceiling_seconds
+ ):
+ logger.info(
+ "Session hygiene compression for "
+ "session %s still streaming after "
+ "%.0fs (last progress %.1fs ago) — "
+ "extending wait (ceiling %.0fs)",
+ session_entry.session_id,
+ _hyg_waited, _idle,
+ _hyg_total_ceiling_seconds,
+ )
+ continue
+ raise
+ except asyncio.TimeoutError:
+ _cancelled = None
+ while _cancelled is None:
+ _cancelled = (
+ _hyg_commit_fence.try_cancel_before_commit()
+ )
+ if _cancelled is None:
+ await asyncio.sleep(0.001)
+ if not _cancelled:
+ # The worker crossed the commit boundary just
+ # before the timeout. The fence poll waited for
+ # that boundary to finish, so consume the
+ # completed result instead of treating a
+ # successful compaction as a timeout.
+ _compressed, _ = await _hyg_future
+ else:
+ self._defer_agent_cleanup_until_future_done(
+ _hyg_future,
+ _hyg_agent,
+ context="session hygiene timeout",
+ )
+ _hyg_cleanup_deferred = True
+ if _hyg_failure_cooldown_seconds >= 0:
+ self._hygiene_compression_failure_cooldowns[
+ session_entry.session_id
+ ] = time.time() + _hyg_failure_cooldown_seconds
+ logger.warning(
+ "Session hygiene compression for session %s "
+ "made no progress for %.1fs "
+ "(total wait %.1fs, ceiling %.1fs); "
+ "continuing without compression",
+ session_entry.session_id,
+ _hyg_commit_fence.seconds_since_progress(),
+ time.monotonic() - _hyg_wait_started,
+ _hyg_total_ceiling_seconds,
+ )
+ _timeout_msg = (
+ "⚠️ Context compression timed out "
+ f"after {_hyg_timeout_seconds:.1f}s "
+ "with no output from the summary model. "
+ "No messages were dropped — continuing without "
+ "compression. Run /compress to retry, /reset for "
+ "a clean session, or check your "
+ "auxiliary.compression model configuration."
+ )
+ try:
+ _adapter = self._adapter_for_source(source)
+ if _adapter and source.chat_id:
+ await _adapter.send(
+ source.chat_id,
+ _timeout_msg,
+ metadata=_hyg_meta,
+ )
+ except Exception as _werr:
+ logger.warning(
+ "Failed to deliver compression-timeout "
+ "warning to user: %s",
+ _werr,
+ )
+ raise
- return handle_suggestions_command(args, origin=origin, surface="gateway")
- except Exception as e:
- logger.debug("suggestions command failed: %s", e)
- return f"Suggestions command failed: {e}"
+ # _compress_context ends the old session and creates
+ # a new session_id. Write compressed messages into
+ # the NEW session so the old transcript stays intact
+ # and searchable via session_search.
+ _hyg_new_sid = _hyg_agent.session_id
+ _hyg_rotated = _hyg_new_sid != session_entry.session_id
+ _hyg_in_place = bool(
+ getattr(_hyg_agent, "_last_compaction_in_place", False)
+ )
+ # Only rewrite the transcript when rotation produced
+ # a NEW session id. In-place compaction does NOT
+ # need a rewrite: archive_and_compact() has already
+ # soft-archived the previous active rows and inserted
+ # the compacted messages as the new active set inside
+ # _compress_context(). Calling rewrite_transcript()
+ # after in-place compaction would invoke
+ # replace_messages(active_only=False) which DELETEs
+ # ALL rows — including the archived turns that
+ # archive_and_compact() deliberately preserved
+ # (silent data loss, #61145).
+ #
+ # The danger this guards against (mirrors the
+ # /compress fix #44794/#39704): if _compress_context
+ # returns a summary but neither rotates nor completes
+ # archive_and_compact(), the session_id is unchanged
+ # for a FAILURE reason, and an unconditional
+ # rewrite_transcript() would DELETE the original
+ # messages and replace them with only the compressed
+ # summary (permanent data loss, #21301).
+ #
+ # Write-before-repoint (mirrors manual /compress):
+ # if we repointed session_entry onto the child SID
+ # and rewrite_transcript then failed (lock/ENOSPC),
+ # the live entry would already reference a brand-new
+ # empty session while the turn continues — the
+ # conversation silently vanishes. Persist the child
+ # transcript first; only then rebind the live entry.
+ if _hyg_rotated:
+ if not await self.async_session_store.rewrite_transcript(
+ _hyg_new_sid, _compressed
+ ):
+ logger.error(
+ "Session hygiene: failed to persist "
+ "compressed transcript for rotated "
+ "session %s → %s; keeping the live "
+ "entry on the original session so the "
+ "conversation is not dropped",
+ session_entry.session_id,
+ _hyg_new_sid,
+ )
+ # Fail closed: treat like no rotation.
+ _hyg_rotated = False
+ _hyg_in_place = False
+ else:
+ session_entry.session_id = _hyg_new_sid
+ # The held turn lease follows the
+ # rotation so an alias key resolving
+ # the fresh child still serializes
+ # against this turn (#64934).
+ self._rebind_turn_lease(
+ _quick_key, run_generation, _hyg_new_sid
+ )
+ await self.async_session_store._save()
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding,
+ source, session_entry,
+ reason="hygiene-compression",
+ )
- async def _handle_blueprint_command(self, event: MessageEvent):
- """Handle /blueprint in the gateway.
+ if _hyg_rotated:
+ # Reset stored token count — transcript rewritten
+ session_entry.last_prompt_tokens = 0
+ history = _compressed
+ _new_count = len(_compressed)
+ _new_tokens = estimate_messages_tokens_rough(
+ _compressed
+ )
+ elif _hyg_in_place:
+ # archive_and_compact() already persisted the
+ # compacted transcript inside _compress_context.
+ # Reset counts to match the new active set.
+ session_entry.last_prompt_tokens = 0
+ history = _compressed
+ _new_count = len(_compressed)
+ _new_tokens = estimate_messages_tokens_rough(
+ _compressed
+ )
+ else:
+ # No rewrite happened — transcript preserved
+ # unchanged, so the post-compression counts equal
+ # the pre-compression ones.
+ _new_count = _msg_count
+ _new_tokens = _approx_tokens
+ logger.warning(
+ "Gateway hygiene compression for session %s "
+ "did not rotate or compact in place "
+ "(no session_db on the hygiene agent) — "
+ "preserving the original transcript instead "
+ "of overwriting it with the summary (#21301).",
+ session_entry.session_id,
+ )
- Delegates to the shared handler so CLI, TUI, and gateway never drift.
- Returns a BlueprintCommandResult: ``text`` is shown to the user, and if
- ``agent_seed`` is set the dispatch site rewrites ``event.text`` to the
- seed and falls through to the agent (the ``/steer`` pattern) so the
- agent gathers the slot values conversationally. Origin is built from the
- event source so a directly created blueprint job delivers back to this chat.
- """
- args = (event.get_command_args() or "").strip()
- source = event.source
- origin = None
- try:
- platform = getattr(source.platform, "value", None) or str(getattr(source, "platform", "") or "")
- chat_id = getattr(source, "chat_id", None)
- if platform and chat_id:
- origin = {
- "platform": platform,
- "chat_id": str(chat_id),
- "chat_name": getattr(source, "chat_name", None),
- "thread_id": getattr(source, "thread_id", None),
- }
- except Exception:
- origin = None
- try:
- from hermes_cli.blueprint_cmd import handle_blueprint_command
+ logger.info(
+ "Session hygiene: compressed %s → %s msgs, "
+ "~%s → ~%s tokens",
+ _msg_count, _new_count,
+ f"{_approx_tokens:,}", f"{_new_tokens:,}",
+ )
- return handle_blueprint_command(args, origin=origin, surface="gateway")
- except Exception as e:
- logger.debug("blueprint command failed: %s", e)
- from hermes_cli.blueprint_cmd import BlueprintCommandResult
+ if _new_tokens >= _warn_token_threshold:
+ logger.warning(
+ "Session hygiene: still ~%s tokens after "
+ "compression",
+ f"{_new_tokens:,}",
+ )
- return BlueprintCommandResult(f"Cron blueprint command failed: {e}")
+ # If summary generation failed, the
+ # compressor aborts entirely and returns
+ # messages unchanged — nothing is dropped.
+ # Surface a visible warning to the gateway
+ # user — agent.log alone is invisible on
+ # TG/Discord/etc. — so they know the chat
+ # is "frozen" at the current size and can
+ # /compress to retry or /reset to start
+ # fresh.
+ _comp = getattr(_hyg_agent, "context_compressor", None)
+ if _comp is not None and getattr(_comp, "_last_compress_aborted", False):
+ if _hyg_failure_cooldown_seconds >= 0:
+ self._hygiene_compression_failure_cooldowns[
+ session_entry.session_id
+ ] = time.time() + _hyg_failure_cooldown_seconds
+ _err = getattr(_comp, "_last_summary_error", None) or "unknown error"
+ # Force-redact: provider exception text
+ # may contain credentials; this message
+ # reaches gateway users directly.
+ from agent.redact import redact_sensitive_text
+ _err = redact_sensitive_text(_err, force=True)
+ _warn_msg = (
+ "⚠️ Context compression aborted "
+ f"({_err}). No messages were dropped — "
+ "conversation is unchanged. Run /compress "
+ "to retry, /reset for a clean session, or "
+ "check your auxiliary.compression model "
+ "configuration."
+ )
+ try:
+ _adapter = self._adapter_for_source(source)
+ if _adapter and source.chat_id:
+ await _adapter.send(source.chat_id, _warn_msg, metadata=_hyg_meta)
+ except Exception as _werr:
+ logger.warning(
+ "Failed to deliver compression-failure warning to user: %s",
+ _werr,
+ )
+ # Separately: if the user's CONFIGURED aux
+ # model failed and we recovered by falling
+ # back to the main model, tell them — a
+ # misconfigured auxiliary.compression.model
+ # is something only they can fix, and
+ # silent recovery would hide it.
+ elif _comp is not None and getattr(_comp, "_last_aux_model_failure_model", None):
+ _aux_model = getattr(_comp, "_last_aux_model_failure_model", "")
+ _aux_err = getattr(_comp, "_last_aux_model_failure_error", None) or "unknown error"
+ _aux_msg = (
+ f"ℹ️ Configured compression model `{_aux_model}` "
+ f"failed ({_aux_err}). Recovered using your main "
+ "model — context is intact — but you may want to "
+ "check `auxiliary.compression.model` in config.yaml."
+ )
+ try:
+ _adapter = self._adapter_for_source(source)
+ if _adapter and source.chat_id:
+ await _adapter.send(source.chat_id, _aux_msg, metadata=_hyg_meta)
+ except Exception as _werr:
+ logger.warning(
+ "Failed to deliver aux-model-fallback notice to user: %s",
+ _werr,
+ )
+ finally:
+ # Evict the cached agent so the next turn
+ # rebuilds its system prompt from current
+ # SOUL.md, memory, and skills.
+ self._evict_cached_agent(session_key)
+ if not _hyg_cleanup_deferred:
+ await self._cleanup_agent_resources_off_loop(
+ _hyg_agent, context="session hygiene"
+ )
- # ────────────────────────────────────────────────────────────────
- # /goal — persistent cross-turn goals (Ralph-style loop)
- # ────────────────────────────────────────────────────────────────
- def _goal_max_turns_from_config(self) -> int:
- """Resolve the configured /goal turn budget for gateway sessions.
+ except Exception as e:
+ logger.warning(
+ "Session hygiene auto-compress failed: %s", e
+ )
- GatewayRunner.config is a GatewayConfig dataclass, not the full
- user config mapping. Top-level config blocks such as ``goals`` are
- therefore only available through hermes_cli.config.load_config().
- """
- try:
- goals_cfg = (
- (self.config or {}).get("goals", {})
- if isinstance(self.config, dict)
- else getattr(self.config, "goals", {}) or {}
+ # First-message onboarding -- only on the very first interaction ever.
+ # Delivered on the current user message (sidecar), NOT the ephemeral
+ # system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed
+ # system-prompt diff and agent rebuild.
+ if not history and not await self.async_session_store.has_any_sessions():
+ # Default first-contact note: a brief self-introduction.
+ _intro_note = (
+ "[System note: This is the user's very first message ever. "
+ "Briefly introduce yourself and mention that /help shows available commands. "
+ "Keep the introduction concise -- one or two sentences max.]"
)
- if not goals_cfg:
- from hermes_cli.config import load_config
+ # Opt-in structured profile-build path. When enabled (default
+ # "ask") and not yet offered on this install, swap the plain intro
+ # for a consent-gated directive that offers to build a user
+ # profile and persists confirmed facts via memory(target="user").
+ # The offer fires at most once (onboarding.seen flag); set
+ # onboarding.profile_build: off in config.yaml to disable.
+ try:
+ from agent.onboarding import (
+ PROFILE_BUILD_FLAG,
+ is_seen,
+ mark_seen,
+ profile_build_directive,
+ profile_build_mode,
+ )
+ _onb_cfg = _load_gateway_config()
+ if (
+ profile_build_mode(_onb_cfg) == "ask"
+ and not is_seen(_onb_cfg, PROFILE_BUILD_FLAG)
+ ):
+ turn_sidecar_notes.append(profile_build_directive().strip())
+ mark_seen(_hermes_home / "config.yaml", PROFILE_BUILD_FLAG)
+ else:
+ turn_sidecar_notes.append(_intro_note)
+ except Exception as _pb_err:
+ logger.debug(
+ "Profile-build onboarding directive failed, using plain intro: %s",
+ _pb_err,
+ )
+ turn_sidecar_notes.append(_intro_note)
+
+ # One-time prompt if no home channel is set for this platform
+ # Skip for webhooks - they deliver directly to configured targets (github_comment, etc.)
+ if not history and source.platform and source.platform != Platform.LOCAL and source.platform != Platform.WEBHOOK:
+ platform_name = source.platform.value
+ env_key = _home_target_env_var(platform_name)
+ # Multiplex: home channel may live only in the profile secret
+ # scope / PlatformConfig, not process os.environ.
+ home_env = ""
+ try:
+ from agent.secret_scope import get_secret
- goals_cfg = (load_config() or {}).get("goals") or {}
- return int(goals_cfg.get("max_turns", 20) or 20)
- except Exception:
- return 20
+ home_env = (get_secret(env_key) or "").strip() if env_key else ""
+ except Exception:
+ home_env = ""
+ if not home_env:
+ home_env = (os.getenv(env_key) or "").strip() if env_key else ""
+ # Also honor in-memory / yaml home_channel on this platform.
+ try:
+ if not home_env and self.config.get_home_channel(source.platform):
+ home_env = "set"
+ except Exception:
+ pass
+ # Secondary-profile platforms (e.g. Slack on yolo) may only exist
+ # under that profile's loaded config — check after scope install.
+ if not home_env:
+ try:
+ from gateway.config import load_gateway_config as _lgc
+ prof = (getattr(source, "profile", None) or "").strip()
+ if prof and prof != "default":
+ # Already inside profile scope for secondary handlers;
+ # re-read live config for home_channel.
+ _pcfg = _lgc()
+ if _pcfg.get_home_channel(source.platform):
+ home_env = "set"
+ except Exception:
+ pass
+ if not home_env:
+ # Slack dispatches all Hermes commands through a single
+ # parent slash command `/hermes`; bare `/sethome` is not
+ # registered and would fail with "app did not respond".
+ sethome_cmd = (
+ "/hermes sethome"
+ if source.platform == Platform.SLACK
+ else "/sethome"
+ )
+ notice = (
+ f"📬 No home channel is set for {platform_name.title()}. "
+ f"A home channel is where Hermes delivers cron job results "
+ f"and cross-platform messages.\n\n"
+ f"Type {sethome_cmd} to make this chat your home channel, "
+ f"or ignore to skip."
+ )
+ await self._deliver_platform_notice(source, notice)
+
+ # -----------------------------------------------------------------
+ # Voice channel awareness — deliver current voice channel state so
+ # the agent knows who is in the channel and who is speaking, without
+ # needing a separate tool call. Delivered on the current user
+ # message and ONLY when it changed since the previous turn: the
+ # member/speaking serialization differs essentially every turn, and
+ # appending it to the ephemeral system prompt forced a full agent
+ # rebuild + prompt-cache re-key per message. The system prompt
+ # carries a static pointer line instead (gateway/session.py).
+ # -----------------------------------------------------------------
+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)
+ if _vc_note:
+ turn_sidecar_notes.append(_vc_note)
- async def _get_goal_manager_for_event(self, event: "MessageEvent"):
- """Return a GoalManager bound to the session for this gateway event.
+ # -----------------------------------------------------------------
+ # Auto-analyze images sent by the user
+ #
+ # If the user attached image(s), we run the vision tool eagerly so
+ # the conversation model always receives a text description. The
+ # local file path is also included so the model can re-examine the
+ # image later with a more targeted question via vision_analyze.
+ #
+ # We filter to image paths only (by media_type) so that non-image
+ # attachments (documents, audio, etc.) are not sent to the vision
+ # tool even when they appear in the same message.
+ # -----------------------------------------------------------------
+ message_text = await self._prepare_profile_scoped_inbound_message_text(
+ event=event,
+ source=source,
+ history=history,
+ session_key=session_key,
+ )
+ if message_text is None:
+ return
- Returns ``(manager, session_entry)`` or ``(None, None)`` if the
- goals module can't be loaded.
- """
- try:
- from hermes_cli.goals import GoalManager
- except Exception as exc:
- logger.debug("goal manager unavailable: %s", exc)
- return None, None
+ # Capture the platform event time as message metadata and keep the
+ # persisted transcript clean (strip any leading timestamp prefix).
+ # This runs regardless of the toggle so storage stays clean and the
+ # send-time is preserved. Only the in-context RENDER (prepending the
+ # human-readable prefix the model sees) is gated behind
+ # gateway.message_timestamps.enabled — default OFF.
try:
- session_entry = await self.async_session_store.get_or_create_session(event.source)
- except Exception as exc:
- logger.debug("goal manager: session lookup failed: %s", exc)
- return None, None
- sid = getattr(session_entry, "session_id", None) or ""
- if not sid:
- return None, None
- max_turns = self._goal_max_turns_from_config()
- return GoalManager(session_id=sid, default_max_turns=max_turns), session_entry
-
+ from hermes_time import get_timezone as _get_evt_tz
+ from gateway.message_timestamps import (
+ coerce_message_timestamp as _coerce_msg_ts,
+ render_user_content_with_timestamp as _render_msg_ts,
+ strip_leading_message_timestamps as _strip_msg_ts,
+ )
+ _evt_tz = _get_evt_tz()
+ _evt_ts = getattr(event, "timestamp", None)
+ if message_text and isinstance(message_text, str):
+ _clean_message_text, _embedded_ts = _strip_msg_ts(
+ message_text, tz=_evt_tz)
+ persist_user_message = _clean_message_text
+ _event_epoch = _coerce_msg_ts(_evt_ts, tz=_evt_tz)
+ persist_user_timestamp = (
+ _event_epoch if _event_epoch is not None else _embedded_ts
+ )
+ if _message_timestamps_enabled(_load_gateway_config()):
+ message_text = _render_msg_ts(
+ _clean_message_text,
+ persist_user_timestamp,
+ tz=_evt_tz,
+ )
+ else:
+ # Toggle off: model sees the clean message; the timestamp
+ # is still stored as metadata for later opt-in.
+ message_text = _clean_message_text
+ except Exception as _ts_err:
+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)
+ # Stage the collected must-deliver notes for this turn's agent run
+ # (one-shot; consumed in run_sync). Staged AFTER the message_text
+ # early-out above so an aborted turn cannot leak its notes into the
+ # next turn's user message.
+ if turn_sidecar_notes and session_key:
+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)
- async def _send_goal_status_notice(self, source: Any, message: str) -> None:
- """Send a /goal judge status line back to the originating chat/thread."""
- adapter = self._adapter_for_source(source)
- if not adapter:
- logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None))
- return
+ # Bind this gateway run generation to the adapter's active-session
+ # event so deferred post-delivery callbacks can be released by the
+ # same run that registered them.
+ self._bind_adapter_run_generation(
+ self._adapter_for_source(source),
+ session_key,
+ run_generation,
+ )
try:
- metadata = self._thread_metadata_for_source(source)
- except Exception:
- metadata = None
+ # Emit agent:start hook
+ hook_ctx = {
+ "platform": source.platform.value if source.platform else "",
+ "user_id": source.user_id,
+ "chat_id": source.chat_id or "",
+ "thread_id": str(getattr(source, "thread_id", None)) if getattr(source, "thread_id", None) else "",
+ "chat_type": getattr(source, "chat_type", "") or "",
+ "session_id": session_entry.session_id,
+ "message": message_text[:500],
+ }
+ await self.hooks.emit("agent:start", hook_ctx)
- result = await adapter.send(source.chat_id, message, metadata=metadata)
- if result is not None and not getattr(result, "success", True):
- logger.warning(
- "goal continuation: status send failed: %s",
- getattr(result, "error", "unknown error"),
+ # Run the agent. Capture the session id that this run was launched
+ # against so post-run compression publication can be identity-guarded
+ # below; a /new or another lifecycle transition may move
+ # session_entry.session_id while the old run is still unwinding.
+ _run_start_session_id = session_entry.session_id
+ agent_result = await self._run_agent(
+ message=message_text,
+ context_prompt=context_prompt,
+ history=history,
+ source=source,
+ session_id=_run_start_session_id,
+ session_key=session_key,
+ run_generation=run_generation,
+ event_message_id=self._reply_anchor_for_event(event),
+ channel_prompt=event.channel_prompt,
+ moa_config=getattr(event, "_moa_config", None),
+ persist_user_message=persist_user_message,
+ persist_user_timestamp=persist_user_timestamp,
+ message_type=event.message_type,
)
- async def _defer_goal_status_notice_after_delivery(self, source: Any, message: str) -> None:
- """Send a /goal status line after the main response is delivered.
-
- The gateway message handler returns the agent response to the platform
- adapter, which sends it after this method's caller has returned. For a
- natural Discord/Telegram reading order, goal status belongs after that
- send. Platform adapters provide a one-shot post-delivery callback for
- exactly this boundary; when unavailable, fall back to direct awaited
- delivery rather than silently dropping the notice.
- """
- adapter = self._adapter_for_source(source)
- if not adapter:
- logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None))
- return
-
- async def _deliver() -> None:
+ # Stop persistent typing indicator now that the agent is done.
+ # Slack AI status is scoped to a thread/workspace, so preserve the
+ # same routing metadata used by the response delivery path.
try:
- await self._send_goal_status_notice(source, message)
- except Exception as exc:
- logger.warning("goal continuation: status send failed: %s", exc, exc_info=True)
+ _typing_adapter = self._adapter_for_source(source)
+ _stop_with_metadata = getattr(
+ type(_typing_adapter), "_stop_typing_with_metadata", None
+ )
+ _stop_typing = getattr(type(_typing_adapter), "stop_typing", None)
+ if _typing_adapter and callable(_stop_with_metadata):
+ await _typing_adapter._stop_typing_with_metadata(
+ source.chat_id,
+ self._thread_metadata_for_source(
+ source, self._reply_anchor_for_event(event)
+ ),
+ )
+ elif _typing_adapter and callable(_stop_typing):
+ await _typing_adapter.stop_typing(source.chat_id)
+ except Exception:
+ pass
- try:
- session_key = self._session_key_for_source(source)
- except Exception:
- session_key = None
+ if not self._is_session_run_current(_quick_key, run_generation):
+ logger.info(
+ "Discarding stale agent result for %s — generation %d is no longer current",
+ _quick_key or "?",
+ run_generation,
+ )
+ _stale_adapter = self._adapter_for_source(source)
+ if getattr(type(_stale_adapter), "pop_post_delivery_callback", None) is not None:
+ _stale_adapter.pop_post_delivery_callback(
+ _quick_key,
+ generation=run_generation,
+ )
+ elif _stale_adapter and hasattr(_stale_adapter, "_post_delivery_callbacks"):
+ _stale_adapter._post_delivery_callbacks.pop(_quick_key, None)
+ return None
- if session_key and hasattr(adapter, "register_post_delivery_callback"):
+ response = agent_result.get("final_response") or ""
+ # Hidden-reasoning-only retry exhaustion: the loop's sentinel text
+ # ("Codex response remained incomplete after 3 continuation
+ # attempts") doubles as final_response, so it would be delivered
+ # verbatim into the channel — where peer agents can ingest it as a
+ # completed assistant turn (#51628). Blank it here so the normal
+ # empty-response handling (and the suppression below) applies.
+ if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):
+ response = ""
try:
- generation = None
- active = getattr(adapter, "_active_sessions", {}).get(session_key)
- if active is not None:
- generation = getattr(active, "_hermes_run_generation", None)
- adapter.register_post_delivery_callback(
- session_key,
- _deliver,
- generation=generation,
+ from gateway.response_filters import is_intentional_silence_agent_result
+ _intentional_silence = is_intentional_silence_agent_result(
+ agent_result, response,
)
- return
- except Exception as exc:
- logger.debug("goal continuation: post-delivery callback registration failed: %s", exc)
-
- await _deliver()
-
- async def _post_turn_goal_continuation(
- self,
- *,
- session_entry: Any,
- source: Any,
- final_response: str,
- ) -> None:
- """Run the goal judge after a gateway turn and, if still active,
- enqueue a continuation prompt for the same session.
-
- Called from ``_handle_message_with_agent`` at turn boundary, AFTER
- the response has been delivered. Safe when no goal is set.
+ except Exception:
+ _intentional_silence = False
- We use the adapter's pending-message / FIFO machinery so any real
- user message that arrives simultaneously is handled by the same
- queue and takes priority naturally.
- """
- try:
- from hermes_cli.goals import GoalManager
- except Exception as exc:
- logger.debug("goal continuation: goals module unavailable: %s", exc)
- return
+ # Convert the agent's internal "(empty)" sentinel into a
+ # user-friendly message. "(empty)" means the model failed to
+ # produce visible content after exhausting all retries (nudge,
+ # prefill, empty-retry, fallback). Sending the raw sentinel
+ # looks like a bug; a short explanation is more helpful.
+ if response == "(empty)" and not _intentional_silence:
+ response = (
+ "⚠️ The model returned no response after processing tool "
+ "results. This can happen with some models — try again or "
+ "rephrase your question."
+ )
+ agent_messages = agent_result.get("messages", [])
+ _response_time = time.time() - _msg_start_time
+ _api_calls = agent_result.get("api_calls", 0)
+ _resp_len = len(response)
+ logger.info(
+ "response ready: platform=%s chat=%s time=%.1fs api_calls=%d response=%d chars",
+ _platform_name, source.chat_id or "unknown",
+ _response_time, _api_calls, _resp_len,
+ )
- sid = getattr(session_entry, "session_id", None) or ""
- if not sid:
- return
+ # NOTE: the cross-process cache-coherence re-baseline
+ # (_refresh_agent_cache_message_count) is intentionally deferred
+ # until AFTER this turn's transcript persistence block below — it
+ # must include the first-turn `session_meta` marker row and the
+ # compression session_id swap, both of which happen later. See
+ # the call site after the `update_session(...)` write.
- max_turns = self._goal_max_turns_from_config()
+ # Successful turn — clear any stuck-loop counter for this session.
+ # This ensures the counter only accumulates across CONSECUTIVE
+ # restarts where the session was active (never completed).
+ #
+ # Also clear the resume_pending flag (set by drain-timeout
+ # shutdown) — the turn ran to completion, so recovery
+ # succeeded and subsequent messages should no longer receive
+ # the restart-interruption system note.
+ if session_key and _should_clear_resume_pending_after_turn(agent_result):
+ self._clear_restart_failure_count(session_key)
+ try:
+ await self.async_session_store.clear_resume_pending(session_key)
+ except Exception as _e:
+ logger.debug(
+ "clear_resume_pending failed for %s: %s",
+ session_key, _e,
+ )
- mgr = GoalManager(session_id=sid, default_max_turns=max_turns)
- if not mgr.is_active():
- return
+ # Normalize empty responses: surface errors, partial failures, and
+ # the case where agent did work but returned no text. Fix for #18765.
+ if not _intentional_silence:
+ response = _normalize_empty_agent_response(
+ agent_result, response, history_len=len(history),
+ )
+ response = _sanitize_gateway_final_response(source.platform, response)
- try:
- from hermes_cli.goals import gather_background_processes as _gather_bg
- _bg_procs = _gather_bg()
- except Exception:
- _bg_procs = None
+ # Ordering contract: the agent thread already updated the contextvar
+ # in conversation_compression.py; propagate to SessionEntry + _save().
+ # If the agent's session_id changed during compression, update
+ # session_entry so transcript writes below go to the right session.
+ if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:
+ if session_entry.session_id == _run_start_session_id:
+ session_entry.session_id = agent_result["session_id"]
+ # The held turn lease follows the rotation: the transcript
+ # persistence below writes to the NEW id, so the
+ # serialization boundary must move with it or an alias
+ # key resolving the fresh child could interleave (#64934).
+ self._rebind_turn_lease(
+ _quick_key, run_generation, session_entry.session_id
+ )
+ await self.async_session_store._save()
+ await self.async_session_store._record_gateway_session_peer(
+ session_entry.session_id,
+ session_key,
+ source,
+ )
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding,
+ source, session_entry, reason="agent-result-compression",
+ )
+ else:
+ logger.info(
+ "Skipping agent-result session split sync for %s because "
+ "the session binding moved from %s to %s before "
+ "compression finished",
+ session_key or "?",
+ _run_start_session_id,
+ session_entry.session_id,
+ )
- decision = mgr.evaluate_after_turn(
- final_response or "",
- user_initiated=True,
- background_processes=_bg_procs,
- )
- msg = decision.get("message") or ""
+ # Prepend reasoning/thinking if display is enabled (per-platform).
+ # Mattermost requires explicit per-platform opt-in because this is
+ # scratch text, not ordinary final-answer content.
+ try:
+ _show_reasoning_effective = _resolve_gateway_display_bool(
+ _load_gateway_config(),
+ _platform_config_key(source.platform),
+ "show_reasoning",
+ default=bool(getattr(self, "_show_reasoning", False)),
+ platform=source.platform,
+ require_platform_override_for={Platform.MATTERMOST},
+ )
+ except Exception:
+ _show_reasoning_effective = (
+ False
+ if source.platform == Platform.MATTERMOST
+ else getattr(self, "_show_reasoning", False)
+ )
+ if _show_reasoning_effective and response and not _intentional_silence:
+ last_reasoning = agent_result.get("last_reasoning")
+ if last_reasoning:
+ from gateway.stream_consumer import escape_code_fences_for_display
+ # Collapse long reasoning to keep messages readable
+ lines = last_reasoning.strip().splitlines()
+ if len(lines) > 15:
+ display_reasoning = "\n".join(lines[:15])
+ display_reasoning += f"\n_... ({len(lines) - 15} more lines)_"
+ else:
+ display_reasoning = last_reasoning.strip()
+ # Render style is per-platform: Discord defaults to "-# "
+ # subtext (native small grey metadata text); other
+ # platforms keep the fenced code block.
+ try:
+ from gateway.display_config import resolve_display_setting
+ _reasoning_style = resolve_display_setting(
+ _load_gateway_config(),
+ _platform_config_key(source.platform),
+ "reasoning_style",
+ "code",
+ )
+ except Exception:
+ _reasoning_style = "code"
+ if _reasoning_style == "subtext":
+ _quoted = "\n".join(
+ f"-# {ln}" if ln else "-#" for ln in display_reasoning.splitlines()
+ )
+ response = f"-# 💭 Reasoning\n{_quoted}\n\n{response}"
+ elif _reasoning_style == "blockquote":
+ _quoted = "\n".join(
+ f"> {ln}" if ln else ">" for ln in display_reasoning.splitlines()
+ )
+ response = f"> 💭 **Reasoning:**\n{_quoted}\n\n{response}"
+ else:
+ # Escape ``` inside reasoning so inner fences don't
+ # break the outer code block used to render it.
+ display_reasoning = escape_code_fences_for_display(display_reasoning)
+ response = f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"
- # Defer the status line until after the adapter has delivered the
- # agent's visible final response. The judge runs after the response is
- # produced but before BasePlatformAdapter sends it, so sending here
- # would show "✓ Goal achieved" before the answer itself. Registering
- # an awaited post-delivery callback preserves delivery reliability
- # without reversing the user-visible ordering.
- if msg and source is not None:
- await self._defer_goal_status_notice_after_delivery(source, msg)
+ # Runtime-metadata footer — only on the FINAL message of the turn.
+ # Off by default (display.runtime_footer.enabled=false). When
+ # streaming already delivered the body, we can't mutate the sent
+ # text, so we fire a separate trailing send below.
+ _footer_line = ""
+ try:
+ from gateway.runtime_footer import build_footer_line as _bfl
+ _footer_line = _bfl(
+ user_config=_load_gateway_config(),
+ platform_key=_platform_config_key(source.platform),
+ model=agent_result.get("model"),
+ context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,
+ context_length=agent_result.get("context_length") or None,
+ cwd=os.environ.get("TERMINAL_CWD", ""),
+ )
+ except Exception as _footer_err:
+ logger.debug("runtime_footer build failed: %s", _footer_err)
+ _footer_line = ""
+ if _footer_line and response and not agent_result.get("already_sent") and not _intentional_silence:
+ response = f"{response}\n\n{_footer_line}"
- if not decision.get("should_continue"):
- return
+ # Emit agent:end hook
+ await self.hooks.emit("agent:end", {
+ **hook_ctx,
+ "response": (response or "")[:500],
+ })
+
+ # Check for pending process watchers (check_interval on background processes)
+ try:
+ from tools.process_registry import process_registry
+ # Detach the current batch atomically (see crash-recovery drain
+ # above): reassign to a fresh list so a watcher appended by a
+ # concurrent session during the yield isn't dropped by clear().
+ watchers = process_registry.pending_watchers
+ process_registry.pending_watchers = []
+ for i, watcher in enumerate(watchers):
+ asyncio.create_task(self._run_process_watcher(watcher))
+ if i % 100 == 99:
+ await asyncio.sleep(0)
+ except Exception as e:
+ logger.error("Process watcher setup error: %s", e)
- prompt = decision.get("continuation_prompt") or ""
- if not prompt or source is None:
- return
+ # Drain watch pattern notifications that arrived during the agent run.
+ # Watch events and completions share the same queue; process
+ # completions are already handled by the per-process watcher task
+ # above, so we only inject watch-type events here.
+ #
+ # Async-delegation completions ALSO ride this shared queue but are
+ # owned by the dedicated _async_delegation_watcher (started at
+ # boot), which covers both the idle and post-turn cases with a
+ # single consumer — so we leave them on the queue here.
+ try:
+ from tools.process_registry import process_registry as _pr
+ _watch_events = _drain_gateway_watch_events(_pr.completion_queue)
+ for evt in _watch_events:
+ synth_text = _format_gateway_process_notification(evt)
+ if synth_text:
+ try:
+ await self._inject_watch_notification(synth_text, evt)
+ except Exception as e2:
+ logger.error("Watch notification injection error: %s", e2)
+ except Exception as e:
+ logger.debug("Watch queue drain error: %s", e)
- # Enqueue via the adapter's FIFO so a user message already in
- # flight preempts the continuation naturally.
- try:
- adapter = self._adapter_for_source(source)
- _quick_key = self._session_key_for_source(source)
- if adapter and _quick_key:
- cont_event = MessageEvent(
- text=prompt,
- message_type=MessageType.TEXT,
- source=source,
- message_id=None,
- channel_prompt=None,
+ # NOTE: Dangerous command approvals are now handled inline by the
+ # blocking gateway approval mechanism in tools/approval.py. The agent
+ # thread blocks until the user responds with /approve or /deny, so by
+ # the time we reach here the approval has already been resolved. The
+ # old post-loop pop_pending + approval_hint code was removed in favour
+ # of the blocking approach that mirrors CLI's synchronous input().
+
+ # Save the full conversation to the transcript, including tool calls.
+ # This preserves the complete agent loop (tool_calls, tool results,
+ # intermediate reasoning) so sessions can be resumed with full context
+ # and transcripts are useful for debugging and training data.
+ #
+ # IMPORTANT: For context-overflow failures (compression exhausted,
+ # generic 400 on large sessions) we must NOT persist the user's
+ # message — doing so would grow the session further and cause the
+ # same failure on the next attempt, an infinite loop. (#1630, #9893)
+ #
+ # Transient failures (429, timeout, connection error, provider 5xx)
+ # are different: the session is not oversized, and silently dropping
+ # the user message causes severe context loss on retry — the agent
+ # forgets what was just asked. Persist the user turn so the
+ # conversation is preserved. (#7100)
+ agent_failed_early = bool(agent_result.get("failed"))
+ hidden_reasoning_incomplete = _is_gateway_hidden_reasoning_incomplete_turn(
+ agent_result
+ )
+ _err_str_for_classify = str(agent_result.get("error", "")).lower()
+ # Use specific multi-word phrases (not bare "exceed" or "token")
+ # to avoid false positives on transient errors like "rate limit
+ # exceeded" or "invalid auth token". Matches run_agent.py's
+ # own context-length classifier.
+ is_context_overflow_failure = agent_failed_early and (
+ bool(agent_result.get("compression_exhausted"))
+ or any(p in _err_str_for_classify for p in (
+ "context length", "context size", "context window",
+ "maximum context", "token limit", "too many tokens",
+ "reduce the length", "exceeds the limit",
+ "request entity too large", "prompt is too long",
+ "payload too large", "input is too long",
+ ))
+ or ("400" in _err_str_for_classify and len(history) > 50)
+ )
+ if is_context_overflow_failure:
+ logger.info(
+ "Skipping transcript persistence for context-overflow "
+ "failure in session %s to prevent session growth loop.",
+ session_entry.session_id,
+ )
+ elif agent_failed_early:
+ logger.info(
+ "Transient agent failure in session %s — persisting user "
+ "message so conversation context is preserved on retry.",
+ session_entry.session_id,
+ )
+ elif hidden_reasoning_incomplete:
+ logger.warning(
+ "Suppressing hidden-reasoning-only incomplete gateway turn "
+ "for session %s: %s",
+ session_entry.session_id,
+ agent_result.get("error", "processing incomplete"),
)
- self._enqueue_fifo(_quick_key, cont_event, adapter)
- except Exception as exc:
- logger.debug("goal continuation: enqueue failed: %s", exc)
-
+ # When compression is exhausted, the session is permanently too
+ # large to process. Auto-reset it so the next message starts
+ # fresh instead of replaying the same oversized context in an
+ # infinite fail loop. (#9893)
+ #
+ # A lock-contended defer is the OPPOSITE case: the session is
+ # temporarily uncompressible only because a concurrent path holds
+ # the compression lock and is actively shrinking it. Never wipe
+ # the session for that — retry-next-message semantics apply
+ # (#69870 lock-skip consumer; salvaged from #49874).
+ if agent_result.get("compression_deferred"):
+ logger.info(
+ "Compression deferred for session %s — the compression "
+ "lock is held by a concurrent compressor. Keeping the "
+ "session intact; the next message retries normally.",
+ session_entry.session_id if session_entry else "?",
+ )
+ elif agent_result.get("compression_exhausted") and session_entry and session_key:
+ logger.info(
+ "Auto-resetting session %s after compression exhaustion.",
+ session_entry.session_id,
+ )
+ new_entry = await self.async_session_store.reset_session(session_key)
+ self._evict_cached_agent(session_key)
+ # Conversation boundary: one funnel call clears every
+ # conversation-scoped per-session dict (#58403 and siblings).
+ # See _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(
+ session_key, reason="compression_exhausted_reset"
+ )
+ if new_entry is not None:
+ # Drop the stale reference to the bloated compressed child and
+ # re-point the Telegram topic binding at the fresh session.
+ # Compression rotated session_entry.session_id to the oversized
+ # compressed child earlier this turn (the agent-result sync
+ # above), and that _sync also rewrote the (chat_id, thread_id)
+ # -> bloated-child binding. reset_session swaps in a clean,
+ # parentless session, but without re-syncing the binding the
+ # next inbound message in this topic gets switch_session'd back
+ # onto the bloated child by the binding-heal walk, reloads the
+ # oversized transcript, and re-triggers compression exhaustion
+ # forever (#35809 — regression of the #9893/#10063 auto-reset).
+ # No-op on non-topic lanes.
+ session_entry = new_entry
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding,
+ source, session_entry, reason="compression-exhausted-reset",
+ )
+ response = (response or "") + (
+ "\n\n🔄 Session auto-reset — the conversation exceeded the "
+ "maximum context size and could not be compressed further. "
+ "Your next message will start a fresh session."
+ )
- @staticmethod
- def _get_guild_id(event: MessageEvent) -> Optional[int]:
- """Extract Discord guild_id from the raw message object."""
- raw = getattr(event, "raw_message", None)
- if raw is None:
- return None
- # Slash command interaction
- if hasattr(raw, "guild_id") and raw.guild_id:
- return int(raw.guild_id)
- # Regular message
- if hasattr(raw, "guild") and raw.guild:
- return raw.guild.id
- return None
+ ts = time.time() # Unix epoch float — consistent with DB storage
+
+ # If this is a fresh session (no history), write the full tool
+ # definitions as the first entry so the transcript is self-describing
+ # -- the same list of dicts sent as tools=[...] in the API request.
+ if is_context_overflow_failure:
+ pass # Skip all transcript writes — don't grow a broken session
+ elif not history:
+ tool_defs = agent_result.get("tools", [])
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id,
+ {
+ "role": "session_meta",
+ "tools": tool_defs or [],
+ "model": _resolve_gateway_model(),
+ "platform": source.platform.value if source.platform else "",
+ "timestamp": ts,
+ }
+ )
+
+ # The agent already persisted these messages to SQLite via
+ # _flush_messages_to_session_db(), so skip the DB write here
+ # to prevent the duplicate-write bug (#860 / #42039). This holds
+ # for the codex app-server runtime too: although it early-returns
+ # and bypasses conversation_loop's per-step flushes, it flushes its
+ # own projected assistant/tool messages before returning and
+ # reports agent_persisted=True (see agent/codex_runtime.py). Reading
+ # the flag (default = self._session_db is not None) keeps the
+ # persistence contract explicit and lets any future non-persisting
+ # runtime opt into a gateway-side write by returning False.
+ agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)
+ # Find only the NEW messages from this turn (skip history we loaded).
+ # Use the filtered history length (history_offset) that was actually
+ # passed to the agent, not len(history) which includes session_meta
+ # entries that were stripped before the agent saw them.
+ if is_context_overflow_failure:
+ pass # handled above — skip all transcript writes
+ elif agent_failed_early or hidden_reasoning_incomplete:
+ # Transient failure (429/timeout/5xx): persist only the user
+ # message so the next message can load a transcript that
+ # reflects what was said. Skip the assistant error text since
+ # it's a gateway-generated hint, not model output. Hidden-
+ # reasoning-only incomplete turns follow the same persistence
+ # rule so peer-agent channels don't ingest them as completed
+ # assistant turns. (#7100, #51628)
+ _user_entry = {
+ "role": "user",
+ "content": (
+ persist_user_message
+ if persist_user_message is not None
+ else message_text
+ ),
+ "timestamp": (
+ persist_user_timestamp
+ if persist_user_timestamp is not None
+ else ts
+ ),
+ }
+ if event.message_id:
+ _user_entry["message_id"] = str(event.message_id)
+ # Dedupe: skip if this platform message_id is already in the
+ # transcript (prevents duplicate user turns on Telegram retries
+ # after transient failures). #47237
+ _skip_persist = (
+ event.message_id
+ and await self.async_session_store.has_platform_message_id(
+ session_entry.session_id, str(event.message_id)
+ )
+ )
+ if _skip_persist:
+ logger.info(
+ "Skipping duplicate user turn "
+ "(message_id=%s) in session %s",
+ event.message_id, session_entry.session_id,
+ )
+ else:
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id,
+ _user_entry,
+ skip_db=agent_persisted,
+ )
+ else:
+ history_len = agent_result.get("history_offset", len(history))
+ new_messages = agent_messages[history_len:] if len(agent_messages) > history_len else []
- async def _handle_voice_channel_join(self, event: MessageEvent) -> str:
- """Join the user's current Discord voice channel."""
- adapter = self._adapter_for_source(event.source)
- if not hasattr(adapter, "join_voice_channel"):
- return "Voice channels are not supported on this platform."
+ # If no new messages found (edge case), fall back to simple user/assistant
+ if not new_messages:
+ _user_entry = {
+ "role": "user",
+ "content": (
+ persist_user_message
+ if persist_user_message is not None
+ else message_text
+ ),
+ "timestamp": (
+ persist_user_timestamp
+ if persist_user_timestamp is not None
+ else ts
+ ),
+ }
+ if event.message_id:
+ _user_entry["message_id"] = str(event.message_id)
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id,
+ _user_entry,
+ skip_db=agent_persisted,
+ )
+ if response:
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id,
+ {"role": "assistant", "content": response, "timestamp": ts},
+ skip_db=agent_persisted,
+ )
+ else:
+ # Attach the inbound platform message_id to the first user
+ # entry written this turn so platform-level quote-resolution
+ # (e.g. Yuanbao QuoteContextMiddleware's transcript fallback)
+ # can find earlier @bot messages by their original message_id.
+ _user_msg_id_attached = False
+ for msg in new_messages:
+ # Skip system messages (they're rebuilt each run)
+ if msg.get("role") == "system":
+ continue
+ # Add timestamp to each message for debugging
+ entry = {**msg, "timestamp": ts}
+ if (
+ not _user_msg_id_attached
+ and msg.get("role") == "user"
+ and event.message_id
+ and "message_id" not in entry
+ ):
+ entry["message_id"] = str(event.message_id)
+ _user_msg_id_attached = True
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id, entry,
+ skip_db=agent_persisted,
+ )
+
+ # Token counts and model are now persisted by the agent directly.
+ # Keep only last_prompt_tokens here for context-window tracking and
+ # compression decisions.
+ await self.async_session_store.update_session(
+ session_entry.session_key,
+ last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),
+ )
- guild_id = self._get_guild_id(event)
- if not guild_id:
- return "This command only works in a Discord server."
+ # Re-baseline the cached agent's message_count snapshot now that
+ # ALL of this turn's transcript writes are done — the agent's
+ # flushed user/assistant/tool rows AND the first-turn `session_meta`
+ # marker appended above. The cross-process coherence guard (#45966)
+ # snapshots the count at agent-BUILD time (before this turn's own
+ # writes) and never refreshes it on reuse, so without this the
+ # process's own turn grows message_count and the next turn sees a
+ # mismatch and rebuilds the agent — destroying prompt caching.
+ #
+ # This MUST run after the `session_meta` append: that row also
+ # increments message_count, so re-baselining before it (the old
+ # position) left the snapshot one short and the guard mis-fired on
+ # turn 2 of EVERY fresh gateway conversation, rebuilding the cached
+ # agent and busting the prompt cache. Running here also uses the
+ # compaction-updated session_id (the agent_result session_id swap
+ # above), matching this function's documented contract. Refreshing
+ # here makes the guard fire only on a DIFFERENT process's writes.
+ # Fail-safe inside the helper.
+ await self._refresh_agent_cache_message_count(
+ session_key, session_entry.session_id
+ )
- voice_channel = await adapter.get_user_voice_channel(
- guild_id, event.source.user_id
- )
- if not voice_channel:
- return "You need to be in a voice channel first."
+ # Intentional silence is a delivery decision, not a transcript
+ # mutation. The agent's [SILENT]/NO_REPLY assistant turn above is
+ # still persisted in session history so later turns keep normal
+ # user/assistant alternation; only the outbound chat delivery is
+ # suppressed.
+ if _intentional_silence:
+ logger.info(
+ "Suppressing intentional silence marker for session %s",
+ session_entry.session_id,
+ )
+ response = ""
- # Wire callbacks BEFORE join so voice input arriving immediately
- # after connection is not lost.
- if hasattr(adapter, "_voice_input_callback"):
- adapter._voice_input_callback = self._handle_voice_channel_input
- if hasattr(adapter, "_on_voice_disconnect"):
- adapter._on_voice_disconnect = self._handle_voice_timeout_cleanup
- # Let the adapter's inactivity timer see the live voice-reply mode so it
- # doesn't disconnect a deliberately text-only (/voice off) session.
- if hasattr(adapter, "_voice_mode_getter"):
- adapter._voice_mode_getter = lambda chat_id: self._voice_mode.get(
- self._voice_key(Platform.DISCORD, str(chat_id)), "off"
+ # Auto voice reply: send TTS audio before the text response
+ _already_sent = bool(agent_result.get("already_sent"))
+ # Skip when streaming TTS already delivered audio for this turn (#60671).
+ _stts_adapter = self._adapter_for_source(source)
+ _streaming_tts_done = (
+ _stts_adapter is not None
+ and bool(getattr(_stts_adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation))
)
+ if (
+ not _streaming_tts_done
+ and self._should_send_voice_reply(event, response, agent_messages, already_sent=_already_sent)
+ ):
+ await self._send_voice_reply(event, response)
- try:
- success = await adapter.join_voice_channel(voice_channel)
+ # If streaming already delivered the response, extract and
+ # deliver any MEDIA: files before returning None. Streaming
+ # sends raw text chunks that include MEDIA: tags — the normal
+ # post-processing in _process_message_background is skipped
+ # when already_sent is True, so media files would never be
+ # delivered without this.
+ #
+ # Never skip when the agent failed — the error message is new
+ # content the user hasn't seen (streaming only sent earlier
+ # partial output before the failure). Without this guard,
+ # users see the agent "stop responding without explanation."
+ if agent_result.get("already_sent") and not agent_result.get("failed"):
+ if response:
+ _media_adapter = self._adapter_for_source(source)
+ if _media_adapter:
+ await self._deliver_media_from_response(
+ response, event, _media_adapter,
+ history_media_paths=_collect_history_media_paths(history),
+ )
+ # Streaming already delivered the body text, but the footer was
+ # intentionally held back (see the `not already_sent` gate above).
+ # Send it now as a small trailing message so Telegram/Discord/etc.
+ # still surface the runtime metadata on the final reply.
+ if _footer_line:
+ try:
+ _foot_adapter = self._adapter_for_source(source)
+ if _foot_adapter:
+ await _foot_adapter.send(
+ source.chat_id,
+ _footer_line,
+ metadata=self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)),
+ )
+ except Exception as _e:
+ logger.debug("trailing footer send failed: %s", _e)
+ return None
+
+ return response
+
except Exception as e:
- logger.warning("Failed to join voice channel: %s", e)
- adapter._voice_input_callback = None
- err_lower = str(e).lower()
- if "pynacl" in err_lower or "nacl" in err_lower or "davey" in err_lower:
- return (
- "Voice dependencies are missing (PyNaCl / davey). "
- f"Install with: `{sys.executable} -m pip install PyNaCl`"
+ # Stop typing indicator on error too, retaining Slack thread/workspace
+ # routing so a failed turn cannot leave its status visible.
+ try:
+ _err_adapter = self._adapter_for_source(source)
+ _stop_with_metadata = getattr(
+ type(_err_adapter), "_stop_typing_with_metadata", None
)
- return f"Failed to join voice channel: {e}"
-
- if success:
- adapter._voice_text_channels[guild_id] = int(event.source.chat_id)
- if hasattr(adapter, "_voice_sources"):
- adapter._voice_sources[guild_id] = event.source.to_dict()
- self._voice_mode[self._voice_key(event.source.platform, event.source.chat_id)] = "all"
- self._save_voice_modes()
- self._set_adapter_auto_tts_enabled(adapter, event.source.chat_id, enabled=True)
+ _stop_typing = getattr(type(_err_adapter), "stop_typing", None)
+ if _err_adapter and callable(_stop_with_metadata):
+ await _err_adapter._stop_typing_with_metadata(
+ source.chat_id,
+ self._thread_metadata_for_source(
+ source, self._reply_anchor_for_event(event)
+ ),
+ )
+ elif _err_adapter and callable(_stop_typing):
+ await _err_adapter.stop_typing(source.chat_id)
+ except Exception:
+ pass
+ logger.exception("Agent error in session %s", session_key)
+ # Crash-resilience for failures that happen before AIAgent enters
+ # run_conversation() (for example: provider/httpx client init
+ # failures). In that path the agent cannot persist the current
+ # inbound turn itself, so append the user message here once. If the
+ # agent already reached its early turn-start persistence, the latest
+ # transcript user row will match and we skip the duplicate.
+ try:
+ if 'message_text' in locals() and message_text is not None and session_entry is not None:
+ _already_persisted = False
+ try:
+ _recent_transcript = await self.async_session_store.load_transcript(session_entry.session_id)
+ except Exception:
+ _recent_transcript = []
+ for _msg in reversed(_recent_transcript[-10:]):
+ if _msg.get("role") == "user":
+ _expected_user_content = (
+ persist_user_message
+ if persist_user_message is not None
+ else message_text
+ )
+ _already_persisted = (_msg.get("content") == _expected_user_content)
+ break
+ if not _already_persisted:
+ _user_entry = {
+ "role": "user",
+ "content": (
+ persist_user_message
+ if persist_user_message is not None
+ else message_text
+ ),
+ "timestamp": (
+ persist_user_timestamp
+ if persist_user_timestamp is not None
+ else time.time()
+ ),
+ }
+ if getattr(event, "message_id", None):
+ _user_entry["message_id"] = str(event.message_id)
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id,
+ _user_entry,
+ )
+ except Exception:
+ logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)
+ # Log full details server-side only; never expose raw exception
+ # types or messages to end users (info-leakage risk).
+ status_hint = ""
+ status_code = getattr(e, "status_code", None)
+ _hist_len = len(history) if 'history' in locals() else 0
+ if status_code == 401:
+ status_hint = " Check your API key or run `claude /login` to refresh OAuth credentials."
+ elif status_code == 402:
+ status_hint = " Your API balance or quota is exhausted. Check your provider dashboard."
+ elif status_code == 429:
+ # Check if this is a plan usage limit (resets on a schedule) vs a transient rate limit
+ _err_body = getattr(e, "response", None)
+ _err_json = {}
+ try:
+ if _err_body is not None:
+ _err_json = _err_body.json().get("error", {})
+ if not isinstance(_err_json, dict):
+ _err_json = {}
+ except Exception:
+ pass
+ if _err_json.get("type") == "usage_limit_reached":
+ _resets_in = _err_json.get("resets_in_seconds")
+ if _resets_in and _resets_in > 0:
+ import math
+ _hours = math.ceil(_resets_in / 3600)
+ status_hint = f" Your plan's usage limit has been reached. It resets in ~{_hours}h."
+ else:
+ status_hint = " Your plan's usage limit has been reached. Please wait until it resets."
+ else:
+ status_hint = " You are being rate-limited. Please wait a moment and try again."
+ elif status_code == 529:
+ status_hint = " The API is temporarily overloaded. Please try again shortly."
+ elif status_code in {400, 500}:
+ # 400 with a large session is context overflow.
+ # 500 with a large session often means the payload is too large
+ # for the API to process — treat it the same way.
+ if _hist_len > 50:
+ return (
+ "⚠️ Session too large for the model's context window.\n"
+ "Use /compact to compress the conversation, or "
+ "/reset to start fresh."
+ )
+ elif status_code == 400:
+ status_hint = " The request was rejected by the API."
return (
- f"Joined voice channel **{voice_channel.name}**.\n"
- f"I'll speak my replies and listen to you. Use /voice leave to disconnect."
+ f"Sorry, I encountered an unexpected error.{status_hint}\n"
+ "Try again or use /reset to start a fresh session."
)
- # Join failed — clear callback
- adapter._voice_input_callback = None
- return "Failed to join voice channel. Check bot permissions (Connect + Speak)."
-
- async def _handle_voice_channel_leave(self, event: MessageEvent) -> str:
- """Leave the Discord voice channel."""
- adapter = self._adapter_for_source(event.source)
- guild_id = self._get_guild_id(event)
+ finally:
+ # Restore session context variables to their pre-handler state
+ self._clear_session_env(_session_env_tokens)
- if not guild_id or not hasattr(adapter, "leave_voice_channel"):
- return "Not in a voice channel."
+ def _reset_notice_session_info(self, source: SessionSource) -> str:
+ """Session-info block for the auto-reset notice, profile-scoped.
- if not hasattr(adapter, "is_in_voice_channel") or not adapter.is_in_voice_channel(guild_id):
- return "Not in a voice channel."
+ When multiplexing, resolve model/provider/context inside the profile
+ serving ``source`` — otherwise the banner advertises the base config's
+ model while the session actually runs on the profile's (#59003).
+ Mirrors ``_run_agent``'s gating so single-profile gateways never
+ enter the scope.
- try:
- await adapter.leave_voice_channel(guild_id)
- except Exception as e:
- logger.warning("Error leaving voice channel: %s", e)
- # Always clean up state even if leave raised an exception
- self._voice_mode[self._voice_key(event.source.platform, event.source.chat_id)] = "off"
- self._save_voice_modes()
- self._set_adapter_auto_tts_disabled(adapter, event.source.chat_id, disabled=True)
- if hasattr(adapter, "_voice_input_callback"):
- adapter._voice_input_callback = None
- return "Left voice channel."
+ Call via ``asyncio.to_thread`` from async handlers: under the scope,
+ resolution can do blocking work (credential refresh, context-length
+ HTTP probes) that must not run on the event loop. The scope is entered
+ inside this method, so contextvars behave correctly in the worker
+ thread.
+ """
+ if getattr(getattr(self, "config", None), "multiplex_profiles", False):
+ with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):
+ return self._format_session_info()
+ return self._format_session_info()
- def _handle_voice_timeout_cleanup(self, chat_id: str) -> None:
- """Called by the adapter when a voice channel times out.
+ def _format_session_info(self) -> str:
+ """Resolve current model config and return a formatted info block.
- Cleans up runner-side voice_mode state that the adapter cannot reach.
+ Surfaces model, provider, context length, and endpoint so gateway
+ users can immediately see if context detection went wrong (e.g.
+ local models falling to the 128K default).
"""
- self._voice_mode[self._voice_key(Platform.DISCORD, chat_id)] = "off"
- self._save_voice_modes()
- adapter = self.adapters.get(Platform.DISCORD)
- self._set_adapter_auto_tts_disabled(adapter, chat_id, disabled=True)
+ from agent.model_metadata import get_model_context_length, DEFAULT_FALLBACK_CONTEXT
- def _is_duplicate_voice_transcript(self, guild_id: int, user_id: int, transcript: str) -> bool:
- """Suppress repeated STT outputs for the same recent utterance.
+ model = _resolve_gateway_model()
+ config_context_length = None
+ provider = None
+ base_url = None
+ api_key = None
+ custom_provs = None
+ data = None
+ configured_model = None
+ configured_provider = None
+ configured_base_url = None
- Voice capture can occasionally emit the same utterance twice a few
- seconds apart, which creates a second queued agent run and overlapping
- spoken replies. Dedup exact and near-exact repeats per guild/user over a
- short window while allowing genuinely new turns through.
- """
- from difflib import SequenceMatcher
+ try:
+ data = _load_gateway_config()
+ if data:
+ model_cfg = data.get("model", {})
+ if isinstance(model_cfg, dict):
+ configured_model = model_cfg.get("default") or model_cfg.get("model")
+ raw_ctx = model_cfg.get("context_length")
+ if raw_ctx is not None:
+ try:
+ config_context_length = int(raw_ctx)
+ except (TypeError, ValueError):
+ pass
+ provider = model_cfg.get("provider") or None
+ base_url = model_cfg.get("base_url") or None
+ configured_provider = provider
+ configured_base_url = base_url
+ try:
+ from hermes_cli.config import get_compatible_custom_providers
+ custom_provs = get_compatible_custom_providers(data)
+ except Exception:
+ custom_provs = data.get("custom_providers")
+ except Exception:
+ pass
- normalized = re.sub(r"\s+", " ", transcript).strip().lower()
- normalized = re.sub(r"[^\w\s]", "", normalized)
- if not normalized:
- return False
+ # Resolve runtime credentials for probing
+ try:
+ runtime = _resolve_runtime_agent_kwargs()
+ provider = runtime.get("provider") or provider
+ base_url = runtime.get("base_url") or base_url
+ api_key = runtime.get("api_key")
+ except Exception:
+ pass
- now = time.monotonic()
- window_seconds = 12.0
- key = (guild_id, user_id)
- recent_store = getattr(self, "_recent_voice_transcripts", None)
- if not isinstance(recent_store, dict):
- recent_store = {}
- self._recent_voice_transcripts = recent_store
- recent = [
- (ts, txt)
- for ts, txt in recent_store.get(key, [])
- if now - ts <= window_seconds
- ]
+ if config_context_length is not None:
+ try:
+ from hermes_cli.route_identity import should_clear_context_pin
- for _, prior in recent:
- if prior == normalized:
- recent_store[key] = recent
- return True
- if len(prior) >= 16 and len(normalized) >= 16:
- if SequenceMatcher(None, prior, normalized).ratio() >= 0.95:
- recent_store[key] = recent
- return True
+ if should_clear_context_pin(
+ configured_model,
+ model,
+ configured_base_url,
+ base_url,
+ configured_provider,
+ provider,
+ ):
+ config_context_length = None
+ except Exception:
+ config_context_length = None
- recent.append((now, normalized))
- recent_store[key] = recent[-5:]
- return False
+ if config_context_length is None and custom_provs and base_url:
+ try:
+ from hermes_cli.config import get_custom_provider_context_length
- async def _handle_voice_channel_input(
- self, guild_id: int, user_id: int, transcript: str
- ):
- """Handle transcribed voice from a user in a voice channel.
+ custom_ctx = get_custom_provider_context_length(
+ model=model,
+ base_url=base_url,
+ custom_providers=custom_provs,
+ )
+ if custom_ctx:
+ config_context_length = custom_ctx
+ except Exception:
+ pass
- Creates a synthetic MessageEvent and processes it through the
- adapter's full message pipeline (session, typing, agent, TTS reply).
- """
- adapter = self.adapters.get(Platform.DISCORD)
- if not adapter:
- return
+ context_length = get_model_context_length(
+ model,
+ base_url=base_url or "",
+ api_key=api_key or "",
+ config_context_length=config_context_length,
+ provider=provider or "",
+ custom_providers=custom_provs,
+ )
- text_ch_id = adapter._voice_text_channels.get(guild_id)
- if not text_ch_id:
- return
+ # Format context source hint
+ if config_context_length is not None:
+ ctx_source = "config"
+ elif context_length == DEFAULT_FALLBACK_CONTEXT:
+ ctx_source = "default — set model.context_length in config to override"
+ else:
+ ctx_source = "detected"
- # Build source — reuse the linked text channel's metadata when available
- # so voice input shares the same session as the bound text conversation.
- source_data = getattr(adapter, "_voice_sources", {}).get(guild_id)
- if source_data:
- source = SessionSource.from_dict(source_data)
- source.user_id = str(user_id)
- source.user_name = str(user_id)
+ # Format context length for display
+ if context_length >= 1_000_000:
+ ctx_display = f"{context_length / 1_000_000:.1f}M"
+ elif context_length >= 1_000:
+ ctx_display = f"{context_length // 1_000}K"
else:
- source = SessionSource(
- platform=Platform.DISCORD,
- chat_id=str(text_ch_id),
- user_id=str(user_id),
- user_name=str(user_id),
- chat_type="channel",
- )
+ ctx_display = str(context_length)
+
+ lines = [
+ f"◆ Model: `{model}`",
+ f"◆ Provider: {provider or 'openrouter'}",
+ f"◆ Context: {ctx_display} tokens ({ctx_source})",
+ ]
- # Check authorization before processing voice input
- if not self._is_user_authorized(source):
- logger.debug("Unauthorized voice input from user %d, ignoring", user_id)
- return
+ # Show endpoint for local/custom setups
+ if base_url and ("localhost" in base_url or "127.0.0.1" in base_url or "0.0.0.0" in base_url):
+ lines.append(f"◆ Endpoint: {base_url}")
- if self._is_duplicate_voice_transcript(guild_id, user_id, transcript):
- logger.info(
- "Suppressing duplicate voice transcript for guild=%s user=%s: %s",
- guild_id,
- user_id,
- transcript[:100],
- )
- return
+ return "\n".join(lines)
- # Show transcript in text channel (after auth, with mention sanitization)
- try:
- channel = adapter._client.get_channel(text_ch_id)
- if channel:
- safe_text = transcript[:2000].replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere")
- await channel.send(f"**[Voice]** <@{user_id}>: {safe_text}")
- except Exception:
- pass
- # Build a synthetic MessageEvent and feed through the normal pipeline
- # Use SimpleNamespace as raw_message so _get_guild_id() can extract
- # guild_id and _send_voice_reply() plays audio in the voice channel.
- from types import SimpleNamespace
- # Resolve the bound text channel's channel_prompt so voice input gets
- # the same per-channel context as typed messages (#50149).
- channel_prompt: Optional[str] = None
- resolver = getattr(adapter, "_resolve_channel_prompt", None)
- if callable(resolver):
- try:
- resolved = resolver(str(text_ch_id))
- channel_prompt = resolved if isinstance(resolved, str) else None
- except Exception:
- channel_prompt = None
- event = MessageEvent(
- source=source,
- text=transcript,
- message_type=MessageType.VOICE,
- raw_message=SimpleNamespace(guild_id=guild_id, guild=None),
- channel_prompt=channel_prompt,
- )
- await adapter.handle_message(event)
- def _should_send_voice_reply(
- self,
- event: MessageEvent,
- response: str,
- agent_messages: list,
- already_sent: bool = False,
- ) -> bool:
- """Decide whether the runner should send a TTS voice reply.
+ def _check_slash_access(
+ self, source: SessionSource, canonical_cmd: str
+ ) -> Optional[str]:
+ """Return a denial message if ``source`` cannot run ``canonical_cmd``,
+ else None. Used by both the cold and running-agent dispatch paths
+ in ``_handle_message`` so admin/user gating can't be bypassed by
+ an in-flight agent.
- Returns False when:
- - voice_mode is off for this chat
- - response is empty or an error
- - agent already called text_to_speech tool (dedup)
- - voice input and base adapter auto-TTS already handled it (skip_double)
- UNLESS streaming already consumed the response (already_sent=True),
- in which case the base adapter won't have text for auto-TTS so the
- runner must handle it.
+ Backward-compat semantics live in
+ :func:`gateway.slash_access.policy_for_source` — when the operator
+ hasn't set ``allow_admin_from`` for the scope, the policy returns
+ ``enabled=False`` and this method always returns None.
"""
- if not response or response.startswith("Error:"):
- return False
-
- chat_id = event.source.chat_id
- voice_key = self._voice_key(event.source.platform, chat_id)
- voice_mode = self._voice_mode.get(voice_key)
- is_voice_input = (event.message_type == MessageType.VOICE)
-
- adapter = self.adapters.get(event.source.platform)
- adapter_auto_tts = False
- if adapter and hasattr(adapter, "_should_auto_tts_for_chat"):
- try:
- adapter_auto_tts = bool(adapter._should_auto_tts_for_chat(chat_id))
- except Exception:
- adapter_auto_tts = False
+ from gateway.slash_access import policy_for_source as _policy_for_source
- should = (
- (voice_mode == "all")
- or (voice_mode == "voice_only" and is_voice_input)
- # ``voice.auto_tts`` is synced into the adapter on gateway startup.
- # Treat it as "voice accompanies text replies" unless a chat was
- # explicitly turned off. The base adapter's own auto-TTS path only
- # covers voice-input replies, so final text replies need the runner
- # path here.
- or (voice_mode != "off" and adapter_auto_tts)
+ if not canonical_cmd:
+ return None
+ policy = _policy_for_source(self.config, source)
+ if not policy.enabled or policy.can_run(source.user_id, canonical_cmd):
+ return None
+ logger.info(
+ "Slash command /%s denied for %s:%s (not admin, not in user_allowed_commands)",
+ canonical_cmd,
+ source.platform.value if source.platform else "?",
+ source.user_id,
)
- if not should:
- logger.debug(
- "Auto voice reply skipped: mode=%s adapter_auto_tts=%s chat=%s platform=%s",
- voice_mode, adapter_auto_tts, chat_id, event.source.platform.value,
+ allowed_preview = sorted(policy.user_allowed_commands)
+ if allowed_preview:
+ suffix = (
+ "You can run: "
+ + ", ".join(f"/{c}" for c in allowed_preview[:12])
+ + ("…" if len(allowed_preview) > 12 else "")
+ + ". Use /whoami for the full list."
)
- return False
-
- # Dedup: agent already called TTS tool in THIS turn only
- last_user_idx = None
- for i, msg in enumerate(reversed(agent_messages)):
- if msg.get("role") == "user":
- last_user_idx = len(agent_messages) - 1 - i; break
- turn_messages = agent_messages[last_user_idx:] if last_user_idx is not None else agent_messages
- has_agent_tts = any(
- msg.get("role") == "assistant"
- and any(
- (tc.get("function") or {}).get("name") == "text_to_speech"
- for tc in (msg.get("tool_calls") or [])
+ else:
+ suffix = (
+ "No slash commands are enabled for non-admins on this "
+ "platform. Ask an admin to add you to allow_admin_from "
+ "or to set user_allowed_commands."
)
- for msg in turn_messages
- )
- if has_agent_tts:
- return False
+ return f"⛔ /{canonical_cmd} is admin-only here. {suffix}"
- # Dedup: base adapter auto-TTS already handles voice input
- # (play_tts plays in VC when connected, so runner can skip).
- # When streaming already delivered the text (already_sent=True),
- # the base adapter will receive None and can't run auto-TTS,
- # so the runner must take over.
- if is_voice_input and not already_sent:
- return False
- return True
- def _should_echo_stt_transcripts(self) -> bool:
- """Return whether inbound voice/STT transcripts should be echoed to chat."""
- return bool(getattr(self.config, "stt_echo_transcripts", True))
- async def _send_voice_reply(self, event: MessageEvent, text: str) -> None:
- """Generate TTS audio and send as a voice message before the text reply."""
- audio_path = None
- actual_path = None
- try:
- from tools.tts_tool import text_to_speech_tool, _strip_markdown_for_tts
- tts_text = _strip_markdown_for_tts(text[:4000])
- if not tts_text:
- return
- # Platform-aware output path: platforms whose native voice
- # bubbles require Ogg/Opus (OPUS_VOICE_PLATFORMS — Telegram,
- # Matrix, Feishu, WhatsApp, Signal) get an explicit .ogg path;
- # the TTS tool's central container repair guarantees real
- # Ogg/Opus bytes for every provider. Others keep MP3.
- audio_path = build_auto_tts_output_path(event.source.platform)
- result_json = await asyncio.to_thread(
- text_to_speech_tool, text=tts_text, output_path=audio_path
- )
- try:
- result = json.loads(result_json)
- except (json.JSONDecodeError, TypeError):
- logger.warning("Auto voice reply TTS returned invalid JSON: %s", result_json[:200] if result_json else result_json)
- return
+ def _sibling_thread_run_keys(self, source: SessionSource, own_key: str) -> list:
+ """Find running-agent keys for OTHER participants in the same thread.
- # Use the actual file path from result (may differ after opus conversion)
- actual_path = result.get("file_path", audio_path)
- if not result.get("success") or not os.path.isfile(actual_path):
- logger.warning("Auto voice reply TTS failed: %s", result.get("error"))
- return
+ Only applies when the message originates in a thread. In per-user
+ thread mode (``thread_sessions_per_user=True``) each participant gets
+ an isolated session key of the form
+ ``agent:main:{platform}:{chat_type}:{chat_id}:{thread_id}:{user_id}``,
+ so a run started by another user is invisible to the caller's own
+ ``/stop``. This returns the keys of any *actually running* agents
+ (not the pending sentinel, not the caller's own key) whose key shares
+ the caller's ``{chat_id}:{thread_id}`` prefix.
+
+ Returns an empty list when the source is not in a thread, or when no
+ sibling runs exist — callers must still gate on authorization.
+ """
+ thread_id = getattr(source, "thread_id", None)
+ chat_id = getattr(source, "chat_id", None)
+ if not thread_id or not chat_id:
+ return []
+ platform = source.platform.value
+ chat_type = getattr(source, "chat_type", None) or ""
+ # Prefix that every per-user key in this thread shares, up to and
+ # including the thread_id segment. Matching either the exact
+ # shared-thread key or any key with a further (user_id) segment
+ # (prefix + ":") avoids cross-matching an unrelated thread whose id
+ # merely starts with this one.
+ prefix = ":".join(
+ ["agent:main", platform, chat_type, str(chat_id), str(thread_id)]
+ )
+ matches = []
+ for key, agent in self._running_agent_items():
+ if key == own_key:
+ continue
+ if agent is _AGENT_PENDING_SENTINEL or not agent:
+ continue
+ if key == prefix or key.startswith(prefix + ":"):
+ matches.append(key)
+ return matches
- adapter = self._adapter_for_source(event.source)
- # If connected to a voice channel, play there instead of sending a file
- guild_id = self._get_guild_id(event)
- if (guild_id
- and hasattr(adapter, "play_in_voice_channel")
- and hasattr(adapter, "is_in_voice_channel")
- and adapter.is_in_voice_channel(guild_id)):
- await adapter.play_in_voice_channel(guild_id, actual_path)
- elif adapter and hasattr(adapter, "send_voice"):
- reply_anchor = self._reply_anchor_for_event(event)
- thread_meta = self._thread_metadata_for_source(event.source, reply_anchor)
- # Mark the auto voice reply as notify-worthy. Mirrors the
- # final-text path in gateway/platforms/base.py which sets
- # ``notify=True`` so platform adapters that gate push
- # notifications (Telegram "important" mode) deliver the
- # final voice reply as a normal notification instead of a
- # silent message. Clone first so we don't mutate metadata
- # shared with concurrent typing-indicator state.
- if thread_meta is not None:
- thread_meta = dict(thread_meta)
- thread_meta["notify"] = True
- else:
- thread_meta = {"notify": True}
- send_kwargs: Dict[str, Any] = {
- "chat_id": event.source.chat_id,
- "audio_path": actual_path,
- "reply_to": reply_anchor,
- "metadata": thread_meta,
- }
- await adapter.send_voice(**send_kwargs)
- except Exception as e:
- logger.warning("Auto voice reply failed: %s", e, exc_info=True)
- finally:
- for p in {audio_path, actual_path} - {None}:
- try:
- os.unlink(p)
- except OSError:
- pass
- async def _deliver_media_from_response(
- self,
- response: str,
- event: MessageEvent,
- adapter,
- history_media_paths: Optional[set] = None,
- ) -> None:
- """Extract explicit MEDIA: tags from a response and deliver them.
- Called after streaming has already sent the text to the user, so the
- text itself is already delivered — this only handles file attachments
- that the normal _process_message_background path would have caught.
+ def _is_stale_restart_redelivery(self, event: MessageEvent) -> bool:
+ """Return True if this /restart is a Telegram re-delivery we already handled.
- Unlike the non-streaming path in ``gateway/platforms/base.py`` (which
- also auto-detects bare local paths via ``extract_local_files``), this
- post-stream rescan is EXPLICIT-ONLY. The visible reply has already
- been streamed verbatim, so a bare path string here was either (a)
- already shown to the user as text, or (b) stale tool/inspected
- content that was never part of the intended visible reply. Promoting
- such paths into uploads after the fact sent files the model never
- asked to deliver (#20834). Only ``MEDIA:`` directives — the explicit
- attachment contract — trigger post-stream uploads.
+ The previous gateway wrote ``.restart_last_processed.json`` with the
+ triggering platform + update_id when it processed the /restart. If
+ we now see a /restart on the same platform with an update_id <= that
+ recorded value, it is a redelivery when this process booted from that
+ restart. Otherwise the marker must still be recent (< 5 minutes).
+
+ Only applies to Telegram today (the only platform that exposes a
+ numeric cross-session update ordering); other platforms return False.
"""
- from pathlib import Path
- from urllib.parse import quote as _quote
+ if event is None or event.source is None:
+ return False
+ if event.platform_update_id is None:
+ return False
+ if event.source.platform is None:
+ return False
+ # Only Telegram populates platform_update_id currently; be explicit
+ # so future platforms aren't accidentally gated by this check.
+ try:
+ platform_value = event.source.platform.value
+ except Exception:
+ return False
+ if platform_value != "telegram":
+ return False
try:
- # Capture [[as_document]] before extract_media strips it, so the
- # dispatch partition below can route image-extension files
- # through send_document (preserving bytes) instead of
- # send_multiple_images (Telegram sendPhoto recompresses to ~1280px).
- force_document_attachments = "[[as_document]]" in response
+ marker_path = _hermes_home / ".restart_last_processed.json"
+ if not marker_path.exists():
+ # Belt-and-suspenders for when the dedup marker goes missing
+ # (manually cleaned up, or the previous cycle's write failed).
+ # Without a marker the update_id comparison below can't run, so
+ # a redelivered /restart would sail through and re-restart the
+ # gateway — an infinite loop (issue #18528).
+ #
+ # Suppress ONLY when we can independently confirm we just came
+ # out of a restart cycle: this process booted from a
+ # chat-originated /restart (_booted_from_restart) AND is still
+ # within a short post-boot window. This never swallows a
+ # genuine first /restart on a fresh boot (no restart marker on
+ # boot → flag stays False). Consume the flag one-shot so a
+ # legitimate /restart sent later in the same session is honored.
+ if (
+ getattr(self, "_booted_from_restart", False)
+ and time.time() - getattr(self, "_startup_time", 0.0) < 60
+ ):
+ self._booted_from_restart = False
+ return True
+ return False
+ data = json.loads(marker_path.read_text(encoding="utf-8"))
+ except Exception:
+ return False
- from gateway.platforms.base import BasePlatformAdapter, should_send_media_as_audio
+ if data.get("platform") != platform_value:
+ return False
+ recorded_uid = data.get("update_id")
+ if not isinstance(recorded_uid, int):
+ return False
+ if event.platform_update_id > recorded_uid:
+ return False
- media_files, cleaned = adapter.extract_media(response)
- media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)
- # Deduplicate against media already delivered in prior turns —
- # the model may echo a previous turn's MEDIA: tag in a later
- # response; without this guard the same file is re-sent.
- if history_media_paths:
- media_files = [
- (path, is_voice)
- for path, is_voice in media_files
- if path not in history_media_paths
- ]
- # Strip image URLs from the cleaned text for parity with the
- # non-streaming chain, but do NOT run extract_local_files here:
- # post-stream delivery is explicit-only (#20834). Bare local paths
- # in an already-streamed reply are text the user has seen (or
- # stale inspected content), not an attachment request.
- adapter.extract_images(cleaned)
+ # A service-managed restart can legitimately take longer than the
+ # marker's normal five-minute trust window while adapters, cron, and
+ # in-flight deliveries drain. If this process booted from the recorded
+ # chat restart, the first same-or-older update is still that restart's
+ # redelivery regardless of elapsed wall time. Consume the boot signal
+ # one-shot so a later genuine command is evaluated normally.
+ if getattr(self, "_booted_from_restart", False):
+ self._booted_from_restart = False
+ return True
- _thread_meta = self._thread_metadata_for_source(event.source, self._reply_anchor_for_event(event))
+ # Staleness guard: ignore markers older than 5 minutes. A legitimately
+ # old marker (e.g. crash recovery where notify never fired) should not
+ # swallow a fresh /restart from the user.
+ requested_at = data.get("requested_at")
+ if isinstance(requested_at, (int, float)):
+ if time.time() - requested_at > 300:
+ return False
+ return True
- _VIDEO_EXTS = {'.mp4', '.mov', '.avi', '.mkv', '.webm', '.3gp'}
- _IMAGE_EXTS = {'.jpg', '.jpeg', '.png', '.webp', '.gif'}
- # Partition out images so they can be sent as a single batch
- # (e.g. Signal's multi-attachment RPC). When [[as_document]] was
- # set, image-extension files skip the photo path and route to
- # send_document below — preserving original bytes.
- image_paths: list = []
- non_image_media: list = []
- for media_path, is_voice in media_files:
- ext = Path(media_path).suffix.lower()
- if (ext in _IMAGE_EXTS
- and not is_voice
- and not force_document_attachments):
- image_paths.append(media_path)
- else:
- non_image_media.append((media_path, is_voice))
- if image_paths:
- try:
- images = [(f"file://{_quote(p)}", "") for p in image_paths]
- await adapter.send_multiple_images(
- chat_id=event.source.chat_id,
- images=images,
- metadata=_thread_meta,
- )
- except Exception as e:
- logger.warning("[%s] Post-stream image batch delivery failed: %s", adapter.name, e)
- for media_path, is_voice in non_image_media:
- try:
- ext = Path(media_path).suffix.lower()
- if should_send_media_as_audio(event.source.platform, ext, is_voice=is_voice):
- await adapter.send_voice(
- chat_id=event.source.chat_id,
- audio_path=media_path,
- metadata=_thread_meta,
- )
- elif ext in _VIDEO_EXTS:
- await adapter.send_video(
- chat_id=event.source.chat_id,
- video_path=media_path,
- metadata=_thread_meta,
- )
- else:
- await adapter.send_document(
- chat_id=event.source.chat_id,
- file_path=media_path,
- metadata=_thread_meta,
- )
- except Exception as e:
- logger.warning("[%s] Post-stream media delivery failed: %s", adapter.name, e)
- except Exception as e:
- logger.warning("Post-stream media extraction failed: %s", e)
- async def _run_background_task(
- self,
- prompt: str,
- source: "SessionSource",
- task_id: str,
- event_message_id: Optional[str] = None,
- media_urls: Optional[List[str]] = None,
- media_types: Optional[List[str]] = None,
- ) -> None:
- """Profile-scoping wrapper around the background agent task.
- When multiplexing is active, resolve the inbound source's profile and
- run the whole task inside ``_profile_runtime_scope`` so credentials
- resolve from that profile's secret scope. Mirrors the pattern in
- ``_run_agent``.
+ async def _handle_suggestions_command(self, event: MessageEvent) -> str:
+ """Handle /suggestions in the gateway.
+
+ Delegates to the shared handler so CLI and gateway never drift. The
+ origin is built from the event source so an accepted suggestion's job
+ delivers back to this chat/thread.
"""
- if not getattr(getattr(self, "config", None), "multiplex_profiles", False):
- return await self._run_background_task_inner(
- prompt, source, task_id, event_message_id, media_urls, media_types,
- )
+ args = (event.get_command_args() or "").strip()
+ source = event.source
+ origin = None
+ try:
+ platform = getattr(source.platform, "value", None) or str(getattr(source, "platform", "") or "")
+ chat_id = getattr(source, "chat_id", None)
+ if platform and chat_id:
+ origin = {
+ "platform": platform,
+ "chat_id": str(chat_id),
+ "chat_name": getattr(source, "chat_name", None),
+ "thread_id": getattr(source, "thread_id", None),
+ }
+ except Exception:
+ origin = None
+ try:
+ from hermes_cli.suggestions_cmd import handle_suggestions_command
- profile_home = self._resolve_profile_home_for_source(source)
- with _profile_runtime_scope(profile_home):
- return await self._run_background_task_inner(
- prompt, source, task_id, event_message_id, media_urls, media_types,
- )
+ return handle_suggestions_command(args, origin=origin, surface="gateway")
+ except Exception as e:
+ logger.debug("suggestions command failed: %s", e)
+ return f"Suggestions command failed: {e}"
- async def _run_background_task_inner(
- self,
- prompt: str,
- source: "SessionSource",
- task_id: str,
- event_message_id: Optional[str] = None,
- media_urls: Optional[List[str]] = None,
- media_types: Optional[List[str]] = None,
- ) -> None:
- """Execute a background agent task and deliver the result to the chat."""
- from run_agent import AIAgent
+ async def _handle_blueprint_command(self, event: MessageEvent):
+ """Handle /blueprint in the gateway.
+
+ Delegates to the shared handler so CLI, TUI, and gateway never drift.
+ Returns a BlueprintCommandResult: ``text`` is shown to the user, and if
+ ``agent_seed`` is set the dispatch site rewrites ``event.text`` to the
+ seed and falls through to the agent (the ``/steer`` pattern) so the
+ agent gathers the slot values conversationally. Origin is built from the
+ event source so a directly created blueprint job delivers back to this chat.
+ """
+ args = (event.get_command_args() or "").strip()
+ source = event.source
+ origin = None
+ try:
+ platform = getattr(source.platform, "value", None) or str(getattr(source, "platform", "") or "")
+ chat_id = getattr(source, "chat_id", None)
+ if platform and chat_id:
+ origin = {
+ "platform": platform,
+ "chat_id": str(chat_id),
+ "chat_name": getattr(source, "chat_name", None),
+ "thread_id": getattr(source, "thread_id", None),
+ }
+ except Exception:
+ origin = None
+ try:
+ from hermes_cli.blueprint_cmd import handle_blueprint_command
- media_urls = media_urls or []
- media_types = media_types or []
+ return handle_blueprint_command(args, origin=origin, surface="gateway")
+ except Exception as e:
+ logger.debug("blueprint command failed: %s", e)
+ from hermes_cli.blueprint_cmd import BlueprintCommandResult
- adapter = self._adapter_for_source(source)
- if not adapter:
- logger.warning("No adapter for platform %s in background task %s", source.platform, task_id)
- return
+ return BlueprintCommandResult(f"Cron blueprint command failed: {e}")
- _thread_metadata = self._thread_metadata_for_source(source, event_message_id)
+ # ────────────────────────────────────────────────────────────────
+ # /goal — persistent cross-turn goals (Ralph-style loop)
+ # ────────────────────────────────────────────────────────────────
+ def _goal_max_turns_from_config(self) -> int:
+ """Resolve the configured /goal turn budget for gateway sessions.
+ GatewayRunner.config is a GatewayConfig dataclass, not the full
+ user config mapping. Top-level config blocks such as ``goals`` are
+ therefore only available through hermes_cli.config.load_config().
+ """
try:
- user_config = _load_gateway_config()
- model, runtime_kwargs = self._resolve_session_agent_runtime(
- source=source,
- user_config=user_config,
+ goals_cfg = (
+ (self.config or {}).get("goals", {})
+ if isinstance(self.config, dict)
+ else getattr(self.config, "goals", {}) or {}
)
- if not runtime_kwargs.get("api_key"):
- await adapter.send(
- source.chat_id,
- f"❌ Background task {task_id} failed: no provider credentials configured.",
- metadata=_thread_metadata,
- )
- return
+ if not goals_cfg:
+ from hermes_cli.config import load_config
- platform_key = _platform_config_key(source.platform)
+ goals_cfg = (load_config() or {}).get("goals") or {}
+ return int(goals_cfg.get("max_turns", 20) or 20)
+ except Exception:
+ return 20
- from hermes_cli.tools_config import _get_platform_tools
- enabled_toolsets = sorted(_get_platform_tools(user_config, platform_key))
- agent_cfg = user_config.get("agent") or {}
- disabled_toolsets = agent_cfg.get("disabled_toolsets") or None
+ async def _get_goal_manager_for_event(self, event: "MessageEvent"):
+ """Return a GoalManager bound to the session for this gateway event.
- pr = self._provider_routing
- max_iterations = _current_max_iterations()
- reasoning_config = self._resolve_session_reasoning_config(
- source=source, model=model
- )
- self._reasoning_config = reasoning_config
- self._service_tier = self._resolve_session_service_tier(source=source)
- turn_route = self._resolve_turn_agent_config(prompt, model, runtime_kwargs)
+ Returns ``(manager, session_entry)`` or ``(None, None)`` if the
+ goals module can't be loaded.
+ """
+ try:
+ from hermes_cli.goals import GoalManager
+ except Exception as exc:
+ logger.debug("goal manager unavailable: %s", exc)
+ return None, None
+ try:
+ session_entry = await self.async_session_store.get_or_create_session(event.source)
+ except Exception as exc:
+ logger.debug("goal manager: session lookup failed: %s", exc)
+ return None, None
+ sid = getattr(session_entry, "session_id", None) or ""
+ if not sid:
+ return None, None
+ max_turns = self._goal_max_turns_from_config()
+ return GoalManager(session_id=sid, default_max_turns=max_turns), session_entry
- # Enrich the prompt with image descriptions so the background
- # agent can see user-attached images (same as the main flow).
- enriched_prompt = prompt
- if media_urls:
- image_paths = []
- for i, path in enumerate(media_urls):
- mtype = media_types[i] if i < len(media_types) else ""
- if mtype.startswith("image/"):
- image_paths.append(path)
- if image_paths:
- try:
- enriched_prompt = await self._enrich_message_with_vision(
- prompt, image_paths,
- )
- except Exception as e:
- logger.warning("Background task vision enrichment failed: %s", e)
- def run_sync():
- agent = AIAgent(
- model=turn_route["model"],
- **turn_route["runtime"],
- **_checkpoint_agent_kwargs(user_config),
- max_iterations=max_iterations,
- quiet_mode=True,
- verbose_logging=False,
- enabled_toolsets=enabled_toolsets,
- disabled_toolsets=disabled_toolsets,
- reasoning_config=reasoning_config,
- service_tier=self._service_tier,
- request_overrides=turn_route.get("request_overrides"),
- providers_allowed=pr.get("only"),
- providers_ignored=pr.get("ignore"),
- providers_order=pr.get("order"),
- provider_sort=pr.get("sort"),
- provider_require_parameters=pr.get("require_parameters", False),
- provider_data_collection=pr.get("data_collection"),
- session_id=task_id,
- platform=platform_key,
- user_id=source.user_id,
- user_id_alt=source.user_id_alt,
- user_name=source.user_name,
- chat_id=source.chat_id,
- chat_name=source.chat_name,
- chat_type=source.chat_type,
- thread_id=source.thread_id,
- session_db=getattr(self._session_db, "_db", self._session_db),
- # Reload from disk — do not reuse the startup snapshot (#60955).
- fallback_model=self._refresh_fallback_model(),
- )
- try:
- return agent.run_conversation(
- user_message=enriched_prompt,
- task_id=task_id,
- )
- finally:
- self._cleanup_agent_resources(agent)
- result = await self._run_in_executor_with_context(run_sync)
+ async def _send_goal_status_notice(self, source: Any, message: str) -> None:
+ """Send a /goal judge status line back to the originating chat/thread."""
+ adapter = self._adapter_for_source(source)
+ if not adapter:
+ logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None))
+ return
- response = result.get("final_response", "") if result else ""
- if not response and result and result.get("error"):
- response = f"Error: {result['error']}"
+ try:
+ metadata = self._thread_metadata_for_source(source)
+ except Exception:
+ metadata = None
- # Extract media files from the response
- if response:
- media_files, response = adapter.extract_media(response)
- from gateway.platforms.base import BasePlatformAdapter
- media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)
- images, text_content = adapter.extract_images(response)
+ result = await adapter.send(source.chat_id, message, metadata=metadata)
+ if result is not None and not getattr(result, "success", True):
+ logger.warning(
+ "goal continuation: status send failed: %s",
+ getattr(result, "error", "unknown error"),
+ )
- preview = prompt[:60] + ("..." if len(prompt) > 60 else "")
- header = f'✅ Background task complete\nPrompt: "{preview}"\n\n'
+ async def _defer_goal_status_notice_after_delivery(self, source: Any, message: str) -> None:
+ """Send a /goal status line after the main response is delivered.
- if text_content:
- await adapter.send(
- chat_id=source.chat_id,
- content=header + text_content,
- metadata=_thread_metadata,
- )
- elif not images and not media_files:
- await adapter.send(
- chat_id=source.chat_id,
- content=header + "(No response generated)",
- metadata=_thread_metadata,
- )
+ The gateway message handler returns the agent response to the platform
+ adapter, which sends it after this method's caller has returned. For a
+ natural Discord/Telegram reading order, goal status belongs after that
+ send. Platform adapters provide a one-shot post-delivery callback for
+ exactly this boundary; when unavailable, fall back to direct awaited
+ delivery rather than silently dropping the notice.
+ """
+ adapter = self._adapter_for_source(source)
+ if not adapter:
+ logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None))
+ return
- # Send extracted images
- for image_url, alt_text in (images or []):
- try:
- await adapter.send_image(
- chat_id=source.chat_id,
- image_url=image_url,
- caption=alt_text,
- metadata=_thread_metadata,
- )
- except Exception:
- pass
+ async def _deliver() -> None:
+ try:
+ await self._send_goal_status_notice(source, message)
+ except Exception as exc:
+ logger.warning("goal continuation: status send failed: %s", exc, exc_info=True)
- # Send media files, routing each by type so a TTS clip
- # arrives as a voice bubble / a clip as a video rather than
- # a generic document. Mirrors the streaming + kanban paths.
- from gateway.platforms.base import (
- should_send_media_as_audio as _should_send_media_as_audio,
- )
- _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp"}
- _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
- for media_path, _is_voice in (media_files or []):
- _ext = os.path.splitext(media_path)[1].lower()
- try:
- if _should_send_media_as_audio(source.platform, _ext, _is_voice):
- await adapter.send_voice(
- chat_id=source.chat_id,
- audio_path=media_path,
- metadata=_thread_metadata,
- )
- elif _ext in _VIDEO_EXTS:
- await adapter.send_video(
- chat_id=source.chat_id,
- video_path=media_path,
- metadata=_thread_metadata,
- )
- elif _ext in _IMAGE_EXTS:
- await adapter.send_image_file(
- chat_id=source.chat_id,
- image_path=media_path,
- metadata=_thread_metadata,
- )
- else:
- await adapter.send_document(
- chat_id=source.chat_id,
- file_path=media_path,
- metadata=_thread_metadata,
- )
- except Exception:
- pass
- else:
- preview = prompt[:60] + ("..." if len(prompt) > 60 else "")
- await adapter.send(
- chat_id=source.chat_id,
- content=f'✅ Background task complete\nPrompt: "{preview}"\n\n(No response generated)',
- metadata=_thread_metadata,
+ try:
+ session_key = self._session_key_for_source(source)
+ except Exception:
+ session_key = None
+
+ if session_key and hasattr(adapter, "register_post_delivery_callback"):
+ try:
+ generation = None
+ active = getattr(adapter, "_active_sessions", {}).get(session_key)
+ if active is not None:
+ generation = getattr(active, "_hermes_run_generation", None)
+ adapter.register_post_delivery_callback(
+ session_key,
+ _deliver,
+ generation=generation,
)
+ return
+ except Exception as exc:
+ logger.debug("goal continuation: post-delivery callback registration failed: %s", exc)
- except Exception as e:
- logger.exception("Background task %s failed", task_id)
- try:
- await adapter.send(
- chat_id=source.chat_id,
- content=f"❌ Background task {task_id} failed: {e}",
- metadata=_thread_metadata,
- )
- except Exception:
- pass
+ await _deliver()
+ async def _post_turn_goal_continuation(
+ self,
+ *,
+ session_entry: Any,
+ source: Any,
+ final_response: str,
+ ) -> None:
+ """Run the goal judge after a gateway turn and, if still active,
+ enqueue a continuation prompt for the same session.
+ Called from ``_handle_message_with_agent`` at turn boundary, AFTER
+ the response has been delivered. Safe when no goal is set.
+ We use the adapter's pending-message / FIFO machinery so any real
+ user message that arrives simultaneously is handled by the same
+ queue and takes priority naturally.
+ """
+ try:
+ from hermes_cli.goals import GoalManager
+ except Exception as exc:
+ logger.debug("goal continuation: goals module unavailable: %s", exc)
+ return
+ sid = getattr(session_entry, "session_id", None) or ""
+ if not sid:
+ return
+ max_turns = self._goal_max_turns_from_config()
+ mgr = GoalManager(session_id=sid, default_max_turns=max_turns)
+ if not mgr.is_active():
+ return
- async def _get_telegram_topic_capabilities(self, source: SessionSource) -> dict:
- """Read Telegram private-topic capability flags via Bot API getMe."""
- adapter = self._adapter_for_source(source)
- bot = getattr(adapter, "_bot", None)
- if bot is None or not hasattr(bot, "get_me"):
- return {"checked": False}
try:
- me = await bot.get_me()
+ from hermes_cli.goals import gather_background_processes as _gather_bg
+ _bg_procs = _gather_bg()
except Exception:
- logger.debug("Failed to fetch Telegram getMe topic capabilities", exc_info=True)
- return {"checked": False}
-
- def _field(name: str):
- if hasattr(me, name):
- return getattr(me, name)
- api_kwargs = getattr(me, "api_kwargs", None)
- if isinstance(api_kwargs, dict) and name in api_kwargs:
- return api_kwargs.get(name)
- if isinstance(me, dict):
- return me.get(name)
- return None
+ _bg_procs = None
- return {
- "checked": True,
- "has_topics_enabled": _field("has_topics_enabled"),
- "allows_users_to_create_topics": _field("allows_users_to_create_topics"),
- }
+ decision = mgr.evaluate_after_turn(
+ final_response or "",
+ user_initiated=True,
+ background_processes=_bg_procs,
+ )
+ msg = decision.get("message") or ""
- async def _ensure_telegram_system_topic(self, source: SessionSource) -> None:
- """Create/pin the managed System topic after /topic activation when possible."""
- adapter = self._adapter_for_source(source)
- if adapter is None or not source.chat_id:
- return
+ # Defer the status line until after the adapter has delivered the
+ # agent's visible final response. The judge runs after the response is
+ # produced but before BasePlatformAdapter sends it, so sending here
+ # would show "✓ Goal achieved" before the answer itself. Registering
+ # an awaited post-delivery callback preserves delivery reliability
+ # without reversing the user-visible ordering.
+ if msg and source is not None:
+ await self._defer_goal_status_notice_after_delivery(source, msg)
- thread_id = None
- create_topic = getattr(adapter, "_create_dm_topic", None)
- if callable(create_topic):
- try:
- thread_id = await create_topic(int(source.chat_id), "System")
- except Exception:
- logger.debug("Failed to create Telegram System topic", exc_info=True)
- if not thread_id:
+ if not decision.get("should_continue"):
return
- message_id = None
- try:
- send_result = await adapter.send(
- source.chat_id,
- "System topic for Hermes commands and status.",
- metadata={"thread_id": str(thread_id)},
- )
- message_id = getattr(send_result, "message_id", None)
- except Exception:
- logger.debug("Failed to send Telegram System topic intro", exc_info=True)
- if not message_id:
+ prompt = decision.get("continuation_prompt") or ""
+ if not prompt or source is None:
return
- bot = getattr(adapter, "_bot", None)
- if bot is None or not hasattr(bot, "pin_chat_message"):
- return
+ # Enqueue via the adapter's FIFO so a user message already in
+ # flight preempts the continuation naturally.
try:
- await bot.pin_chat_message(
- chat_id=int(source.chat_id),
- message_id=int(message_id),
- disable_notification=True,
- )
- except Exception:
- logger.debug("Failed to pin Telegram System topic intro", exc_info=True)
+ adapter = self._adapter_for_source(source)
+ _quick_key = self._session_key_for_source(source)
+ if adapter and _quick_key:
+ cont_event = MessageEvent(
+ text=prompt,
+ message_type=MessageType.TEXT,
+ source=source,
+ message_id=None,
+ channel_prompt=None,
+ )
+ self._enqueue_fifo(_quick_key, cont_event, adapter)
+ except Exception as exc:
+ logger.debug("goal continuation: enqueue failed: %s", exc)
- async def _send_telegram_topic_setup_image(self, source: SessionSource) -> None:
- """Send the bundled BotFather Threads Settings screenshot when available."""
- adapter = self._adapter_for_source(source)
- if adapter is None or not source.chat_id or not hasattr(adapter, "send_image_file"):
- return
- image_path = Path(__file__).resolve().parent / "assets" / "telegram-botfather-threads-settings.jpg"
- if not image_path.exists():
- return
- try:
- await adapter.send_image_file(
- chat_id=source.chat_id,
- image_path=str(image_path),
- caption="BotFather → Bot Settings → Threads Settings",
- metadata={"thread_id": str(source.thread_id)} if source.thread_id else None,
- )
- except Exception:
- logger.debug("Failed to send Telegram topic setup image", exc_info=True)
- def _sanitize_telegram_topic_title(self, title: str) -> str:
- """Return a Bot API-safe forum topic name from a generated session title."""
- cleaned = re.sub(r"\s+", " ", str(title or "")).strip()
- if not cleaned:
- return "Hermes Chat"
- # Telegram forum topic names are short (currently 1-128 chars). Keep
- # extra room for multi-byte titles and avoid trailing ellipsis churn.
- if len(cleaned) > 120:
- cleaned = cleaned[:117].rstrip() + "..."
- return cleaned
- def _is_discord_auto_thread_lane(self, source: SessionSource) -> bool:
- """Return True only for Discord threads Hermes just auto-created."""
- return (
- source.platform == Platform.DISCORD
- and source.chat_type == "thread"
- and bool(getattr(source, "auto_thread_created", False))
- and bool(source.thread_id)
- and bool(getattr(source, "auto_thread_initial_name", None))
- )
+ @staticmethod
+ def _get_guild_id(event: MessageEvent) -> Optional[int]:
+ """Extract Discord guild_id from the raw message object."""
+ raw = getattr(event, "raw_message", None)
+ if raw is None:
+ return None
+ # Slash command interaction
+ if hasattr(raw, "guild_id") and raw.guild_id:
+ return int(raw.guild_id)
+ # Regular message
+ if hasattr(raw, "guild") and raw.guild:
+ return raw.guild.id
+ return None
- def _sanitize_discord_thread_title(self, title: str) -> str:
- """Return a Discord-safe semantic thread title from a session title.
- Discord thread names are capped at 100 characters measured in UTF-16
- code units (emoji count double), so truncate with the UTF-16 helpers
- rather than Python code-point slices.
- """
- cleaned = re.sub(r"\s+", " ", str(title or "")).strip()
- if not cleaned:
- return "Hermes Chat"
- if utf16_len(cleaned) > 80:
- cleaned = _prefix_within_utf16_limit(cleaned, 77).rstrip() + "..."
- return cleaned
+ async def _handle_voice_channel_join(self, event: MessageEvent) -> str:
+ """Join the user's current Discord voice channel."""
+ adapter = self._adapter_for_source(event.source)
+ if not hasattr(adapter, "join_voice_channel"):
+ return "Voice channels are not supported on this platform."
- async def _rename_discord_auto_thread_for_session_title(
- self,
- source: SessionSource,
- session_id: str,
- title: str,
- ) -> None:
- """Best-effort semantic rename of a newly auto-created Discord thread."""
- if not await asyncio.to_thread(self._is_discord_auto_thread_lane, source):
- return
- adapter = self._adapter_for_source(source) if getattr(self, "adapters", None) else None
- if adapter is None:
- return
- rename_thread = getattr(adapter, "rename_thread", None)
- if rename_thread is None:
- return
- thread_name = self._sanitize_discord_thread_title(title)
- try:
- await rename_thread(
- str(source.thread_id),
- thread_name,
- only_if_current_name=getattr(source, "auto_thread_initial_name", None),
- )
- except Exception:
- logger.debug("Failed to rename Discord auto-thread for generated session title", exc_info=True)
+ guild_id = self._get_guild_id(event)
+ if not guild_id:
+ return "This command only works in a Discord server."
- def _schedule_discord_semantic_thread_rename(
- self,
- source: SessionSource,
- session_id: str,
- title: str,
- ) -> None:
- """Schedule Discord auto-thread rename from the auto-title background thread."""
- if not title or not self._is_discord_auto_thread_lane(source):
- return
- try:
- loop = asyncio.get_running_loop()
- except RuntimeError:
- loop = getattr(self, "_gateway_loop", None)
- if loop is None or loop.is_closed():
- return
- try:
- copied_source = dataclasses.replace(source)
- except Exception:
- copied_source = source
- future = safe_schedule_threadsafe(
- self._rename_discord_auto_thread_for_session_title(copied_source, session_id, title),
- loop,
- logger=logger,
- log_message="Discord semantic thread rename failed to schedule",
+ voice_channel = await adapter.get_user_voice_channel(
+ guild_id, event.source.user_id
)
- if future is None:
- return
+ if not voice_channel:
+ return "You need to be in a voice channel first."
- def _log_rename_failure(fut) -> None:
- try:
- fut.result()
- except Exception:
- logger.debug("Discord semantic thread rename failed", exc_info=True)
+ # Wire callbacks BEFORE join so voice input arriving immediately
+ # after connection is not lost.
+ if hasattr(adapter, "_voice_input_callback"):
+ adapter._voice_input_callback = self._handle_voice_channel_input
+ if hasattr(adapter, "_on_voice_disconnect"):
+ adapter._on_voice_disconnect = self._handle_voice_timeout_cleanup
+ # Let the adapter's inactivity timer see the live voice-reply mode so it
+ # doesn't disconnect a deliberately text-only (/voice off) session.
+ if hasattr(adapter, "_voice_mode_getter"):
+ adapter._voice_mode_getter = lambda chat_id: self._voice_mode.get(
+ self._voice_key(Platform.DISCORD, str(chat_id)), "off"
+ )
- future.add_done_callback(_log_rename_failure)
+ try:
+ success = await adapter.join_voice_channel(voice_channel)
+ except Exception as e:
+ logger.warning("Failed to join voice channel: %s", e)
+ adapter._voice_input_callback = None
+ err_lower = str(e).lower()
+ if "pynacl" in err_lower or "nacl" in err_lower or "davey" in err_lower:
+ return (
+ "Voice dependencies are missing (PyNaCl / davey). "
+ f"Install with: `{sys.executable} -m pip install PyNaCl`"
+ )
+ return f"Failed to join voice channel: {e}"
- async def _rename_telegram_topic_for_session_title(
- self,
- source: SessionSource,
- session_id: str,
- title: str,
- ) -> None:
- """Best-effort rename of a Telegram DM topic when Hermes auto-titles a session."""
- if not await asyncio.to_thread(self._is_telegram_topic_lane, source) or not source.chat_id or not source.thread_id:
- return
+ if success:
+ adapter._voice_text_channels[guild_id] = int(event.source.chat_id)
+ if hasattr(adapter, "_voice_sources"):
+ adapter._voice_sources[guild_id] = event.source.to_dict()
+ self._voice_mode[self._voice_key(event.source.platform, event.source.chat_id)] = "all"
+ self._save_voice_modes()
+ self._set_adapter_auto_tts_enabled(adapter, event.source.chat_id, enabled=True)
+ return (
+ f"Joined voice channel **{voice_channel.name}**.\n"
+ f"I'll speak my replies and listen to you. Use /voice leave to disconnect."
+ )
+ # Join failed — clear callback
+ adapter._voice_input_callback = None
+ return "Failed to join voice channel. Check bot permissions (Connect + Speak)."
- # Operator can fully disable per-topic auto-rename via
- # extra.disable_topic_auto_rename. Useful when topics are managed
- # by the user (ad-hoc Threaded Mode) and auto-rename would
- # overwrite their chosen names every time the auto-title fires.
- if self._telegram_topic_auto_rename_disabled(source):
- return
+ async def _handle_voice_channel_leave(self, event: MessageEvent) -> str:
+ """Leave the Discord voice channel."""
+ adapter = self._adapter_for_source(event.source)
+ guild_id = self._get_guild_id(event)
- # Skip rename when the topic is operator-declared via
- # extra.dm_topics. Those topics have fixed names chosen by the
- # operator (plus optional skill binding); auto-renaming would
- # silently mutate operator config.
- #
- # Check the class, not the instance — getattr() on MagicMock
- # auto-creates attributes, so `hasattr(adapter, "_get_dm_topic_info")`
- # would return True for every test double.
- adapter = self._adapter_for_source(source)
- if adapter is not None:
- get_info = getattr(type(adapter), "_get_dm_topic_info", None)
- if callable(get_info):
- try:
- operator_topic = get_info(adapter, str(source.chat_id), str(source.thread_id))
- except Exception:
- operator_topic = None
- # Only treat dict-shaped returns as operator-declared; a
- # bare MagicMock or other sentinel shouldn't count.
- if isinstance(operator_topic, dict):
- return
+ if not guild_id or not hasattr(adapter, "leave_voice_channel"):
+ return "Not in a voice channel."
- session_db = getattr(self, "_session_db", None)
- if session_db is not None:
- try:
- binding = await session_db.get_telegram_topic_binding(
- chat_id=str(source.chat_id),
- thread_id=str(source.thread_id),
- )
- if binding and str(binding.get("session_id") or "") != str(session_id):
- return
- except Exception:
- logger.debug("Failed to verify Telegram topic binding before rename", exc_info=True)
- return
+ if not hasattr(adapter, "is_in_voice_channel") or not adapter.is_in_voice_channel(guild_id):
+ return "Not in a voice channel."
- if adapter is None:
- return
- topic_name = self._sanitize_telegram_topic_title(title)
try:
- rename_topic = getattr(adapter, "rename_dm_topic", None)
- if rename_topic is not None:
- await rename_topic(
- chat_id=str(source.chat_id),
- thread_id=str(source.thread_id),
- name=topic_name,
- )
- return
+ await adapter.leave_voice_channel(guild_id)
+ except Exception as e:
+ logger.warning("Error leaving voice channel: %s", e)
+ # Always clean up state even if leave raised an exception
+ self._voice_mode[self._voice_key(event.source.platform, event.source.chat_id)] = "off"
+ self._save_voice_modes()
+ self._set_adapter_auto_tts_disabled(adapter, event.source.chat_id, disabled=True)
+ if hasattr(adapter, "_voice_input_callback"):
+ adapter._voice_input_callback = None
+ return "Left voice channel."
- bot = getattr(adapter, "_bot", None)
- edit_forum_topic = getattr(bot, "edit_forum_topic", None) if bot is not None else None
- if edit_forum_topic is None:
- edit_forum_topic = getattr(bot, "editForumTopic", None) if bot is not None else None
- if edit_forum_topic is None:
- return
- try:
- await edit_forum_topic(
- chat_id=int(source.chat_id),
- message_thread_id=int(source.thread_id),
- name=topic_name,
- )
- except (TypeError, ValueError):
- await edit_forum_topic(
- chat_id=source.chat_id,
- message_thread_id=source.thread_id,
- name=topic_name,
- )
- except Exception:
- logger.debug("Failed to rename Telegram topic for auto-generated title", exc_info=True)
+ def _handle_voice_timeout_cleanup(self, chat_id: str) -> None:
+ """Called by the adapter when a voice channel times out.
- def _telegram_topic_auto_rename_disabled(self, source: SessionSource) -> bool:
- """Return True when operator disabled per-topic auto-rename for this Telegram chat.
+ Cleans up runner-side voice_mode state that the adapter cannot reach.
+ """
+ self._voice_mode[self._voice_key(Platform.DISCORD, chat_id)] = "off"
+ self._save_voice_modes()
+ adapter = self.adapters.get(Platform.DISCORD)
+ self._set_adapter_auto_tts_disabled(adapter, chat_id, disabled=True)
- Controlled via ``gateway.platforms.telegram.extra.disable_topic_auto_rename``.
- Default is False (auto-rename enabled, preserves prior behaviour).
+ def _is_duplicate_voice_transcript(self, guild_id: int, user_id: int, transcript: str) -> bool:
+ """Suppress repeated STT outputs for the same recent utterance.
+
+ Voice capture can occasionally emit the same utterance twice a few
+ seconds apart, which creates a second queued agent run and overlapping
+ spoken replies. Dedup exact and near-exact repeats per guild/user over a
+ short window while allowing genuinely new turns through.
"""
- platform_cfg = (
- self.config.platforms.get(source.platform)
- if getattr(self, "config", None) and getattr(self.config, "platforms", None)
- else None
- )
- if platform_cfg is None:
- return False
- extra = getattr(platform_cfg, "extra", None) or {}
- value = extra.get("disable_topic_auto_rename")
- if value is None:
+ from difflib import SequenceMatcher
+
+ normalized = re.sub(r"\s+", " ", transcript).strip().lower()
+ normalized = re.sub(r"[^\w\s]", "", normalized)
+ if not normalized:
return False
- if isinstance(value, bool):
- return value
- if isinstance(value, str):
- return value.strip().lower() in {"1", "true", "yes", "on"}
- return bool(value)
- def _schedule_telegram_topic_title_rename(
- self,
- source: SessionSource,
- session_id: str,
- title: str,
- ) -> None:
- """Schedule a topic rename from the auto-title background thread."""
- if not title or not self._is_telegram_topic_lane(source):
+ now = time.monotonic()
+ window_seconds = 12.0
+ key = (guild_id, user_id)
+ recent_store = getattr(self, "_recent_voice_transcripts", None)
+ if not isinstance(recent_store, dict):
+ recent_store = {}
+ self._recent_voice_transcripts = recent_store
+ recent = [
+ (ts, txt)
+ for ts, txt in recent_store.get(key, [])
+ if now - ts <= window_seconds
+ ]
+
+ for _, prior in recent:
+ if prior == normalized:
+ recent_store[key] = recent
+ return True
+ if len(prior) >= 16 and len(normalized) >= 16:
+ if SequenceMatcher(None, prior, normalized).ratio() >= 0.95:
+ recent_store[key] = recent
+ return True
+
+ recent.append((now, normalized))
+ recent_store[key] = recent[-5:]
+ return False
+
+ async def _handle_voice_channel_input(
+ self, guild_id: int, user_id: int, transcript: str
+ ):
+ """Handle transcribed voice from a user in a voice channel.
+
+ Creates a synthetic MessageEvent and processes it through the
+ adapter's full message pipeline (session, typing, agent, TTS reply).
+ """
+ adapter = self.adapters.get(Platform.DISCORD)
+ if not adapter:
return
- if self._telegram_topic_auto_rename_disabled(source):
+
+ text_ch_id = adapter._voice_text_channels.get(guild_id)
+ if not text_ch_id:
return
- try:
- loop = asyncio.get_running_loop()
- except RuntimeError:
- loop = getattr(self, "_gateway_loop", None)
- if loop is None or loop.is_closed():
+
+ # Build source — reuse the linked text channel's metadata when available
+ # so voice input shares the same session as the bound text conversation.
+ source_data = getattr(adapter, "_voice_sources", {}).get(guild_id)
+ if source_data:
+ source = SessionSource.from_dict(source_data)
+ source.user_id = str(user_id)
+ source.user_name = str(user_id)
+ else:
+ source = SessionSource(
+ platform=Platform.DISCORD,
+ chat_id=str(text_ch_id),
+ user_id=str(user_id),
+ user_name=str(user_id),
+ chat_type="channel",
+ )
+
+ # Check authorization before processing voice input
+ if not self._is_user_authorized(source):
+ logger.debug("Unauthorized voice input from user %d, ignoring", user_id)
return
+
+ if self._is_duplicate_voice_transcript(guild_id, user_id, transcript):
+ logger.info(
+ "Suppressing duplicate voice transcript for guild=%s user=%s: %s",
+ guild_id,
+ user_id,
+ transcript[:100],
+ )
+ return
+
+ # Show transcript in text channel (after auth, with mention sanitization)
try:
- copied_source = dataclasses.replace(source)
+ channel = adapter._client.get_channel(text_ch_id)
+ if channel:
+ safe_text = transcript[:2000].replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere")
+ await channel.send(f"**[Voice]** <@{user_id}>: {safe_text}")
except Exception:
- copied_source = source
- future = safe_schedule_threadsafe(
- self._rename_telegram_topic_for_session_title(copied_source, session_id, title),
- loop,
- logger=logger,
- log_message="Telegram topic title rename failed to schedule",
- )
- if future is None:
- return
- def _log_rename_failure(fut) -> None:
+ pass
+
+ # Build a synthetic MessageEvent and feed through the normal pipeline
+ # Use SimpleNamespace as raw_message so _get_guild_id() can extract
+ # guild_id and _send_voice_reply() plays audio in the voice channel.
+ from types import SimpleNamespace
+ # Resolve the bound text channel's channel_prompt so voice input gets
+ # the same per-channel context as typed messages (#50149).
+ channel_prompt: Optional[str] = None
+ resolver = getattr(adapter, "_resolve_channel_prompt", None)
+ if callable(resolver):
try:
- fut.result()
+ resolved = resolver(str(text_ch_id))
+ channel_prompt = resolved if isinstance(resolved, str) else None
except Exception:
- logger.debug("Telegram topic title rename failed", exc_info=True)
-
- future.add_done_callback(_log_rename_failure)
+ channel_prompt = None
+ event = MessageEvent(
+ source=source,
+ text=transcript,
+ message_type=MessageType.VOICE,
+ raw_message=SimpleNamespace(guild_id=guild_id, guild=None),
+ channel_prompt=channel_prompt,
+ )
- _TELEGRAM_CAPABILITY_HINT_COOLDOWN_S = 300.0
+ await adapter.handle_message(event)
- def _should_send_telegram_capability_hint(self, source: SessionSource) -> bool:
- """Rate-limit the BotFather Threads Settings screenshot.
+ def _should_send_voice_reply(
+ self,
+ event: MessageEvent,
+ response: str,
+ agent_messages: list,
+ already_sent: bool = False,
+ ) -> bool:
+ """Decide whether the runner should send a TTS voice reply.
- If a user sends /topic repeatedly while Threads Settings are still
- off, we shouldn't keep re-uploading the screenshot every time.
+ Returns False when:
+ - voice_mode is off for this chat
+ - response is empty or an error
+ - agent already called text_to_speech tool (dedup)
+ - voice input and base adapter auto-TTS already handled it (skip_double)
+ UNLESS streaming already consumed the response (already_sent=True),
+ in which case the base adapter won't have text for auto-TTS so the
+ runner must handle it.
"""
- if not hasattr(self, "_telegram_capability_hint_ts"):
- self._telegram_capability_hint_ts = {}
- chat_id = str(source.chat_id or "")
- if not chat_id:
- return True
- import time as _time
- now = _time.monotonic()
- last = self._telegram_capability_hint_ts.get(chat_id, 0.0)
- if now - last < self._TELEGRAM_CAPABILITY_HINT_COOLDOWN_S:
+ if not response or response.startswith("Error:"):
return False
- self._telegram_capability_hint_ts[chat_id] = now
- return True
-
- def _telegram_topic_help_text(self) -> str:
- return (
- "/topic — enable multi-session DM mode (one bot, many parallel chats)\n"
- "\n"
- "Usage:\n"
- " /topic Enable topic mode, or show status if already on\n"
- " /topic help Show this message\n"
- " /topic off Disable topic mode and clear topic bindings\n"
- " /topic <id> Inside a topic: restore a previous session by ID\n"
- "\n"
- "How it works:\n"
- "1. Run /topic once in this DM — Hermes checks BotFather Threads\n"
- " Settings are enabled and flips on multi-session mode.\n"
- "2. Tap All Messages at the top of the bot and send any message.\n"
- " Telegram creates a new topic for that message; each topic is\n"
- " an independent Hermes session (fresh history, fresh context).\n"
- "3. The root DM becomes a system lobby — send /topic, /status,\n"
- " /help, /usage there. Normal prompts go in a topic.\n"
- "4. /new inside a topic resets just that topic's session.\n"
- "5. /topic <id> inside a topic restores an old session into it."
- )
- async def _disable_telegram_topic_mode_for_chat(self, source: SessionSource) -> str:
- """Cleanly disable topic mode for a chat via /topic off."""
- if not self._session_db:
- from hermes_state import format_session_db_unavailable
- return format_session_db_unavailable(prefix=t("gateway.shared.session_db_unavailable_prefix"))
- chat_id = str(source.chat_id or "")
- if not chat_id:
- return "Could not determine chat ID."
- # No-op if never enabled.
- try:
- currently_enabled = await self._session_db.is_telegram_topic_mode_enabled(
- chat_id=chat_id,
- user_id=str(source.user_id or ""),
- )
- except Exception:
- currently_enabled = False
- if not currently_enabled:
- return "Multi-session topic mode is not currently enabled for this chat."
- try:
- await self._session_db.disable_telegram_topic_mode(chat_id=chat_id)
- except Exception as exc:
- logger.exception("Failed to disable Telegram topic mode")
- return f"Failed to disable topic mode: {exc}"
- # Reset per-chat debounce state so the user doesn't see a stale
- # cooldown on the next activation.
- for attr in ("_telegram_lobby_reminder_ts", "_telegram_capability_hint_ts"):
- store = getattr(self, attr, None)
- if isinstance(store, dict):
- store.pop(chat_id, None)
- return (
- "Multi-session topic mode is now OFF for this chat.\n\n"
- "Existing topics in Telegram aren't removed — they'll just stop "
- "being gated as independent sessions. The root DM works as a "
- "normal Hermes chat again. Run /topic to re-enable later."
- )
+ chat_id = event.source.chat_id
+ voice_key = self._voice_key(event.source.platform, chat_id)
+ voice_mode = self._voice_mode.get(voice_key)
+ is_voice_input = (event.message_type == MessageType.VOICE)
+ adapter = self.adapters.get(event.source.platform)
+ adapter_auto_tts = False
+ if adapter and hasattr(adapter, "_should_auto_tts_for_chat"):
+ try:
+ adapter_auto_tts = bool(adapter._should_auto_tts_for_chat(chat_id))
+ except Exception:
+ adapter_auto_tts = False
- async def _telegram_topic_root_status_message(self, source: SessionSource) -> str:
- lines = [
- "Telegram multi-session topics are enabled.",
- "",
- "To create a new Hermes chat, open All Messages at the top of this "
- "bot interface and send any message there. Telegram will create a "
- "new topic for it.",
- "",
- ]
- try:
- sessions = await self._session_db.list_unlinked_telegram_sessions_for_user(
- chat_id=str(source.chat_id),
- user_id=str(source.user_id),
- limit=10,
+ should = (
+ (voice_mode == "all")
+ or (voice_mode == "voice_only" and is_voice_input)
+ # ``voice.auto_tts`` is synced into the adapter on gateway startup.
+ # Treat it as "voice accompanies text replies" unless a chat was
+ # explicitly turned off. The base adapter's own auto-TTS path only
+ # covers voice-input replies, so final text replies need the runner
+ # path here.
+ or (voice_mode != "off" and adapter_auto_tts)
+ )
+ if not should:
+ logger.debug(
+ "Auto voice reply skipped: mode=%s adapter_auto_tts=%s chat=%s platform=%s",
+ voice_mode, adapter_auto_tts, chat_id, event.source.platform.value,
)
- except Exception:
- logger.debug("Failed to list unlinked Telegram sessions", exc_info=True)
- sessions = []
-
- if sessions:
- lines.append("Previous unlinked sessions:")
- for session in sessions:
- session_id = str(session.get("id") or "")
- title = str(session.get("title") or "Untitled session")
- preview = str(session.get("preview") or "").strip()
- line = f"- {title} — `{session_id}`"
- if preview:
- line += f" — {preview}"
- lines.append(line)
- lines.extend([
- "",
- "To restore one:",
- "1. Create or open a topic. To create a new one, open All Messages and send any message there.",
- "2. Send /topic <session-id> inside that topic.",
- f"Example: Send /topic {sessions[0].get('id')} inside a topic.",
- ])
- else:
- lines.extend([
- "No previous unlinked Telegram sessions found.",
- "",
- "To restore a previous session later:",
- "1. Create or open a topic. To create a new one, open All Messages and send any message there.",
- "2. Send /topic <session-id> inside that topic.",
- ])
- return "\n".join(lines)
-
- async def _restore_telegram_topic_session(self, event: MessageEvent, raw_session_id: str) -> str:
- """Restore an existing Telegram-owned Hermes session into this topic."""
- source = event.source
- session_id = await self._session_db.resolve_session_id(raw_session_id.strip())
- if not session_id:
- return f"Session not found: {raw_session_id.strip()}"
-
- session = await self._session_db.get_session(session_id)
- if not session:
- return f"Session not found: {raw_session_id.strip()}"
- if str(session.get("source") or "") != "telegram":
- return "That session is not a Telegram session and cannot be restored into this topic."
- if str(session.get("user_id") or "") != str(source.user_id):
- return "That session does not belong to this Telegram user."
+ return False
- linked = await self._session_db.is_telegram_session_linked_to_topic(session_id=session_id)
- current_binding = await self._session_db.get_telegram_topic_binding(
- chat_id=str(source.chat_id),
- thread_id=str(source.thread_id),
+ # Dedup: agent already called TTS tool in THIS turn only
+ last_user_idx = None
+ for i, msg in enumerate(reversed(agent_messages)):
+ if msg.get("role") == "user":
+ last_user_idx = len(agent_messages) - 1 - i; break
+ turn_messages = agent_messages[last_user_idx:] if last_user_idx is not None else agent_messages
+ has_agent_tts = any(
+ msg.get("role") == "assistant"
+ and any(
+ (tc.get("function") or {}).get("name") == "text_to_speech"
+ for tc in (msg.get("tool_calls") or [])
+ )
+ for msg in turn_messages
)
- if linked:
- if not current_binding or current_binding.get("session_id") != session_id:
- return "That session is already linked to another Telegram topic."
+ if has_agent_tts:
+ return False
+
+ # Dedup: base adapter auto-TTS already handles voice input
+ # (play_tts plays in VC when connected, so runner can skip).
+ # When streaming already delivered the text (already_sent=True),
+ # the base adapter will receive None and can't run auto-TTS,
+ # so the runner must take over.
+ if is_voice_input and not already_sent:
+ return False
- session_key = self._session_key_for_source(source)
- try:
- await self._session_db.bind_telegram_topic(
- chat_id=str(source.chat_id),
- thread_id=str(source.thread_id),
- user_id=str(source.user_id),
- session_key=session_key,
- session_id=session_id,
- managed_mode="restored",
- )
- except ValueError as exc:
- if "already linked" in str(exc):
- return "That session is already linked to another Telegram topic."
- raise
+ return True
- title = await self._session_db.get_session_title(session_id) or session_id
- last_assistant = None
+ def _should_echo_stt_transcripts(self) -> bool:
+ """Return whether inbound voice/STT transcripts should be echoed to chat."""
+ return bool(getattr(self.config, "stt_echo_transcripts", True))
+
+ async def _send_voice_reply(self, event: MessageEvent, text: str) -> None:
+ """Generate TTS audio and send as a voice message before the text reply."""
+ audio_path = None
+ actual_path = None
try:
- for message in reversed(await self._session_db.get_messages(session_id)):
- if message.get("role") == "assistant" and message.get("content"):
- last_assistant = str(message.get("content"))
- break
- except Exception:
- last_assistant = None
+ from tools.tts_tool import text_to_speech_tool, _strip_markdown_for_tts
- response = f"Session restored: {title}"
- if last_assistant:
- response += f"\n\nLast Hermes message:\n{last_assistant}"
- return response
+ tts_text = _strip_markdown_for_tts(text[:4000])
+ if not tts_text:
+ return
+ # Platform-aware output path: platforms whose native voice
+ # bubbles require Ogg/Opus (OPUS_VOICE_PLATFORMS — Telegram,
+ # Matrix, Feishu, WhatsApp, Signal) get an explicit .ogg path;
+ # the TTS tool's central container repair guarantees real
+ # Ogg/Opus bytes for every provider. Others keep MP3.
+ audio_path = build_auto_tts_output_path(event.source.platform)
+ result_json = await asyncio.to_thread(
+ text_to_speech_tool, text=tts_text, output_path=audio_path
+ )
+ try:
+ result = json.loads(result_json)
+ except (json.JSONDecodeError, TypeError):
+ logger.warning("Auto voice reply TTS returned invalid JSON: %s", result_json[:200] if result_json else result_json)
+ return
+ # Use the actual file path from result (may differ after opus conversion)
+ actual_path = result.get("file_path", audio_path)
+ if not result.get("success") or not os.path.isfile(actual_path):
+ logger.warning("Auto voice reply TTS failed: %s", result.get("error"))
+ return
+ adapter = self._adapter_for_source(event.source)
+ # If connected to a voice channel, play there instead of sending a file
+ guild_id = self._get_guild_id(event)
+ if (guild_id
+ and hasattr(adapter, "play_in_voice_channel")
+ and hasattr(adapter, "is_in_voice_channel")
+ and adapter.is_in_voice_channel(guild_id)):
+ await adapter.play_in_voice_channel(guild_id, actual_path)
+ elif adapter and hasattr(adapter, "send_voice"):
+ reply_anchor = self._reply_anchor_for_event(event)
+ thread_meta = self._thread_metadata_for_source(event.source, reply_anchor)
+ # Mark the auto voice reply as notify-worthy. Mirrors the
+ # final-text path in gateway/platforms/base.py which sets
+ # ``notify=True`` so platform adapters that gate push
+ # notifications (Telegram "important" mode) deliver the
+ # final voice reply as a normal notification instead of a
+ # silent message. Clone first so we don't mutate metadata
+ # shared with concurrent typing-indicator state.
+ if thread_meta is not None:
+ thread_meta = dict(thread_meta)
+ thread_meta["notify"] = True
+ else:
+ thread_meta = {"notify": True}
+ send_kwargs: Dict[str, Any] = {
+ "chat_id": event.source.chat_id,
+ "audio_path": actual_path,
+ "reply_to": reply_anchor,
+ "metadata": thread_meta,
+ }
+ await adapter.send_voice(**send_kwargs)
+ except Exception as e:
+ logger.warning("Auto voice reply failed: %s", e, exc_info=True)
+ finally:
+ for p in {audio_path, actual_path} - {None}:
+ try:
+ os.unlink(p)
+ except OSError:
+ pass
+ async def _deliver_media_from_response(
+ self,
+ response: str,
+ event: MessageEvent,
+ adapter,
+ history_media_paths: Optional[set] = None,
+ ) -> None:
+ """Extract explicit MEDIA: tags from a response and deliver them.
- async def _execute_mcp_reload(self, event: MessageEvent) -> str:
- """Actually disconnect, reconnect, and notify MCP tool changes.
+ Called after streaming has already sent the text to the user, so the
+ text itself is already delivered — this only handles file attachments
+ that the normal _process_message_background path would have caught.
- Split out from ``_handle_reload_mcp_command`` so the confirmation
- wrapper can invoke the same path whether the user confirmed via
- button, text reply, or has the confirm gate disabled.
+ Unlike the non-streaming path in ``gateway/platforms/base.py`` (which
+ also auto-detects bare local paths via ``extract_local_files``), this
+ post-stream rescan is EXPLICIT-ONLY. The visible reply has already
+ been streamed verbatim, so a bare path string here was either (a)
+ already shown to the user as text, or (b) stale tool/inspected
+ content that was never part of the intended visible reply. Promoting
+ such paths into uploads after the fact sent files the model never
+ asked to deliver (#20834). Only ``MEDIA:`` directives — the explicit
+ attachment contract — trigger post-stream uploads.
"""
- loop = asyncio.get_running_loop()
- try:
- from tools.mcp_tool import shutdown_mcp_servers, discover_mcp_tools, _servers, _lock
-
- # Capture old server names before shutdown
- with _lock:
- old_servers = set(_servers.keys())
+ from pathlib import Path
+ from urllib.parse import quote as _quote
- # Read new config before shutting down, so we know what will be added/removed
- # Shutdown existing connections
- await loop.run_in_executor(None, shutdown_mcp_servers)
+ try:
+ # Capture [[as_document]] before extract_media strips it, so the
+ # dispatch partition below can route image-extension files
+ # through send_document (preserving bytes) instead of
+ # send_multiple_images (Telegram sendPhoto recompresses to ~1280px).
+ force_document_attachments = "[[as_document]]" in response
- # Reconnect by discovering tools (reads config.yaml fresh)
- new_tools = await loop.run_in_executor(None, discover_mcp_tools)
+ from gateway.platforms.base import BasePlatformAdapter, should_send_media_as_audio
- # Compute what changed
- with _lock:
- connected_servers = set(_servers.keys())
+ media_files, cleaned = adapter.extract_media(response)
+ media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)
+ # Deduplicate against media already delivered in prior turns —
+ # the model may echo a previous turn's MEDIA: tag in a later
+ # response; without this guard the same file is re-sent.
+ if history_media_paths:
+ media_files = [
+ (path, is_voice)
+ for path, is_voice in media_files
+ if path not in history_media_paths
+ ]
+ # Strip image URLs from the cleaned text for parity with the
+ # non-streaming chain, but do NOT run extract_local_files here:
+ # post-stream delivery is explicit-only (#20834). Bare local paths
+ # in an already-streamed reply are text the user has seen (or
+ # stale inspected content), not an attachment request.
+ adapter.extract_images(cleaned)
- added = connected_servers - old_servers
- removed = old_servers - connected_servers
- reconnected = connected_servers & old_servers
+ _thread_meta = self._thread_metadata_for_source(event.source, self._reply_anchor_for_event(event))
- lines = [t("gateway.reload_mcp.header")]
- if reconnected:
- lines.append(t("gateway.reload_mcp.reconnected", names=", ".join(sorted(reconnected))))
- if added:
- lines.append(t("gateway.reload_mcp.added", names=", ".join(sorted(added))))
- if removed:
- lines.append(t("gateway.reload_mcp.removed", names=", ".join(sorted(removed))))
- if not connected_servers:
- lines.append(t("gateway.reload_mcp.none_connected"))
- else:
- lines.append(t("gateway.reload_mcp.tools_available", tools=len(new_tools), servers=len(connected_servers)))
+ _VIDEO_EXTS = {'.mp4', '.mov', '.avi', '.mkv', '.webm', '.3gp'}
+ _IMAGE_EXTS = {'.jpg', '.jpeg', '.png', '.webp', '.gif'}
- # Refresh cached agents so existing sessions see new MCP tools on
- # their next turn — without this, the user has to `/new` (which
- # discards conversation history) to pick up tools from a server
- # that was just added or reconnected. The user has already
- # consented to the prompt-cache invalidation via the slash-confirm
- # gate in _handle_reload_mcp_command before we reach this point.
- try:
- from tools.mcp_tool import refresh_agent_mcp_tools
- _cache = getattr(self, "_agent_cache", None)
- _cache_lock = getattr(self, "_agent_cache_lock", None)
- if _cache_lock is not None and _cache:
- with _cache_lock:
- for _sess_key, _entry in list(_cache.items()):
- try:
- _agent = _entry[0] if isinstance(_entry, tuple) else _entry
- except Exception:
- continue
- if _agent is None:
- continue
- # Preserve each cached agent's build-time toolset
- # selection EXACTLY: a gateway session built with a
- # restricted enabled_toolsets (e.g. ["safe"]) must
- # NOT silently gain tools after a reload. This is the
- # opposite of the interactive CLI/TUI /reload-mcp,
- # which is a single user re-applying their own config
- # edit; gateway agents are per-session and may be
- # deliberately locked down. (Contract is asserted by
- # test_reload_mcp_preserves_per_agent_toolset_overrides.)
- refresh_agent_mcp_tools(_agent, quiet_mode=True)
- except Exception as _exc:
- logger.debug(
- "Failed to update cached agent tools after MCP reload: %s",
- _exc,
- )
+ # Partition out images so they can be sent as a single batch
+ # (e.g. Signal's multi-attachment RPC). When [[as_document]] was
+ # set, image-extension files skip the photo path and route to
+ # send_document below — preserving original bytes.
+ image_paths: list = []
+ non_image_media: list = []
+ for media_path, is_voice in media_files:
+ ext = Path(media_path).suffix.lower()
+ if (ext in _IMAGE_EXTS
+ and not is_voice
+ and not force_document_attachments):
+ image_paths.append(media_path)
+ else:
+ non_image_media.append((media_path, is_voice))
- # Inject a message at the END of the session history so the
- # model knows tools changed on its next turn. Appended after
- # all existing messages to preserve prompt-cache for the prefix.
- change_parts = []
- if added:
- change_parts.append(f"Added servers: {', '.join(sorted(added))}")
- if removed:
- change_parts.append(f"Removed servers: {', '.join(sorted(removed))}")
- if reconnected:
- change_parts.append(f"Reconnected servers: {', '.join(sorted(reconnected))}")
- tool_summary = f"{len(new_tools)} MCP tool(s) now available" if new_tools else "No MCP tools available"
- change_detail = ". ".join(change_parts) + ". " if change_parts else ""
- reload_msg = {
- "role": "user",
- "content": f"[IMPORTANT: MCP servers have been reloaded. {change_detail}{tool_summary}. The tool list for this conversation has been updated accordingly.]",
- }
- try:
- session_entry = await self.async_session_store.get_or_create_session(event.source)
- await self.async_session_store.append_to_transcript(
- session_entry.session_id, reload_msg
- )
- except Exception:
- pass # Best-effort; don't fail the reload over a transcript write
+ if image_paths:
+ try:
+ images = [(f"file://{_quote(p)}", "") for p in image_paths]
+ await adapter.send_multiple_images(
+ chat_id=event.source.chat_id,
+ images=images,
+ metadata=_thread_meta,
+ )
+ except Exception as e:
+ logger.warning("[%s] Post-stream image batch delivery failed: %s", adapter.name, e)
- return "\n".join(lines)
+ for media_path, is_voice in non_image_media:
+ try:
+ ext = Path(media_path).suffix.lower()
+ if should_send_media_as_audio(event.source.platform, ext, is_voice=is_voice):
+ await adapter.send_voice(
+ chat_id=event.source.chat_id,
+ audio_path=media_path,
+ metadata=_thread_meta,
+ )
+ elif ext in _VIDEO_EXTS:
+ await adapter.send_video(
+ chat_id=event.source.chat_id,
+ video_path=media_path,
+ metadata=_thread_meta,
+ )
+ else:
+ await adapter.send_document(
+ chat_id=event.source.chat_id,
+ file_path=media_path,
+ metadata=_thread_meta,
+ )
+ except Exception as e:
+ logger.warning("[%s] Post-stream media delivery failed: %s", adapter.name, e)
except Exception as e:
- logger.warning("MCP reload failed: %s", e)
- return t("gateway.reload_mcp.failed", error=e)
+ logger.warning("Post-stream media extraction failed: %s", e)
- # ------------------------------------------------------------------
- # Slash-command confirmation primitive (generic)
- # ------------------------------------------------------------------
- # Used by slash commands that have a non-destructive but expensive
- # side effect worth an explicit user confirmation (currently only
- # /reload-mcp, which invalidates the prompt cache). Two delivery
- # paths:
- # 1. Button UI — adapters that override ``send_slash_confirm``
- # (Telegram, Discord, Slack, Matrix, Feishu) render three
- # inline buttons. The adapter routes the button click back via
- # ``tools.slash_confirm.resolve(session_key, confirm_id, choice)``.
- # 2. Text fallback — adapters that don't override the hook get a
- # plain text prompt. Users reply with /approve, /always, or
- # /cancel; the early intercept in ``_handle_message`` matches
- # those replies against ``tools.slash_confirm.get_pending()``.
+ async def _run_background_task(
+ self,
+ prompt: str,
+ source: "SessionSource",
+ task_id: str,
+ event_message_id: Optional[str] = None,
+ media_urls: Optional[List[str]] = None,
+ media_types: Optional[List[str]] = None,
+ ) -> None:
+ """Profile-scoping wrapper around the background agent task.
- async def _maybe_confirm_destructive_slash(
+ When multiplexing is active, resolve the inbound source's profile and
+ run the whole task inside ``_profile_runtime_scope`` so credentials
+ resolve from that profile's secret scope. Mirrors the pattern in
+ ``_run_agent``.
+ """
+ if not getattr(getattr(self, "config", None), "multiplex_profiles", False):
+ return await self._run_background_task_inner(
+ prompt, source, task_id, event_message_id, media_urls, media_types,
+ )
+
+ profile_home = self._resolve_profile_home_for_source(source)
+ with _profile_runtime_scope(profile_home):
+ return await self._run_background_task_inner(
+ prompt, source, task_id, event_message_id, media_urls, media_types,
+ )
+
+ async def _run_background_task_inner(
self,
- *,
- event: MessageEvent,
- command: str,
- title: str,
- detail: str,
- execute,
- ) -> Union[str, "EphemeralReply", None]:
- """Gate a destructive session slash command (/new, /reset, /undo).
+ prompt: str,
+ source: "SessionSource",
+ task_id: str,
+ event_message_id: Optional[str] = None,
+ media_urls: Optional[List[str]] = None,
+ media_types: Optional[List[str]] = None,
+ ) -> None:
+ """Execute a background agent task and deliver the result to the chat."""
+ from run_agent import AIAgent
- ``execute`` is an async callable ``execute() -> str | EphemeralReply``
- that performs the destructive action. If the
- ``approvals.destructive_slash_confirm`` config gate is off, ``execute``
- runs immediately (returning its result). Otherwise this routes
- through ``_request_slash_confirm`` — native yes/no buttons on
- Telegram/Discord/Slack, text fallback elsewhere.
+ media_urls = media_urls or []
+ media_types = media_types or []
- Three-option resolution:
+ adapter = self._adapter_for_source(source)
+ if not adapter:
+ logger.warning("No adapter for platform %s in background task %s", source.platform, task_id)
+ return
+
+ _thread_metadata = self._thread_metadata_for_source(source, event_message_id)
- - ``once`` — run ``execute`` and return its result
- - ``always`` — persist ``approvals.destructive_slash_confirm: false``,
- then run ``execute``
- - ``cancel`` — return a "cancelled" message; do not run ``execute``
- """
- # Gate check.
- confirm_required = True
try:
- cfg = self._read_user_config()
- approvals = cfg.get("approvals") if isinstance(cfg, dict) else None
- if isinstance(approvals, dict):
- confirm_required = bool(approvals.get("destructive_slash_confirm", True))
- except Exception:
- pass
+ user_config = _load_gateway_config()
+ model, runtime_kwargs = self._resolve_session_agent_runtime(
+ source=source,
+ user_config=user_config,
+ )
+ if not runtime_kwargs.get("api_key"):
+ await adapter.send(
+ source.chat_id,
+ f"❌ Background task {task_id} failed: no provider credentials configured.",
+ metadata=_thread_metadata,
+ )
+ return
- if not confirm_required:
- return await execute()
+ platform_key = _platform_config_key(source.platform)
- session_key = self._session_key_for_source(event.source)
+ from hermes_cli.tools_config import _get_platform_tools
+ enabled_toolsets = sorted(_get_platform_tools(user_config, platform_key))
+ agent_cfg = user_config.get("agent") or {}
+ disabled_toolsets = agent_cfg.get("disabled_toolsets") or None
- async def _on_confirm(choice: str):
- if choice == "cancel":
- return f"🟡 /{command} cancelled. Conversation unchanged."
- if choice == "always":
- try:
- from cli import save_config_value
- save_config_value("approvals.destructive_slash_confirm", False)
- logger.info(
- "User opted out of destructive slash confirm (session=%s)",
- session_key,
- )
- except Exception as exc:
- logger.warning(
- "Failed to persist destructive_slash_confirm=false: %s", exc,
- )
- result = await execute()
- if choice == "always":
- note = (
- "\n\nℹ️ Future /clear, /new, /reset, and /undo will run "
- "without confirmation. Re-enable via "
- "`approvals.destructive_slash_confirm: true` in config.yaml."
- )
- if isinstance(result, str):
- return result + note
- # EphemeralReply or other — leave untouched; the opt-out note
- # would otherwise mangle structured replies. The persist itself
- # already happened above; user gets the same UX next time.
- return result
- return result
+ pr = self._provider_routing
+ max_iterations = _current_max_iterations()
+ reasoning_config = self._resolve_session_reasoning_config(
+ source=source, model=model
+ )
+ self._reasoning_config = reasoning_config
+ self._service_tier = self._resolve_session_service_tier(source=source)
+ turn_route = self._resolve_turn_agent_config(prompt, model, runtime_kwargs)
- _p = self._typed_command_prefix_for(event.source.platform)
- prompt_message = (
- f"⚠️ **Confirm /{command}**\n\n"
- f"{detail}\n\n"
- "Choose:\n"
- "• **Approve Once** — proceed this time only\n"
- "• **Always Approve** — proceed and silence this prompt permanently\n"
- "• **Cancel** — keep current conversation\n\n"
- f"_Text fallback: reply `{_p}approve`, `{_p}always`, or `{_p}cancel`._"
- )
- return await self._request_slash_confirm(
- event=event,
- command=command,
- title=title,
- message=prompt_message,
- handler=_on_confirm,
- )
+ # Enrich the prompt with image descriptions so the background
+ # agent can see user-attached images (same as the main flow).
+ enriched_prompt = prompt
+ if media_urls:
+ image_paths = []
+ for i, path in enumerate(media_urls):
+ mtype = media_types[i] if i < len(media_types) else ""
+ if mtype.startswith("image/"):
+ image_paths.append(path)
+ if image_paths:
+ try:
+ enriched_prompt = await self._enrich_message_with_vision(
+ prompt, image_paths,
+ )
+ except Exception as e:
+ logger.warning("Background task vision enrichment failed: %s", e)
- async def _request_slash_confirm(
- self,
- *,
- event: MessageEvent,
- command: str,
- title: str,
- message: str,
- handler,
- ) -> Optional[str]:
- """Ask the user to confirm an expensive slash command.
+ def run_sync():
+ agent = AIAgent(
+ model=turn_route["model"],
+ **turn_route["runtime"],
+ **_checkpoint_agent_kwargs(user_config),
+ max_iterations=max_iterations,
+ quiet_mode=True,
+ verbose_logging=False,
+ enabled_toolsets=enabled_toolsets,
+ disabled_toolsets=disabled_toolsets,
+ reasoning_config=reasoning_config,
+ service_tier=self._service_tier,
+ request_overrides=turn_route.get("request_overrides"),
+ providers_allowed=pr.get("only"),
+ providers_ignored=pr.get("ignore"),
+ providers_order=pr.get("order"),
+ provider_sort=pr.get("sort"),
+ provider_require_parameters=pr.get("require_parameters", False),
+ provider_data_collection=pr.get("data_collection"),
+ session_id=task_id,
+ platform=platform_key,
+ user_id=source.user_id,
+ user_id_alt=source.user_id_alt,
+ user_name=source.user_name,
+ chat_id=source.chat_id,
+ chat_name=source.chat_name,
+ chat_type=source.chat_type,
+ thread_id=source.thread_id,
+ session_db=getattr(self._session_db, "_db", self._session_db),
+ # Reload from disk — do not reuse the startup snapshot (#60955).
+ fallback_model=self._refresh_fallback_model(),
+ )
+ try:
+ return agent.run_conversation(
+ user_message=enriched_prompt,
+ task_id=task_id,
+ )
+ finally:
+ self._cleanup_agent_resources(agent)
- ``handler`` is an async callable ``handler(choice: str) -> str``
- where ``choice`` is ``"once"``, ``"always"``, or ``"cancel"``.
- The handler runs on the event loop when the user responds; its
- return value is sent back as a gateway message.
+ result = await self._run_in_executor_with_context(run_sync)
- Returns a short acknowledgment string to send immediately (before
- the user's response). If buttons rendered successfully the ack
- is ``None`` (buttons are self-explanatory); if we fell back to
- text the message itself IS the ack.
- """
- from tools import slash_confirm as _slash_confirm_mod
+ response = result.get("final_response", "") if result else ""
+ if not response and result and result.get("error"):
+ response = f"Error: {result['error']}"
- source = event.source
- session_key = self._session_key_for_source(source)
- # Bare-runner test harnesses (object.__new__(GatewayRunner)) skip
- # __init__ and don't have the counter attribute — fall back to a
- # local counter so tests don't AttributeError. Real runs always
- # have the instance attribute.
- counter = getattr(self, "_slash_confirm_counter", None)
- if counter is None:
- import itertools as _itertools
- counter = _itertools.count(1)
- self._slash_confirm_counter = counter
- confirm_id = f"{next(counter)}"
+ # Extract media files from the response
+ if response:
+ media_files, response = adapter.extract_media(response)
+ from gateway.platforms.base import BasePlatformAdapter
+ media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)
+ images, text_content = adapter.extract_images(response)
- # Register the pending confirm FIRST so a super-fast button click
- # cannot race the send_slash_confirm return.
- _slash_confirm_mod.register(session_key, confirm_id, command, handler)
+ preview = prompt[:60] + ("..." if len(prompt) > 60 else "")
+ header = f'✅ Background task complete\nPrompt: "{preview}"\n\n'
- adapter = self._adapter_for_source(source)
- metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
+ if text_content:
+ await adapter.send(
+ chat_id=source.chat_id,
+ content=header + text_content,
+ metadata=_thread_metadata,
+ )
+ elif not images and not media_files:
+ await adapter.send(
+ chat_id=source.chat_id,
+ content=header + "(No response generated)",
+ metadata=_thread_metadata,
+ )
- used_buttons = False
- if adapter is not None:
- try:
- button_result = await adapter.send_slash_confirm(
+ # Send extracted images
+ for image_url, alt_text in (images or []):
+ try:
+ await adapter.send_image(
+ chat_id=source.chat_id,
+ image_url=image_url,
+ caption=alt_text,
+ metadata=_thread_metadata,
+ )
+ except Exception:
+ pass
+
+ # Send media files, routing each by type so a TTS clip
+ # arrives as a voice bubble / a clip as a video rather than
+ # a generic document. Mirrors the streaming + kanban paths.
+ from gateway.platforms.base import (
+ should_send_media_as_audio as _should_send_media_as_audio,
+ )
+ _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp"}
+ _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
+ for media_path, _is_voice in (media_files or []):
+ _ext = os.path.splitext(media_path)[1].lower()
+ try:
+ if _should_send_media_as_audio(source.platform, _ext, _is_voice):
+ await adapter.send_voice(
+ chat_id=source.chat_id,
+ audio_path=media_path,
+ metadata=_thread_metadata,
+ )
+ elif _ext in _VIDEO_EXTS:
+ await adapter.send_video(
+ chat_id=source.chat_id,
+ video_path=media_path,
+ metadata=_thread_metadata,
+ )
+ elif _ext in _IMAGE_EXTS:
+ await adapter.send_image_file(
+ chat_id=source.chat_id,
+ image_path=media_path,
+ metadata=_thread_metadata,
+ )
+ else:
+ await adapter.send_document(
+ chat_id=source.chat_id,
+ file_path=media_path,
+ metadata=_thread_metadata,
+ )
+ except Exception:
+ pass
+ else:
+ preview = prompt[:60] + ("..." if len(prompt) > 60 else "")
+ await adapter.send(
chat_id=source.chat_id,
- title=title,
- message=message,
- session_key=session_key,
- confirm_id=confirm_id,
- metadata=metadata,
+ content=f'✅ Background task complete\nPrompt: "{preview}"\n\n(No response generated)',
+ metadata=_thread_metadata,
)
- if button_result and getattr(button_result, "success", False):
- used_buttons = True
- except Exception as exc:
- logger.debug(
- "send_slash_confirm failed for %s on %s: %s",
- command, source.platform, exc,
+
+ except Exception as e:
+ logger.exception("Background task %s failed", task_id)
+ try:
+ await adapter.send(
+ chat_id=source.chat_id,
+ content=f"❌ Background task {task_id} failed: {e}",
+ metadata=_thread_metadata,
)
+ except Exception:
+ pass
- if used_buttons:
- # Buttons rendered — no redundant text ack.
- return None
- # Text fallback — return the prompt message as the direct reply.
- return message
- def _read_user_config(self) -> Dict[str, Any]:
- """Read the user's raw config.yaml (cached) for gate lookups.
- Used by slash-confirm gates that must reflect on-disk state changes
- (e.g. a prior "Always Approve" click) without a gateway restart.
- """
+
+
+
+
+ async def _get_telegram_topic_capabilities(self, source: SessionSource) -> dict:
+ """Read Telegram private-topic capability flags via Bot API getMe."""
+ adapter = self._adapter_for_source(source)
+ bot = getattr(adapter, "_bot", None)
+ if bot is None or not hasattr(bot, "get_me"):
+ return {"checked": False}
try:
- from hermes_cli.config import load_config
- cfg = load_config()
- return cfg if isinstance(cfg, dict) else {}
+ me = await bot.get_me()
except Exception:
- return {}
-
- def _thread_metadata_for_source(
- self,
- source,
- reply_to_message_id: Optional[str] = None,
- ) -> Optional[Dict[str, Any]]:
- """Build the metadata dict platforms need for thread-aware replies."""
- metadata = self._thread_metadata_for_target(
- getattr(source, "platform", None),
- getattr(source, "chat_id", None),
- getattr(source, "thread_id", None),
- chat_type=getattr(source, "chat_type", None),
- reply_to_message_id=reply_to_message_id or getattr(source, "message_id", None),
- )
- if getattr(source, "platform", None) == Platform.SLACK:
- team_id = getattr(source, "scope_id", None)
- if team_id:
- metadata = dict(metadata or {})
- metadata["slack_team_id"] = str(team_id)
- return metadata
+ logger.debug("Failed to fetch Telegram getMe topic capabilities", exc_info=True)
+ return {"checked": False}
- def _thread_metadata_for_target(
- self,
- platform: Optional[Platform],
- chat_id: Optional[str],
- thread_id: Optional[str],
- *,
- chat_type: Optional[str] = None,
- reply_to_message_id: Optional[str] = None,
- adapter: Optional[Any] = None,
- ) -> Optional[Dict[str, Any]]:
- """Build thread metadata for synthetic sends that only have routing state."""
- if thread_id is None:
+ def _field(name: str):
+ if hasattr(me, name):
+ return getattr(me, name)
+ api_kwargs = getattr(me, "api_kwargs", None)
+ if isinstance(api_kwargs, dict) and name in api_kwargs:
+ return api_kwargs.get(name)
+ if isinstance(me, dict):
+ return me.get(name)
return None
- metadata: Dict[str, Any] = {"thread_id": thread_id}
- if self._is_telegram_dm_topic_target(
- platform,
- chat_id,
- thread_id,
- chat_type=chat_type,
- adapter=adapter,
- ):
- metadata["telegram_dm_topic_reply_fallback"] = True
- # Telegram DM topic lanes need direct_messages_topic_id in metadata
- # so synthetic/queued messages (goal continuations, status notices)
- # route to the correct topic even when reply anchor is unavailable.
- tid = str(thread_id)
- if tid and tid not in {"", "1"}:
- metadata["direct_messages_topic_id"] = tid
- if reply_to_message_id is not None:
- metadata["telegram_reply_to_message_id"] = str(reply_to_message_id)
- if platform == Platform.SLACK and reply_to_message_id is not None:
- # Slack's reply_in_thread=false path uses message_id to distinguish
- # real existing threads from synthetic top-level session keys.
- metadata["message_id"] = str(reply_to_message_id)
- return metadata
- @staticmethod
- def _is_telegram_dm_topic_target(
- platform: Optional[Platform],
- chat_id: Optional[str],
- thread_id: Optional[str],
- *,
- chat_type: Optional[str] = None,
- adapter: Optional[Any] = None,
- ) -> bool:
- """Return True when a target is a Telegram private DM topic lane."""
- if platform != Platform.TELEGRAM or thread_id is None:
- return False
- if chat_type == "dm":
- return True
- # Inspect operator-declared DM topics via the adapter's lookup. Resolve
- # the method on the CLASS, not the instance: getattr() on a MagicMock
- # auto-creates a callable child for any attribute, so an instance-level
- # lookup would report a DM topic for every test double. Only a
- # dict-shaped return counts as an operator-declared topic — a bare
- # MagicMock or other sentinel must not. Mirrors the guard in
- # _rename_telegram_topic_for_session_title.
- if adapter is not None and chat_id:
- get_dm_topic_info = getattr(type(adapter), "_get_dm_topic_info", None)
- if callable(get_dm_topic_info):
- try:
- topic_info = get_dm_topic_info(adapter, str(chat_id), str(thread_id))
- except Exception:
- logger.debug("Failed to inspect Telegram DM topic metadata", exc_info=True)
- else:
- return isinstance(topic_info, dict)
- return False
+ return {
+ "checked": True,
+ "has_topics_enabled": _field("has_topics_enabled"),
+ "allows_users_to_create_topics": _field("allows_users_to_create_topics"),
+ }
- @staticmethod
- def _reply_anchor_for_event(event: MessageEvent) -> Optional[str]:
- """Return the platform-specific reply anchor for GatewayRunner sends."""
- return _reply_anchor_for_event(event)
+ async def _ensure_telegram_system_topic(self, source: SessionSource) -> None:
+ """Create/pin the managed System topic after /topic activation when possible."""
+ adapter = self._adapter_for_source(source)
+ if adapter is None or not source.chat_id:
+ return
+ thread_id = None
+ create_topic = getattr(adapter, "_create_dm_topic", None)
+ if callable(create_topic):
+ try:
+ thread_id = await create_topic(int(source.chat_id), "System")
+ except Exception:
+ logger.debug("Failed to create Telegram System topic", exc_info=True)
+ if not thread_id:
+ return
- # ------------------------------------------------------------------
- # /approve & /deny — explicit dangerous-command approval
- # ------------------------------------------------------------------
+ message_id = None
+ try:
+ send_result = await adapter.send(
+ source.chat_id,
+ "System topic for Hermes commands and status.",
+ metadata={"thread_id": str(thread_id)},
+ )
+ message_id = getattr(send_result, "message_id", None)
+ except Exception:
+ logger.debug("Failed to send Telegram System topic intro", exc_info=True)
+ if not message_id:
+ return
- _APPROVAL_TIMEOUT_SECONDS = 300 # 5 minutes
+ bot = getattr(adapter, "_bot", None)
+ if bot is None or not hasattr(bot, "pin_chat_message"):
+ return
+ try:
+ await bot.pin_chat_message(
+ chat_id=int(source.chat_id),
+ message_id=int(message_id),
+ disable_notification=True,
+ )
+ except Exception:
+ logger.debug("Failed to pin Telegram System topic intro", exc_info=True)
+ async def _send_telegram_topic_setup_image(self, source: SessionSource) -> None:
+ """Send the bundled BotFather Threads Settings screenshot when available."""
+ adapter = self._adapter_for_source(source)
+ if adapter is None or not source.chat_id or not hasattr(adapter, "send_image_file"):
+ return
+ image_path = Path(__file__).resolve().parent / "assets" / "telegram-botfather-threads-settings.jpg"
+ if not image_path.exists():
+ return
+ try:
+ await adapter.send_image_file(
+ chat_id=source.chat_id,
+ image_path=str(image_path),
+ caption="BotFather → Bot Settings → Threads Settings",
+ metadata={"thread_id": str(source.thread_id)} if source.thread_id else None,
+ )
+ except Exception:
+ logger.debug("Failed to send Telegram topic setup image", exc_info=True)
+ def _sanitize_telegram_topic_title(self, title: str) -> str:
+ """Return a Bot API-safe forum topic name from a generated session title."""
+ cleaned = re.sub(r"\s+", " ", str(title or "")).strip()
+ if not cleaned:
+ return "Hermes Chat"
+ # Telegram forum topic names are short (currently 1-128 chars). Keep
+ # extra room for multi-byte titles and avoid trailing ellipsis churn.
+ if len(cleaned) > 120:
+ cleaned = cleaned[:117].rstrip() + "..."
+ return cleaned
- # Built-in messaging platforms where the ``/update`` command is allowed.
- # ACP, API server, and webhooks are programmatic interfaces that should
- # not trigger system updates. Plugin-migrated platforms (discord,
- # mattermost, teams, irc, line, …) are NOT listed here — they declare
- # ``allow_update_command=True`` on their ``PlatformEntry`` and are
- # honored via the registry fallback at ``_handle_update_command`` below.
- _UPDATE_ALLOWED_PLATFORMS = frozenset({
- Platform.TELEGRAM, Platform.SLACK, Platform.WHATSAPP,
- Platform.SIGNAL, Platform.MATRIX,
- Platform.EMAIL, Platform.SMS, Platform.DINGTALK,
- Platform.FEISHU, Platform.WECOM, Platform.WECOM_CALLBACK, Platform.WEIXIN, Platform.BLUEBUBBLES, Platform.QQBOT, Platform.LOCAL,
- })
+ def _is_discord_auto_thread_lane(self, source: SessionSource) -> bool:
+ """Return True only for Discord threads Hermes just auto-created."""
+ return (
+ source.platform == Platform.DISCORD
+ and source.chat_type == "thread"
+ and bool(getattr(source, "auto_thread_created", False))
+ and bool(source.thread_id)
+ and bool(getattr(source, "auto_thread_initial_name", None))
+ )
+ def _sanitize_discord_thread_title(self, title: str) -> str:
+ """Return a Discord-safe semantic thread title from a session title.
+ Discord thread names are capped at 100 characters measured in UTF-16
+ code units (emoji count double), so truncate with the UTF-16 helpers
+ rather than Python code-point slices.
+ """
+ cleaned = re.sub(r"\s+", " ", str(title or "")).strip()
+ if not cleaned:
+ return "Hermes Chat"
+ if utf16_len(cleaned) > 80:
+ cleaned = _prefix_within_utf16_limit(cleaned, 77).rstrip() + "..."
+ return cleaned
- def _schedule_update_notification_watch(self) -> None:
- """Ensure a background task is watching for update completion."""
- existing_task = getattr(self, "_update_notification_task", None)
- if existing_task and not existing_task.done():
+ async def _rename_discord_auto_thread_for_session_title(
+ self,
+ source: SessionSource,
+ session_id: str,
+ title: str,
+ ) -> None:
+ """Best-effort semantic rename of a newly auto-created Discord thread."""
+ if not await asyncio.to_thread(self._is_discord_auto_thread_lane, source):
return
-
+ adapter = self._adapter_for_source(source) if getattr(self, "adapters", None) else None
+ if adapter is None:
+ return
+ rename_thread = getattr(adapter, "rename_thread", None)
+ if rename_thread is None:
+ return
+ thread_name = self._sanitize_discord_thread_title(title)
try:
- self._update_notification_task = asyncio.create_task(
- self._watch_update_progress()
+ await rename_thread(
+ str(source.thread_id),
+ thread_name,
+ only_if_current_name=getattr(source, "auto_thread_initial_name", None),
)
- except RuntimeError:
- logger.debug("Skipping update notification watcher: no running event loop")
+ except Exception:
+ logger.debug("Failed to rename Discord auto-thread for generated session title", exc_info=True)
- async def _watch_update_progress(
+ def _schedule_discord_semantic_thread_rename(
self,
- poll_interval: float = 2.0,
- stream_interval: float = 4.0,
- timeout: float = 1800.0,
+ source: SessionSource,
+ session_id: str,
+ title: str,
) -> None:
- """Watch ``hermes update --gateway``, streaming output + forwarding prompts.
-
- Polls ``.update_output.txt`` for new content and sends chunks to the
- user periodically. Detects ``.update_prompt.json`` (written by the
- update process when it needs user input) and forwards the prompt to
- the messenger. The user's next message is intercepted by
- ``_handle_message`` and written to ``.update_response``.
- """
- pending_path = _hermes_home / ".update_pending.json"
- claimed_path = _hermes_home / ".update_pending.claimed.json"
- output_path = _hermes_home / ".update_output.txt"
- exit_code_path = _hermes_home / ".update_exit_code"
- prompt_path = _hermes_home / ".update_prompt.json"
-
- loop = asyncio.get_running_loop()
- deadline = loop.time() + timeout
-
- # Resolve the adapter and chat_id for sending messages
- adapter = None
- chat_id = None
- session_key = None
- metadata = None
- for path in (claimed_path, pending_path):
- if path.exists():
- try:
- pending = json.loads(path.read_text(encoding="utf-8"))
- platform_str = pending.get("platform")
- chat_id = pending.get("chat_id")
- chat_type = pending.get("chat_type")
- session_key = pending.get("session_key")
- thread_id = pending.get("thread_id")
- message_id = pending.get("message_id")
- if platform_str and chat_id:
- platform = Platform(platform_str)
- adapter = self.adapters.get(platform)
- metadata = self._thread_metadata_for_target(
- platform,
- chat_id,
- thread_id,
- chat_type=chat_type,
- reply_to_message_id=message_id,
- adapter=adapter,
- )
- # Fallback session key if not stored (old pending files)
- if not session_key:
- session_key = f"{platform_str}:{chat_id}"
- break
- except Exception:
- pass
-
- if not adapter or not chat_id:
- logger.warning("Update watcher: cannot resolve adapter/chat_id, falling back to completion-only")
- # Fall back to completion-only: wait for the exit code and send the
- # final notification. _send_update_notification re-resolves the
- # adapter on every call, so when the target platform is still
- # reconnecting it returns False and keeps the markers. Keep polling
- # until it actually delivers (returns True) instead of giving up
- # after the first completion check — otherwise a platform that
- # reconnects a few seconds after completion never gets notified.
- while (pending_path.exists() or claimed_path.exists()) and loop.time() < deadline:
- if exit_code_path.exists() and await self._send_update_notification():
- return
- await asyncio.sleep(poll_interval)
- if (pending_path.exists() or claimed_path.exists()) and not exit_code_path.exists():
- exit_code_path.write_text("124", encoding="utf-8")
- await self._send_update_notification()
+ """Schedule Discord auto-thread rename from the auto-title background thread."""
+ if not title or not self._is_discord_auto_thread_lane(source):
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = getattr(self, "_gateway_loop", None)
+ if loop is None or loop.is_closed():
+ return
+ try:
+ copied_source = dataclasses.replace(source)
+ except Exception:
+ copied_source = source
+ future = safe_schedule_threadsafe(
+ self._rename_discord_auto_thread_for_session_title(copied_source, session_id, title),
+ loop,
+ logger=logger,
+ log_message="Discord semantic thread rename failed to schedule",
+ )
+ if future is None:
return
- def _strip_ansi(text: str) -> str:
- from tools.ansi_strip import strip_ansi
- return strip_ansi(text)
-
- bytes_sent = 0
- last_stream_time = loop.time()
- buffer = ""
-
- async def _flush_buffer() -> None:
- """Send buffered output to the user."""
- nonlocal buffer, last_stream_time
- if not buffer.strip():
- buffer = ""
- return
- # Chunk to fit message limits (Telegram: 4096, others: generous)
- clean = _strip_ansi(buffer).strip()
- buffer = ""
- last_stream_time = loop.time()
- if not clean:
- return
- # Split into chunks if too long
- max_chunk = 3500
- chunks = [clean[i:i + max_chunk] for i in range(0, len(clean), max_chunk)]
- for chunk in chunks:
- try:
- await adapter.send(
- chat_id,
- f"```\n{chunk}\n```",
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
- except Exception as e:
- logger.debug("Update stream send failed: %s", e)
-
- while loop.time() < deadline:
- # Check for completion
- if exit_code_path.exists():
- # Read any remaining output
- if output_path.exists():
- try:
- content = output_path.read_text(encoding="utf-8")
- if len(content) > bytes_sent:
- buffer += content[bytes_sent:]
- bytes_sent = len(content)
- except OSError:
- pass
- await _flush_buffer()
+ def _log_rename_failure(fut) -> None:
+ try:
+ fut.result()
+ except Exception:
+ logger.debug("Discord semantic thread rename failed", exc_info=True)
- # Send final status
+ future.add_done_callback(_log_rename_failure)
+
+ async def _rename_telegram_topic_for_session_title(
+ self,
+ source: SessionSource,
+ session_id: str,
+ title: str,
+ ) -> None:
+ """Best-effort rename of a Telegram DM topic when Hermes auto-titles a session."""
+ if not await asyncio.to_thread(self._is_telegram_topic_lane, source) or not source.chat_id or not source.thread_id:
+ return
+
+ # Operator can fully disable per-topic auto-rename via
+ # extra.disable_topic_auto_rename. Useful when topics are managed
+ # by the user (ad-hoc Threaded Mode) and auto-rename would
+ # overwrite their chosen names every time the auto-title fires.
+ if self._telegram_topic_auto_rename_disabled(source):
+ return
+
+ # Skip rename when the topic is operator-declared via
+ # extra.dm_topics. Those topics have fixed names chosen by the
+ # operator (plus optional skill binding); auto-renaming would
+ # silently mutate operator config.
+ #
+ # Check the class, not the instance — getattr() on MagicMock
+ # auto-creates attributes, so `hasattr(adapter, "_get_dm_topic_info")`
+ # would return True for every test double.
+ adapter = self._adapter_for_source(source)
+ if adapter is not None:
+ get_info = getattr(type(adapter), "_get_dm_topic_info", None)
+ if callable(get_info):
try:
- exit_code_raw = exit_code_path.read_text(encoding="utf-8").strip() or "1"
- exit_code = int(exit_code_raw)
- if exit_code == 0:
- await adapter.send(
- chat_id,
- "✅ Hermes update finished.",
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
- else:
- await adapter.send(
- chat_id,
- "❌ Hermes update failed (exit code {}).".format(exit_code),
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
- logger.info("Update finished (exit=%s), notified %s", exit_code, session_key)
- except Exception as e:
- logger.warning("Update final notification failed: %s", e)
+ operator_topic = get_info(adapter, str(source.chat_id), str(source.thread_id))
+ except Exception:
+ operator_topic = None
+ # Only treat dict-shaped returns as operator-declared; a
+ # bare MagicMock or other sentinel shouldn't count.
+ if isinstance(operator_topic, dict):
+ return
- # Cleanup
- for p in (pending_path, claimed_path, output_path,
- exit_code_path, prompt_path):
- p.unlink(missing_ok=True)
- (_hermes_home / ".update_response").unlink(missing_ok=True)
- _up_done = self._peek_session_state(session_key)
- if _up_done is not None:
- _up_done.persistent.update_prompt_pending = False
+ session_db = getattr(self, "_session_db", None)
+ if session_db is not None:
+ try:
+ binding = await session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id),
+ thread_id=str(source.thread_id),
+ )
+ if binding and str(binding.get("session_id") or "") != str(session_id):
+ return
+ except Exception:
+ logger.debug("Failed to verify Telegram topic binding before rename", exc_info=True)
return
- # Check for new output
- if output_path.exists():
- try:
- content = output_path.read_text(encoding="utf-8")
- if len(content) > bytes_sent:
- buffer += content[bytes_sent:]
- bytes_sent = len(content)
- except OSError:
- pass
+ if adapter is None:
+ return
+ topic_name = self._sanitize_telegram_topic_title(title)
+ try:
+ rename_topic = getattr(adapter, "rename_dm_topic", None)
+ if rename_topic is not None:
+ await rename_topic(
+ chat_id=str(source.chat_id),
+ thread_id=str(source.thread_id),
+ name=topic_name,
+ )
+ return
- # Flush buffer periodically
- if buffer.strip() and (loop.time() - last_stream_time) >= stream_interval:
- await _flush_buffer()
+ bot = getattr(adapter, "_bot", None)
+ edit_forum_topic = getattr(bot, "edit_forum_topic", None) if bot is not None else None
+ if edit_forum_topic is None:
+ edit_forum_topic = getattr(bot, "editForumTopic", None) if bot is not None else None
+ if edit_forum_topic is None:
+ return
+ try:
+ await edit_forum_topic(
+ chat_id=int(source.chat_id),
+ message_thread_id=int(source.thread_id),
+ name=topic_name,
+ )
+ except (TypeError, ValueError):
+ await edit_forum_topic(
+ chat_id=source.chat_id,
+ message_thread_id=source.thread_id,
+ name=topic_name,
+ )
+ except Exception:
+ logger.debug("Failed to rename Telegram topic for auto-generated title", exc_info=True)
- # Check for prompts — only forward if we haven't already sent
- # one that's still awaiting a response. Without this guard the
- # watcher would re-read the same .update_prompt.json every poll
- # cycle and spam the user with duplicate prompt messages.
- _up_pending_state = (
- self._peek_session_state(session_key) if session_key else None
- )
- if (prompt_path.exists() and session_key
- and not (
- _up_pending_state is not None
- and _up_pending_state.persistent.update_prompt_pending
- )):
- try:
- prompt_data = json.loads(prompt_path.read_text(encoding="utf-8"))
- prompt_text = prompt_data.get("prompt", "")
- default = prompt_data.get("default", "")
- if prompt_text:
- # Flush any buffered output first so the user sees
- # context before the prompt
- await _flush_buffer()
- # Try platform-native buttons first (Discord, Telegram)
- sent_buttons = False
- if getattr(type(adapter), "send_update_prompt", None) is not None:
- try:
- await adapter.send_update_prompt(
- chat_id=chat_id,
- prompt=prompt_text,
- default=default,
- session_key=session_key,
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
- sent_buttons = True
- except Exception as btn_err:
- logger.debug("Button-based update prompt failed: %s", btn_err)
- if not sent_buttons:
- default_hint = f" (default: {default})" if default else ""
- _p = getattr(adapter, "typed_command_prefix", "/")
- await adapter.send(
- chat_id,
- f"⚕ **Update needs your input:**\n\n"
- f"{prompt_text}{default_hint}\n\n"
- f"Reply `{_p}approve` (yes) or `{_p}deny` (no), "
- f"or type your answer directly.",
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
- # Keep the prompt marker on disk until the user
- # answers. If the gateway restarts mid-prompt, the
- # next watcher can recover by re-forwarding it from
- # disk. Duplicate sends in the same process are
- # still suppressed by _update_prompt_pending.
- self._session_state(
- session_key
- ).persistent.update_prompt_pending = True
- # .update_response to continue — it doesn't re-check
- logger.info("Forwarded update prompt to %s: %s", session_key, prompt_text[:80])
- except (json.JSONDecodeError, OSError) as e:
- logger.debug("Failed to read update prompt: %s", e)
+ def _telegram_topic_auto_rename_disabled(self, source: SessionSource) -> bool:
+ """Return True when operator disabled per-topic auto-rename for this Telegram chat.
- await asyncio.sleep(poll_interval)
+ Controlled via ``gateway.platforms.telegram.extra.disable_topic_auto_rename``.
+ Default is False (auto-rename enabled, preserves prior behaviour).
+ """
+ platform_cfg = (
+ self.config.platforms.get(source.platform)
+ if getattr(self, "config", None) and getattr(self.config, "platforms", None)
+ else None
+ )
+ if platform_cfg is None:
+ return False
+ extra = getattr(platform_cfg, "extra", None) or {}
+ value = extra.get("disable_topic_auto_rename")
+ if value is None:
+ return False
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ return value.strip().lower() in {"1", "true", "yes", "on"}
+ return bool(value)
- # Timeout
- if not exit_code_path.exists():
- logger.warning("Update watcher timed out after %.0fs", timeout)
- exit_code_path.write_text("124", encoding="utf-8")
- await _flush_buffer()
+ def _schedule_telegram_topic_title_rename(
+ self,
+ source: SessionSource,
+ session_id: str,
+ title: str,
+ ) -> None:
+ """Schedule a topic rename from the auto-title background thread."""
+ if not title or not self._is_telegram_topic_lane(source):
+ return
+ if self._telegram_topic_auto_rename_disabled(source):
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = getattr(self, "_gateway_loop", None)
+ if loop is None or loop.is_closed():
+ return
+ try:
+ copied_source = dataclasses.replace(source)
+ except Exception:
+ copied_source = source
+ future = safe_schedule_threadsafe(
+ self._rename_telegram_topic_for_session_title(copied_source, session_id, title),
+ loop,
+ logger=logger,
+ log_message="Telegram topic title rename failed to schedule",
+ )
+ if future is None:
+ return
+ def _log_rename_failure(fut) -> None:
try:
- await adapter.send(
- chat_id,
- "❌ Hermes update timed out after 30 minutes.",
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
+ fut.result()
except Exception:
- pass
- for p in (pending_path, claimed_path, output_path,
- exit_code_path, prompt_path):
- p.unlink(missing_ok=True)
- (_hermes_home / ".update_response").unlink(missing_ok=True)
- _up_timeout_state = self._peek_session_state(session_key)
- if _up_timeout_state is not None:
- _up_timeout_state.persistent.update_prompt_pending = False
+ logger.debug("Telegram topic title rename failed", exc_info=True)
- async def _send_update_notification(self) -> bool:
- """If an update finished, notify the user.
+ future.add_done_callback(_log_rename_failure)
- Returns False when the update is still running so a caller can retry
- later. Returns True after a definitive send/skip decision.
+ _TELEGRAM_CAPABILITY_HINT_COOLDOWN_S = 300.0
- This is the legacy notification path used when the streaming watcher
- cannot resolve the adapter (e.g. after a gateway restart where the
- platform hasn't reconnected yet).
- """
- pending_path = _hermes_home / ".update_pending.json"
- claimed_path = _hermes_home / ".update_pending.claimed.json"
- output_path = _hermes_home / ".update_output.txt"
- exit_code_path = _hermes_home / ".update_exit_code"
+ def _should_send_telegram_capability_hint(self, source: SessionSource) -> bool:
+ """Rate-limit the BotFather Threads Settings screenshot.
- if not pending_path.exists() and not claimed_path.exists():
+ If a user sends /topic repeatedly while Threads Settings are still
+ off, we shouldn't keep re-uploading the screenshot every time.
+ """
+ if not hasattr(self, "_telegram_capability_hint_ts"):
+ self._telegram_capability_hint_ts = {}
+ chat_id = str(source.chat_id or "")
+ if not chat_id:
+ return True
+ import time as _time
+ now = _time.monotonic()
+ last = self._telegram_capability_hint_ts.get(chat_id, 0.0)
+ if now - last < self._TELEGRAM_CAPABILITY_HINT_COOLDOWN_S:
return False
+ self._telegram_capability_hint_ts[chat_id] = now
+ return True
- cleanup = True
- active_pending_path = claimed_path
- try:
- if pending_path.exists():
- try:
- pending_path.replace(claimed_path)
- except FileNotFoundError:
- if not claimed_path.exists():
- return True
- elif not claimed_path.exists():
- return True
-
- pending = json.loads(claimed_path.read_text(encoding="utf-8"))
- platform_str = pending.get("platform")
- chat_id = pending.get("chat_id")
- chat_type = pending.get("chat_type")
- thread_id = pending.get("thread_id")
- message_id = pending.get("message_id")
-
- if not exit_code_path.exists():
- logger.info("Update notification deferred: update still running")
- cleanup = False
- active_pending_path = pending_path
- claimed_path.replace(pending_path)
- return False
-
- exit_code_raw = exit_code_path.read_text(encoding="utf-8").strip() or "1"
- exit_code = int(exit_code_raw)
-
- # Read the captured update output
- output = ""
- if output_path.exists():
- output = output_path.read_text(encoding="utf-8")
-
- # Resolve adapter
- platform = Platform(platform_str)
- adapter = self.adapters.get(platform)
-
- if not adapter and chat_id:
- # The update finished, but the target platform has not
- # reconnected yet (common right after the restart that
- # `hermes update` triggers). Treating "adapter missing" as a
- # definitive skip would delete the markers and silently lose the
- # completion notification — the user never learns whether the
- # update succeeded or timed out. Preserve the markers instead so
- # a later retry (the watcher poll loop, or the next gateway
- # startup) can deliver the result once the adapter is back.
- logger.info(
- "Update notification deferred: %s adapter not connected yet",
- platform_str,
- )
- cleanup = False
- active_pending_path = pending_path
- claimed_path.replace(pending_path)
- return False
-
- if adapter and chat_id:
- metadata = self._thread_metadata_for_target(
- platform,
- chat_id,
- thread_id,
- chat_type=chat_type,
- reply_to_message_id=message_id,
- adapter=adapter,
- )
- # Strip ANSI escape codes for clean display
- from tools.ansi_strip import strip_ansi
- output = strip_ansi(output).strip()
- if output:
- if len(output) > 3500:
- output = "…" + output[-3500:]
- if exit_code == 0:
- msg = f"✅ Hermes update finished.\n\n```\n{output}\n```"
- else:
- msg = f"❌ Hermes update failed.\n\n```\n{output}\n```"
- elif exit_code == 0:
- msg = "✅ Hermes update finished successfully."
- else:
- msg = "❌ Hermes update failed. Check the gateway logs or run `hermes update` manually for details."
- await adapter.send(
- chat_id,
- msg,
- metadata=_non_conversational_metadata(metadata, platform=platform),
- )
- logger.info(
- "Sent post-update notification to %s:%s (exit=%s)",
- platform_str,
- chat_id,
- exit_code,
- )
- except Exception as e:
- logger.warning("Post-update notification failed: %s", e)
- finally:
- if cleanup:
- active_pending_path.unlink(missing_ok=True)
- claimed_path.unlink(missing_ok=True)
- output_path.unlink(missing_ok=True)
- exit_code_path.unlink(missing_ok=True)
+ def _telegram_topic_help_text(self) -> str:
+ return (
+ "/topic — enable multi-session DM mode (one bot, many parallel chats)\n"
+ "\n"
+ "Usage:\n"
+ " /topic Enable topic mode, or show status if already on\n"
+ " /topic help Show this message\n"
+ " /topic off Disable topic mode and clear topic bindings\n"
+ " /topic <id> Inside a topic: restore a previous session by ID\n"
+ "\n"
+ "How it works:\n"
+ "1. Run /topic once in this DM — Hermes checks BotFather Threads\n"
+ " Settings are enabled and flips on multi-session mode.\n"
+ "2. Tap All Messages at the top of the bot and send any message.\n"
+ " Telegram creates a new topic for that message; each topic is\n"
+ " an independent Hermes session (fresh history, fresh context).\n"
+ "3. The root DM becomes a system lobby — send /topic, /status,\n"
+ " /help, /usage there. Normal prompts go in a topic.\n"
+ "4. /new inside a topic resets just that topic's session.\n"
+ "5. /topic <id> inside a topic restores an old session into it."
+ )
- return True
+ async def _disable_telegram_topic_mode_for_chat(self, source: SessionSource) -> str:
+ """Cleanly disable topic mode for a chat via /topic off."""
+ if not self._session_db:
+ from hermes_state import format_session_db_unavailable
+ return format_session_db_unavailable(prefix=t("gateway.shared.session_db_unavailable_prefix"))
+ chat_id = str(source.chat_id or "")
+ if not chat_id:
+ return "Could not determine chat ID."
+ # No-op if never enabled.
+ try:
+ currently_enabled = await self._session_db.is_telegram_topic_mode_enabled(
+ chat_id=chat_id,
+ user_id=str(source.user_id or ""),
+ )
+ except Exception:
+ currently_enabled = False
+ if not currently_enabled:
+ return "Multi-session topic mode is not currently enabled for this chat."
+ try:
+ await self._session_db.disable_telegram_topic_mode(chat_id=chat_id)
+ except Exception as exc:
+ logger.exception("Failed to disable Telegram topic mode")
+ return f"Failed to disable topic mode: {exc}"
+ # Reset per-chat debounce state so the user doesn't see a stale
+ # cooldown on the next activation.
+ for attr in ("_telegram_lobby_reminder_ts", "_telegram_capability_hint_ts"):
+ store = getattr(self, attr, None)
+ if isinstance(store, dict):
+ store.pop(chat_id, None)
+ return (
+ "Multi-session topic mode is now OFF for this chat.\n\n"
+ "Existing topics in Telegram aren't removed — they'll just stop "
+ "being gated as independent sessions. The root DM works as a "
+ "normal Hermes chat again. Run /topic to re-enable later."
+ )
- async def _send_restart_notification(self) -> Optional[tuple[str, str, Optional[str]]]:
- """Notify the chat that initiated /restart that the gateway is back."""
- notify_path = _hermes_home / ".restart_notify.json"
- if not notify_path.exists():
- return None
+ async def _telegram_topic_root_status_message(self, source: SessionSource) -> str:
+ lines = [
+ "Telegram multi-session topics are enabled.",
+ "",
+ "To create a new Hermes chat, open All Messages at the top of this "
+ "bot interface and send any message there. Telegram will create a "
+ "new topic for it.",
+ "",
+ ]
try:
- data = json.loads(notify_path.read_text(encoding="utf-8"))
- platform_str = data.get("platform")
- chat_id = data.get("chat_id")
- chat_type = data.get("chat_type")
- thread_id = data.get("thread_id")
- message_id = data.get("message_id")
+ sessions = await self._session_db.list_unlinked_telegram_sessions_for_user(
+ chat_id=str(source.chat_id),
+ user_id=str(source.user_id),
+ limit=10,
+ )
+ except Exception:
+ logger.debug("Failed to list unlinked Telegram sessions", exc_info=True)
+ sessions = []
+
+ if sessions:
+ lines.append("Previous unlinked sessions:")
+ for session in sessions:
+ session_id = str(session.get("id") or "")
+ title = str(session.get("title") or "Untitled session")
+ preview = str(session.get("preview") or "").strip()
+ line = f"- {title} — `{session_id}`"
+ if preview:
+ line += f" — {preview}"
+ lines.append(line)
+ lines.extend([
+ "",
+ "To restore one:",
+ "1. Create or open a topic. To create a new one, open All Messages and send any message there.",
+ "2. Send /topic <session-id> inside that topic.",
+ f"Example: Send /topic {sessions[0].get('id')} inside a topic.",
+ ])
+ else:
+ lines.extend([
+ "No previous unlinked Telegram sessions found.",
+ "",
+ "To restore a previous session later:",
+ "1. Create or open a topic. To create a new one, open All Messages and send any message there.",
+ "2. Send /topic <session-id> inside that topic.",
+ ])
+ return "\n".join(lines)
- if not platform_str or not chat_id:
- return None
+ async def _restore_telegram_topic_session(self, event: MessageEvent, raw_session_id: str) -> str:
+ """Restore an existing Telegram-owned Hermes session into this topic."""
+ source = event.source
+ session_id = await self._session_db.resolve_session_id(raw_session_id.strip())
+ if not session_id:
+ return f"Session not found: {raw_session_id.strip()}"
- platform = Platform(platform_str)
- transport = resolve_delivery_transport(platform, self.config, self.adapters)
- if transport is None:
- logger.debug(
- "Restart notification skipped: no live transport for %s",
- platform_str,
- )
- return None
+ session = await self._session_db.get_session(session_id)
+ if not session:
+ return f"Session not found: {raw_session_id.strip()}"
+ if str(session.get("source") or "") != "telegram":
+ return "That session is not a Telegram session and cannot be restored into this topic."
+ if str(session.get("user_id") or "") != str(source.user_id):
+ return "That session does not belong to this Telegram user."
- platform_cfg = self.config.platforms.get(platform)
- if platform_cfg is not None and not platform_cfg.gateway_restart_notification:
- logger.info(
- "Restart notification suppressed: %s has gateway_restart_notification=false",
- platform_str,
- )
- return None
+ linked = await self._session_db.is_telegram_session_linked_to_topic(session_id=session_id)
+ current_binding = await self._session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id),
+ thread_id=str(source.thread_id),
+ )
+ if linked:
+ if not current_binding or current_binding.get("session_id") != session_id:
+ return "That session is already linked to another Telegram topic."
- metadata = self._thread_metadata_for_target(
- platform,
- chat_id,
- thread_id,
- chat_type=chat_type,
- reply_to_message_id=message_id,
- adapter=transport.adapter,
- )
- if data.get("delivered_via_upstream_relay") is True:
- metadata = dict(metadata or {})
- if data.get("user_id"):
- metadata["user_id"] = str(data["user_id"])
- if data.get("scope_id"):
- metadata["scope_id"] = str(data["scope_id"])
- result = await transport.send(
- platform,
- str(chat_id),
- "♻ Gateway restarted successfully. Your session continues.",
- metadata=_non_conversational_metadata(metadata, platform=platform),
+ session_key = self._session_key_for_source(source)
+ try:
+ await self._session_db.bind_telegram_topic(
+ chat_id=str(source.chat_id),
+ thread_id=str(source.thread_id),
+ user_id=str(source.user_id),
+ session_key=session_key,
+ session_id=session_id,
+ managed_mode="restored",
)
- # adapter.send() catches provider errors (e.g. "Chat not found")
- # and returns SendResult(success=False) rather than raising, so
- # we must inspect the result before claiming success — otherwise
- # the log line is misleading and hides real delivery failures.
- if result is not None and getattr(result, "success", True) is False:
- logger.warning(
- "Restart notification to %s:%s was not delivered: %s",
- platform_str,
- chat_id,
- getattr(result, "error", "send returned success=False"),
- )
- return None
+ except ValueError as exc:
+ if "already linked" in str(exc):
+ return "That session is already linked to another Telegram topic."
+ raise
- logger.info(
- "Sent restart notification to %s:%s",
- platform_str,
- chat_id,
- )
- return str(platform_str), str(chat_id), str(thread_id) if thread_id else None
- except Exception as e:
- logger.warning("Restart notification failed: %s", e)
- return None
- finally:
- notify_path.unlink(missing_ok=True)
+ title = await self._session_db.get_session_title(session_id) or session_id
+ last_assistant = None
+ try:
+ for message in reversed(await self._session_db.get_messages(session_id)):
+ if message.get("role") == "assistant" and message.get("content"):
+ last_assistant = str(message.get("content"))
+ break
+ except Exception:
+ last_assistant = None
- async def _send_home_channel_startup_notifications(
- self,
- *,
- skip_targets: Optional[set[tuple[str, str, Optional[str]]]] = None,
- ) -> set[tuple[str, str, Optional[str]]]:
- """Notify configured home channels that the gateway is back online.
+ response = f"Session restored: {title}"
+ if last_assistant:
+ response += f"\n\nLast Hermes message:\n{last_assistant}"
+ return response
- The notification is best-effort and sent once per connected platform
- home channel. ``skip_targets`` lets startup avoid duplicate messages
- when a more specific restart notification is queued for the same chat.
- """
- delivered: set[tuple[str, str, Optional[str]]] = set()
- skipped = skip_targets or set()
- message = "♻️ Gateway online — Hermes is back and ready."
- for platform, platform_cfg in self.config.platforms.items():
- home = platform_cfg.home_channel
- if not home or not home.chat_id:
- continue
- transport = resolve_delivery_transport(platform, self.config, self.adapters)
- if transport is None:
- continue
- if not platform_cfg.gateway_restart_notification:
- logger.info(
- "Home-channel startup notification suppressed: %s has gateway_restart_notification=false",
- platform.value,
- )
- continue
- target = (platform.value, str(home.chat_id), str(home.thread_id) if home.thread_id else None)
- if target in skipped or target in delivered:
- continue
- try:
- metadata = self._thread_metadata_for_target(
- platform,
- home.chat_id,
- home.thread_id,
- adapter=transport.adapter,
- )
- if transport.is_relay:
- metadata = dict(metadata or {})
- if home.user_id:
- metadata["user_id"] = home.user_id
- if home.scope_id:
- metadata["scope_id"] = home.scope_id
- send_metadata = _non_conversational_metadata(metadata, platform=platform)
- if send_metadata is not None or transport.is_relay:
- result = await transport.send(
- platform,
- str(home.chat_id),
- message,
- metadata=send_metadata,
- )
- else:
- result = await transport.adapter.send(str(home.chat_id), message)
- if result is not None and getattr(result, "success", True) is False:
- logger.warning(
- "Home-channel startup notification failed for %s:%s: %s",
- platform.value,
- home.chat_id,
- getattr(result, "error", "send returned success=False"),
- )
- continue
- delivered.add(target)
- logger.info(
- "Sent home-channel startup notification to %s:%s",
- platform.value,
- home.chat_id,
- )
- except Exception as exc:
- logger.warning(
- "Home-channel startup notification failed for %s:%s: %s",
- platform.value,
- home.chat_id,
- exc,
- )
+ async def _execute_mcp_reload(self, event: MessageEvent) -> str:
+ """Actually disconnect, reconnect, and notify MCP tool changes.
- return delivered
+ Split out from ``_handle_reload_mcp_command`` so the confirmation
+ wrapper can invoke the same path whether the user confirmed via
+ button, text reply, or has the confirm gate disabled.
+ """
+ loop = asyncio.get_running_loop()
+ try:
+ from tools.mcp_tool import shutdown_mcp_servers, discover_mcp_tools, _servers, _lock
- def _set_session_env(self, context: SessionContext) -> list:
- """Set session context variables for the current async task.
+ # Capture old server names before shutdown
+ with _lock:
+ old_servers = set(_servers.keys())
- Uses ``contextvars`` instead of ``os.environ`` so that concurrent
- gateway messages cannot overwrite each other's session state.
+ # Read new config before shutting down, so we know what will be added/removed
+ # Shutdown existing connections
+ await loop.run_in_executor(None, shutdown_mcp_servers)
- Returns a list of reset tokens; pass them to ``_clear_session_env``
- in a ``finally`` block.
- """
- from gateway.session_context import set_session_vars
- # Propagate the adapter's async-delivery capability so async tools
- # (terminal notify_on_complete / watch_patterns, delegate_task
- # background=True) know whether this channel can wake a later turn.
- # Default True keeps CLI / unknown paths working; stateless adapters
- # (api_server) declare supports_async_delivery=False. Use getattr so
- # bare runners built via object.__new__ (tests) without self.adapters
- # don't blow up — they simply default to supported.
- _adapters = getattr(self, "adapters", None) or {}
- _adapter = _adapters.get(context.source.platform)
- _async_delivery = getattr(_adapter, "supports_async_delivery", True)
- return set_session_vars(
- platform=context.source.platform.value,
- chat_id=context.source.chat_id,
- chat_type=(
- str(context.source.chat_type) if context.source.chat_type else ""
- ),
- chat_name=context.source.chat_name or "",
- thread_id=str(context.source.thread_id) if context.source.thread_id else "",
- user_id=str(context.source.user_id) if context.source.user_id else "",
- user_name=str(context.source.user_name) if context.source.user_name else "",
- session_key=context.session_key,
- message_id=str(context.source.message_id) if context.source.message_id else "",
- profile=getattr(context.source, "profile", "") or "",
- async_delivery=_async_delivery,
- )
+ # Reconnect by discovering tools (reads config.yaml fresh)
+ new_tools = await loop.run_in_executor(None, discover_mcp_tools)
- def _clear_session_env(self, tokens: list) -> None:
- """Restore session context variables to their pre-handler values."""
- from gateway.session_context import clear_session_vars
- clear_session_vars(tokens)
+ # Compute what changed
+ with _lock:
+ connected_servers = set(_servers.keys())
- async def _run_in_executor_with_context(self, func, *args):
- """Run blocking work in the thread pool while preserving session contextvars."""
- loop = asyncio.get_running_loop()
- ctx = copy_context()
- return await loop.run_in_executor(
- self._get_executor(),
- ctx.run,
- func,
- *args,
- )
+ added = connected_servers - old_servers
+ removed = old_servers - connected_servers
+ reconnected = connected_servers & old_servers
+
+ lines = [t("gateway.reload_mcp.header")]
+ if reconnected:
+ lines.append(t("gateway.reload_mcp.reconnected", names=", ".join(sorted(reconnected))))
+ if added:
+ lines.append(t("gateway.reload_mcp.added", names=", ".join(sorted(added))))
+ if removed:
+ lines.append(t("gateway.reload_mcp.removed", names=", ".join(sorted(removed))))
+ if not connected_servers:
+ lines.append(t("gateway.reload_mcp.none_connected"))
+ else:
+ lines.append(t("gateway.reload_mcp.tools_available", tools=len(new_tools), servers=len(connected_servers)))
- def _get_executor(self) -> concurrent.futures.ThreadPoolExecutor:
- """Return the gateway-owned executor for blocking agent work."""
- lock = getattr(self, "_executor_lock", None)
- if lock is None:
- lock = threading.Lock()
- self._executor_lock = lock
+ # Refresh cached agents so existing sessions see new MCP tools on
+ # their next turn — without this, the user has to `/new` (which
+ # discards conversation history) to pick up tools from a server
+ # that was just added or reconnected. The user has already
+ # consented to the prompt-cache invalidation via the slash-confirm
+ # gate in _handle_reload_mcp_command before we reach this point.
+ try:
+ from tools.mcp_tool import refresh_agent_mcp_tools
+ _cache = getattr(self, "_agent_cache", None)
+ _cache_lock = getattr(self, "_agent_cache_lock", None)
+ if _cache_lock is not None and _cache:
+ with _cache_lock:
+ for _sess_key, _entry in list(_cache.items()):
+ try:
+ _agent = _entry[0] if isinstance(_entry, tuple) else _entry
+ except Exception:
+ continue
+ if _agent is None:
+ continue
+ # Preserve each cached agent's build-time toolset
+ # selection EXACTLY: a gateway session built with a
+ # restricted enabled_toolsets (e.g. ["safe"]) must
+ # NOT silently gain tools after a reload. This is the
+ # opposite of the interactive CLI/TUI /reload-mcp,
+ # which is a single user re-applying their own config
+ # edit; gateway agents are per-session and may be
+ # deliberately locked down. (Contract is asserted by
+ # test_reload_mcp_preserves_per_agent_toolset_overrides.)
+ refresh_agent_mcp_tools(_agent, quiet_mode=True)
+ except Exception as _exc:
+ logger.debug(
+ "Failed to update cached agent tools after MCP reload: %s",
+ _exc,
+ )
- with lock:
- if getattr(self, "_executor_closing", False):
- raise RuntimeError("Gateway is shutting down; executor unavailable")
- executor = getattr(self, "_executor", None)
- if executor is None or getattr(executor, "_shutdown", False):
- executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=10,
- thread_name_prefix="hermes-gateway",
+ # Inject a message at the END of the session history so the
+ # model knows tools changed on its next turn. Appended after
+ # all existing messages to preserve prompt-cache for the prefix.
+ change_parts = []
+ if added:
+ change_parts.append(f"Added servers: {', '.join(sorted(added))}")
+ if removed:
+ change_parts.append(f"Removed servers: {', '.join(sorted(removed))}")
+ if reconnected:
+ change_parts.append(f"Reconnected servers: {', '.join(sorted(reconnected))}")
+ tool_summary = f"{len(new_tools)} MCP tool(s) now available" if new_tools else "No MCP tools available"
+ change_detail = ". ".join(change_parts) + ". " if change_parts else ""
+ reload_msg = {
+ "role": "user",
+ "content": f"[IMPORTANT: MCP servers have been reloaded. {change_detail}{tool_summary}. The tool list for this conversation has been updated accordingly.]",
+ }
+ try:
+ session_entry = await self.async_session_store.get_or_create_session(event.source)
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id, reload_msg
)
- self._executor = executor
- return executor
+ except Exception:
+ pass # Best-effort; don't fail the reload over a transcript write
- def _shutdown_executor(self) -> None:
- """Stop the gateway-owned executor without touching the loop default."""
- lock = getattr(self, "_executor_lock", None)
- if lock is None:
- return
+ return "\n".join(lines)
- with lock:
- self._executor_closing = True
- executor = getattr(self, "_executor", None)
- self._executor = None
+ except Exception as e:
+ logger.warning("MCP reload failed: %s", e)
+ return t("gateway.reload_mcp.failed", error=e)
- if executor is None:
- return
- try:
- executor.shutdown(wait=False, cancel_futures=True)
- except TypeError:
- executor.shutdown(wait=False)
- def _decide_image_input_mode(
+ # ------------------------------------------------------------------
+ # Slash-command confirmation primitive (generic)
+ # ------------------------------------------------------------------
+ # Used by slash commands that have a non-destructive but expensive
+ # side effect worth an explicit user confirmation (currently only
+ # /reload-mcp, which invalidates the prompt cache). Two delivery
+ # paths:
+ # 1. Button UI — adapters that override ``send_slash_confirm``
+ # (Telegram, Discord, Slack, Matrix, Feishu) render three
+ # inline buttons. The adapter routes the button click back via
+ # ``tools.slash_confirm.resolve(session_key, confirm_id, choice)``.
+ # 2. Text fallback — adapters that don't override the hook get a
+ # plain text prompt. Users reply with /approve, /always, or
+ # /cancel; the early intercept in ``_handle_message`` matches
+ # those replies against ``tools.slash_confirm.get_pending()``.
+
+ async def _maybe_confirm_destructive_slash(
self,
*,
- source: Optional[SessionSource] = None,
- session_key: Optional[str] = None,
- user_config: Optional[dict] = None,
- provider: Optional[str] = None,
- model: Optional[str] = None,
- ) -> str:
- """Resolve image-input routing for the effective model this turn.
+ event: MessageEvent,
+ command: str,
+ title: str,
+ detail: str,
+ execute,
+ ) -> Union[str, "EphemeralReply", None]:
+ """Gate a destructive session slash command (/new, /reset, /undo).
- Returns ``"native"`` (attach pixels on the user turn) or ``"text"``
- (pre-analyze with vision_analyze and prepend the description). See
- agent/image_routing.py for the full decision table.
+ ``execute`` is an async callable ``execute() -> str | EphemeralReply``
+ that performs the destructive action. If the
+ ``approvals.destructive_slash_confirm`` config gate is off, ``execute``
+ runs immediately (returning its result). Otherwise this routes
+ through ``_request_slash_confirm`` — native yes/no buttons on
+ Telegram/Discord/Slack, text fallback elsewhere.
- Gateway sessions can have /model overrides that live outside
- config.yaml. Image preprocessing runs before AIAgent sets the
- auxiliary_client runtime globals, so resolve the same per-session
- runtime bundle the upcoming agent turn will use instead of consulting
- only the persisted default model.
+ Three-option resolution:
+
+ - ``once`` — run ``execute`` and return its result
+ - ``always`` — persist ``approvals.destructive_slash_confirm: false``,
+ then run ``execute``
+ - ``cancel`` — return a "cancelled" message; do not run ``execute``
"""
+ # Gate check.
+ confirm_required = True
try:
- from agent.image_routing import decide_image_input_mode
- from agent.auxiliary_client import _read_main_model, _read_main_provider
- from hermes_cli.config import load_config
+ cfg = self._read_user_config()
+ approvals = cfg.get("approvals") if isinstance(cfg, dict) else None
+ if isinstance(approvals, dict):
+ confirm_required = bool(approvals.get("destructive_slash_confirm", True))
+ except Exception:
+ pass
- cfg = user_config if isinstance(user_config, dict) else load_config()
- resolved_provider = (provider or "").strip()
- resolved_model = (model or "").strip()
- resolved_requested_provider = ""
+ if not confirm_required:
+ return await execute()
- needs_session_runtime = not resolved_provider or not resolved_model
- has_session_identity = source is not None or session_key
- if needs_session_runtime and has_session_identity:
+ session_key = self._session_key_for_source(event.source)
+
+ async def _on_confirm(choice: str):
+ if choice == "cancel":
+ return f"🟡 /{command} cancelled. Conversation unchanged."
+ if choice == "always":
try:
- turn_model, runtime_kwargs = self._resolve_session_agent_runtime(
- source=source,
- session_key=session_key,
- user_config=cfg,
- )
- if not resolved_model and isinstance(turn_model, str):
- resolved_model = turn_model.strip()
- runtime_provider = runtime_kwargs.get("provider") if isinstance(runtime_kwargs, dict) else None
- runtime_requested_provider = (
- runtime_kwargs.get("requested_provider")
- if isinstance(runtime_kwargs, dict)
- else None
+ from cli import save_config_value
+ save_config_value("approvals.destructive_slash_confirm", False)
+ logger.info(
+ "User opted out of destructive slash confirm (session=%s)",
+ session_key,
)
- if not resolved_provider and isinstance(runtime_provider, str):
- resolved_provider = runtime_provider.strip()
- if isinstance(runtime_requested_provider, str):
- resolved_requested_provider = runtime_requested_provider.strip()
except Exception as exc:
- logger.debug(
- "image_routing: session runtime resolution failed, falling back to config — %s",
- exc,
+ logger.warning(
+ "Failed to persist destructive_slash_confirm=false: %s", exc,
)
+ result = await execute()
+ if choice == "always":
+ note = (
+ "\n\nℹ️ Future /clear, /new, /reset, and /undo will run "
+ "without confirmation. Re-enable via "
+ "`approvals.destructive_slash_confirm: true` in config.yaml."
+ )
+ if isinstance(result, str):
+ return result + note
+ # EphemeralReply or other — leave untouched; the opt-out note
+ # would otherwise mangle structured replies. The persist itself
+ # already happened above; user gets the same UX next time.
+ return result
+ return result
- if not resolved_provider:
- resolved_provider = _read_main_provider()
- if not resolved_model:
- resolved_model = _read_main_model()
-
- return decide_image_input_mode(
- resolved_provider,
- resolved_model,
- cfg,
- requested_provider=resolved_requested_provider,
- )
- except Exception as exc:
- logger.debug("image_routing: decision failed, falling back to text — %s", exc)
- return "text"
-
- async def _enrich_message_with_vision(
- self,
- user_text: str,
- image_paths: List[str],
- ) -> str:
- """
- Auto-analyze user-attached images with the vision tool and prepend
- the descriptions to the message text.
+ _p = self._typed_command_prefix_for(event.source.platform)
+ prompt_message = (
+ f"⚠️ **Confirm /{command}**\n\n"
+ f"{detail}\n\n"
+ "Choose:\n"
+ "• **Approve Once** — proceed this time only\n"
+ "• **Always Approve** — proceed and silence this prompt permanently\n"
+ "• **Cancel** — keep current conversation\n\n"
+ f"_Text fallback: reply `{_p}approve`, `{_p}always`, or `{_p}cancel`._"
+ )
+ return await self._request_slash_confirm(
+ event=event,
+ command=command,
+ title=title,
+ message=prompt_message,
+ handler=_on_confirm,
+ )
- Each image is analyzed with a general-purpose prompt. The resulting
- description *and* the local cache path are injected so the model can:
- 1. Immediately understand what the user sent (no extra tool call).
- 2. Re-examine the image with vision_analyze if it needs more detail.
+ async def _request_slash_confirm(
+ self,
+ *,
+ event: MessageEvent,
+ command: str,
+ title: str,
+ message: str,
+ handler,
+ ) -> Optional[str]:
+ """Ask the user to confirm an expensive slash command.
- Args:
- user_text: The user's original caption / message text.
- image_paths: List of local file paths to cached images.
+ ``handler`` is an async callable ``handler(choice: str) -> str``
+ where ``choice`` is ``"once"``, ``"always"``, or ``"cancel"``.
+ The handler runs on the event loop when the user responds; its
+ return value is sent back as a gateway message.
- Returns:
- The enriched message string with vision descriptions prepended.
+ Returns a short acknowledgment string to send immediately (before
+ the user's response). If buttons rendered successfully the ack
+ is ``None`` (buttons are self-explanatory); if we fell back to
+ text the message itself IS the ack.
"""
- from tools.vision_tools import vision_analyze_tool
- from agent.memory_manager import sanitize_context
+ from tools import slash_confirm as _slash_confirm_mod
- analysis_prompt = (
- "Describe everything visible in this image in thorough detail. "
- "Include any text, code, data, objects, people, layout, colors, "
- "and any other notable visual information."
- )
+ source = event.source
+ session_key = self._session_key_for_source(source)
+ # Bare-runner test harnesses (object.__new__(GatewayRunner)) skip
+ # __init__ and don't have the counter attribute — fall back to a
+ # local counter so tests don't AttributeError. Real runs always
+ # have the instance attribute.
+ counter = getattr(self, "_slash_confirm_counter", None)
+ if counter is None:
+ import itertools as _itertools
+ counter = _itertools.count(1)
+ self._slash_confirm_counter = counter
+ confirm_id = f"{next(counter)}"
- enriched_parts = []
- for path in image_paths:
+ # Register the pending confirm FIRST so a super-fast button click
+ # cannot race the send_slash_confirm return.
+ _slash_confirm_mod.register(session_key, confirm_id, command, handler)
+
+ adapter = self._adapter_for_source(source)
+ metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
+
+ used_buttons = False
+ if adapter is not None:
try:
- logger.debug("Auto-analyzing user image: %s", path)
- result_json = await vision_analyze_tool(
- image_url=path,
- user_prompt=analysis_prompt,
+ button_result = await adapter.send_slash_confirm(
+ chat_id=source.chat_id,
+ title=title,
+ message=message,
+ session_key=session_key,
+ confirm_id=confirm_id,
+ metadata=metadata,
)
- result = json.loads(result_json)
- if result.get("success"):
- description = result.get("analysis", "")
- description = sanitize_context(description)
- enriched_parts.append(
- f"[The user sent an image~ Here's what I can see:\n{description}]\n"
- f"[If you need a closer look, use vision_analyze with "
- f"image_url: {path} ~]"
- )
- else:
- enriched_parts.append(
- "[The user sent an image but I couldn't quite see it "
- "this time (>_<) You can try looking at it yourself "
- f"with vision_analyze using image_url: {path}]"
- )
- except Exception as e:
- logger.error("Vision auto-analysis error: %s", e)
- enriched_parts.append(
- f"[The user sent an image but something went wrong when I "
- f"tried to look at it~ You can try examining it yourself "
- f"with vision_analyze using image_url: {path}]"
+ if button_result and getattr(button_result, "success", False):
+ used_buttons = True
+ except Exception as exc:
+ logger.debug(
+ "send_slash_confirm failed for %s on %s: %s",
+ command, source.platform, exc,
)
- # Combine: vision descriptions first, then the user's original text
- if enriched_parts:
- prefix = "\n\n".join(enriched_parts)
- if user_text:
- return f"{prefix}\n\n{user_text}"
- return prefix
- return user_text
+ if used_buttons:
+ # Buttons rendered — no redundant text ack.
+ return None
+ # Text fallback — return the prompt message as the direct reply.
+ return message
- async def _enrich_message_with_transcription(
- self,
- user_text: str,
- audio_paths: List[str],
- ) -> tuple[str, List[str]]:
+ def _read_user_config(self) -> Dict[str, Any]:
+ """Read the user's raw config.yaml (cached) for gate lookups.
+
+ Used by slash-confirm gates that must reflect on-disk state changes
+ (e.g. a prior "Always Approve" click) without a gateway restart.
"""
- Auto-transcribe user voice/audio messages using the configured STT provider
- and prepend the transcript to the message text.
+ try:
+ from hermes_cli.config import load_config
+ cfg = load_config()
+ return cfg if isinstance(cfg, dict) else {}
+ except Exception:
+ return {}
- Args:
- user_text: The user's original caption / message text.
- audio_paths: List of local file paths to cached audio files.
+ def _thread_metadata_for_source(
+ self,
+ source,
+ reply_to_message_id: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ """Build the metadata dict platforms need for thread-aware replies."""
+ metadata = self._thread_metadata_for_target(
+ getattr(source, "platform", None),
+ getattr(source, "chat_id", None),
+ getattr(source, "thread_id", None),
+ chat_type=getattr(source, "chat_type", None),
+ reply_to_message_id=reply_to_message_id or getattr(source, "message_id", None),
+ )
+ if getattr(source, "platform", None) == Platform.SLACK:
+ team_id = getattr(source, "scope_id", None)
+ if team_id:
+ metadata = dict(metadata or {})
+ metadata["slack_team_id"] = str(team_id)
+ return metadata
- Returns:
- A tuple of ``(enriched_text, successful_transcripts)``:
- - ``enriched_text``: the message string with transcription wrappers
- prepended (same as before).
- - ``successful_transcripts``: the raw transcript strings for audio
- clips that were successfully transcribed, in input order. Empty
- list if every clip failed or STT is disabled. Callers can use
- this to echo transcripts back to the user before the agent loop.
- """
- seen = set()
- audio_paths = [p for p in audio_paths if p not in seen and not seen.add(p)]
- if not getattr(self.config, "stt_enabled", True):
- notes = []
- for path in audio_paths:
- abs_path = os.path.abspath(path)
- duration_str = await _probe_audio_duration(abs_path)
- if duration_str:
- notes.append(
- f"[The user sent a voice message: {abs_path} (duration: {duration_str})]"
- )
+ def _thread_metadata_for_target(
+ self,
+ platform: Optional[Platform],
+ chat_id: Optional[str],
+ thread_id: Optional[str],
+ *,
+ chat_type: Optional[str] = None,
+ reply_to_message_id: Optional[str] = None,
+ adapter: Optional[Any] = None,
+ ) -> Optional[Dict[str, Any]]:
+ """Build thread metadata for synthetic sends that only have routing state."""
+ if thread_id is None:
+ return None
+ metadata: Dict[str, Any] = {"thread_id": thread_id}
+ if self._is_telegram_dm_topic_target(
+ platform,
+ chat_id,
+ thread_id,
+ chat_type=chat_type,
+ adapter=adapter,
+ ):
+ metadata["telegram_dm_topic_reply_fallback"] = True
+ # Telegram DM topic lanes need direct_messages_topic_id in metadata
+ # so synthetic/queued messages (goal continuations, status notices)
+ # route to the correct topic even when reply anchor is unavailable.
+ tid = str(thread_id)
+ if tid and tid not in {"", "1"}:
+ metadata["direct_messages_topic_id"] = tid
+ if reply_to_message_id is not None:
+ metadata["telegram_reply_to_message_id"] = str(reply_to_message_id)
+ if platform == Platform.SLACK and reply_to_message_id is not None:
+ # Slack's reply_in_thread=false path uses message_id to distinguish
+ # real existing threads from synthetic top-level session keys.
+ metadata["message_id"] = str(reply_to_message_id)
+ return metadata
+
+ @staticmethod
+ def _is_telegram_dm_topic_target(
+ platform: Optional[Platform],
+ chat_id: Optional[str],
+ thread_id: Optional[str],
+ *,
+ chat_type: Optional[str] = None,
+ adapter: Optional[Any] = None,
+ ) -> bool:
+ """Return True when a target is a Telegram private DM topic lane."""
+ if platform != Platform.TELEGRAM or thread_id is None:
+ return False
+ if chat_type == "dm":
+ return True
+ # Inspect operator-declared DM topics via the adapter's lookup. Resolve
+ # the method on the CLASS, not the instance: getattr() on a MagicMock
+ # auto-creates a callable child for any attribute, so an instance-level
+ # lookup would report a DM topic for every test double. Only a
+ # dict-shaped return counts as an operator-declared topic — a bare
+ # MagicMock or other sentinel must not. Mirrors the guard in
+ # _rename_telegram_topic_for_session_title.
+ if adapter is not None and chat_id:
+ get_dm_topic_info = getattr(type(adapter), "_get_dm_topic_info", None)
+ if callable(get_dm_topic_info):
+ try:
+ topic_info = get_dm_topic_info(adapter, str(chat_id), str(thread_id))
+ except Exception:
+ logger.debug("Failed to inspect Telegram DM topic metadata", exc_info=True)
else:
- notes.append(f"[The user sent a voice message: {abs_path}]")
- if not notes:
- return user_text, []
- prefix = "\n\n".join(notes)
- _placeholder = "(The user sent a message with no text content)"
- if user_text and user_text.strip() == _placeholder:
- return prefix, []
- if user_text:
- return f"{prefix}\n\n{user_text}", []
- return prefix, []
+ return isinstance(topic_info, dict)
+ return False
+
+ @staticmethod
+ def _reply_anchor_for_event(event: MessageEvent) -> Optional[str]:
+ """Return the platform-specific reply anchor for GatewayRunner sends."""
+ return _reply_anchor_for_event(event)
+
+
+ # ------------------------------------------------------------------
+ # /approve & /deny — explicit dangerous-command approval
+ # ------------------------------------------------------------------
+
+ _APPROVAL_TIMEOUT_SECONDS = 300 # 5 minutes
+
+
+
+ # Built-in messaging platforms where the ``/update`` command is allowed.
+ # ACP, API server, and webhooks are programmatic interfaces that should
+ # not trigger system updates. Plugin-migrated platforms (discord,
+ # mattermost, teams, irc, line, …) are NOT listed here — they declare
+ # ``allow_update_command=True`` on their ``PlatformEntry`` and are
+ # honored via the registry fallback at ``_handle_update_command`` below.
+ _UPDATE_ALLOWED_PLATFORMS = frozenset({
+ Platform.TELEGRAM, Platform.SLACK, Platform.WHATSAPP,
+ Platform.SIGNAL, Platform.MATRIX,
+ Platform.EMAIL, Platform.SMS, Platform.DINGTALK,
+ Platform.FEISHU, Platform.WECOM, Platform.WECOM_CALLBACK, Platform.WEIXIN, Platform.BLUEBUBBLES, Platform.QQBOT, Platform.LOCAL,
+ })
+
+
+
+ def _schedule_update_notification_watch(self) -> None:
+ """Ensure a background task is watching for update completion."""
+ existing_task = getattr(self, "_update_notification_task", None)
+ if existing_task and not existing_task.done():
+ return
try:
- from tools.transcription_tools import (
- transcribe_audio,
- transcribe_audio_local_fallback,
+ self._update_notification_task = asyncio.create_task(
+ self._watch_update_progress()
)
- except ModuleNotFoundError as e:
- logger.error("Transcription module unavailable: %s", e)
- unavailable_note = "[voice message could not be transcribed]"
- _placeholder = "(The user sent a message with no text content)"
- if user_text and user_text.strip() == _placeholder:
- return unavailable_note, []
- if user_text:
- return f"{unavailable_note}\n\n{user_text}", []
- return unavailable_note, []
+ except RuntimeError:
+ logger.debug("Skipping update notification watcher: no running event loop")
- enriched_parts = []
- successful_transcripts: List[str] = []
- for path in audio_paths:
- try:
- logger.debug("Transcribing user voice: %s", path)
- result = await asyncio.to_thread(transcribe_audio, path)
- if not result.get("success"):
- fallback = await asyncio.to_thread(
- transcribe_audio_local_fallback,
- path,
- )
- if fallback.get("success"):
- logger.info(
- "Configured STT failed for %s; recovered with local STT",
- path,
- )
- result = fallback
- if result["success"]:
- transcript = result["transcript"]
- # Speech-to-text can return success=True with an empty or
- # whitespace-only transcript on silence, cut-off, or
- # inaudible audio. Emitting empty quotes ('""') makes the
- # agent reply to nothing and can loop, so that case gets a
- # clear sentinel note instead (#41603).
- if not (transcript or "").strip():
- enriched_parts.append(
- "[The user sent a voice message but it came through "
- "empty or inaudible — speech-to-text returned no "
- "words. Do not guess at the content; ask the user "
- "to resend or type it out.]"
+ async def _watch_update_progress(
+ self,
+ poll_interval: float = 2.0,
+ stream_interval: float = 4.0,
+ timeout: float = 1800.0,
+ ) -> None:
+ """Watch ``hermes update --gateway``, streaming output + forwarding prompts.
+
+ Polls ``.update_output.txt`` for new content and sends chunks to the
+ user periodically. Detects ``.update_prompt.json`` (written by the
+ update process when it needs user input) and forwards the prompt to
+ the messenger. The user's next message is intercepted by
+ ``_handle_message`` and written to ``.update_response``.
+ """
+ pending_path = _hermes_home / ".update_pending.json"
+ claimed_path = _hermes_home / ".update_pending.claimed.json"
+ output_path = _hermes_home / ".update_output.txt"
+ exit_code_path = _hermes_home / ".update_exit_code"
+ prompt_path = _hermes_home / ".update_prompt.json"
+
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout
+
+ # Resolve the adapter and chat_id for sending messages
+ adapter = None
+ chat_id = None
+ session_key = None
+ metadata = None
+ for path in (claimed_path, pending_path):
+ if path.exists():
+ try:
+ pending = json.loads(path.read_text(encoding="utf-8"))
+ platform_str = pending.get("platform")
+ chat_id = pending.get("chat_id")
+ chat_type = pending.get("chat_type")
+ session_key = pending.get("session_key")
+ thread_id = pending.get("thread_id")
+ message_id = pending.get("message_id")
+ if platform_str and chat_id:
+ platform = Platform(platform_str)
+ adapter = self.adapters.get(platform)
+ metadata = self._thread_metadata_for_target(
+ platform,
+ chat_id,
+ thread_id,
+ chat_type=chat_type,
+ reply_to_message_id=message_id,
+ adapter=adapter,
)
- continue
- successful_transcripts.append(transcript)
- # Pass the transcript through as a plain quoted line. The
- # earlier wording ("The user sent a voice message~ Here's
- # what they said: ...") read as a meta-instruction and made
- # the LLM volunteer commentary about voice mode rather than
- # reply to the content.
- enriched_parts.append(f'"{transcript}"')
- else:
- error = result.get("error", "unknown error")
- # All failure branches: a single, minimal, neutral marker.
- # Do NOT mention "no STT provider configured", "setup
- # instructions", or the "hermes-agent-setup" skill, and do
- # NOT claim a direct message was sent — those phrases get
- # persisted in conversation history and poison every later
- # turn, so the model keeps volunteering STT-setup advice
- # even after transcription starts working. The cause is
- # logged for operator diagnosis but kept out of the
- # LLM-visible prompt.
- logger.info("Voice transcription failed for %s: %s", path, error)
- from tools.credential_files import to_agent_visible_cache_path
+ # Fallback session key if not stored (old pending files)
+ if not session_key:
+ session_key = f"{platform_str}:{chat_id}"
+ break
+ except Exception:
+ pass
- agent_path = to_agent_visible_cache_path(os.path.abspath(path))
- enriched_parts.append(
- "[voice message could not be transcribed automatically; "
- f"the audio is available at: {agent_path}]"
- )
- except Exception as e:
- logger.error("Transcription error: %s", e)
- from tools.credential_files import to_agent_visible_cache_path
+ if not adapter or not chat_id:
+ logger.warning("Update watcher: cannot resolve adapter/chat_id, falling back to completion-only")
+ # Fall back to completion-only: wait for the exit code and send the
+ # final notification. _send_update_notification re-resolves the
+ # adapter on every call, so when the target platform is still
+ # reconnecting it returns False and keeps the markers. Keep polling
+ # until it actually delivers (returns True) instead of giving up
+ # after the first completion check — otherwise a platform that
+ # reconnects a few seconds after completion never gets notified.
+ while (pending_path.exists() or claimed_path.exists()) and loop.time() < deadline:
+ if exit_code_path.exists() and await self._send_update_notification():
+ return
+ await asyncio.sleep(poll_interval)
+ if (pending_path.exists() or claimed_path.exists()) and not exit_code_path.exists():
+ exit_code_path.write_text("124", encoding="utf-8")
+ await self._send_update_notification()
+ return
- agent_path = to_agent_visible_cache_path(os.path.abspath(path))
- enriched_parts.append(
- "[voice message could not be transcribed automatically; "
- f"the audio is available at: {agent_path}]"
- )
+ def _strip_ansi(text: str) -> str:
+ from tools.ansi_strip import strip_ansi
+ return strip_ansi(text)
- if enriched_parts:
- prefix = "\n\n".join(enriched_parts)
- # Strip the empty-content placeholder from the Discord adapter
- # when we successfully transcribed the audio — it's redundant.
- _placeholder = "(The user sent a message with no text content)"
- if user_text and user_text.strip() == _placeholder:
- return prefix, successful_transcripts
- if user_text:
- return f"{prefix}\n\n{user_text}", successful_transcripts
- return prefix, successful_transcripts
- return user_text, successful_transcripts
+ bytes_sent = 0
+ last_stream_time = loop.time()
+ buffer = ""
- def _pending_event_audio_paths(self, event) -> List[str]:
- """Return STT-eligible paths from a pending voice message."""
- audio_paths: List[str] = []
- media_urls = getattr(event, "media_urls", None) or []
- for i, path in enumerate(media_urls):
- if _event_media_is_stt_input(event, i):
- audio_paths.append(path)
- return audio_paths
+ async def _flush_buffer() -> None:
+ """Send buffered output to the user."""
+ nonlocal buffer, last_stream_time
+ if not buffer.strip():
+ buffer = ""
+ return
+ # Chunk to fit message limits (Telegram: 4096, others: generous)
+ clean = _strip_ansi(buffer).strip()
+ buffer = ""
+ last_stream_time = loop.time()
+ if not clean:
+ return
+ # Split into chunks if too long
+ max_chunk = 3500
+ chunks = [clean[i:i + max_chunk] for i in range(0, len(clean), max_chunk)]
+ for chunk in chunks:
+ try:
+ await adapter.send(
+ chat_id,
+ f"```\n{chunk}\n```",
+ metadata=_non_conversational_metadata(metadata, platform=platform),
+ )
+ except Exception as e:
+ logger.debug("Update stream send failed: %s", e)
+
+ while loop.time() < deadline:
+ # Check for completion
+ if exit_code_path.exists():
+ # Read any remaining output
+ if output_path.exists():
+ try:
+ content = output_path.read_text(encoding="utf-8")
+ if len(content) > bytes_sent:
+ buffer += content[bytes_sent:]
+ bytes_sent = len(content)
+ except OSError:
+ pass
+ await _flush_buffer()
+
+ # Send final status
+ try:
+ exit_code_raw = exit_code_path.read_text(encoding="utf-8").strip() or "1"
+ exit_code = int(exit_code_raw)
+ if exit_code == 0:
+ await adapter.send(
+ chat_id,
+ "✅ Hermes update finished.",
+ metadata=_non_conversational_metadata(metadata, platform=platform),
+ )
+ else:
+ await adapter.send(
+ chat_id,
+ "❌ Hermes update failed (exit code {}).".format(exit_code),
+ metadata=_non_conversational_metadata(metadata, platform=platform),
+ )
+ logger.info("Update finished (exit=%s), notified %s", exit_code, session_key)
+ except Exception as e:
+ logger.warning("Update final notification failed: %s", e)
- async def _transcribe_pending_audio_event_once(
- self,
- event,
- user_text: Optional[str] = None,
- ) -> tuple[str | None, List[str]]:
- """Transcribe a pending audio event once and cache the result on the event.
+ # Cleanup
+ for p in (pending_path, claimed_path, output_path,
+ exit_code_path, prompt_path):
+ p.unlink(missing_ok=True)
+ (_hermes_home / ".update_response").unlink(missing_ok=True)
+ _up_done = self._peek_session_state(session_key)
+ if _up_done is not None:
+ _up_done.persistent.update_prompt_pending = False
+ return
- Voice follow-ups can be inspected first by the interrupt monitor and
- later consumed by the pending-drain path. Both need the same transcript,
- but only one STT call and one transcript echo should happen for the
- platform message.
- """
- if hasattr(event, "_gateway_pending_stt_text"):
- cached_text = getattr(event, "_gateway_pending_stt_text")
- cached_transcripts = getattr(event, "_gateway_pending_stt_transcripts", []) or []
- return cached_text, list(cached_transcripts)
+ # Check for new output
+ if output_path.exists():
+ try:
+ content = output_path.read_text(encoding="utf-8")
+ if len(content) > bytes_sent:
+ buffer += content[bytes_sent:]
+ bytes_sent = len(content)
+ except OSError:
+ pass
- audio_paths = self._pending_event_audio_paths(event)
- if not audio_paths:
- return user_text if user_text is not None else (getattr(event, "text", None) or None), []
+ # Flush buffer periodically
+ if buffer.strip() and (loop.time() - last_stream_time) >= stream_interval:
+ await _flush_buffer()
- text = user_text if user_text is not None else (getattr(event, "text", "") or "")
- enriched_text, successful_transcripts = await self._enrich_message_with_transcription(
- text,
- audio_paths,
- )
- setattr(event, "_gateway_pending_stt_text", enriched_text)
- setattr(event, "_gateway_pending_stt_transcripts", list(successful_transcripts))
- return enriched_text, successful_transcripts
+ # Check for prompts — only forward if we haven't already sent
+ # one that's still awaiting a response. Without this guard the
+ # watcher would re-read the same .update_prompt.json every poll
+ # cycle and spam the user with duplicate prompt messages.
+ _up_pending_state = (
+ self._peek_session_state(session_key) if session_key else None
+ )
+ if (prompt_path.exists() and session_key
+ and not (
+ _up_pending_state is not None
+ and _up_pending_state.persistent.update_prompt_pending
+ )):
+ try:
+ prompt_data = json.loads(prompt_path.read_text(encoding="utf-8"))
+ prompt_text = prompt_data.get("prompt", "")
+ default = prompt_data.get("default", "")
+ if prompt_text:
+ # Flush any buffered output first so the user sees
+ # context before the prompt
+ await _flush_buffer()
+ # Try platform-native buttons first (Discord, Telegram)
+ sent_buttons = False
+ if getattr(type(adapter), "send_update_prompt", None) is not None:
+ try:
+ await adapter.send_update_prompt(
+ chat_id=chat_id,
+ prompt=prompt_text,
+ default=default,
+ session_key=session_key,
+ metadata=_non_conversational_metadata(metadata, platform=platform),
+ )
+ sent_buttons = True
+ except Exception as btn_err:
+ logger.debug("Button-based update prompt failed: %s", btn_err)
+ if not sent_buttons:
+ default_hint = f" (default: {default})" if default else ""
+ _p = getattr(adapter, "typed_command_prefix", "/")
+ await adapter.send(
+ chat_id,
+ f"⚕ **Update needs your input:**\n\n"
+ f"{prompt_text}{default_hint}\n\n"
+ f"Reply `{_p}approve` (yes) or `{_p}deny` (no), "
+ f"or type your answer directly.",
+ metadata=_non_conversational_metadata(metadata, platform=platform),
+ )
+ # Keep the prompt marker on disk until the user
+ # answers. If the gateway restarts mid-prompt, the
+ # next watcher can recover by re-forwarding it from
+ # disk. Duplicate sends in the same process are
+ # still suppressed by _update_prompt_pending.
+ self._session_state(
+ session_key
+ ).persistent.update_prompt_pending = True
+ # .update_response to continue — it doesn't re-check
+ logger.info("Forwarded update prompt to %s: %s", session_key, prompt_text[:80])
+ except (json.JSONDecodeError, OSError) as e:
+ logger.debug("Failed to read update prompt: %s", e)
- async def _echo_pending_stt_transcripts_once(
- self,
- event,
- adapter,
- source,
- transcripts: List[str],
- *,
- metadata=None,
- log_context: str = "Transcript",
- ) -> None:
- """Echo pending-event STT transcripts to the chat at most once.
+ await asyncio.sleep(poll_interval)
- The already-echoed transcripts are tracked as a COUNT rather than a
- single boolean. ``merge_pending_message_event`` can append a second
- voice note to an event whose first transcript was already echoed and
- invalidates the transcription cache; the re-run transcription then
- returns the earlier transcripts as a prefix of the new list, so
- echoing only the unsent tail suppresses the repeat while still
- surfacing the newly merged note. A count rather than a set of seen
- values because two separate notes that transcribe identically are two
- distinct deliveries and both must be echoed.
- """
- if (
- not transcripts
- or not self._should_echo_stt_transcripts()
- or adapter is None
- ):
- return
- already_echoed = int(getattr(event, "_gateway_pending_stt_echoed", 0) or 0)
- unsent = transcripts[already_echoed:]
- setattr(event, "_gateway_pending_stt_echoed", already_echoed + len(unsent))
- for tx in unsent:
+ # Timeout
+ if not exit_code_path.exists():
+ logger.warning("Update watcher timed out after %.0fs", timeout)
+ exit_code_path.write_text("124", encoding="utf-8")
+ await _flush_buffer()
try:
await adapter.send(
- source.chat_id,
- f'🎙️ "{tx}"',
- metadata=metadata,
+ chat_id,
+ "❌ Hermes update timed out after 30 minutes.",
+ metadata=_non_conversational_metadata(metadata, platform=platform),
)
- except Exception as echo_exc:
- logger.debug("%s echo failed (non-fatal): %s", log_context, echo_exc)
+ except Exception:
+ pass
+ for p in (pending_path, claimed_path, output_path,
+ exit_code_path, prompt_path):
+ p.unlink(missing_ok=True)
+ (_hermes_home / ".update_response").unlink(missing_ok=True)
+ _up_timeout_state = self._peek_session_state(session_key)
+ if _up_timeout_state is not None:
+ _up_timeout_state.persistent.update_prompt_pending = False
- async def _transcribe_and_echo_pending_voice(
- self,
- event,
- adapter,
- source,
- text: str,
- *,
- log_context: str,
- metadata=_UNSET,
- ) -> tuple[str, List[str]]:
- """Transcribe a pending voice event and echo transcripts once.
+ async def _send_update_notification(self) -> bool:
+ """If an update finished, notify the user.
- Unified helper for all interrupt/monitor/backup/drain paths that need
- to transcribe a pending voice event and echo the transcript to chat.
- Returns ``(enriched_text, transcripts)`` so the caller can feed the
- enriched text into ``agent.interrupt()`` or the pending-drain flow.
+ Returns False when the update is still running so a caller can retry
+ later. Returns True after a definitive send/skip decision.
- If the event has no STT-eligible media, returns ``(text, [])`` unchanged.
- The caller is responsible for the ``_build_media_placeholder`` fallback
- when ``text`` is empty and the event has non-audio media.
+ This is the legacy notification path used when the streaming watcher
+ cannot resolve the adapter (e.g. after a gateway restart where the
+ platform hasn't reconnected yet).
"""
- if not self._pending_event_audio_paths(event):
- return text, []
+ pending_path = _hermes_home / ".update_pending.json"
+ claimed_path = _hermes_home / ".update_pending.claimed.json"
+ output_path = _hermes_home / ".update_output.txt"
+ exit_code_path = _hermes_home / ".update_exit_code"
+
+ if not pending_path.exists() and not claimed_path.exists():
+ return False
+
+ cleanup = True
+ active_pending_path = claimed_path
try:
- enriched_text, transcripts = await self._transcribe_pending_audio_event_once(
- event,
- text,
- )
- echo_meta = self._thread_metadata_for_source(
- source,
- self._reply_anchor_for_event(event),
- ) if metadata is _UNSET else metadata
- await self._echo_pending_stt_transcripts_once(
- event,
- adapter,
- source,
- transcripts,
- metadata=echo_meta,
- log_context=log_context,
- )
- return enriched_text or text, transcripts
- except Exception as trans_exc:
- logger.warning("%s transcription failed: %s", log_context, trans_exc)
- return text, []
+ if pending_path.exists():
+ try:
+ pending_path.replace(claimed_path)
+ except FileNotFoundError:
+ if not claimed_path.exists():
+ return True
+ elif not claimed_path.exists():
+ return True
- def _build_process_event_source(self, evt: dict):
- """Resolve the canonical source for a synthetic background-process event.
+ pending = json.loads(claimed_path.read_text(encoding="utf-8"))
+ platform_str = pending.get("platform")
+ chat_id = pending.get("chat_id")
+ chat_type = pending.get("chat_type")
+ thread_id = pending.get("thread_id")
+ message_id = pending.get("message_id")
- Prefer the persisted session-store origin for the event's session key.
- Falling back to the currently active foreground event is what causes
- cross-topic bleed, so don't do that.
- """
- from gateway.session import SessionSource
+ if not exit_code_path.exists():
+ logger.info("Update notification deferred: update still running")
+ cleanup = False
+ active_pending_path = pending_path
+ claimed_path.replace(pending_path)
+ return False
- session_key = str(evt.get("session_key") or "").strip()
- derived_platform = ""
- derived_chat_type = ""
- derived_chat_id = ""
+ exit_code_raw = exit_code_path.read_text(encoding="utf-8").strip() or "1"
+ exit_code = int(exit_code_raw)
+
+ # Read the captured update output
+ output = ""
+ if output_path.exists():
+ output = output_path.read_text(encoding="utf-8")
- if session_key:
- try:
- self.session_store._ensure_loaded()
- entry = self.session_store._entries.get(session_key)
- if entry and getattr(entry, "origin", None):
- return entry.origin
- except Exception as exc:
- logger.debug(
- "Synthetic process-event session-store lookup failed for %s: %s",
- session_key,
- exc,
+ # Resolve adapter
+ platform = Platform(platform_str)
+ adapter = self.adapters.get(platform)
+
+ if not adapter and chat_id:
+ # The update finished, but the target platform has not
+ # reconnected yet (common right after the restart that
+ # `hermes update` triggers). Treating "adapter missing" as a
+ # definitive skip would delete the markers and silently lose the
+ # completion notification — the user never learns whether the
+ # update succeeded or timed out. Preserve the markers instead so
+ # a later retry (the watcher poll loop, or the next gateway
+ # startup) can deliver the result once the adapter is back.
+ logger.info(
+ "Update notification deferred: %s adapter not connected yet",
+ platform_str,
)
+ cleanup = False
+ active_pending_path = pending_path
+ claimed_path.replace(pending_path)
+ return False
- cached_source = self._get_cached_session_source(session_key)
- if cached_source is not None:
- return cached_source
+ if adapter and chat_id:
+ metadata = self._thread_metadata_for_target(
+ platform,
+ chat_id,
+ thread_id,
+ chat_type=chat_type,
+ reply_to_message_id=message_id,
+ adapter=adapter,
+ )
+ # Strip ANSI escape codes for clean display
+ from tools.ansi_strip import strip_ansi
+ output = strip_ansi(output).strip()
+ if output:
+ if len(output) > 3500:
+ output = "…" + output[-3500:]
+ if exit_code == 0:
+ msg = f"✅ Hermes update finished.\n\n```\n{output}\n```"
+ else:
+ msg = f"❌ Hermes update failed.\n\n```\n{output}\n```"
+ elif exit_code == 0:
+ msg = "✅ Hermes update finished successfully."
+ else:
+ msg = "❌ Hermes update failed. Check the gateway logs or run `hermes update` manually for details."
+ await adapter.send(
+ chat_id,
+ msg,
+ metadata=_non_conversational_metadata(metadata, platform=platform),
+ )
+ logger.info(
+ "Sent post-update notification to %s:%s (exit=%s)",
+ platform_str,
+ chat_id,
+ exit_code,
+ )
+ except Exception as e:
+ logger.warning("Post-update notification failed: %s", e)
+ finally:
+ if cleanup:
+ active_pending_path.unlink(missing_ok=True)
+ claimed_path.unlink(missing_ok=True)
+ output_path.unlink(missing_ok=True)
+ exit_code_path.unlink(missing_ok=True)
- _parsed = _parse_session_key(session_key)
- if _parsed:
- derived_platform = _parsed["platform"]
- derived_chat_type = _parsed["chat_type"]
- derived_chat_id = _parsed["chat_id"]
+ return True
- platform_name = str(evt.get("platform") or derived_platform or "").strip().lower()
- chat_type = str(evt.get("chat_type") or derived_chat_type or "").strip().lower()
- chat_id = str(evt.get("chat_id") or derived_chat_id or "").strip()
- if not platform_name or not chat_type or not chat_id:
- logger.warning(
- "Synthetic event source unresolvable: "
- "session_key=%r platform=%r chat_type=%r chat_id=%r "
- "evt_type=%s",
- session_key, platform_name, chat_type, chat_id,
- evt.get("type", "?"),
- )
+ async def _send_restart_notification(self) -> Optional[tuple[str, str, Optional[str]]]:
+ """Notify the chat that initiated /restart that the gateway is back."""
+ notify_path = _hermes_home / ".restart_notify.json"
+ if not notify_path.exists():
return None
try:
- platform = Platform(platform_name)
- # Reject arbitrary strings that create dynamic pseudo-members.
- # Built-in platforms are always valid; plugin platforms must be
- # registered in the platform registry.
- if platform.value not in _BUILTIN_PLATFORM_VALUES:
- try:
- from gateway.platform_registry import platform_registry
- if not platform_registry.is_registered(platform.value):
- raise ValueError(platform_name)
- except Exception:
- raise ValueError(platform_name)
- except Exception:
- logger.warning(
- "Synthetic process event has invalid platform metadata: %r",
- platform_name,
- )
- return None
-
- return SessionSource(
- platform=platform,
- chat_id=chat_id,
- chat_type=chat_type,
- thread_id=str(evt.get("thread_id") or "").strip() or None,
- user_id=str(evt.get("user_id") or "").strip() or None,
- user_name=str(evt.get("user_name") or "").strip() or None,
- )
+ data = json.loads(notify_path.read_text(encoding="utf-8"))
+ platform_str = data.get("platform")
+ chat_id = data.get("chat_id")
+ chat_type = data.get("chat_type")
+ thread_id = data.get("thread_id")
+ message_id = data.get("message_id")
- async def _inject_watch_notification(
- self, synth_text: str, evt: dict,
- ) -> Optional[bool]:
- """Inject a watch/completion notification as a synthetic message event.
+ if not platform_str or not chat_id:
+ return None
- Routing must come from the queued event itself, not from whatever
- foreground message happened to be active when the queue was drained.
- Returns ``True`` after adapter acceptance, ``False`` after a retryable
- adapter failure, and ``None`` when the event has no gateway route. This
- is not a transactional boundary: a process crash after adapter
- acceptance can still cause durable at-least-once replay.
- """
- source = self._build_process_event_source(evt)
- if not source:
- # API-server-originated sessions bind a RAW session key (the
- # X-Hermes-Session-Id value — see _bind_api_server_session), not a
- # structured ``agent:main:...`` key, so _build_process_event_source
- # cannot derive routing metadata from it and returns None above.
- # Recover the raw session id and wake the real session via the API
- # server's own /v1/chat/completions entry point instead of
- # dropping the event.
- raw_sid = str(evt.get("origin_session_id") or "").strip()
- if not raw_sid:
- _sk = str(evt.get("session_key") or "").strip()
- if _sk and _parse_session_key(_sk) is None:
- raw_sid = _sk
- if raw_sid:
- adapter = self.adapters.get(Platform.API_SERVER)
- from gateway.wake import adapter_supports_push, deliver_wake
- if adapter is not None and not adapter_supports_push(adapter):
- try:
- logger.info(
- "Watch pattern notification — waking api_server "
- "session %s via self-post",
- raw_sid,
- )
- await deliver_wake(adapter, text=synth_text, session_id=raw_sid)
- return True
- except Exception as e:
- logger.warning(
- "Watch notification self-post wake failed for "
- "session %s: %s",
- raw_sid, e,
- )
- return False
- logger.warning(
- "Dropping watch notification for raw session %s: no "
- "api_server adapter to self-post through",
- raw_sid,
+ platform = Platform(platform_str)
+ transport = resolve_delivery_transport(platform, self.config, self.adapters)
+ if transport is None:
+ logger.debug(
+ "Restart notification skipped: no live transport for %s",
+ platform_str,
)
return None
- logger.warning(
- "Dropping watch notification with no routing metadata for process %s",
- evt.get("session_id", "unknown"),
- )
- return None
- platform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform)
- adapter = None
- for p, a in self.adapters.items():
- if p.value == platform_name:
- adapter = a
- break
- if not adapter:
- return None
- from gateway.wake import adapter_supports_push as _wake_push_ok
- if not _wake_push_ok(adapter):
- # Non-push adapter (api_server) resolved WITH routing metadata:
- # its chat_id is the raw session id (see _bind_api_server_session,
- # which binds chat_id = session_id). handle_message would run the
- # wake under a build_session_key()-derived key that never matches
- # the raw X-Hermes-Session-Id session — self-post instead.
- from gateway.wake import deliver_wake
- raw_sid = str(evt.get("origin_session_id") or "").strip() or str(source.chat_id or "")
- try:
+
+ platform_cfg = self.config.platforms.get(platform)
+ if platform_cfg is not None and not platform_cfg.gateway_restart_notification:
logger.info(
- "Watch pattern notification — waking api_server session "
- "%s via self-post",
- raw_sid,
- )
- await deliver_wake(adapter, text=synth_text, session_id=raw_sid)
- return True
- except Exception as e:
- logger.warning(
- "Watch notification self-post wake failed for session "
- "%s: %s",
- raw_sid, e,
+ "Restart notification suppressed: %s has gateway_restart_notification=false",
+ platform_str,
)
- return False
- try:
- metadata = {}
- parent_session_id = str(evt.get("parent_session_id") or "").strip()
- if parent_session_id:
- metadata["gateway_session_id"] = parent_session_id
- synth_event = MessageEvent(
- text=synth_text,
- message_type=MessageType.TEXT,
- source=source,
- internal=True,
- message_id=str(evt.get("message_id") or "").strip() or None,
- metadata=metadata,
+ return None
+
+ metadata = self._thread_metadata_for_target(
+ platform,
+ chat_id,
+ thread_id,
+ chat_type=chat_type,
+ reply_to_message_id=message_id,
+ adapter=transport.adapter,
+ )
+ if data.get("delivered_via_upstream_relay") is True:
+ metadata = dict(metadata or {})
+ if data.get("user_id"):
+ metadata["user_id"] = str(data["user_id"])
+ if data.get("scope_id"):
+ metadata["scope_id"] = str(data["scope_id"])
+ result = await transport.send(
+ platform,
+ str(chat_id),
+ "♻ Gateway restarted successfully. Your session continues.",
+ metadata=_non_conversational_metadata(metadata, platform=platform),
)
+ # adapter.send() catches provider errors (e.g. "Chat not found")
+ # and returns SendResult(success=False) rather than raising, so
+ # we must inspect the result before claiming success — otherwise
+ # the log line is misleading and hides real delivery failures.
+ if result is not None and getattr(result, "success", True) is False:
+ logger.warning(
+ "Restart notification to %s:%s was not delivered: %s",
+ platform_str,
+ chat_id,
+ getattr(result, "error", "send returned success=False"),
+ )
+ return None
+
logger.info(
- "Watch pattern notification — injecting for %s chat=%s thread=%s",
- platform_name,
- source.chat_id,
- source.thread_id,
+ "Sent restart notification to %s:%s",
+ platform_str,
+ chat_id,
)
- await adapter.handle_message(synth_event)
- return True
+ return str(platform_str), str(chat_id), str(thread_id) if thread_id else None
except Exception as e:
- logger.error("Watch notification injection error: %s", e)
- return False
+ logger.warning("Restart notification failed: %s", e)
+ return None
+ finally:
+ notify_path.unlink(missing_ok=True)
- @staticmethod
- def _completion_delivery_identity(evt: dict) -> Optional[tuple[str, str, object]]:
- """Return a producer-stable identity when one is available.
+ async def _send_home_channel_startup_notifications(
+ self,
+ *,
+ skip_targets: Optional[set[tuple[str, str, Optional[str]]]] = None,
+ ) -> set[tuple[str, str, Optional[str]]]:
+ """Notify configured home channels that the gateway is back online.
- Delegation UUIDs identify one producer completion. Process session IDs
- are normally unique too, but include the persisted spawn epoch so an
- explicitly reused ID represents a distinct process incarnation. Legacy
- process events without ``started_at`` are delivered without deduplication
- rather than risking suppression of a real completion.
+ The notification is best-effort and sent once per connected platform
+ home channel. ``skip_targets`` lets startup avoid duplicate messages
+ when a more specific restart notification is queued for the same chat.
"""
- evt_type = str(evt.get("type") or "")
- if evt_type == "async_delegation":
- producer_id = str(evt.get("delegation_id") or "")
- return (evt_type, producer_id, "") if producer_id else None
- if evt_type == "completion":
- producer_id = str(evt.get("session_id") or "")
- started_at = evt.get("started_at")
- if producer_id and started_at is not None:
- return (evt_type, producer_id, started_at)
- return None
-
- async def _classify_completion_target(self, parent_session_id: str) -> str:
- """Classify an async-completion delivery target before adapter acceptance.
+ delivered: set[tuple[str, str, Optional[str]]] = set()
+ skipped = skip_targets or set()
+ message = "♻️ Gateway online — Hermes is back and ready."
- Returns one of:
+ for platform, platform_cfg in self.config.platforms.items():
+ home = platform_cfg.home_channel
+ if not home or not home.chat_id:
+ continue
- - ``"deliver"`` — the spawning session is live, or ended by a
- compression rotation with a verified live continuation. The inner
- #55578 resolver (:meth:`_resolve_async_delegation_session`) still
- owns the actual route retarget; this pre-flight only proves the
- completion is deliverable so the durable ack stays honest.
- - ``"terminal"`` — the spawning session is gone for good (unknown, or
- ended at an explicit user boundary such as /new). Delivery can never
- succeed; the durable row should be terminally dropped rather than
- falsely acknowledged as delivered or replayed forever as pending.
- - ``"retry"`` — transient uncertainty (session DB unavailable, lookup
- error, or a compression rotation caught mid-flight before its
- continuation exists). The claim should be released so a later
- consumer can retry; the attempt cap bounds the churn.
- """
- session_db = getattr(self, "_session_db", None)
- if session_db is None:
- return "retry"
- try:
- parent = await session_db.get_session(parent_session_id)
- except Exception:
- logger.debug(
- "Async-completion pre-flight parent lookup failed for %s",
- parent_session_id, exc_info=True,
- )
- return "retry"
- if parent is None:
- return "terminal"
- if not parent.get("ended_at"):
- return "deliver"
- if parent.get("end_reason") != "compression":
- return "terminal"
- try:
- tip_session_id = await session_db.get_compression_tip(parent_session_id)
- if not tip_session_id or tip_session_id == parent_session_id:
- # Rotation caught mid-flight: parent is compression-ended but
- # its continuation isn't visible yet. Retry, don't drop.
- return "retry"
- tip = await session_db.get_session(tip_session_id)
- except Exception:
- logger.debug(
- "Async-completion pre-flight tip lookup failed for %s",
- parent_session_id, exc_info=True,
- )
- return "retry"
- if tip is None or tip.get("ended_at"):
- return "retry"
- return "deliver"
+ transport = resolve_delivery_transport(platform, self.config, self.adapters)
+ if transport is None:
+ continue
- async def _deliver_completion_notification(
- self, synth_text: str, evt: dict,
- ) -> Optional[bool]:
- """Deliver once per live gateway, or return False for a retry.
+ if not platform_cfg.gateway_restart_notification:
+ logger.info(
+ "Home-channel startup notification suppressed: %s has gateway_restart_notification=false",
+ platform.value,
+ )
+ continue
- ``True`` means this caller reached adapter acceptance, ``False`` means
- injection failed and the claim was released for retry, and ``None``
- means either another same-lifecycle caller owns/delivered the producer
- event or the event has no gateway route. No cross-process exactly-once
- guarantee is claimed.
- """
- identity = self._completion_delivery_identity(evt)
- durable_claim_id = ""
- durable_delegation_id = ""
- if evt.get("type") == "async_delegation":
- durable_delegation_id = str(evt.get("delegation_id") or "")
- if durable_delegation_id:
- try:
- from tools.async_delegation import claim_completion_delivery
+ target = (platform.value, str(home.chat_id), str(home.thread_id) if home.thread_id else None)
+ if target in skipped or target in delivered:
+ continue
- durable_claim_id = f"gateway:{id(self)}:{__import__('uuid').uuid4().hex}"
- if not claim_completion_delivery(
- durable_delegation_id, durable_claim_id,
- ):
- return None
- except Exception as exc:
- logger.warning(
- "Could not claim durable async completion %s: %s",
- durable_delegation_id, exc,
+ try:
+ metadata = self._thread_metadata_for_target(
+ platform,
+ home.chat_id,
+ home.thread_id,
+ adapter=transport.adapter,
+ )
+ if transport.is_relay:
+ metadata = dict(metadata or {})
+ if home.user_id:
+ metadata["user_id"] = home.user_id
+ if home.scope_id:
+ metadata["scope_id"] = home.scope_id
+ send_metadata = _non_conversational_metadata(metadata, platform=platform)
+ if send_metadata is not None or transport.is_relay:
+ result = await transport.send(
+ platform,
+ str(home.chat_id),
+ message,
+ metadata=send_metadata,
)
- return False
- parent_session_id = str(evt.get("parent_session_id") or "").strip()
- if parent_session_id:
- # Pre-flight (#65838-class): adapter acceptance is NOT proof of
- # delivery — the inner #55578 resolver can still fail closed
- # inside the message pipeline AFTER the adapter accepted, which
- # would falsely acknowledge the durable row as delivered.
- # Verify the target here, before acceptance, and give drops an
- # honest durable disposition.
- verdict = await self._classify_completion_target(parent_session_id)
- if verdict == "terminal":
+ else:
+ result = await transport.adapter.send(str(home.chat_id), message)
+ if result is not None and getattr(result, "success", True) is False:
logger.warning(
- "Async delegation %s targets permanently-gone session %s; "
- "terminally dropping delivery (result remains in the "
- "delegation records).",
- durable_delegation_id or "<legacy>", parent_session_id,
+ "Home-channel startup notification failed for %s:%s: %s",
+ platform.value,
+ home.chat_id,
+ getattr(result, "error", "send returned success=False"),
)
- if durable_claim_id:
- try:
- from tools.async_delegation import drop_completion_delivery
+ continue
+
+ delivered.add(target)
+ logger.info(
+ "Sent home-channel startup notification to %s:%s",
+ platform.value,
+ home.chat_id,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Home-channel startup notification failed for %s:%s: %s",
+ platform.value,
+ home.chat_id,
+ exc,
+ )
+
+ return delivered
+
+ def _set_session_env(self, context: SessionContext) -> list:
+ """Set session context variables for the current async task.
+
+ Uses ``contextvars`` instead of ``os.environ`` so that concurrent
+ gateway messages cannot overwrite each other's session state.
+
+ Returns a list of reset tokens; pass them to ``_clear_session_env``
+ in a ``finally`` block.
+ """
+ from gateway.session_context import set_session_vars
+ # Propagate the adapter's async-delivery capability so async tools
+ # (terminal notify_on_complete / watch_patterns, delegate_task
+ # background=True) know whether this channel can wake a later turn.
+ # Default True keeps CLI / unknown paths working; stateless adapters
+ # (api_server) declare supports_async_delivery=False. Use getattr so
+ # bare runners built via object.__new__ (tests) without self.adapters
+ # don't blow up — they simply default to supported.
+ _adapters = getattr(self, "adapters", None) or {}
+ _adapter = _adapters.get(context.source.platform)
+ _async_delivery = getattr(_adapter, "supports_async_delivery", True)
+ return set_session_vars(
+ platform=context.source.platform.value,
+ chat_id=context.source.chat_id,
+ chat_type=(
+ str(context.source.chat_type) if context.source.chat_type else ""
+ ),
+ chat_name=context.source.chat_name or "",
+ thread_id=str(context.source.thread_id) if context.source.thread_id else "",
+ user_id=str(context.source.user_id) if context.source.user_id else "",
+ user_name=str(context.source.user_name) if context.source.user_name else "",
+ session_key=context.session_key,
+ message_id=str(context.source.message_id) if context.source.message_id else "",
+ profile=getattr(context.source, "profile", "") or "",
+ async_delivery=_async_delivery,
+ )
+
+ def _clear_session_env(self, tokens: list) -> None:
+ """Restore session context variables to their pre-handler values."""
+ from gateway.session_context import clear_session_vars
+ clear_session_vars(tokens)
- drop_completion_delivery(
- durable_delegation_id, durable_claim_id,
- )
- except Exception:
- logger.debug(
- "Could not drop durable completion claim",
- exc_info=True,
- )
- return None
- if verdict == "retry":
- if durable_claim_id:
- try:
- from tools.async_delegation import release_completion_delivery
+ async def _run_in_executor_with_context(self, func, *args):
+ """Run blocking work in the thread pool while preserving session contextvars."""
+ loop = asyncio.get_running_loop()
+ ctx = copy_context()
+ return await loop.run_in_executor(
+ self._get_executor(),
+ ctx.run,
+ func,
+ *args,
+ )
- release_completion_delivery(
- durable_delegation_id, durable_claim_id,
- )
- except Exception:
- logger.debug(
- "Could not release durable completion claim",
- exc_info=True,
- )
- return False
- if identity is not None:
- with self._completion_delivery_lock:
- if (
- identity in self._completion_deliveries_inflight
- or identity in self._completion_deliveries_delivered
- ):
- return None
- self._completion_deliveries_inflight.add(identity)
+ def _get_executor(self) -> concurrent.futures.ThreadPoolExecutor:
+ """Return the gateway-owned executor for blocking agent work."""
+ lock = getattr(self, "_executor_lock", None)
+ if lock is None:
+ lock = threading.Lock()
+ self._executor_lock = lock
- accepted = False
- try:
- injection_result = await self._inject_watch_notification(synth_text, evt)
- if injection_result is not True:
- return injection_result
- accepted = True
+ with lock:
+ if getattr(self, "_executor_closing", False):
+ raise RuntimeError("Gateway is shutting down; executor unavailable")
+ executor = getattr(self, "_executor", None)
+ if executor is None or getattr(executor, "_shutdown", False):
+ executor = concurrent.futures.ThreadPoolExecutor(
+ max_workers=10,
+ thread_name_prefix="hermes-gateway",
+ )
+ self._executor = executor
+ return executor
- if identity is not None:
- with self._completion_delivery_lock:
- self._completion_deliveries_inflight.discard(identity)
- self._completion_deliveries_delivered[identity] = None
- while (
- len(self._completion_deliveries_delivered)
- > self._completion_delivery_retention
- ):
- self._completion_deliveries_delivered.popitem(last=False)
+ def _shutdown_executor(self) -> None:
+ """Stop the gateway-owned executor without touching the loop default."""
+ lock = getattr(self, "_executor_lock", None)
+ if lock is None:
+ return
- # If the durable async-delegation producer branch is present, its
- # SQLite row remains the authoritative replay state. Acknowledge it
- # after adapter acceptance; this gateway keeps no parallel ledger.
- if durable_claim_id:
- try:
- from tools.async_delegation import complete_completion_delivery
+ with lock:
+ self._executor_closing = True
+ executor = getattr(self, "_executor", None)
+ self._executor = None
- complete_completion_delivery(
- durable_delegation_id, durable_claim_id,
- )
- except Exception as exc:
- logger.warning(
- "Could not acknowledge durable async completion %s: %s",
- durable_delegation_id, exc,
- )
- return True
- finally:
- if identity is not None and not accepted:
- with self._completion_delivery_lock:
- self._completion_deliveries_inflight.discard(identity)
- if durable_claim_id and not accepted:
- try:
- from tools.async_delegation import release_completion_delivery
+ if executor is None:
+ return
- release_completion_delivery(
- durable_delegation_id, durable_claim_id,
- )
- except Exception:
- logger.debug("Could not release durable completion claim", exc_info=True)
+ try:
+ executor.shutdown(wait=False, cancel_futures=True)
+ except TypeError:
+ executor.shutdown(wait=False)
- def _enrich_async_delegation_routing(self, evt: dict) -> None:
- """Fill platform/chat_id/thread_id/chat_type on an async-delegation event.
+ def _decide_image_input_mode(
+ self,
+ *,
+ source: Optional[SessionSource] = None,
+ session_key: Optional[str] = None,
+ user_config: Optional[dict] = None,
+ provider: Optional[str] = None,
+ model: Optional[str] = None,
+ ) -> str:
+ """Resolve image-input routing for the effective model this turn.
- Async-delegation completion events only carry ``session_key`` (the
- daemon worker has no access to the per-message routing metadata the
- terminal background watcher captures at spawn time). Parse the
- session_key into the routing fields ``_build_process_event_source``
- expects. Best-effort: a CLI-origin event (empty session_key) is left
- as-is and simply won't route on the gateway.
+ Returns ``"native"`` (attach pixels on the user turn) or ``"text"``
+ (pre-analyze with vision_analyze and prepend the description). See
+ agent/image_routing.py for the full decision table.
+
+ Gateway sessions can have /model overrides that live outside
+ config.yaml. Image preprocessing runs before AIAgent sets the
+ auxiliary_client runtime globals, so resolve the same per-session
+ runtime bundle the upcoming agent turn will use instead of consulting
+ only the persisted default model.
"""
- if evt.get("platform"):
- return # already enriched
- parsed = _parse_session_key(evt.get("session_key", "") or "")
- if not parsed:
- return
- evt["platform"] = parsed.get("platform", "")
- evt["chat_type"] = parsed.get("chat_type", "")
- evt["chat_id"] = parsed.get("chat_id", "")
- if parsed.get("thread_id"):
- evt["thread_id"] = parsed["thread_id"]
+ try:
+ from agent.image_routing import decide_image_input_mode
+ from agent.auxiliary_client import _read_main_model, _read_main_provider
+ from hermes_cli.config import load_config
- async def _async_delegation_watcher(self, interval: float = 2.0) -> None:
- """Drain async-delegation completions and inject them as new turns.
+ cfg = user_config if isinstance(user_config, dict) else load_config()
+ resolved_provider = (provider or "").strip()
+ resolved_model = (model or "").strip()
+ resolved_requested_provider = ""
- Background subagents (``delegate_task(background=true)``) run on the
- async-delegation daemon executor — they have no per-process watcher
- task, so their completion events would only be seen by the post-turn
- queue drain. This watcher covers the IDLE case: when a background
- subagent finishes while no agent turn is running, its result still
- re-enters the originating session promptly.
+ needs_session_runtime = not resolved_provider or not resolved_model
+ has_session_identity = source is not None or session_key
+ if needs_session_runtime and has_session_identity:
+ try:
+ turn_model, runtime_kwargs = self._resolve_session_agent_runtime(
+ source=source,
+ session_key=session_key,
+ user_config=cfg,
+ )
+ if not resolved_model and isinstance(turn_model, str):
+ resolved_model = turn_model.strip()
+ runtime_provider = runtime_kwargs.get("provider") if isinstance(runtime_kwargs, dict) else None
+ runtime_requested_provider = (
+ runtime_kwargs.get("requested_provider")
+ if isinstance(runtime_kwargs, dict)
+ else None
+ )
+ if not resolved_provider and isinstance(runtime_provider, str):
+ resolved_provider = runtime_provider.strip()
+ if isinstance(runtime_requested_provider, str):
+ resolved_requested_provider = runtime_requested_provider.strip()
+ except Exception as exc:
+ logger.debug(
+ "image_routing: session runtime resolution failed, falling back to config — %s",
+ exc,
+ )
- Mirrors the CLI's idle ``process_loop`` drain. Stays silent when the
- queue has nothing for us; ignores non-async event types (those are
- handled by ``_run_process_watcher`` / the post-turn drain).
- """
- await asyncio.sleep(3) # let platforms finish connecting
- from tools.process_registry import process_registry as _pr
- while self._running:
- try:
- # Peek the queue for async-delegation events. We must NOT
- # consume watch/completion events here (other drains own them),
- # so requeue anything that isn't ours.
- requeue = []
- async_events = []
- while not _pr.completion_queue.empty():
- try:
- evt = _pr.completion_queue.get_nowait()
- except Exception:
- break
- if evt.get("type") == "async_delegation":
- async_events.append(evt)
- else:
- requeue.append(evt)
- for evt in requeue:
- _pr.completion_queue.put(evt)
- for evt in async_events:
- self._enrich_async_delegation_routing(evt)
- synth_text = _format_gateway_process_notification(evt)
- if not synth_text:
- continue
- try:
- delivered = await self._deliver_completion_notification(synth_text, evt)
- if delivered is False:
- _pr.completion_queue.put(evt)
- except Exception as e:
- _pr.completion_queue.put(evt)
- logger.error("Async delegation injection error: %s", e)
- except Exception as e:
- logger.debug("Async delegation watcher error: %s", e)
- await asyncio.sleep(interval)
+ if not resolved_provider:
+ resolved_provider = _read_main_provider()
+ if not resolved_model:
+ resolved_model = _read_main_model()
- async def _run_process_watcher(self, watcher: dict) -> None:
+ return decide_image_input_mode(
+ resolved_provider,
+ resolved_model,
+ cfg,
+ requested_provider=resolved_requested_provider,
+ )
+ except Exception as exc:
+ logger.debug("image_routing: decision failed, falling back to text — %s", exc)
+ return "text"
+
+ async def _enrich_message_with_vision(
+ self,
+ user_text: str,
+ image_paths: List[str],
+ ) -> str:
"""
- Periodically check a background process and push updates to the user.
+ Auto-analyze user-attached images with the vision tool and prepend
+ the descriptions to the message text.
- Runs as an asyncio task. Stays silent when nothing changed.
- Auto-removes when the process exits or is killed.
+ Each image is analyzed with a general-purpose prompt. The resulting
+ description *and* the local cache path are injected so the model can:
+ 1. Immediately understand what the user sent (no extra tool call).
+ 2. Re-examine the image with vision_analyze if it needs more detail.
- Notification mode (from ``display.background_process_notifications``):
- - ``all`` — running-output updates + final message
- - ``result`` — final completion message only
- - ``error`` — final message only when exit code != 0
- - ``off`` — no messages at all
- """
- from tools.process_registry import process_registry
+ Args:
+ user_text: The user's original caption / message text.
+ image_paths: List of local file paths to cached images.
- session_id = watcher["session_id"]
- interval = watcher["check_interval"]
- session_key = watcher.get("session_key", "")
- platform_name = watcher.get("platform", "")
- chat_id = watcher.get("chat_id", "")
- thread_id = watcher.get("thread_id", "")
- user_id = watcher.get("user_id", "")
- user_name = watcher.get("user_name", "")
- message_id = str(watcher.get("message_id") or "").strip() or None
- agent_notify = watcher.get("notify_on_complete", False)
- notify_mode = self._load_background_notifications_mode()
+ Returns:
+ The enriched message string with vision descriptions prepended.
+ """
+ from tools.vision_tools import vision_analyze_tool
+ from agent.memory_manager import sanitize_context
- logger.debug("Process watcher started: %s (every %ss, notify=%s, agent_notify=%s)",
- session_id, interval, notify_mode, agent_notify)
+ analysis_prompt = (
+ "Describe everything visible in this image in thorough detail. "
+ "Include any text, code, data, objects, people, layout, colors, "
+ "and any other notable visual information."
+ )
- if notify_mode == "off" and not agent_notify:
- # Still wait for the process to exit so we can log it, but don't
- # push any messages to the user.
- while True:
- await asyncio.sleep(interval)
- session = process_registry.get(session_id)
- if session is None or session.exited:
- break
- logger.debug("Process watcher ended (silent): %s", session_id)
- return
+ enriched_parts = []
+ for path in image_paths:
+ try:
+ logger.debug("Auto-analyzing user image: %s", path)
+ result_json = await vision_analyze_tool(
+ image_url=path,
+ user_prompt=analysis_prompt,
+ )
+ result = json.loads(result_json)
+ if result.get("success"):
+ description = result.get("analysis", "")
+ description = sanitize_context(description)
+ enriched_parts.append(
+ f"[The user sent an image~ Here's what I can see:\n{description}]\n"
+ f"[If you need a closer look, use vision_analyze with "
+ f"image_url: {path} ~]"
+ )
+ else:
+ enriched_parts.append(
+ "[The user sent an image but I couldn't quite see it "
+ "this time (>_<) You can try looking at it yourself "
+ f"with vision_analyze using image_url: {path}]"
+ )
+ except Exception as e:
+ logger.error("Vision auto-analysis error: %s", e)
+ enriched_parts.append(
+ f"[The user sent an image but something went wrong when I "
+ f"tried to look at it~ You can try examining it yourself "
+ f"with vision_analyze using image_url: {path}]"
+ )
- last_output_len = 0
- while True:
- await asyncio.sleep(interval)
+ # Combine: vision descriptions first, then the user's original text
+ if enriched_parts:
+ prefix = "\n\n".join(enriched_parts)
+ if user_text:
+ return f"{prefix}\n\n{user_text}"
+ return prefix
+ return user_text
- session = process_registry.get(session_id)
- if session is None:
- break
+ async def _enrich_message_with_transcription(
+ self,
+ user_text: str,
+ audio_paths: List[str],
+ ) -> tuple[str, List[str]]:
+ """
+ Auto-transcribe user voice/audio messages using the configured STT provider
+ and prepend the transcript to the message text.
- current_output_len = len(session.output_buffer)
- has_new_output = current_output_len > last_output_len
- last_output_len = current_output_len
+ Args:
+ user_text: The user's original caption / message text.
+ audio_paths: List of local file paths to cached audio files.
- if session.exited:
- # --- Agent-triggered completion: inject synthetic message ---
- # Skip if the agent already consumed the result via wait/log.
- # poll() is read-only and intentionally does NOT mark consumed
- # (#10156) — a status check must not suppress this delivery turn.
- from tools.process_registry import format_process_notification, process_registry as _pr_check
- if agent_notify and not _pr_check.is_completion_consumed(session_id):
- from agent.redact import redact_terminal_output
- from tools.ansi_strip import strip_ansi
- _command = getattr(session, "command", "") or ""
- _raw = strip_ansi(session.output_buffer) if session.output_buffer else ""
- _raw = redact_terminal_output(_raw, _command)
- _command = _redact_gateway_user_facing_secrets(_command)
- # Truncate at line boundaries so notifications never start
- # mid-line (fixes #23284). Keep the last ~2000 chars but
- # snap to the nearest preceding newline, then prepend a
- # truncation marker when output was cut.
- _LIMIT = 2000
- if len(_raw) > _LIMIT:
- _tail = _raw[-_LIMIT:]
- _nl = _tail.find("\n")
- _tail = _tail[_nl + 1:] if _nl != -1 else _tail
- _out = f"[… output truncated — showing last {len(_tail)} chars]\n{_tail}"
- else:
- _out = _raw
- completion_evt = {
- "type": "completion",
- "session_id": session_id,
- "session_key": session_key,
- "platform": platform_name,
- "chat_type": watcher.get("chat_type", ""),
- "chat_id": chat_id,
- "thread_id": thread_id,
- "user_id": user_id,
- "user_name": user_name,
- "message_id": message_id,
- "started_at": getattr(session, "started_at", None),
- "command": _command,
- "exit_code": session.exit_code,
- "completion_reason": getattr(session, "completion_reason", "exited"),
- "termination_source": getattr(session, "termination_source", ""),
- "output": _out,
- }
- synth_text = format_process_notification(completion_evt)
- if not synth_text:
- break
- delivered = await self._deliver_completion_notification(
- synth_text, completion_evt,
+ Returns:
+ A tuple of ``(enriched_text, successful_transcripts)``:
+ - ``enriched_text``: the message string with transcription wrappers
+ prepended (same as before).
+ - ``successful_transcripts``: the raw transcript strings for audio
+ clips that were successfully transcribed, in input order. Empty
+ list if every clip failed or STT is disabled. Callers can use
+ this to echo transcripts back to the user before the agent loop.
+ """
+ seen = set()
+ audio_paths = [p for p in audio_paths if p not in seen and not seen.add(p)]
+ if not getattr(self.config, "stt_enabled", True):
+ notes = []
+ for path in audio_paths:
+ abs_path = os.path.abspath(path)
+ duration_str = await _probe_audio_duration(abs_path)
+ if duration_str:
+ notes.append(
+ f"[The user sent a voice message: {abs_path} (duration: {duration_str})]"
)
- if delivered is False:
- # The process remains terminal; retry after failed
- # adapter injection instead of suppressing the result.
- continue
- break
+ else:
+ notes.append(f"[The user sent a voice message: {abs_path}]")
+ if not notes:
+ return user_text, []
+ prefix = "\n\n".join(notes)
+ _placeholder = "(The user sent a message with no text content)"
+ if user_text and user_text.strip() == _placeholder:
+ return prefix, []
+ if user_text:
+ return f"{prefix}\n\n{user_text}", []
+ return prefix, []
- # --- Normal text-only notification ---
- # Skip when the agent already consumed this completion via
- # wait/log (#65379): process(wait) returned the exit code and
- # output inline, so the raw "[Background process ... finished
- # with exit code ...]" message would be a duplicate delivery
- # of the same completion. The agent_notify branch above
- # already honors _completion_consumed; without this check its
- # skip FALLS THROUGH to this block and re-delivers the output
- # the agent is actively summarizing. poll() is read-only and
- # intentionally does not mark consumed (#10156), so a status
- # check never suppresses this message.
- if _pr_check.is_completion_consumed(session_id):
- logger.debug(
- "Process watcher: completion for %s already consumed "
- "via wait/log — skipping raw notification (#65379)",
- session_id,
+ try:
+ from tools.transcription_tools import (
+ transcribe_audio,
+ transcribe_audio_local_fallback,
+ )
+ except ModuleNotFoundError as e:
+ logger.error("Transcription module unavailable: %s", e)
+ unavailable_note = "[voice message could not be transcribed]"
+ _placeholder = "(The user sent a message with no text content)"
+ if user_text and user_text.strip() == _placeholder:
+ return unavailable_note, []
+ if user_text:
+ return f"{unavailable_note}\n\n{user_text}", []
+ return unavailable_note, []
+
+ enriched_parts = []
+ successful_transcripts: List[str] = []
+ for path in audio_paths:
+ try:
+ logger.debug("Transcribing user voice: %s", path)
+ result = await asyncio.to_thread(transcribe_audio, path)
+ if not result.get("success"):
+ fallback = await asyncio.to_thread(
+ transcribe_audio_local_fallback,
+ path,
)
- break
- # Decide whether to notify based on mode
- should_notify = (
- notify_mode in {"all", "result"}
- or (notify_mode == "error" and session.exit_code not in {0, None})
- )
- if should_notify:
- new_output = session.output_buffer[-1000:] if session.output_buffer else ""
- if new_output:
- from agent.redact import redact_terminal_output
- new_output = redact_terminal_output(
- new_output, getattr(session, "command", "") or ""
+ if fallback.get("success"):
+ logger.info(
+ "Configured STT failed for %s; recovered with local STT",
+ path,
+ )
+ result = fallback
+ if result["success"]:
+ transcript = result["transcript"]
+ # Speech-to-text can return success=True with an empty or
+ # whitespace-only transcript on silence, cut-off, or
+ # inaudible audio. Emitting empty quotes ('""') makes the
+ # agent reply to nothing and can loop, so that case gets a
+ # clear sentinel note instead (#41603).
+ if not (transcript or "").strip():
+ enriched_parts.append(
+ "[The user sent a voice message but it came through "
+ "empty or inaudible — speech-to-text returned no "
+ "words. Do not guess at the content; ask the user "
+ "to resend or type it out.]"
)
- message_text = (
- f"[Background process {session_id} finished with exit code {session.exit_code}~ "
- f"Here's the final output:\n{new_output}]"
- )
- adapter = None
- for p, a in self.adapters.items():
- if p.value == platform_name:
- adapter = a
- break
- if adapter and chat_id:
- try:
- send_meta = {"thread_id": thread_id} if thread_id else None
- await adapter.send(
- chat_id,
- message_text,
- metadata=_non_conversational_metadata(send_meta, platform=platform_name),
- )
- except Exception as e:
- logger.error("Watcher delivery error: %s", e)
- break
+ continue
+ successful_transcripts.append(transcript)
+ # Pass the transcript through as a plain quoted line. The
+ # earlier wording ("The user sent a voice message~ Here's
+ # what they said: ...") read as a meta-instruction and made
+ # the LLM volunteer commentary about voice mode rather than
+ # reply to the content.
+ enriched_parts.append(f'"{transcript}"')
+ else:
+ error = result.get("error", "unknown error")
+ # All failure branches: a single, minimal, neutral marker.
+ # Do NOT mention "no STT provider configured", "setup
+ # instructions", or the "hermes-agent-setup" skill, and do
+ # NOT claim a direct message was sent — those phrases get
+ # persisted in conversation history and poison every later
+ # turn, so the model keeps volunteering STT-setup advice
+ # even after transcription starts working. The cause is
+ # logged for operator diagnosis but kept out of the
+ # LLM-visible prompt.
+ logger.info("Voice transcription failed for %s: %s", path, error)
+ from tools.credential_files import to_agent_visible_cache_path
- elif has_new_output and notify_mode == "all" and not agent_notify:
- # New output available -- deliver status update (only in "all" mode)
- # Skip periodic updates for agent_notify watchers (they only care about completion)
- new_output = session.output_buffer[-500:] if session.output_buffer else ""
- if new_output:
- from agent.redact import redact_terminal_output
- new_output = redact_terminal_output(
- new_output, getattr(session, "command", "") or ""
+ agent_path = to_agent_visible_cache_path(os.path.abspath(path))
+ enriched_parts.append(
+ "[voice message could not be transcribed automatically; "
+ f"the audio is available at: {agent_path}]"
)
- message_text = (
- f"[Background process {session_id} is still running~ "
- f"New output:\n{new_output}]"
+ except Exception as e:
+ logger.error("Transcription error: %s", e)
+ from tools.credential_files import to_agent_visible_cache_path
+
+ agent_path = to_agent_visible_cache_path(os.path.abspath(path))
+ enriched_parts.append(
+ "[voice message could not be transcribed automatically; "
+ f"the audio is available at: {agent_path}]"
)
- adapter = None
- for p, a in self.adapters.items():
- if p.value == platform_name:
- adapter = a
- break
- if adapter and chat_id:
- try:
- send_meta = {"thread_id": thread_id} if thread_id else None
- await adapter.send(
- chat_id,
- message_text,
- metadata=_non_conversational_metadata(send_meta, platform=platform_name),
- )
- except Exception as e:
- logger.error("Watcher delivery error: %s", e)
- logger.debug("Process watcher ended: %s", session_id)
+ if enriched_parts:
+ prefix = "\n\n".join(enriched_parts)
+ # Strip the empty-content placeholder from the Discord adapter
+ # when we successfully transcribed the audio — it's redundant.
+ _placeholder = "(The user sent a message with no text content)"
+ if user_text and user_text.strip() == _placeholder:
+ return prefix, successful_transcripts
+ if user_text:
+ return f"{prefix}\n\n{user_text}", successful_transcripts
+ return prefix, successful_transcripts
+ return user_text, successful_transcripts
- _MAX_INTERRUPT_DEPTH = 3 # Cap recursive interrupt handling (#816)
+ def _pending_event_audio_paths(self, event) -> List[str]:
+ """Return STT-eligible paths from a pending voice message."""
+ audio_paths: List[str] = []
+ media_urls = getattr(event, "media_urls", None) or []
+ for i, path in enumerate(media_urls):
+ if _event_media_is_stt_input(event, i):
+ audio_paths.append(path)
+ return audio_paths
- # Config keys whose values MUST invalidate the gateway's cached agent
- # when they change. The agent bakes these into its compressor / context
- # handling at construction time, so a mid-running-gateway config edit
- # would otherwise be silently ignored until the user triggers a
- # different cache eviction (model switch, /reset, etc.).
- #
- # Each entry is a tuple of (section, key) read from the raw config dict.
- # Add more here as new baked-at-construction config settings are added.
- _CACHE_BUSTING_CONFIG_KEYS: tuple = (
- ("model", "context_length"),
- ("model", "max_tokens"),
- ("compression", "enabled"),
- ("compression", "progress_notices"),
- ("compression", "threshold"),
- ("compression", "model_thresholds"),
- ("compression", "threshold_tokens"),
- ("compression", "codex_gpt55_autoraise"),
- ("compression", "codex_app_server_auto"),
- ("compression", "target_ratio"),
- ("compression", "protect_last_n"),
- ("compression", "proactive_prune_tokens"),
- ("compression", "proactive_prune_min_result_chars"),
- ("compression", "proactive_prune_min_reclaim_tokens"),
- ("compression", "min_tail_user_messages"),
- ("agent", "disabled_toolsets"),
- ("memory", "provider"),
- ("checkpoints", "enabled"),
- ("checkpoints", "max_snapshots"),
- ("checkpoints", "max_total_size_mb"),
- ("checkpoints", "max_file_size_mb"),
- )
+ async def _transcribe_pending_audio_event_once(
+ self,
+ event,
+ user_text: Optional[str] = None,
+ ) -> tuple[str | None, List[str]]:
+ """Transcribe a pending audio event once and cache the result on the event.
- _HONCHO_CACHE_BUSTING_KEYS = (
- "honcho.peer_name",
- "honcho.ai_peer",
- "honcho.pin_peer_name",
- "honcho.runtime_peer_prefix",
- "honcho.user_peer_aliases",
- )
- _HONCHO_CACHE_BUSTING_MEMO: dict[tuple[str, int | None], dict[str, Any]] = {}
+ Voice follow-ups can be inspected first by the interrupt monitor and
+ later consumed by the pending-drain path. Both need the same transcript,
+ but only one STT call and one transcript echo should happen for the
+ platform message.
+ """
+ if hasattr(event, "_gateway_pending_stt_text"):
+ cached_text = getattr(event, "_gateway_pending_stt_text")
+ cached_transcripts = getattr(event, "_gateway_pending_stt_transcripts", []) or []
+ return cached_text, list(cached_transcripts)
+
+ audio_paths = self._pending_event_audio_paths(event)
+ if not audio_paths:
+ return user_text if user_text is not None else (getattr(event, "text", None) or None), []
+
+ text = user_text if user_text is not None else (getattr(event, "text", "") or "")
+ enriched_text, successful_transcripts = await self._enrich_message_with_transcription(
+ text,
+ audio_paths,
+ )
+ setattr(event, "_gateway_pending_stt_text", enriched_text)
+ setattr(event, "_gateway_pending_stt_transcripts", list(successful_transcripts))
+ return enriched_text, successful_transcripts
+
+ async def _echo_pending_stt_transcripts_once(
+ self,
+ event,
+ adapter,
+ source,
+ transcripts: List[str],
+ *,
+ metadata=None,
+ log_context: str = "Transcript",
+ ) -> None:
+ """Echo pending-event STT transcripts to the chat at most once.
+
+ The already-echoed transcripts are tracked as a COUNT rather than a
+ single boolean. ``merge_pending_message_event`` can append a second
+ voice note to an event whose first transcript was already echoed and
+ invalidates the transcription cache; the re-run transcription then
+ returns the earlier transcripts as a prefix of the new list, so
+ echoing only the unsent tail suppresses the repeat while still
+ surfacing the newly merged note. A count rather than a set of seen
+ values because two separate notes that transcribe identically are two
+ distinct deliveries and both must be echoed.
+ """
+ if (
+ not transcripts
+ or not self._should_echo_stt_transcripts()
+ or adapter is None
+ ):
+ return
+ already_echoed = int(getattr(event, "_gateway_pending_stt_echoed", 0) or 0)
+ unsent = transcripts[already_echoed:]
+ setattr(event, "_gateway_pending_stt_echoed", already_echoed + len(unsent))
+ for tx in unsent:
+ try:
+ await adapter.send(
+ source.chat_id,
+ f'🎙️ "{tx}"',
+ metadata=metadata,
+ )
+ except Exception as echo_exc:
+ logger.debug("%s echo failed (non-fatal): %s", log_context, echo_exc)
+
+ async def _transcribe_and_echo_pending_voice(
+ self,
+ event,
+ adapter,
+ source,
+ text: str,
+ *,
+ log_context: str,
+ metadata=_UNSET,
+ ) -> tuple[str, List[str]]:
+ """Transcribe a pending voice event and echo transcripts once.
+
+ Unified helper for all interrupt/monitor/backup/drain paths that need
+ to transcribe a pending voice event and echo the transcript to chat.
+ Returns ``(enriched_text, transcripts)`` so the caller can feed the
+ enriched text into ``agent.interrupt()`` or the pending-drain flow.
+
+ If the event has no STT-eligible media, returns ``(text, [])`` unchanged.
+ The caller is responsible for the ``_build_media_placeholder`` fallback
+ when ``text`` is empty and the event has non-audio media.
+ """
+ if not self._pending_event_audio_paths(event):
+ return text, []
+ try:
+ enriched_text, transcripts = await self._transcribe_pending_audio_event_once(
+ event,
+ text,
+ )
+ echo_meta = self._thread_metadata_for_source(
+ source,
+ self._reply_anchor_for_event(event),
+ ) if metadata is _UNSET else metadata
+ await self._echo_pending_stt_transcripts_once(
+ event,
+ adapter,
+ source,
+ transcripts,
+ metadata=echo_meta,
+ log_context=log_context,
+ )
+ return enriched_text or text, transcripts
+ except Exception as trans_exc:
+ logger.warning("%s transcription failed: %s", log_context, trans_exc)
+ return text, []
- @classmethod
- def _empty_honcho_cache_busting_config(cls) -> dict[str, Any]:
- return {key: None for key in cls._HONCHO_CACHE_BUSTING_KEYS}
+ def _build_process_event_source(self, evt: dict):
+ """Resolve the canonical source for a synthetic background-process event.
- @classmethod
- def _extract_honcho_cache_busting_config(cls) -> dict[str, Any]:
- """Extract Honcho identity keys, memoized by honcho.json mtime."""
- try:
- from plugins.memory.honcho.client import HonchoClientConfig, resolve_config_path
+ Prefer the persisted session-store origin for the event's session key.
+ Falling back to the currently active foreground event is what causes
+ cross-topic bleed, so don't do that.
+ """
+ from gateway.session import SessionSource
- path = resolve_config_path()
+ session_key = str(evt.get("session_key") or "").strip()
+ derived_platform = ""
+ derived_chat_type = ""
+ derived_chat_id = ""
+
+ if session_key:
try:
- mtime_ns = path.stat().st_mtime_ns
- except OSError:
- mtime_ns = None
- memo_key = (str(path), mtime_ns)
- cached = cls._HONCHO_CACHE_BUSTING_MEMO.get(memo_key)
- if cached is not None:
- return dict(cached)
+ self.session_store._ensure_loaded()
+ entry = self.session_store._entries.get(session_key)
+ if entry and getattr(entry, "origin", None):
+ return entry.origin
+ except Exception as exc:
+ logger.debug(
+ "Synthetic process-event session-store lookup failed for %s: %s",
+ session_key,
+ exc,
+ )
- hcfg = HonchoClientConfig.from_global_config(config_path=path)
- aliases = hcfg.user_peer_aliases or {}
- values = {
- "honcho.peer_name": hcfg.peer_name,
- "honcho.ai_peer": hcfg.ai_peer,
- "honcho.pin_peer_name": bool(hcfg.pin_peer_name),
- "honcho.runtime_peer_prefix": hcfg.runtime_peer_prefix or "",
- "honcho.user_peer_aliases": sorted(aliases.items()) if isinstance(aliases, dict) else [],
- }
- cls._HONCHO_CACHE_BUSTING_MEMO = {memo_key: values}
- return dict(values)
- except Exception:
- return cls._empty_honcho_cache_busting_config()
+ cached_source = self._get_cached_session_source(session_key)
+ if cached_source is not None:
+ return cached_source
- @classmethod
- def _extract_cache_busting_config(cls, user_config: dict | None) -> dict:
- """Pull values that must bust the cached agent.
+ _parsed = _parse_session_key(session_key)
+ if _parsed:
+ derived_platform = _parsed["platform"]
+ derived_chat_type = _parsed["chat_type"]
+ derived_chat_id = _parsed["chat_id"]
- Returns a flat dict keyed by 'section.key'. Missing config keys and
- non-dict sections yield None values, which still contribute to the
- signature (so 'absent' vs 'present-and-null' differ).
+ platform_name = str(evt.get("platform") or derived_platform or "").strip().lower()
+ chat_type = str(evt.get("chat_type") or derived_chat_type or "").strip().lower()
+ chat_id = str(evt.get("chat_id") or derived_chat_id or "").strip()
+ if not platform_name or not chat_type or not chat_id:
+ logger.warning(
+ "Synthetic event source unresolvable: "
+ "session_key=%r platform=%r chat_type=%r chat_id=%r "
+ "evt_type=%s",
+ session_key, platform_name, chat_type, chat_id,
+ evt.get("type", "?"),
+ )
+ return None
- The live tool registry generation is included too. MCP reloads and
- dynamic MCP tool-list changes mutate the registry without necessarily
- changing config.yaml. Cached AIAgent instances freeze their tool
- schemas at construction time, so a registry generation change must
- rebuild the agent before the next turn.
- """
- out: Dict[str, Any] = {}
- cfg = user_config if isinstance(user_config, dict) else {}
- for section, key in cls._CACHE_BUSTING_CONFIG_KEYS:
- section_val = cfg.get(section)
- if section == "checkpoints" and isinstance(section_val, bool):
- # Preserve legacy ``checkpoints: true`` behavior. A live
- # toggle must still rebuild the cached agent.
- out[f"{section}.{key}"] = section_val if key == "enabled" else None
- elif isinstance(section_val, dict):
- out[f"{section}.{key}"] = section_val.get(key)
- else:
- out[f"{section}.{key}"] = None
try:
- from tools.registry import registry
-
- out["tools.registry_generation"] = getattr(registry, "_generation", None)
+ platform = Platform(platform_name)
+ # Reject arbitrary strings that create dynamic pseudo-members.
+ # Built-in platforms are always valid; plugin platforms must be
+ # registered in the platform registry.
+ if platform.value not in _BUILTIN_PLATFORM_VALUES:
+ try:
+ from gateway.platform_registry import platform_registry
+ if not platform_registry.is_registered(platform.value):
+ raise ValueError(platform_name)
+ except Exception:
+ raise ValueError(platform_name)
except Exception:
- out["tools.registry_generation"] = None
-
- # Honcho identity-mapping keys live in honcho.json, not user_config.
- # Only read that file when Honcho is the active memory provider.
- provider = cfg_get(cfg, "memory", "provider")
- if isinstance(provider, str) and provider.lower() == "honcho":
- out.update(cls._extract_honcho_cache_busting_config())
- else:
- out.update(cls._empty_honcho_cache_busting_config())
+ logger.warning(
+ "Synthetic process event has invalid platform metadata: %r",
+ platform_name,
+ )
+ return None
- return out
+ return SessionSource(
+ platform=platform,
+ chat_id=chat_id,
+ chat_type=chat_type,
+ thread_id=str(evt.get("thread_id") or "").strip() or None,
+ user_id=str(evt.get("user_id") or "").strip() or None,
+ user_name=str(evt.get("user_name") or "").strip() or None,
+ )
- @staticmethod
- def _agent_config_signature(
- model: str,
- runtime: dict,
- enabled_toolsets: list,
- ephemeral_prompt: str,
- cache_keys: dict | None = None,
- user_id: str | None = None,
- user_id_alt: str | None = None,
- ) -> str:
- """Compute a stable string key from agent config values.
+ async def _inject_watch_notification(
+ self, synth_text: str, evt: dict,
+ ) -> Optional[bool]:
+ """Inject a watch/completion notification as a synthetic message event.
- When this signature changes between messages, the cached AIAgent is
- discarded and rebuilt. When it stays the same, the cached agent is
- reused — preserving the frozen system prompt and tool schemas for
- prompt cache hits.
+ Routing must come from the queued event itself, not from whatever
+ foreground message happened to be active when the queue was drained.
+ Returns ``True`` after adapter acceptance, ``False`` after a retryable
+ adapter failure, and ``None`` when the event has no gateway route. This
+ is not a transactional boundary: a process crash after adapter
+ acceptance can still cause durable at-least-once replay.
+ """
+ source = self._build_process_event_source(evt)
+ if not source:
+ # API-server-originated sessions bind a RAW session key (the
+ # X-Hermes-Session-Id value — see _bind_api_server_session), not a
+ # structured ``agent:main:...`` key, so _build_process_event_source
+ # cannot derive routing metadata from it and returns None above.
+ # Recover the raw session id and wake the real session via the API
+ # server's own /v1/chat/completions entry point instead of
+ # dropping the event.
+ raw_sid = str(evt.get("origin_session_id") or "").strip()
+ if not raw_sid:
+ _sk = str(evt.get("session_key") or "").strip()
+ if _sk and _parse_session_key(_sk) is None:
+ raw_sid = _sk
+ if raw_sid:
+ adapter = self.adapters.get(Platform.API_SERVER)
+ from gateway.wake import adapter_supports_push, deliver_wake
+ if adapter is not None and not adapter_supports_push(adapter):
+ try:
+ logger.info(
+ "Watch pattern notification — waking api_server "
+ "session %s via self-post",
+ raw_sid,
+ )
+ await deliver_wake(adapter, text=synth_text, session_id=raw_sid)
+ return True
+ except Exception as e:
+ logger.warning(
+ "Watch notification self-post wake failed for "
+ "session %s: %s",
+ raw_sid, e,
+ )
+ return False
+ logger.warning(
+ "Dropping watch notification for raw session %s: no "
+ "api_server adapter to self-post through",
+ raw_sid,
+ )
+ return None
+ logger.warning(
+ "Dropping watch notification with no routing metadata for process %s",
+ evt.get("session_id", "unknown"),
+ )
+ return None
+ platform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform)
+ adapter = None
+ for p, a in self.adapters.items():
+ if p.value == platform_name:
+ adapter = a
+ break
+ if not adapter:
+ return None
+ from gateway.wake import adapter_supports_push as _wake_push_ok
+ if not _wake_push_ok(adapter):
+ # Non-push adapter (api_server) resolved WITH routing metadata:
+ # its chat_id is the raw session id (see _bind_api_server_session,
+ # which binds chat_id = session_id). handle_message would run the
+ # wake under a build_session_key()-derived key that never matches
+ # the raw X-Hermes-Session-Id session — self-post instead.
+ from gateway.wake import deliver_wake
+ raw_sid = str(evt.get("origin_session_id") or "").strip() or str(source.chat_id or "")
+ try:
+ logger.info(
+ "Watch pattern notification — waking api_server session "
+ "%s via self-post",
+ raw_sid,
+ )
+ await deliver_wake(adapter, text=synth_text, session_id=raw_sid)
+ return True
+ except Exception as e:
+ logger.warning(
+ "Watch notification self-post wake failed for session "
+ "%s: %s",
+ raw_sid, e,
+ )
+ return False
+ try:
+ metadata = {}
+ parent_session_id = str(evt.get("parent_session_id") or "").strip()
+ if parent_session_id:
+ metadata["gateway_session_id"] = parent_session_id
+ synth_event = MessageEvent(
+ text=synth_text,
+ message_type=MessageType.TEXT,
+ source=source,
+ internal=True,
+ message_id=str(evt.get("message_id") or "").strip() or None,
+ metadata=metadata,
+ )
+ logger.info(
+ "Watch pattern notification — injecting for %s chat=%s thread=%s",
+ platform_name,
+ source.chat_id,
+ source.thread_id,
+ )
+ await adapter.handle_message(synth_event)
+ return True
+ except Exception as e:
+ logger.error("Watch notification injection error: %s", e)
+ return False
- ``cache_keys`` is an optional flat dict of additional config values
- that should invalidate the cache when they change. Callers pass
- the output of ``_extract_cache_busting_config(user_config)`` so
- edits to model.context_length / compression.* in config.yaml are
- picked up on the next gateway message without a manual restart.
+ @staticmethod
+ def _completion_delivery_identity(evt: dict) -> Optional[tuple[str, str, object]]:
+ """Return a producer-stable identity when one is available.
- ``user_id`` and ``user_id_alt`` are the runtime user identities
- carried by the current message's gateway source. They participate
- in the cache key because the Honcho memory provider freezes them
- into ``HonchoSessionManager`` at first-message init (see
- ``plugins/memory/honcho/__init__.py::_do_session_init``). Without
- them in the signature, a shared-thread session_key (one in which
- ``build_session_key`` intentionally omits the participant ID,
- e.g. ``thread_sessions_per_user=False``) would reuse the cached
- AIAgent across distinct users, causing the second user's messages
- to be attributed to the first user's resolved Honcho peer. This
- broke #27371's per-user-peer contract in multi-user gateways.
- Per-user agent rebuilds in shared threads trade prompt-cache
- warmth for correct memory attribution.
+ Delegation UUIDs identify one producer completion. Process session IDs
+ are normally unique too, but include the persisted spawn epoch so an
+ explicitly reused ID represents a distinct process incarnation. Legacy
+ process events without ``started_at`` are delivered without deduplication
+ rather than risking suppression of a real completion.
"""
- import hashlib, json as _j
-
- # Fingerprint the FULL credential string instead of using a short
- # prefix. OAuth/JWT-style tokens frequently share a common prefix
- # (e.g. "eyJhbGci"), which can cause false cache hits across auth
- # switches if only the first few characters are considered.
- _api_key = str(runtime.get("api_key", "") or "")
- _api_key_fingerprint = hashlib.sha256(_api_key.encode()).hexdigest() if _api_key else ""
-
- _cache_keys_sorted = sorted((cache_keys or {}).items())
-
- blob = _j.dumps(
- [
- model,
- _api_key_fingerprint,
- runtime.get("base_url", ""),
- runtime.get("provider", ""),
- runtime.get("requested_provider", ""),
- runtime.get("api_mode", ""),
- sorted(enabled_toolsets) if enabled_toolsets else [],
- # reasoning_config excluded — it's set per-message on the
- # cached agent and doesn't affect system prompt or tools.
- ephemeral_prompt or "",
- _cache_keys_sorted,
- str(user_id or ""),
- str(user_id_alt or ""),
- ],
- sort_keys=True,
- default=str,
- )
- return hashlib.sha256(blob.encode()).hexdigest()[:16]
+ evt_type = str(evt.get("type") or "")
+ if evt_type == "async_delegation":
+ producer_id = str(evt.get("delegation_id") or "")
+ return (evt_type, producer_id, "") if producer_id else None
+ if evt_type == "completion":
+ producer_id = str(evt.get("session_id") or "")
+ started_at = evt.get("started_at")
+ if producer_id and started_at is not None:
+ return (evt_type, producer_id, started_at)
+ return None
- def _rehydrate_session_model_override(self, session_key: str) -> None:
- """Lazily restore a persisted /model override after a gateway restart.
+ async def _classify_completion_target(self, parent_session_id: str) -> str:
+ """Classify an async-completion delivery target before adapter acceptance.
- ``_session_model_overrides`` is in-memory only, so before persistence
- a restart silently reverted every session to the global default model.
- The non-secret parts (model/provider/base_url) are written through to
- the session store when /model runs (and cleared on /new); here we read
- them back on first use and re-resolve credentials via the normal
- runtime provider resolution — api_key is never persisted to disk.
+ Returns one of:
- No-op when an in-memory override already exists (live state wins) or
- when the store has nothing persisted (e.g. the user ran /new, which
- clears both the in-memory dict and the persisted field).
+ - ``"deliver"`` — the spawning session is live, or ended by a
+ compression rotation with a verified live continuation. The inner
+ #55578 resolver (:meth:`_resolve_async_delegation_session`) still
+ owns the actual route retarget; this pre-flight only proves the
+ completion is deliverable so the durable ack stays honest.
+ - ``"terminal"`` — the spawning session is gone for good (unknown, or
+ ended at an explicit user boundary such as /new). Delivery can never
+ succeed; the durable row should be terminally dropped rather than
+ falsely acknowledged as delivered or replayed forever as pending.
+ - ``"retry"`` — transient uncertainty (session DB unavailable, lookup
+ error, or a compression rotation caught mid-flight before its
+ continuation exists). The claim should be released so a later
+ consumer can retry; the attempt cap bounds the churn.
"""
- _rehydrate_state = self._peek_session_state(session_key)
- if (
- _rehydrate_state is not None
- and _rehydrate_state.conversation.model_override is not None
- ):
- return
- store = getattr(self, "session_store", None)
- if store is None:
- return
+ session_db = getattr(self, "_session_db", None)
+ if session_db is None:
+ return "retry"
try:
- persisted = store.get_model_override(session_key)
+ parent = await session_db.get_session(parent_session_id)
except Exception:
logger.debug(
- "Failed to read persisted session model override", exc_info=True
+ "Async-completion pre-flight parent lookup failed for %s",
+ parent_session_id, exc_info=True,
)
- return
- if not persisted:
- return
- override: Dict[str, Any] = {
- "model": persisted.get("model"),
- "provider": persisted.get("provider"),
- "base_url": persisted.get("base_url"),
- }
- provider = persisted.get("provider")
- if provider:
- # Re-resolve credentials for the persisted provider. On failure
- # (e.g. credentials were removed since the switch) keep the
- # credential-less override — _resolve_session_agent_runtime falls
- # back to env-based resolution and applies model/provider on top.
- try:
- runtime = _resolve_runtime_agent_kwargs_for_provider(provider)
- override["api_key"] = runtime.get("api_key")
- override["api_mode"] = runtime.get("api_mode")
- override["credential_pool"] = runtime.get("credential_pool")
- if not override.get("base_url"):
- override["base_url"] = runtime.get("base_url")
- except Exception:
- logger.debug(
- "Credential re-resolution failed for persisted override "
- "(provider=%s); using credential-less override",
- provider, exc_info=True,
- )
- self._session_state(session_key).conversation.model_override = override
- logger.info(
- "Rehydrated persisted /model override for session=%s: model=%s provider=%s",
- session_key, override.get("model"), provider or "",
- )
+ return "retry"
+ if parent is None:
+ return "terminal"
+ if not parent.get("ended_at"):
+ return "deliver"
+ if parent.get("end_reason") != "compression":
+ return "terminal"
+ try:
+ tip_session_id = await session_db.get_compression_tip(parent_session_id)
+ if not tip_session_id or tip_session_id == parent_session_id:
+ # Rotation caught mid-flight: parent is compression-ended but
+ # its continuation isn't visible yet. Retry, don't drop.
+ return "retry"
+ tip = await session_db.get_session(tip_session_id)
+ except Exception:
+ logger.debug(
+ "Async-completion pre-flight tip lookup failed for %s",
+ parent_session_id, exc_info=True,
+ )
+ return "retry"
+ if tip is None or tip.get("ended_at"):
+ return "retry"
+ return "deliver"
+
+ async def _deliver_completion_notification(
+ self, synth_text: str, evt: dict,
+ ) -> Optional[bool]:
+ """Deliver once per live gateway, or return False for a retry.
+
+ ``True`` means this caller reached adapter acceptance, ``False`` means
+ injection failed and the claim was released for retry, and ``None``
+ means either another same-lifecycle caller owns/delivered the producer
+ event or the event has no gateway route. No cross-process exactly-once
+ guarantee is claimed.
+ """
+ identity = self._completion_delivery_identity(evt)
+ durable_claim_id = ""
+ durable_delegation_id = ""
+ if evt.get("type") == "async_delegation":
+ durable_delegation_id = str(evt.get("delegation_id") or "")
+ if durable_delegation_id:
+ try:
+ from tools.async_delegation import claim_completion_delivery
+
+ durable_claim_id = f"gateway:{id(self)}:{__import__('uuid').uuid4().hex}"
+ if not claim_completion_delivery(
+ durable_delegation_id, durable_claim_id,
+ ):
+ return None
+ except Exception as exc:
+ logger.warning(
+ "Could not claim durable async completion %s: %s",
+ durable_delegation_id, exc,
+ )
+ return False
+ parent_session_id = str(evt.get("parent_session_id") or "").strip()
+ if parent_session_id:
+ # Pre-flight (#65838-class): adapter acceptance is NOT proof of
+ # delivery — the inner #55578 resolver can still fail closed
+ # inside the message pipeline AFTER the adapter accepted, which
+ # would falsely acknowledge the durable row as delivered.
+ # Verify the target here, before acceptance, and give drops an
+ # honest durable disposition.
+ verdict = await self._classify_completion_target(parent_session_id)
+ if verdict == "terminal":
+ logger.warning(
+ "Async delegation %s targets permanently-gone session %s; "
+ "terminally dropping delivery (result remains in the "
+ "delegation records).",
+ durable_delegation_id or "<legacy>", parent_session_id,
+ )
+ if durable_claim_id:
+ try:
+ from tools.async_delegation import drop_completion_delivery
+
+ drop_completion_delivery(
+ durable_delegation_id, durable_claim_id,
+ )
+ except Exception:
+ logger.debug(
+ "Could not drop durable completion claim",
+ exc_info=True,
+ )
+ return None
+ if verdict == "retry":
+ if durable_claim_id:
+ try:
+ from tools.async_delegation import release_completion_delivery
+
+ release_completion_delivery(
+ durable_delegation_id, durable_claim_id,
+ )
+ except Exception:
+ logger.debug(
+ "Could not release durable completion claim",
+ exc_info=True,
+ )
+ return False
+ if identity is not None:
+ with self._completion_delivery_lock:
+ if (
+ identity in self._completion_deliveries_inflight
+ or identity in self._completion_deliveries_delivered
+ ):
+ return None
+ self._completion_deliveries_inflight.add(identity)
+
+ accepted = False
+ try:
+ injection_result = await self._inject_watch_notification(synth_text, evt)
+ if injection_result is not True:
+ return injection_result
+ accepted = True
- def _apply_session_model_override(
- self, session_key: str, model: str, runtime_kwargs: dict
- ) -> tuple:
- """Apply /model session overrides if present, returning (model, runtime_kwargs).
+ if identity is not None:
+ with self._completion_delivery_lock:
+ self._completion_deliveries_inflight.discard(identity)
+ self._completion_deliveries_delivered[identity] = None
+ while (
+ len(self._completion_deliveries_delivered)
+ > self._completion_delivery_retention
+ ):
+ self._completion_deliveries_delivered.popitem(last=False)
- The gateway /model command stores per-session overrides in
- ``_session_model_overrides``. These must take precedence over
- config.yaml defaults so the switched model is actually used for
- subsequent messages. Fields with ``None`` values are skipped so
- partial overrides don't clobber valid config defaults.
- """
- _apply_state = self._peek_session_state(session_key)
- override = _apply_state.conversation.model_override if _apply_state else None
- if not override:
- return model, runtime_kwargs
- model = override.get("model", model)
- for key in ("provider", "api_key", "base_url", "api_mode", "credential_pool"):
- val = override.get(key)
- if val is not None:
- runtime_kwargs[key] = val
- if (
- runtime_kwargs.get("api_key")
- and runtime_kwargs.get("credential_pool") is None
- and override.get("provider")
- ):
- runtime_kwargs["credential_pool"] = _credential_pool_for_provider(
- override.get("provider")
- )
- return model, runtime_kwargs
+ # If the durable async-delegation producer branch is present, its
+ # SQLite row remains the authoritative replay state. Acknowledge it
+ # after adapter acceptance; this gateway keeps no parallel ledger.
+ if durable_claim_id:
+ try:
+ from tools.async_delegation import complete_completion_delivery
- def _snapshot_session_model_override(self, session_key: str) -> dict:
- """Capture a gateway session override before a one-turn switch."""
- _snap_state = self._peek_session_state(session_key)
- override = _snap_state.conversation.model_override if _snap_state else None
- return {
- "had_override": override is not None,
- "override": dict(override) if override is not None else None,
- }
+ complete_completion_delivery(
+ durable_delegation_id, durable_claim_id,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Could not acknowledge durable async completion %s: %s",
+ durable_delegation_id, exc,
+ )
+ return True
+ finally:
+ if identity is not None and not accepted:
+ with self._completion_delivery_lock:
+ self._completion_deliveries_inflight.discard(identity)
+ if durable_claim_id and not accepted:
+ try:
+ from tools.async_delegation import release_completion_delivery
- def _restore_session_model_override(self, session_key: str, snapshot: dict) -> None:
- """Restore the session override captured before a one-turn switch."""
- if not session_key:
- return
- if snapshot.get("had_override"):
- self._session_state(session_key).conversation.model_override = dict(
- snapshot.get("override") or {}
- )
- else:
- _rst_state = self._peek_session_state(session_key)
- if _rst_state is not None:
- _rst_state.conversation.model_override = None
- self._evict_cached_agent(session_key)
+ release_completion_delivery(
+ durable_delegation_id, durable_claim_id,
+ )
+ except Exception:
+ logger.debug("Could not release durable completion claim", exc_info=True)
- def _is_intentional_model_switch(self, session_key: str, agent_model: str) -> bool:
- """Return True if *agent_model* matches an active /model session override."""
- _ims_state = self._peek_session_state(session_key)
- override = _ims_state.conversation.model_override if _ims_state else None
- return override is not None and override.get("model") == agent_model
+ def _enrich_async_delegation_routing(self, evt: dict) -> None:
+ """Fill platform/chat_id/thread_id/chat_type on an async-delegation event.
- def _release_running_agent_state(
- self,
- session_key: str,
- *,
- run_generation: Optional[int] = None,
- ) -> bool:
- """Pop ALL per-running-agent state entries for ``session_key``.
+ Async-delegation completion events only carry ``session_key`` (the
+ daemon worker has no access to the per-message routing metadata the
+ terminal background watcher captures at spawn time). Parse the
+ session_key into the routing fields ``_build_process_event_source``
+ expects. Best-effort: a CLI-origin event (empty session_key) is left
+ as-is and simply won't route on the gateway.
+ """
+ if evt.get("platform"):
+ return # already enriched
+ parsed = _parse_session_key(evt.get("session_key", "") or "")
+ if not parsed:
+ return
+ evt["platform"] = parsed.get("platform", "")
+ evt["chat_type"] = parsed.get("chat_type", "")
+ evt["chat_id"] = parsed.get("chat_id", "")
+ if parsed.get("thread_id"):
+ evt["thread_id"] = parsed["thread_id"]
- Replaces ad-hoc ``del self._running_agents[key]`` calls scattered
- across the gateway. Those sites had drifted: some popped only
- ``_running_agents``; some also ``_running_agents_ts``; only one
- path also cleared ``_busy_ack_ts``. Each missed entry was a
- small, persistent leak — a (str_key → float) tuple per session
- per gateway lifetime.
+ async def _async_delegation_watcher(self, interval: float = 2.0) -> None:
+ """Drain async-delegation completions and inject them as new turns.
- Use this at every site that ends a running turn, regardless of
- cause (normal completion, /stop, /reset, /resume, sentinel
- cleanup, stale-eviction). Per-session state that PERSISTS
- across turns (``_session_model_overrides``, ``_voice_mode``,
- ``_pending_approvals``, ``_update_prompt_pending``) is NOT
- touched here — those have their own lifecycles.
+ Background subagents (``delegate_task(background=true)``) run on the
+ async-delegation daemon executor — they have no per-process watcher
+ task, so their completion events would only be seen by the post-turn
+ queue drain. This watcher covers the IDLE case: when a background
+ subagent finishes while no agent turn is running, its result still
+ re-enters the originating session promptly.
- When ``run_generation`` is provided, only clear the slot if that
- generation is still current for the session. This prevents an
- older async run whose generation was bumped by /stop or /new from
- clobbering a newer run's state during its own unwind. Returns
- True when the slot was cleared, False when an ownership guard
- blocked it.
+ Mirrors the CLI's idle ``process_loop`` drain. Stays silent when the
+ queue has nothing for us; ignores non-async event types (those are
+ handled by ``_run_process_watcher`` / the post-turn drain).
"""
- if not session_key:
- return False
- if run_generation is not None and not self._is_session_run_current(
- session_key, run_generation
- ):
- return False
- state = self._peek_session_state(session_key)
- if state is not None:
- lease = state.turn.lease
- if lease is not None:
- try:
- lease.release()
- except Exception:
- logger.debug(
- "Failed to release active session slot", exc_info=True
- )
- # One structured reset instead of the old drifting pop-list
- # (agent / started_ts / lease / busy_ack_ts). Turn-lease tokens
- # are deliberately NOT cleared here — _release_turn_lease owns
- # them (#64934).
- state.turn.clear()
- # Turn boundary: a running-agent slot was just released. Persist the
- # new (lower) in-flight count so the dashboard readout stays current
- # between lifecycle transitions. Preserves gateway_state (see
- # _persist_active_agents).
- self._persist_active_agents()
- return True
+ await asyncio.sleep(3) # let platforms finish connecting
+ from tools.process_registry import process_registry as _pr
+ while self._running:
+ try:
+ # Peek the queue for async-delegation events. We must NOT
+ # consume watch/completion events here (other drains own them),
+ # so requeue anything that isn't ours.
+ requeue = []
+ async_events = []
+ while not _pr.completion_queue.empty():
+ try:
+ evt = _pr.completion_queue.get_nowait()
+ except Exception:
+ break
+ if evt.get("type") == "async_delegation":
+ async_events.append(evt)
+ else:
+ requeue.append(evt)
+ for evt in requeue:
+ _pr.completion_queue.put(evt)
+ for evt in async_events:
+ self._enrich_async_delegation_routing(evt)
+ synth_text = _format_gateway_process_notification(evt)
+ if not synth_text:
+ continue
+ try:
+ delivered = await self._deliver_completion_notification(synth_text, evt)
+ if delivered is False:
+ _pr.completion_queue.put(evt)
+ except Exception as e:
+ _pr.completion_queue.put(evt)
+ logger.error("Async delegation injection error: %s", e)
+ except Exception as e:
+ logger.debug("Async delegation watcher error: %s", e)
+ await asyncio.sleep(interval)
- def _release_turn_lease(self, session_key: str, run_generation: int) -> bool:
- """Release the turn lease acquired by (``session_key``, ``run_generation``).
+ async def _run_process_watcher(self, watcher: dict) -> None:
+ """
+ Periodically check a background process and push updates to the user.
- Companion to the acquisition in ``_handle_message_with_agent``
- (#64934). The token map is keyed by (routing key, run generation), so
- this can only ever free the lease its own turn acquired — a stale
- unwind whose generation was bumped by /stop or /new pops ITS token,
- and the registry's identity check refuses it if a newer turn already
- holds the lease. Idempotent and safe for bare test runners built via
- ``object.__new__`` (getattr defaults).
+ Runs as an asyncio task. Stays silent when nothing changed.
+ Auto-removes when the process exits or is killed.
+
+ Notification mode (from ``display.background_process_notifications``):
+ - ``all`` — running-output updates + final message
+ - ``result`` — final completion message only
+ - ``error`` — final message only when exit code != 0
+ - ``off`` — no messages at all
"""
- if not session_key:
- return False
- registry = getattr(self, "_turn_leases", None)
- state = self._peek_session_state(session_key)
- if state is None or registry is None:
- return False
- turn = state.turn
- if turn.lease_token is None or turn.lease_generation != run_generation:
- return False
- token = turn.lease_token
- turn.lease_token = None
- turn.lease_generation = None
- try:
- return registry.release(token)
- except Exception:
- logger.debug("Failed to release turn lease", exc_info=True)
- return False
+ from tools.process_registry import process_registry
+
+ session_id = watcher["session_id"]
+ interval = watcher["check_interval"]
+ session_key = watcher.get("session_key", "")
+ platform_name = watcher.get("platform", "")
+ chat_id = watcher.get("chat_id", "")
+ thread_id = watcher.get("thread_id", "")
+ user_id = watcher.get("user_id", "")
+ user_name = watcher.get("user_name", "")
+ message_id = str(watcher.get("message_id") or "").strip() or None
+ agent_notify = watcher.get("notify_on_complete", False)
+ notify_mode = self._load_background_notifications_mode()
- def _rebind_turn_lease(
- self, session_key: str, run_generation: int, new_session_id: str
- ) -> bool:
- """Follow a mid-turn session_id rotation with the held turn lease.
+ logger.debug("Process watcher started: %s (every %ss, notify=%s, agent_notify=%s)",
+ session_id, interval, notify_mode, agent_notify)
- Compression (session-hygiene pre-compression or the agent's own
- compressor) can rotate ``session_entry.session_id`` while this turn
- is in flight. The turn's flush targets the NEW id, so the
- serialization boundary must follow it — otherwise an alias routing
- key resolving the new id (topic tip-walk onto the fresh child) could
- start a concurrent turn the lease never sees (#64934 rotation-alias
- window). Call at every site that reassigns session_entry.session_id
- mid-turn. Fail-open no-op when there is no held token.
- """
- if not session_key or not new_session_id:
- return False
- registry = getattr(self, "_turn_leases", None)
- state = self._peek_session_state(session_key)
- if state is None or registry is None:
- return False
- turn = state.turn
- if turn.lease_token is None or turn.lease_generation != run_generation:
- return False
- try:
- return registry.rebind(turn.lease_token, new_session_id)
- except Exception:
- logger.debug("Failed to rebind turn lease", exc_info=True)
- return False
+ if notify_mode == "off" and not agent_notify:
+ # Still wait for the process to exit so we can log it, but don't
+ # push any messages to the user.
+ while True:
+ await asyncio.sleep(interval)
+ session = process_registry.get(session_id)
+ if session is None or session.exited:
+ break
+ logger.debug("Process watcher ended (silent): %s", session_id)
+ return
- def _clear_conversation_scope(self, session_key: str, *, reason: str) -> None:
- """Clear ALL conversation-scoped per-session state for ``session_key``.
+ last_output_len = 0
+ while True:
+ await asyncio.sleep(interval)
- THE single conversation-boundary funnel. Call this — and nothing
- else — whenever a session_key crosses a conversation boundary:
- /new, /resume, auto-reset (idle/daily/suspended), expiry
- finalization, and the compression-exhausted auto-reset.
+ session = process_registry.get(session_id)
+ if session is None:
+ break
- Why a funnel: these boundaries used to each carry a hand-copied
- pop-list of the per-session dicts, and the lists drifted every time
- a new dict was added (#48031, #58403, #10702, #35809 were all
- "boundary X forgot dict Y" bugs — e.g. /new cleared the /model
- override but not the /model --once restore snapshot). Adding a new
- conversation-scoped dict now means adding its attribute name to
- _CONVERSATION_SCOPED_STATE below; every boundary picks it up
- automatically.
+ current_output_len = len(session.output_buffer)
+ has_new_output = current_output_len > last_output_len
+ last_output_len = current_output_len
- Scope rules:
- - Conversation-scoped (cleared here): model/reasoning overrides,
- one-turn restore snapshots, pending model notes, last-resolved
- model cache, queued follow-up events, and the boundary security
- state (approvals, /yolo, slash-confirm, update prompts).
- - Turn-scoped (NOT cleared here): _running_agents/_ts, slot leases,
- turn-lease tokens — owned by _release_running_agent_state and the
- dispatch finally.
- - Idle agent-cache eviction is NOT a conversation boundary: the
- session is still alive and a resumed turn rebuilds from these
- overrides. Only true boundaries call this.
+ if session.exited:
+ # --- Agent-triggered completion: inject synthetic message ---
+ # Skip if the agent already consumed the result via wait/log.
+ # poll() is read-only and intentionally does NOT mark consumed
+ # (#10156) — a status check must not suppress this delivery turn.
+ from tools.process_registry import format_process_notification, process_registry as _pr_check
+ if agent_notify and not _pr_check.is_completion_consumed(session_id):
+ from agent.redact import redact_terminal_output
+ from tools.ansi_strip import strip_ansi
+ _command = getattr(session, "command", "") or ""
+ _raw = strip_ansi(session.output_buffer) if session.output_buffer else ""
+ _raw = redact_terminal_output(_raw, _command)
+ _command = _redact_gateway_user_facing_secrets(_command)
+ # Truncate at line boundaries so notifications never start
+ # mid-line (fixes #23284). Keep the last ~2000 chars but
+ # snap to the nearest preceding newline, then prepend a
+ # truncation marker when output was cut.
+ _LIMIT = 2000
+ if len(_raw) > _LIMIT:
+ _tail = _raw[-_LIMIT:]
+ _nl = _tail.find("\n")
+ _tail = _tail[_nl + 1:] if _nl != -1 else _tail
+ _out = f"[… output truncated — showing last {len(_tail)} chars]\n{_tail}"
+ else:
+ _out = _raw
+ completion_evt = {
+ "type": "completion",
+ "session_id": session_id,
+ "session_key": session_key,
+ "platform": platform_name,
+ "chat_type": watcher.get("chat_type", ""),
+ "chat_id": chat_id,
+ "thread_id": thread_id,
+ "user_id": user_id,
+ "user_name": user_name,
+ "message_id": message_id,
+ "started_at": getattr(session, "started_at", None),
+ "command": _command,
+ "exit_code": session.exit_code,
+ "completion_reason": getattr(session, "completion_reason", "exited"),
+ "termination_source": getattr(session, "termination_source", ""),
+ "output": _out,
+ }
+ synth_text = format_process_notification(completion_evt)
+ if not synth_text:
+ break
+ delivered = await self._deliver_completion_notification(
+ synth_text, completion_evt,
+ )
+ if delivered is False:
+ # The process remains terminal; retry after failed
+ # adapter injection instead of suppressing the result.
+ continue
+ break
- Safe on bare test runners built via ``object.__new__`` (every
- access is getattr-guarded).
- """
- if not session_key:
- return
- # Structural clear: every conversation-scoped field resets in one
- # call — no per-attribute pop-list to drift.
- state = self._peek_session_state(session_key)
- if state is not None:
- state.conversation.clear()
- # Legacy plain-dict stores still registered in
- # _CONVERSATION_SCOPED_STATE (not yet folded into SessionState),
- # e.g. _pending_model_notes. SessionState-backed names resolve to
- # MutableMapping views (not dict), so the isinstance(dict) guard
- # skips them — already handled above.
- for attr in _CONVERSATION_SCOPED_STATE:
- store = getattr(self, attr, None)
- if isinstance(store, dict):
- store.pop(session_key, None)
- self._clear_session_boundary_security_state(session_key)
- logger.debug(
- "Cleared conversation scope for %s (%s)", session_key, reason
- )
+ # --- Normal text-only notification ---
+ # Skip when the agent already consumed this completion via
+ # wait/log (#65379): process(wait) returned the exit code and
+ # output inline, so the raw "[Background process ... finished
+ # with exit code ...]" message would be a duplicate delivery
+ # of the same completion. The agent_notify branch above
+ # already honors _completion_consumed; without this check its
+ # skip FALLS THROUGH to this block and re-delivers the output
+ # the agent is actively summarizing. poll() is read-only and
+ # intentionally does not mark consumed (#10156), so a status
+ # check never suppresses this message.
+ if _pr_check.is_completion_consumed(session_id):
+ logger.debug(
+ "Process watcher: completion for %s already consumed "
+ "via wait/log — skipping raw notification (#65379)",
+ session_id,
+ )
+ break
+ # Decide whether to notify based on mode
+ should_notify = (
+ notify_mode in {"all", "result"}
+ or (notify_mode == "error" and session.exit_code not in {0, None})
+ )
+ if should_notify:
+ new_output = session.output_buffer[-1000:] if session.output_buffer else ""
+ if new_output:
+ from agent.redact import redact_terminal_output
+ new_output = redact_terminal_output(
+ new_output, getattr(session, "command", "") or ""
+ )
+ message_text = (
+ f"[Background process {session_id} finished with exit code {session.exit_code}~ "
+ f"Here's the final output:\n{new_output}]"
+ )
+ adapter = None
+ for p, a in self.adapters.items():
+ if p.value == platform_name:
+ adapter = a
+ break
+ if adapter and chat_id:
+ try:
+ send_meta = {"thread_id": thread_id} if thread_id else None
+ await adapter.send(
+ chat_id,
+ message_text,
+ metadata=_non_conversational_metadata(send_meta, platform=platform_name),
+ )
+ except Exception as e:
+ logger.error("Watcher delivery error: %s", e)
+ break
- def _clear_session_boundary_security_state(self, session_key: str) -> None:
- """Clear per-session control state that must not survive a boundary switch."""
- if not session_key:
- return
+ elif has_new_output and notify_mode == "all" and not agent_notify:
+ # New output available -- deliver status update (only in "all" mode)
+ # Skip periodic updates for agent_notify watchers (they only care about completion)
+ new_output = session.output_buffer[-500:] if session.output_buffer else ""
+ if new_output:
+ from agent.redact import redact_terminal_output
+ new_output = redact_terminal_output(
+ new_output, getattr(session, "command", "") or ""
+ )
+ message_text = (
+ f"[Background process {session_id} is still running~ "
+ f"New output:\n{new_output}]"
+ )
+ adapter = None
+ for p, a in self.adapters.items():
+ if p.value == platform_name:
+ adapter = a
+ break
+ if adapter and chat_id:
+ try:
+ send_meta = {"thread_id": thread_id} if thread_id else None
+ await adapter.send(
+ chat_id,
+ message_text,
+ metadata=_non_conversational_metadata(send_meta, platform=platform_name),
+ )
+ except Exception as e:
+ logger.error("Watcher delivery error: %s", e)
+
+ logger.debug("Process watcher ended: %s", session_id)
+
+ _MAX_INTERRUPT_DEPTH = 3 # Cap recursive interrupt handling (#816)
+
+ # Config keys whose values MUST invalidate the gateway's cached agent
+ # when they change. The agent bakes these into its compressor / context
+ # handling at construction time, so a mid-running-gateway config edit
+ # would otherwise be silently ignored until the user triggers a
+ # different cache eviction (model switch, /reset, etc.).
+ #
+ # Each entry is a tuple of (section, key) read from the raw config dict.
+ # Add more here as new baked-at-construction config settings are added.
+ _CACHE_BUSTING_CONFIG_KEYS: tuple = (
+ ("model", "context_length"),
+ ("model", "max_tokens"),
+ ("compression", "enabled"),
+ ("compression", "progress_notices"),
+ ("compression", "threshold"),
+ ("compression", "model_thresholds"),
+ ("compression", "threshold_tokens"),
+ ("compression", "codex_gpt55_autoraise"),
+ ("compression", "codex_app_server_auto"),
+ ("compression", "target_ratio"),
+ ("compression", "protect_last_n"),
+ ("compression", "proactive_prune_tokens"),
+ ("compression", "proactive_prune_min_result_chars"),
+ ("compression", "proactive_prune_min_reclaim_tokens"),
+ ("compression", "min_tail_user_messages"),
+ ("agent", "disabled_toolsets"),
+ ("memory", "provider"),
+ ("checkpoints", "enabled"),
+ ("checkpoints", "max_snapshots"),
+ ("checkpoints", "max_total_size_mb"),
+ ("checkpoints", "max_file_size_mb"),
+ )
- pending_skills_reload_notes = getattr(
- self, "_pending_skills_reload_notes", None
- )
- if isinstance(pending_skills_reload_notes, dict):
- pending_skills_reload_notes.pop(session_key, None)
+ _HONCHO_CACHE_BUSTING_KEYS = (
+ "honcho.peer_name",
+ "honcho.ai_peer",
+ "honcho.pin_peer_name",
+ "honcho.runtime_peer_prefix",
+ "honcho.user_peer_aliases",
+ )
+ _HONCHO_CACHE_BUSTING_MEMO: dict[tuple[str, int | None], dict[str, Any]] = {}
- _sec_state = self._peek_session_state(session_key)
- if _sec_state is not None:
- _sec_state.persistent.approvals = None
- _sec_state.persistent.update_prompt_pending = False
+ @classmethod
+ def _empty_honcho_cache_busting_config(cls) -> dict[str, Any]:
+ return {key: None for key in cls._HONCHO_CACHE_BUSTING_KEYS}
+ @classmethod
+ def _extract_honcho_cache_busting_config(cls) -> dict[str, Any]:
+ """Extract Honcho identity keys, memoized by honcho.json mtime."""
try:
- from tools import slash_confirm as _slash_confirm_mod
- except Exception:
- _slash_confirm_mod = None
- if _slash_confirm_mod is not None:
+ from plugins.memory.honcho.client import HonchoClientConfig, resolve_config_path
+
+ path = resolve_config_path()
try:
- _slash_confirm_mod.clear(session_key)
- except Exception as e:
- logger.debug(
- "Failed to clear slash-confirm state for session boundary %s: %s",
- session_key,
- e,
- )
+ mtime_ns = path.stat().st_mtime_ns
+ except OSError:
+ mtime_ns = None
+ memo_key = (str(path), mtime_ns)
+ cached = cls._HONCHO_CACHE_BUSTING_MEMO.get(memo_key)
+ if cached is not None:
+ return dict(cached)
- try:
- from tools.approval import clear_session as _clear_approval_session
+ hcfg = HonchoClientConfig.from_global_config(config_path=path)
+ aliases = hcfg.user_peer_aliases or {}
+ values = {
+ "honcho.peer_name": hcfg.peer_name,
+ "honcho.ai_peer": hcfg.ai_peer,
+ "honcho.pin_peer_name": bool(hcfg.pin_peer_name),
+ "honcho.runtime_peer_prefix": hcfg.runtime_peer_prefix or "",
+ "honcho.user_peer_aliases": sorted(aliases.items()) if isinstance(aliases, dict) else [],
+ }
+ cls._HONCHO_CACHE_BUSTING_MEMO = {memo_key: values}
+ return dict(values)
except Exception:
- return
+ return cls._empty_honcho_cache_busting_config()
- try:
- _clear_approval_session(session_key)
- except Exception as e:
- logger.debug(
- "Failed to clear approval state for session boundary %s: %s",
- session_key,
- e,
- )
+ @classmethod
+ def _extract_cache_busting_config(cls, user_config: dict | None) -> dict:
+ """Pull values that must bust the cached agent.
- def _begin_session_run_generation(self, session_key: str) -> int:
- """Claim a fresh run generation token for ``session_key``.
+ Returns a flat dict keyed by 'section.key'. Missing config keys and
+ non-dict sections yield None values, which still contribute to the
+ signature (so 'absent' vs 'present-and-null' differ).
- Every top-level gateway turn gets a monotonically increasing token.
- If a later command like /stop or /new invalidates that token while the
- old worker is still unwinding, the late result can be recognized and
- dropped instead of bleeding into the fresh session.
+ The live tool registry generation is included too. MCP reloads and
+ dynamic MCP tool-list changes mutate the registry without necessarily
+ changing config.yaml. Cached AIAgent instances freeze their tool
+ schemas at construction time, so a registry generation change must
+ rebuild the agent before the next turn.
"""
- if not session_key:
- return 0
- persistent = self._session_state(session_key).persistent
- # Monotonic by design (#28686): incremented here, NEVER reset.
- persistent.run_generation = int(persistent.run_generation) + 1
- return persistent.run_generation
+ out: Dict[str, Any] = {}
+ cfg = user_config if isinstance(user_config, dict) else {}
+ for section, key in cls._CACHE_BUSTING_CONFIG_KEYS:
+ section_val = cfg.get(section)
+ if section == "checkpoints" and isinstance(section_val, bool):
+ # Preserve legacy ``checkpoints: true`` behavior. A live
+ # toggle must still rebuild the cached agent.
+ out[f"{section}.{key}"] = section_val if key == "enabled" else None
+ elif isinstance(section_val, dict):
+ out[f"{section}.{key}"] = section_val.get(key)
+ else:
+ out[f"{section}.{key}"] = None
+ try:
+ from tools.registry import registry
- def _invalidate_session_run_generation(self, session_key: str, *, reason: str = "") -> int:
- """Invalidate any in-flight run token for ``session_key``."""
- generation = self._begin_session_run_generation(session_key)
- if reason:
- logger.info(
- "Invalidated run generation for %s → %d (%s)",
- session_key,
- generation,
- reason,
- )
- return generation
+ out["tools.registry_generation"] = getattr(registry, "_generation", None)
+ except Exception:
+ out["tools.registry_generation"] = None
- def _is_session_run_current(self, session_key: str, generation: int) -> bool:
- """Return True when ``generation`` is still current for ``session_key``."""
- if not session_key:
- return True
- state = self._peek_session_state(session_key)
- current = state.persistent.run_generation if state is not None else 0
- return int(current) == int(generation)
+ # Honcho identity-mapping keys live in honcho.json, not user_config.
+ # Only read that file when Honcho is the active memory provider.
+ provider = cfg_get(cfg, "memory", "provider")
+ if isinstance(provider, str) and provider.lower() == "honcho":
+ out.update(cls._extract_honcho_cache_busting_config())
+ else:
+ out.update(cls._empty_honcho_cache_busting_config())
- def _bind_adapter_run_generation(
- self,
- adapter: Any,
- session_key: str,
- generation: int | None,
- ) -> None:
- """Bind a gateway run generation to the adapter's active-session event."""
- if not adapter or not session_key or generation is None:
- return
- try:
- interrupt_event = getattr(adapter, "_active_sessions", {}).get(session_key)
- if interrupt_event is not None:
- setattr(interrupt_event, "_hermes_run_generation", int(generation))
- except Exception:
- pass
+ return out
- async def _interrupt_and_clear_session(
- self,
- session_key: str,
- source: SessionSource,
- *,
- interrupt_reason: str,
- invalidation_reason: str,
- release_running_state: bool = True,
- ) -> None:
- """Interrupt the current run and clear queued session state consistently."""
- if not session_key:
- return
- _iac_state = self._peek_session_state(session_key)
- running_agent = _iac_state.turn.agent if _iac_state else None
- if running_agent and running_agent is not _AGENT_PENDING_SENTINEL:
- running_agent.interrupt(interrupt_reason)
- self._invalidate_session_run_generation(session_key, reason=invalidation_reason)
- adapter = self._adapter_for_source(source)
- interrupt_session_activity = getattr(
- type(adapter), "interrupt_session_activity", None
- )
- if adapter and callable(interrupt_session_activity):
- metadata = self._thread_metadata_for_source(source)
- try:
- params = inspect.signature(interrupt_session_activity).parameters
- accepts_metadata = "metadata" in params or any(
- param.kind is inspect.Parameter.VAR_KEYWORD
- for param in params.values()
- )
- except (TypeError, ValueError):
- accepts_metadata = False
- if accepts_metadata:
- await adapter.interrupt_session_activity(
- session_key, source.chat_id, metadata=metadata
- )
- else:
- await adapter.interrupt_session_activity(session_key, source.chat_id)
- if adapter and hasattr(adapter, "get_pending_message"):
- adapter.get_pending_message(session_key) # consume and discard
- if _iac_state is not None:
- _iac_state.persistent.pending_command_text = None
- if release_running_state:
- self._release_running_agent_state(session_key)
- # Evict the cached agent: ``_interrupt_requested`` is only
- # cleared by the turn finalizer, so on a hung or still-draining
- # run the flag survives the lock release and kills the session's
- # NEXT message at the top of the tool loop (interrupted=True,
- # api_calls=0, empty response — silently swallowed, #44212).
- # Evicting mirrors the /new and /model paths: the next message
- # rebuilds the agent from session history, while the old agent
- # object keeps its interrupt flag so a hung drain still dies
- # when it unblocks.
- self._evict_cached_agent(session_key)
+ @staticmethod
+ def _agent_config_signature(
+ model: str,
+ runtime: dict,
+ enabled_toolsets: list,
+ ephemeral_prompt: str,
+ cache_keys: dict | None = None,
+ user_id: str | None = None,
+ user_id_alt: str | None = None,
+ ) -> str:
+ """Compute a stable string key from agent config values.
+
+ When this signature changes between messages, the cached AIAgent is
+ discarded and rebuilt. When it stays the same, the cached agent is
+ reused — preserving the frozen system prompt and tool schemas for
+ prompt cache hits.
+
+ ``cache_keys`` is an optional flat dict of additional config values
+ that should invalidate the cache when they change. Callers pass
+ the output of ``_extract_cache_busting_config(user_config)`` so
+ edits to model.context_length / compression.* in config.yaml are
+ picked up on the next gateway message without a manual restart.
+
+ ``user_id`` and ``user_id_alt`` are the runtime user identities
+ carried by the current message's gateway source. They participate
+ in the cache key because the Honcho memory provider freezes them
+ into ``HonchoSessionManager`` at first-message init (see
+ ``plugins/memory/honcho/__init__.py::_do_session_init``). Without
+ them in the signature, a shared-thread session_key (one in which
+ ``build_session_key`` intentionally omits the participant ID,
+ e.g. ``thread_sessions_per_user=False``) would reuse the cached
+ AIAgent across distinct users, causing the second user's messages
+ to be attributed to the first user's resolved Honcho peer. This
+ broke #27371's per-user-peer contract in multi-user gateways.
+ Per-user agent rebuilds in shared threads trade prompt-cache
+ warmth for correct memory attribution.
+ """
+ import hashlib, json as _j
- async def _refresh_agent_cache_message_count(
- self, session_key: str, session_id: Optional[str]
- ) -> None:
- """Re-baseline a cached agent's stored message_count after THIS turn.
+ # Fingerprint the FULL credential string instead of using a short
+ # prefix. OAuth/JWT-style tokens frequently share a common prefix
+ # (e.g. "eyJhbGci"), which can cause false cache hits across auth
+ # switches if only the first few characters are considered.
+ _api_key = str(runtime.get("api_key", "") or "")
+ _api_key_fingerprint = hashlib.sha256(_api_key.encode()).hexdigest() if _api_key else ""
- The cross-process coherence guard (#45966) compares the session's
- on-disk ``message_count`` against the count snapshotted next to the
- cached agent, and rebuilds the agent on a mismatch. But the snapshot
- is taken at agent-BUILD time — before this turn writes its own user +
- assistant (+ tool) rows — and the cache entry is never rewritten on a
- reuse. So without this re-baseline, THIS process's own turn would
- grow ``message_count`` and the very next turn would see a mismatch
- and rebuild the agent — every turn, for every conversation — silently
- destroying the per-conversation prompt caching the cache exists to
- protect.
+ _cache_keys_sorted = sorted((cache_keys or {}).items())
- Call this once a turn has completed and the agent has flushed its
- rows to the SessionDB. It snapshots the now-current count (which
- includes this process's own writes) so the guard only fires when a
- DIFFERENT process changes the transcript out from under us. The
- ``_sig`` is left untouched; only the count element is refreshed, and
- only when the same agent is still cached (no rebuild/eviction raced
- in between). Fail-safe: any DB error leaves the snapshot as-is, which
- at worst costs one unnecessary rebuild on the next turn.
+ blob = _j.dumps(
+ [
+ model,
+ _api_key_fingerprint,
+ runtime.get("base_url", ""),
+ runtime.get("provider", ""),
+ runtime.get("requested_provider", ""),
+ runtime.get("api_mode", ""),
+ sorted(enabled_toolsets) if enabled_toolsets else [],
+ # reasoning_config excluded — it's set per-message on the
+ # cached agent and doesn't affect system prompt or tools.
+ ephemeral_prompt or "",
+ _cache_keys_sorted,
+ str(user_id or ""),
+ str(user_id_alt or ""),
+ ],
+ sort_keys=True,
+ default=str,
+ )
+ return hashlib.sha256(blob.encode()).hexdigest()[:16]
- When the cache entry records a ``session_id`` (4-tuple form, #54947)
- that differs from the current ``session_id`` — meaning the cache
- was built for a DIFFERENT conversation under the same ``session_key``
- — the snapshot is intentionally left untouched. Overwriting it with
- the current session's count would corrupt the original conversation's
- baseline and cause the next switch back to fire the cross-process
- guard spuriously. Fail-safe: the legacy 3-tuple shape (no
- ``session_id``) is still re-baselined as before.
+ def _rehydrate_session_model_override(self, session_key: str) -> None:
+ """Lazily restore a persisted /model override after a gateway restart.
+
+ ``_session_model_overrides`` is in-memory only, so before persistence
+ a restart silently reverted every session to the global default model.
+ The non-secret parts (model/provider/base_url) are written through to
+ the session store when /model runs (and cleared on /new); here we read
+ them back on first use and re-resolve credentials via the normal
+ runtime provider resolution — api_key is never persisted to disk.
+
+ No-op when an in-memory override already exists (live state wins) or
+ when the store has nothing persisted (e.g. the user ran /new, which
+ clears both the in-memory dict and the persisted field).
"""
- if self._session_db is None or not session_id:
+ _rehydrate_state = self._peek_session_state(session_key)
+ if (
+ _rehydrate_state is not None
+ and _rehydrate_state.conversation.model_override is not None
+ ):
return
- _cache_lock = getattr(self, "_agent_cache_lock", None)
- _cache = getattr(self, "_agent_cache", None)
- if not _cache_lock or _cache is None:
+ store = getattr(self, "session_store", None)
+ if store is None:
return
try:
- _sess_row = await self._session_db.get_session(session_id)
- _live = _sess_row.get("message_count", 0) if _sess_row else None
+ persisted = store.get_model_override(session_key)
except Exception:
+ logger.debug(
+ "Failed to read persisted session model override", exc_info=True
+ )
return
- if _live is None:
- return
- with _cache_lock:
- cached = _cache.get(session_key)
- # Only re-baseline a live 3-tuple entry; skip pending sentinels,
- # legacy 2-tuples (they intentionally opt out of the guard), and
- # the case where the entry was evicted/rebuilt mid-turn.
- if (
- isinstance(cached, tuple)
- and len(cached) > 2
- and cached[0] is not _AGENT_PENDING_SENTINEL
- ):
- # If the snapshot was taken for a different session_id
- # (same session_key, different conversation), leave the
- # snapshot alone — the current session_id's count belongs
- # to a different DB row (#54947).
- _snapshot_sid = cached[3] if len(cached) > 3 else None
- if _snapshot_sid is not None and _snapshot_sid != session_id:
- return
- if cached[2] != _live:
- if _snapshot_sid is None:
- # Legacy 3-tuple: preserve the original 3-element
- # shape so existing entries stay compatible with
- # callers that index ``cached[2]`` directly.
- _cache[session_key] = (cached[0], cached[1], _live)
- else:
- _cache[session_key] = (
- cached[0], cached[1], _live, _snapshot_sid,
- )
-
- def _set_pending_turn_sidecar_notes(self, session_key: str, notes: List[str]) -> None:
- """Stage per-turn must-deliver notes for the next agent run (one-shot)."""
- if not session_key or not notes:
+ if not persisted:
return
- self._session_state(session_key).conversation.sidecar_notes = list(notes)
-
- def _consume_pending_turn_sidecar_notes(self, session_key: str) -> List[str]:
- if not session_key:
- return []
- state = self._peek_session_state(session_key)
- if state is None:
- return []
- staged = state.conversation.sidecar_notes
- state.conversation.sidecar_notes = []
- return list(staged) if isinstance(staged, list) else []
-
- def _voice_channel_sidecar_note(self, event, source: SessionSource, session_key: str) -> Optional[str]:
- """Return a ``[Voice channel now: ...]`` note when VC state changed.
-
- Compares the live Discord voice-channel context against the last
- value delivered for this session and returns a note only on change
- (including leaving the channel). Unchanged state returns ``None`` so
- the per-turn member/speaking serialization cannot churn the prompt.
- """
- if source.platform != Platform.DISCORD:
- return None
- adapter = self.adapters.get(Platform.DISCORD)
- guild_id = self._get_guild_id(event)
- if not (guild_id and adapter and hasattr(adapter, "get_voice_channel_context")):
- return None
- try:
- vc_now = adapter.get_voice_channel_context(guild_id) or ""
- except Exception:
- logger.debug("voice-channel context read failed", exc_info=True)
- return None
- vc_prev = None
- if session_key:
- _vc_state = self._session_state(session_key)
- vc_prev = _vc_state.conversation.vc_last
- _vc_state.conversation.vc_last = vc_now
- if vc_now == (vc_prev if vc_prev is not None else ""):
- return None
- if not vc_now:
- return "[Voice channel now: not connected to a voice channel]"
- return f"[Voice channel now: {vc_now}]"
+ override: Dict[str, Any] = {
+ "model": persisted.get("model"),
+ "provider": persisted.get("provider"),
+ "base_url": persisted.get("base_url"),
+ }
+ provider = persisted.get("provider")
+ if provider:
+ # Re-resolve credentials for the persisted provider. On failure
+ # (e.g. credentials were removed since the switch) keep the
+ # credential-less override — _resolve_session_agent_runtime falls
+ # back to env-based resolution and applies model/provider on top.
+ try:
+ runtime = _resolve_runtime_agent_kwargs_for_provider(provider)
+ override["api_key"] = runtime.get("api_key")
+ override["api_mode"] = runtime.get("api_mode")
+ override["credential_pool"] = runtime.get("credential_pool")
+ if not override.get("base_url"):
+ override["base_url"] = runtime.get("base_url")
+ except Exception:
+ logger.debug(
+ "Credential re-resolution failed for persisted override "
+ "(provider=%s); using credential-less override",
+ provider, exc_info=True,
+ )
+ self._session_state(session_key).conversation.model_override = override
+ logger.info(
+ "Rehydrated persisted /model override for session=%s: model=%s provider=%s",
+ session_key, override.get("model"), provider or "",
+ )
- def _pinned_session_context_prompt(
- self, context, redact_pii: bool, session_key: Optional[str]
- ) -> str:
- """Return the session-context prompt, pinned per session.
+ def _apply_session_model_override(
+ self, session_key: str, model: str, runtime_kwargs: dict
+ ) -> tuple:
+ """Apply /model session overrides if present, returning (model, runtime_kwargs).
- Key hit → the pinned bytes are reused VERBATIM (immunizes the
- composed system prompt against renderer nondeterminism); key miss →
- re-render ``build_session_context_prompt`` and re-pin (a legitimate
- cache bust: rename, topic edit, /sethome, redact_pii flip, ...).
+ The gateway /model command stores per-session overrides in
+ ``_session_model_overrides``. These must take precedence over
+ config.yaml defaults so the switched model is actually used for
+ subsequent messages. Fields with ``None`` values are skipped so
+ partial overrides don't clobber valid config defaults.
"""
- _eph_key = self._ephemeral_change_key(context, redact_pii)
- _eph_pin = None
- if session_key:
- _pin_state = self._peek_session_state(session_key)
- _eph_pin = _pin_state.conversation.ephemeral_pin if _pin_state else None
- if _eph_pin is not None and _eph_pin[0] == _eph_key:
- return _eph_pin[1]
- text = build_session_context_prompt(context, redact_pii=redact_pii)
- if session_key:
- self._session_state(session_key).conversation.ephemeral_pin = (
- _eph_key,
- text,
+ _apply_state = self._peek_session_state(session_key)
+ override = _apply_state.conversation.model_override if _apply_state else None
+ if not override:
+ return model, runtime_kwargs
+ model = override.get("model", model)
+ for key in ("provider", "api_key", "base_url", "api_mode", "credential_pool"):
+ val = override.get(key)
+ if val is not None:
+ runtime_kwargs[key] = val
+ if (
+ runtime_kwargs.get("api_key")
+ and runtime_kwargs.get("credential_pool") is None
+ and override.get("provider")
+ ):
+ runtime_kwargs["credential_pool"] = _credential_pool_for_provider(
+ override.get("provider")
)
- return text
+ return model, runtime_kwargs
- @staticmethod
- def _ephemeral_change_key(context, redact_pii: bool) -> str:
- """Hash the exact inputs ``build_session_context_prompt`` renders.
+ def _snapshot_session_model_override(self, session_key: str) -> dict:
+ """Capture a gateway session override before a one-turn switch."""
+ _snap_state = self._peek_session_state(session_key)
+ override = _snap_state.conversation.model_override if _snap_state else None
+ return {
+ "had_override": override is not None,
+ "override": dict(override) if override is not None else None,
+ }
+
+ def _restore_session_model_override(self, session_key: str, snapshot: dict) -> None:
+ """Restore the session override captured before a one-turn switch."""
+ if not session_key:
+ return
+ if snapshot.get("had_override"):
+ self._session_state(session_key).conversation.model_override = dict(
+ snapshot.get("override") or {}
+ )
+ else:
+ _rst_state = self._peek_session_state(session_key)
+ if _rst_state is not None:
+ _rst_state.conversation.model_override = None
+ self._evict_cached_agent(session_key)
- This key decides when the pinned per-session context-prompt bytes are
- reused verbatim vs re-rendered. The maintained invariant (guarded by
- the parity test in tests/gateway/test_prompt_tail_freeze.py): any
- input whose change alters the rendered bytes MUST appear here —
- omission means a stale pinned prompt (cosmetic staleness); inclusion
- of an extra field only costs a spurious re-render.
- """
- import hashlib
+ def _is_intentional_model_switch(self, session_key: str, agent_model: str) -> bool:
+ """Return True if *agent_model* matches an active /model session override."""
+ _ims_state = self._peek_session_state(session_key)
+ override = _ims_state.conversation.model_override if _ims_state else None
+ return override is not None and override.get("model") == agent_model
- src = context.source
- platform = src.platform.value if src.platform else ""
+ def _release_running_agent_state(
+ self,
+ session_key: str,
+ *,
+ run_generation: Optional[int] = None,
+ ) -> bool:
+ """Pop ALL per-running-agent state entries for ``session_key``.
- discord_ids: tuple = ()
- discord_tools = ""
- if src.platform == Platform.DISCORD:
- from gateway.session import _discord_tools_loaded
+ Replaces ad-hoc ``del self._running_agents[key]`` calls scattered
+ across the gateway. Those sites had drifted: some popped only
+ ``_running_agents``; some also ``_running_agents_ts``; only one
+ path also cleared ``_busy_ack_ts``. Each missed entry was a
+ small, persistent leak — a (str_key → float) tuple per session
+ per gateway lifetime.
- discord_tools = "1" if _discord_tools_loaded() else "0"
- discord_ids = (
- str(src.guild_id or ""),
- str(src.parent_chat_id or ""),
- str(src.thread_id or ""),
- str(src.chat_id or ""),
- # Only PRESENCE is rendered (the id itself is delivered
- # per-turn in the user message) — keying on the value would
- # re-render every message for zero byte change.
- "1" if src.message_id else "0",
- )
+ Use this at every site that ends a running turn, regardless of
+ cause (normal completion, /stop, /reset, /resume, sentinel
+ cleanup, stale-eviction). Per-session state that PERSISTS
+ across turns (``_session_model_overrides``, ``_voice_mode``,
+ ``_pending_approvals``, ``_update_prompt_pending``) is NOT
+ touched here — those have their own lifecycles.
- # Slack renders a capability-aware platform note gated on
- # _slack_tools_loaded() — the gate state must appear in the key
- # (same parity contract as the Discord gate above) so a config /
- # MCP-registration flip re-renders once instead of serving a
- # stale pinned note for the rest of the session.
- slack_tools = ""
- if src.platform == Platform.SLACK:
- from gateway.session import _slack_tools_loaded
+ When ``run_generation`` is provided, only clear the slot if that
+ generation is still current for the session. This prevents an
+ older async run whose generation was bumped by /stop or /new from
+ clobbering a newer run's state during its own unwind. Returns
+ True when the slot was cleared, False when an ownership guard
+ blocked it.
+ """
+ if not session_key:
+ return False
+ if run_generation is not None and not self._is_session_run_current(
+ session_key, run_generation
+ ):
+ return False
+ state = self._peek_session_state(session_key)
+ if state is not None:
+ lease = state.turn.lease
+ if lease is not None:
+ try:
+ lease.release()
+ except Exception:
+ logger.debug(
+ "Failed to release active session slot", exc_info=True
+ )
+ # One structured reset instead of the old drifting pop-list
+ # (agent / started_ts / lease / busy_ack_ts). Turn-lease tokens
+ # are deliberately NOT cleared here — _release_turn_lease owns
+ # them (#64934).
+ state.turn.clear()
+ # Turn boundary: a running-agent slot was just released. Persist the
+ # new (lower) in-flight count so the dashboard readout stays current
+ # between lifecycle transitions. Preserves gateway_state (see
+ # _persist_active_agents).
+ self._persist_active_agents()
+ return True
- slack_tools = "1" if _slack_tools_loaded() else "0"
+ def _release_turn_lease(self, session_key: str, run_generation: int) -> bool:
+ """Release the turn lease acquired by (``session_key``, ``run_generation``).
+ Companion to the acquisition in ``_handle_message_with_agent``
+ (#64934). The token map is keyed by (routing key, run generation), so
+ this can only ever free the lease its own turn acquired — a stale
+ unwind whose generation was bumped by /stop or /new pops ITS token,
+ and the registry's identity check refuses it if a newer turn already
+ holds the lease. Idempotent and safe for bare test runners built via
+ ``object.__new__`` (getattr defaults).
+ """
+ if not session_key:
+ return False
+ registry = getattr(self, "_turn_leases", None)
+ state = self._peek_session_state(session_key)
+ if state is None or registry is None:
+ return False
+ turn = state.turn
+ if turn.lease_token is None or turn.lease_generation != run_generation:
+ return False
+ token = turn.lease_token
+ turn.lease_token = None
+ turn.lease_generation = None
try:
- from hermes_constants import display_hermes_home
+ return registry.release(token)
+ except Exception:
+ logger.debug("Failed to release turn lease", exc_info=True)
+ return False
- home_display = str(display_hermes_home())
+ def _rebind_turn_lease(
+ self, session_key: str, run_generation: int, new_session_id: str
+ ) -> bool:
+ """Follow a mid-turn session_id rotation with the held turn lease.
+
+ Compression (session-hygiene pre-compression or the agent's own
+ compressor) can rotate ``session_entry.session_id`` while this turn
+ is in flight. The turn's flush targets the NEW id, so the
+ serialization boundary must follow it — otherwise an alias routing
+ key resolving the new id (topic tip-walk onto the fresh child) could
+ start a concurrent turn the lease never sees (#64934 rotation-alias
+ window). Call at every site that reassigns session_entry.session_id
+ mid-turn. Fail-open no-op when there is no held token.
+ """
+ if not session_key or not new_session_id:
+ return False
+ registry = getattr(self, "_turn_leases", None)
+ state = self._peek_session_state(session_key)
+ if state is None or registry is None:
+ return False
+ turn = state.turn
+ if turn.lease_token is None or turn.lease_generation != run_generation:
+ return False
+ try:
+ return registry.rebind(turn.lease_token, new_session_id)
except Exception:
- home_display = ""
+ logger.debug("Failed to rebind turn lease", exc_info=True)
+ return False
- key_tuple = (
- platform,
- str(src.chat_id or ""),
- str(src.thread_id or ""),
- str(src.chat_type or ""),
- str(src.chat_name or ""),
- str(src.chat_topic or ""),
- str(src.user_name or ""),
- str(src.user_id or ""),
- str(getattr(src, "profile", None) or ""),
- bool(context.shared_multi_user_session),
- discord_ids,
- discord_tools,
- slack_tools,
- tuple(p.value for p in context.connected_platforms),
- tuple(
- (
- p.value,
- str(getattr(hc, "name", "") or ""),
- str(getattr(hc, "chat_id", "") or ""),
- )
- for p, hc in context.home_channels.items()
- ),
- bool(redact_pii),
- home_display,
- )
- return hashlib.sha256(repr(key_tuple).encode("utf-8")).hexdigest()
+ def _clear_conversation_scope(self, session_key: str, *, reason: str) -> None:
+ """Clear ALL conversation-scoped per-session state for ``session_key``.
- def _evict_cached_agent(self, session_key: str) -> None:
- """Remove a cached agent for a session (called on /new, /model, etc).
+ THE single conversation-boundary funnel. Call this — and nothing
+ else — whenever a session_key crosses a conversation boundary:
+ /new, /resume, auto-reset (idle/daily/suspended), expiry
+ finalization, and the compression-exhausted auto-reset.
- Pops the entry AND soft-releases the evicted agent's LLM client
- pool so the httpx connection (sockets + held buffers) is freed
- promptly rather than waiting on CPython GC — AIAgent holds
- reference cycles (callbacks, tool state) that delay refcount
- collection, so a manual release is required to keep gateway RSS
- flat across many /new, /model, undo and reset operations (#29298,
- same leak class as #25315).
+ Why a funnel: these boundaries used to each carry a hand-copied
+ pop-list of the per-session dicts, and the lists drifted every time
+ a new dict was added (#48031, #58403, #10702, #35809 were all
+ "boundary X forgot dict Y" bugs — e.g. /new cleared the /model
+ override but not the /model --once restore snapshot). Adding a new
+ conversation-scoped dict now means adding its attribute name to
+ _CONVERSATION_SCOPED_STATE below; every boundary picks it up
+ automatically.
- The release is soft (``release_clients()``): it frees the client
- pool and per-turn child subagents but PRESERVES the session's
- terminal sandbox, browser daemon, and tracked bg processes (keyed
- on task_id), because the session may resume with a freshly-built
- agent. Call sites that want a hard teardown (true conversation
- boundaries like /new) already call ``_cleanup_agent_resources``
- before evicting; ``release_clients`` is idempotent and safe to
- run again after that (the client is already None).
+ Scope rules:
+ - Conversation-scoped (cleared here): model/reasoning overrides,
+ one-turn restore snapshots, pending model notes, last-resolved
+ model cache, queued follow-up events, and the boundary security
+ state (approvals, /yolo, slash-confirm, update prompts).
+ - Turn-scoped (NOT cleared here): _running_agents/_ts, slot leases,
+ turn-lease tokens — owned by _release_running_agent_state and the
+ dispatch finally.
+ - Idle agent-cache eviction is NOT a conversation boundary: the
+ session is still alive and a resumed turn rebuilds from these
+ overrides. Only true boundaries call this.
- Cleanup runs on a daemon thread so we never block holding
- ``_agent_cache_lock`` on slow socket teardown — mirrors the
- cap-enforcer and idle-sweeper paths.
+ Safe on bare test runners built via ``object.__new__`` (every
+ access is getattr-guarded).
"""
- # Prompt-stability state rides the agent-cache lifecycle: a fresh
- # agent must re-render its session-context bytes (the pin) and re-see
- # the current voice-channel state once.
- _evict_state = self._peek_session_state(session_key)
- if _evict_state is not None:
- _evict_state.conversation.ephemeral_pin = None
- _evict_state.conversation.vc_last = None
-
- _lock = getattr(self, "_agent_cache_lock", None)
- evicted = None
- if _lock:
- with _lock:
- evicted = self._agent_cache.pop(session_key, None)
- else:
- _cache = getattr(self, "_agent_cache", None)
- if _cache is not None:
- evicted = _cache.pop(session_key, None)
+ if not session_key:
+ return
+ # Structural clear: every conversation-scoped field resets in one
+ # call — no per-attribute pop-list to drift.
+ state = self._peek_session_state(session_key)
+ if state is not None:
+ state.conversation.clear()
+ # Legacy plain-dict stores still registered in
+ # _CONVERSATION_SCOPED_STATE (not yet folded into SessionState),
+ # e.g. _pending_model_notes. SessionState-backed names resolve to
+ # MutableMapping views (not dict), so the isinstance(dict) guard
+ # skips them — already handled above.
+ for attr in _CONVERSATION_SCOPED_STATE:
+ store = getattr(self, attr, None)
+ if isinstance(store, dict):
+ store.pop(session_key, None)
+ self._clear_session_boundary_security_state(session_key)
+ logger.debug(
+ "Cleared conversation scope for %s (%s)", session_key, reason
+ )
- agent = evicted[0] if isinstance(evicted, tuple) and evicted else evicted
- if agent is None or agent is _AGENT_PENDING_SENTINEL:
+ def _clear_session_boundary_security_state(self, session_key: str) -> None:
+ """Clear per-session control state that must not survive a boundary switch."""
+ if not session_key:
return
- # Don't tear down an agent that's actively mid-turn — its client,
- # sandbox and child subagents are in use by the running request.
- running_ids = {
- id(a)
- for _, a in self._running_agent_items()
- if a is not None and a is not _AGENT_PENDING_SENTINEL
- }
- if id(agent) in running_ids:
- return
+ pending_skills_reload_notes = getattr(
+ self, "_pending_skills_reload_notes", None
+ )
+ if isinstance(pending_skills_reload_notes, dict):
+ pending_skills_reload_notes.pop(session_key, None)
+
+ _sec_state = self._peek_session_state(session_key)
+ if _sec_state is not None:
+ _sec_state.persistent.approvals = None
+ _sec_state.persistent.update_prompt_pending = False
try:
- threading.Thread(
- target=self._release_evicted_agent_soft,
- args=(agent,),
- daemon=True,
- name=f"agent-evict-{str(session_key)[:24]}",
- ).start()
+ from tools import slash_confirm as _slash_confirm_mod
except Exception:
- # If we can't spawn a thread (interpreter shutdown), release
- # inline as a best-effort fallback.
+ _slash_confirm_mod = None
+ if _slash_confirm_mod is not None:
try:
- self._release_evicted_agent_soft(agent)
- except Exception:
- pass
+ _slash_confirm_mod.clear(session_key)
+ except Exception as e:
+ logger.debug(
+ "Failed to clear slash-confirm state for session boundary %s: %s",
+ session_key,
+ e,
+ )
- @staticmethod
- def _init_cached_agent_for_turn(agent: Any, interrupt_depth: int) -> None:
- """Reset per-turn state on a cached agent before a new turn starts.
+ try:
+ from tools.approval import clear_session as _clear_approval_session
+ except Exception:
+ return
- Both _last_activity_ts and _last_activity_desc are only reset for
- fresh external turns (depth 0); they are semantically paired —
- desc describes the activity *at* ts, so updating one without the
- other would make get_activity_summary() misleading.
- For interrupt-recursive turns both are preserved so the inactivity
- watchdog can accumulate stuck-turn idle time and fire the 30-min
- timeout (#15654). The depth-0 reset is still needed: a session
- idle for 29 min would otherwise trip the watchdog before the new
- turn makes its first API call (#9051).
- """
- if interrupt_depth == 0:
- agent._last_activity_ts = time.time()
- agent._last_activity_desc = "starting new turn (cached)"
- # Reset the SessionDB flush cursor so the new turn's messages are
- # fully persisted — a stale value from the previous turn would
- # cause `_flush_messages_to_session_db` to skip new rows (#44327).
- if hasattr(agent, "_last_flushed_db_idx"):
- agent._last_flushed_db_idx = 0
- agent._api_call_count = 0
+ try:
+ _clear_approval_session(session_key)
+ except Exception as e:
+ logger.debug(
+ "Failed to clear approval state for session boundary %s: %s",
+ session_key,
+ e,
+ )
- def _commit_memory_before_soft_evict(self, agent: Any, key: str) -> None:
- """Fire on_session_end extraction before soft-evicting a live agent.
+ def _begin_session_run_generation(self, session_key: str) -> int:
+ """Claim a fresh run generation token for ``session_key``.
- Soft eviction (``_release_evicted_agent_soft``) deliberately keeps the
- session resumable and does NOT fire ``on_session_end`` — that hook is
- reserved for the true session boundary, tear-down done by
- ``_session_expiry_watcher`` when the session finally expires.
+ Every top-level gateway turn gets a monotonically increasing token.
+ If a later command like /stop or /new invalidates that token while the
+ old worker is still unwinding, the late result can be recognized and
+ dropped instead of bleeding into the fresh session.
+ """
+ if not session_key:
+ return 0
+ persistent = self._session_state(session_key).persistent
+ # Monotonic by design (#28686): incremented here, NEVER reset.
+ persistent.run_generation = int(persistent.run_generation) + 1
+ return persistent.run_generation
- But the watcher tears down whatever agent it finds in ``_agent_cache``
- at expiry time. If cache pressure (the LRU cap) soft-evicts a
- finalizable session's agent BEFORE it expires, the watcher later finds
- no cached agent and ``on_session_end`` is silently skipped — memory
- providers never see the transcript (#11205, LRU-cap variant).
+ def _invalidate_session_run_generation(self, session_key: str, *, reason: str = "") -> int:
+ """Invalidate any in-flight run token for ``session_key``."""
+ generation = self._begin_session_run_generation(session_key)
+ if reason:
+ logger.info(
+ "Invalidated run generation for %s → %d (%s)",
+ session_key,
+ generation,
+ reason,
+ )
+ return generation
- We hold the live, fully-scoped agent right now, so commit its
- end-of-session memory extraction here using the agent's own memory
- manager (correct per-user/chat scoping, no reconstruction). This uses
- ``commit_memory_session`` — extraction WITHOUT provider teardown — so
- the eviction stays soft and a resumed turn keeps working.
+ def _is_session_run_current(self, session_key: str, generation: int) -> bool:
+ """Return True when ``generation`` is still current for ``session_key``."""
+ if not session_key:
+ return True
+ state = self._peek_session_state(session_key)
+ current = state.persistent.run_generation if state is not None else 0
+ return int(current) == int(generation)
- Only fires for sessions the expiry watcher will eventually finalize
- (finite reset policy). For ``mode == "none"`` sessions the watcher
- never runs, so there is no missed-boundary to compensate for and we
- skip the commit (the agent is simply released). Best-effort: any
- failure is swallowed so eviction still proceeds.
- """
- if agent is None or not hasattr(agent, "commit_memory_session"):
+ def _bind_adapter_run_generation(
+ self,
+ adapter: Any,
+ session_key: str,
+ generation: int | None,
+ ) -> None:
+ """Bind a gateway run generation to the adapter's active-session event."""
+ if not adapter or not session_key or generation is None:
return
- if getattr(agent, "_memory_manager", None) is None:
- return # no external memory provider — nothing to commit
try:
- _store = getattr(self, "session_store", None)
- if _store is None:
- return
- _store._ensure_loaded()
- entry = _store._entries.get(key)
- if entry is None:
- return
- # Only compensate when the watcher would otherwise expect to find
- # this agent at expiry (finite policy, not yet expired). Expired
- # sessions are torn down by the watcher directly; mode="none"
- # sessions are never finalized.
- if not _store.is_session_finalizable(entry):
- return
- if _store._is_session_expired(entry):
- return
- messages = getattr(agent, "_session_messages", None)
- agent.commit_memory_session(messages if isinstance(messages, list) else None)
- logger.debug(
- "Committed on_session_end extraction before soft-evicting "
- "finalizable session=%s (cache pressure, pre-expiry)", key,
- )
- except Exception as _e:
- logger.debug("Pre-evict memory commit failed for %s: %s", key, _e)
+ interrupt_event = getattr(adapter, "_active_sessions", {}).get(session_key)
+ if interrupt_event is not None:
+ setattr(interrupt_event, "_hermes_run_generation", int(generation))
+ except Exception:
+ pass
- def _commit_then_release_soft(self, agent: Any, key: str) -> None:
- """Commit end-of-session memory (if warranted), then soft-release.
+ async def _interrupt_and_clear_session(
+ self,
+ session_key: str,
+ source: SessionSource,
+ *,
+ interrupt_reason: str,
+ invalidation_reason: str,
+ release_running_state: bool = True,
+ ) -> None:
+ """Interrupt the current run and clear queued session state consistently."""
+ if not session_key:
+ return
+ _iac_state = self._peek_session_state(session_key)
+ running_agent = _iac_state.turn.agent if _iac_state else None
+ if running_agent and running_agent is not _AGENT_PENDING_SENTINEL:
+ running_agent.interrupt(interrupt_reason)
+ self._invalidate_session_run_generation(session_key, reason=invalidation_reason)
+ adapter = self._adapter_for_source(source)
+ interrupt_session_activity = getattr(
+ type(adapter), "interrupt_session_activity", None
+ )
+ if adapter and callable(interrupt_session_activity):
+ metadata = self._thread_metadata_for_source(source)
+ try:
+ params = inspect.signature(interrupt_session_activity).parameters
+ accepts_metadata = "metadata" in params or any(
+ param.kind is inspect.Parameter.VAR_KEYWORD
+ for param in params.values()
+ )
+ except (TypeError, ValueError):
+ accepts_metadata = False
+ if accepts_metadata:
+ await adapter.interrupt_session_activity(
+ session_key, source.chat_id, metadata=metadata
+ )
+ else:
+ await adapter.interrupt_session_activity(session_key, source.chat_id)
+ if adapter and hasattr(adapter, "get_pending_message"):
+ adapter.get_pending_message(session_key) # consume and discard
+ if _iac_state is not None:
+ _iac_state.persistent.pending_command_text = None
+ if release_running_state:
+ self._release_running_agent_state(session_key)
+ # Evict the cached agent: ``_interrupt_requested`` is only
+ # cleared by the turn finalizer, so on a hung or still-draining
+ # run the flag survives the lock release and kills the session's
+ # NEXT message at the top of the tool loop (interrupted=True,
+ # api_calls=0, empty response — silently swallowed, #44212).
+ # Evicting mirrors the /new and /model paths: the next message
+ # rebuilds the agent from session history, while the old agent
+ # object keeps its interrupt flag so a hung drain still dies
+ # when it unblocks.
+ self._evict_cached_agent(session_key)
- Runs on the daemon eviction thread so the memory-provider call and the
- client teardown never block the caller's held cache lock. Order matters:
- commit uses the live agent's memory manager before ``release_clients``
- drops the message buffer.
- """
- self._commit_memory_before_soft_evict(agent, key)
- self._release_evicted_agent_soft(agent)
+ async def _refresh_agent_cache_message_count(
+ self, session_key: str, session_id: Optional[str]
+ ) -> None:
+ """Re-baseline a cached agent's stored message_count after THIS turn.
+
+ The cross-process coherence guard (#45966) compares the session's
+ on-disk ``message_count`` against the count snapshotted next to the
+ cached agent, and rebuilds the agent on a mismatch. But the snapshot
+ is taken at agent-BUILD time — before this turn writes its own user +
+ assistant (+ tool) rows — and the cache entry is never rewritten on a
+ reuse. So without this re-baseline, THIS process's own turn would
+ grow ``message_count`` and the very next turn would see a mismatch
+ and rebuild the agent — every turn, for every conversation — silently
+ destroying the per-conversation prompt caching the cache exists to
+ protect.
- def _release_evicted_agent_soft(self, agent: Any) -> None:
- """Soft cleanup for cache-evicted agents — preserves session tool state.
+ Call this once a turn has completed and the agent has flushed its
+ rows to the SessionDB. It snapshots the now-current count (which
+ includes this process's own writes) so the guard only fires when a
+ DIFFERENT process changes the transcript out from under us. The
+ ``_sig`` is left untouched; only the count element is refreshed, and
+ only when the same agent is still cached (no rebuild/eviction raced
+ in between). Fail-safe: any DB error leaves the snapshot as-is, which
+ at worst costs one unnecessary rebuild on the next turn.
- Called from _enforce_agent_cache_cap and _sweep_idle_cached_agents.
- Distinct from _cleanup_agent_resources (full teardown) because a
- cache-evicted session may resume at any time — its terminal
- sandbox, browser daemon, and tracked bg processes must outlive
- the Python AIAgent instance so the next agent built for the
- same task_id inherits them.
+ When the cache entry records a ``session_id`` (4-tuple form, #54947)
+ that differs from the current ``session_id`` — meaning the cache
+ was built for a DIFFERENT conversation under the same ``session_key``
+ — the snapshot is intentionally left untouched. Overwriting it with
+ the current session's count would corrupt the original conversation's
+ baseline and cause the next switch back to fire the cross-process
+ guard spuriously. Fail-safe: the legacy 3-tuple shape (no
+ ``session_id``) is still re-baselined as before.
"""
- if agent is None:
+ if self._session_db is None or not session_id:
+ return
+ _cache_lock = getattr(self, "_agent_cache_lock", None)
+ _cache = getattr(self, "_agent_cache", None)
+ if not _cache_lock or _cache is None:
return
try:
- if hasattr(agent, "release_clients"):
- agent.release_clients()
- else:
- # Older agent instance (shouldn't happen in practice) —
- # fall back to the legacy full-close path.
- self._cleanup_agent_resources(agent)
+ _sess_row = await self._session_db.get_session(session_id)
+ _live = _sess_row.get("message_count", 0) if _sess_row else None
except Exception:
- pass
- # Free conversation history memory — can be tens of MB with tool
- # outputs (file reads, terminal output, search results) on heavy
- # 100+-tool-call sessions. release_clients() deliberately preserves
- # session tool state for resume, but the message list is rebuilt from
- # persisted session JSON on the next turn, so dropping it here is safe.
- if hasattr(agent, "_session_messages"):
- agent._session_messages = []
-
- def _enforce_agent_cache_cap(self) -> None:
- """Evict oldest cached agents when cache exceeds _AGENT_CACHE_MAX_SIZE.
-
- Must be called with _agent_cache_lock held. Resource cleanup
- (memory provider shutdown, tool resource close) is scheduled
- on a daemon thread so the caller doesn't block on slow teardown
- while holding the cache lock.
-
- Agents currently in _running_agents are SKIPPED — their clients,
- terminal sandboxes, background processes, and child subagents
- are all in active use by the running turn. Evicting them would
- tear down those resources mid-turn and crash the request. If
- every candidate in the LRU order is active, we simply leave the
- cache over the cap; it will be re-checked on the next insert.
- """
- _cache = getattr(self, "_agent_cache", None)
- if _cache is None:
return
- # OrderedDict.popitem(last=False) pops oldest; plain dict lacks the
- # arg so skip enforcement if a test fixture swapped the cache type.
- if not hasattr(_cache, "move_to_end"):
+ if _live is None:
return
+ with _cache_lock:
+ cached = _cache.get(session_key)
+ # Only re-baseline a live 3-tuple entry; skip pending sentinels,
+ # legacy 2-tuples (they intentionally opt out of the guard), and
+ # the case where the entry was evicted/rebuilt mid-turn.
+ if (
+ isinstance(cached, tuple)
+ and len(cached) > 2
+ and cached[0] is not _AGENT_PENDING_SENTINEL
+ ):
+ # If the snapshot was taken for a different session_id
+ # (same session_key, different conversation), leave the
+ # snapshot alone — the current session_id's count belongs
+ # to a different DB row (#54947).
+ _snapshot_sid = cached[3] if len(cached) > 3 else None
+ if _snapshot_sid is not None and _snapshot_sid != session_id:
+ return
+ if cached[2] != _live:
+ if _snapshot_sid is None:
+ # Legacy 3-tuple: preserve the original 3-element
+ # shape so existing entries stay compatible with
+ # callers that index ``cached[2]`` directly.
+ _cache[session_key] = (cached[0], cached[1], _live)
+ else:
+ _cache[session_key] = (
+ cached[0], cached[1], _live, _snapshot_sid,
+ )
- # Snapshot of agent instances that are actively mid-turn. Use id()
- # so the lookup is O(1) and doesn't depend on AIAgent.__eq__ (which
- # MagicMock overrides in tests).
- running_ids = {
- id(a)
- for _, a in self._running_agent_items()
- if a is not None and a is not _AGENT_PENDING_SENTINEL
- }
-
- # Walk LRU → MRU and evict excess-LRU entries that aren't mid-turn.
- # We only consider entries in the first (size - cap) LRU positions
- # as eviction candidates. If one of those slots is held by an
- # active agent, we SKIP it without compensating by evicting a
- # newer entry — that would penalise a freshly-inserted session
- # (which has no cache history to retain) while protecting an
- # already-cached long-running one. The cache may therefore stay
- # temporarily over cap; it will re-check on the next insert,
- # after active turns have finished.
- excess = max(0, len(_cache) - _AGENT_CACHE_MAX_SIZE)
- evict_plan: List[tuple] = [] # [(key, agent), ...]
- if excess > 0:
- ordered_keys = list(_cache.keys())
- for key in ordered_keys[:excess]:
- entry = _cache.get(key)
- agent = entry[0] if isinstance(entry, tuple) and entry else None
- if agent is not None and id(agent) in running_ids:
- continue # active mid-turn; don't evict, don't substitute
- evict_plan.append((key, agent))
-
- for key, _ in evict_plan:
- _cache.pop(key, None)
-
- remaining_over_cap = len(_cache) - _AGENT_CACHE_MAX_SIZE
- if remaining_over_cap > 0:
- logger.warning(
- "Agent cache over cap (%d > %d); %d excess slot(s) held by "
- "mid-turn agents — will re-check on next insert.",
- len(_cache), _AGENT_CACHE_MAX_SIZE, remaining_over_cap,
- )
-
- for key, agent in evict_plan:
- logger.info(
- "Agent cache at cap; evicting LRU session=%s (cache_size=%d)",
- key, len(_cache),
- )
- if agent is not None:
- # Commit end-of-session memory extraction, then soft-release,
- # both on the daemon thread so the (possibly network-bound)
- # provider call never blocks the held cache lock. The commit
- # only fires for finalizable-not-yet-expired sessions whose
- # agent would otherwise vanish before the expiry watcher can
- # fire on_session_end (#11205, LRU-cap variant).
- threading.Thread(
- target=self._commit_then_release_soft,
- args=(agent, key),
- daemon=True,
- name=f"agent-cache-evict-{key[:24]}",
- ).start()
-
- def _sweep_idle_cached_agents(self) -> int:
- """Evict cached agents whose AIAgent has been idle > _AGENT_CACHE_IDLE_TTL_SECS.
-
- Safe to call from the session expiry watcher without holding the
- cache lock — acquires it internally. Returns the number of entries
- evicted. Resource cleanup is scheduled on daemon threads.
-
- Agents currently in _running_agents are SKIPPED for the same reason
- as _enforce_agent_cache_cap: tearing down an active turn's clients
- mid-flight would crash the request.
- """
- _cache = getattr(self, "_agent_cache", None)
- _lock = getattr(self, "_agent_cache_lock", None)
- if _cache is None or _lock is None:
- return 0
- now = time.time()
- to_evict: List[tuple] = []
- running_ids = {
- id(a)
- for _, a in self._running_agent_items()
- if a is not None and a is not _AGENT_PENDING_SENTINEL
- }
- with _lock:
- for key, entry in list(_cache.items()):
- agent = entry[0] if isinstance(entry, tuple) and entry else None
- if agent is None:
- continue
- if id(agent) in running_ids:
- continue # mid-turn — don't tear it down
- last_activity = getattr(agent, "_last_activity_ts", None)
- if last_activity is None:
- continue
- if (now - last_activity) > _AGENT_CACHE_IDLE_TTL_SECS:
- # Check whether the session has actually expired in the
- # session store. If it hasn't (e.g. daily-reset mode
- # where the reset fires hours after the user's last
- # message), keep the agent in cache so the session-store
- # expiry watcher can still find it and call
- # on_session_end() with the live transcript. Skipping
- # eviction here means the agent stays alive until the
- # session genuinely expires, at which point the watcher
- # (gateway/run.py _session_expiry_watcher) tears it down
- # properly. (#11205 follow-up)
- #
- # BUT only defer when the watcher will EVER finalize this
- # session. For a mode == "none" session the watcher never
- # fires (is_session_finalizable() is False), so deferring
- # would pin the agent in cache for the gateway's entire
- # lifetime — the exact leak this idle sweep exists to
- # relieve. Those sessions fall through to soft eviction
- # WITHOUT on_session_end, and that is correct: a mode=="none"
- # session never reaches a session-end boundary, so there is
- # no missed on_session_end to compensate for. (The finite
- # case — a session evicted under LRU-cap pressure before it
- # expires — is instead covered by _commit_memory_before_soft_
- # evict on the cap path, which fires on_session_end via the
- # live agent's memory manager before releasing it.)
- session_entry = None
- _store = getattr(self, "session_store", None)
- try:
- if _store is not None:
- _store._ensure_loaded()
- session_entry = _store._entries.get(key)
- except Exception:
- session_entry = None
- if (
- session_entry is not None
- and _store is not None
- and _store.is_session_finalizable(session_entry)
- and not _store._is_session_expired(session_entry)
- ):
- continue # keep agent — finite session hasn't expired
- to_evict.append((key, agent))
- for key, _ in to_evict:
- _cache.pop(key, None)
- for key, agent in to_evict:
- logger.info(
- "Agent cache idle-TTL evict: session=%s (idle=%.0fs)",
- key, now - getattr(agent, "_last_activity_ts", now),
- )
- threading.Thread(
- target=self._release_evicted_agent_soft,
- args=(agent,),
- daemon=True,
- name=f"agent-cache-idle-{key[:24]}",
- ).start()
- return len(to_evict)
+ def _set_pending_turn_sidecar_notes(self, session_key: str, notes: List[str]) -> None:
+ """Stage per-turn must-deliver notes for the next agent run (one-shot)."""
+ if not session_key or not notes:
+ return
+ self._session_state(session_key).conversation.sidecar_notes = list(notes)
- # ------------------------------------------------------------------
- # Proxy mode: forward messages to a remote Hermes API server
- # ------------------------------------------------------------------
+ def _consume_pending_turn_sidecar_notes(self, session_key: str) -> List[str]:
+ if not session_key:
+ return []
+ state = self._peek_session_state(session_key)
+ if state is None:
+ return []
+ staged = state.conversation.sidecar_notes
+ state.conversation.sidecar_notes = []
+ return list(staged) if isinstance(staged, list) else []
- def _get_proxy_url(self) -> Optional[str]:
- """Return the proxy URL if proxy mode is configured, else None.
+ def _voice_channel_sidecar_note(self, event, source: SessionSource, session_key: str) -> Optional[str]:
+ """Return a ``[Voice channel now: ...]`` note when VC state changed.
- Checks GATEWAY_PROXY_URL env var first (convenient for Docker),
- then ``gateway.proxy_url`` in config.yaml.
+ Compares the live Discord voice-channel context against the last
+ value delivered for this session and returns a note only on change
+ (including leaving the channel). Unchanged state returns ``None`` so
+ the per-turn member/speaking serialization cannot churn the prompt.
"""
- url = os.getenv("GATEWAY_PROXY_URL", "").strip()
- if url:
- return url.rstrip("/")
- cfg = _load_gateway_config()
- url = (cfg.get("gateway") or {}).get("proxy_url")
- url = (url or "").strip()
- if url:
- return url.rstrip("/")
- return None
+ if source.platform != Platform.DISCORD:
+ return None
+ adapter = self.adapters.get(Platform.DISCORD)
+ guild_id = self._get_guild_id(event)
+ if not (guild_id and adapter and hasattr(adapter, "get_voice_channel_context")):
+ return None
+ try:
+ vc_now = adapter.get_voice_channel_context(guild_id) or ""
+ except Exception:
+ logger.debug("voice-channel context read failed", exc_info=True)
+ return None
+ vc_prev = None
+ if session_key:
+ _vc_state = self._session_state(session_key)
+ vc_prev = _vc_state.conversation.vc_last
+ _vc_state.conversation.vc_last = vc_now
+ if vc_now == (vc_prev if vc_prev is not None else ""):
+ return None
+ if not vc_now:
+ return "[Voice channel now: not connected to a voice channel]"
+ return f"[Voice channel now: {vc_now}]"
- def _build_stream_consumer_config(
- self,
- source: "SessionSource",
- scfg: Any,
- adapter: Any,
- *,
- on_missing_cursor: str,
- ) -> "tuple[Any, Optional[Callable[[], None]]]":
- """Build the shared ``StreamConsumerConfig`` and the optional
- Telegram pause-typing closure used by both agent-run paths.
+ def _pinned_session_context_prompt(
+ self, context, redact_pii: bool, session_key: Optional[str]
+ ) -> str:
+ """Return the session-context prompt, pinned per session.
- ``on_missing_cursor`` controls how platforms whose adapter sets
- ``SUPPORTS_MESSAGE_EDITING = False`` are handled — both semantics
- are preserved verbatim from the pre-refactor call sites:
+ Key hit → the pinned bytes are reused VERBATIM (immunizes the
+ composed system prompt against renderer nondeterminism); key miss →
+ re-render ``build_session_context_prompt`` and re-pin (a legitimate
+ cache bust: rename, topic edit, /sethome, redact_pii flip, ...).
+ """
+ _eph_key = self._ephemeral_change_key(context, redact_pii)
+ _eph_pin = None
+ if session_key:
+ _pin_state = self._peek_session_state(session_key)
+ _eph_pin = _pin_state.conversation.ephemeral_pin if _pin_state else None
+ if _eph_pin is not None and _eph_pin[0] == _eph_key:
+ return _eph_pin[1]
+ text = build_session_context_prompt(context, redact_pii=redact_pii)
+ if session_key:
+ self._session_state(session_key).conversation.ephemeral_pin = (
+ _eph_key,
+ text,
+ )
+ return text
- - ``"fallback"`` (proxy path): stream anyway with an empty cursor.
- - ``"raise"`` (in-process agent path): raise ``RuntimeError`` so
- the caller's ``except`` skips streaming entirely.
+ @staticmethod
+ def _ephemeral_change_key(context, redact_pii: bool) -> str:
+ """Hash the exact inputs ``build_session_context_prompt`` renders.
- Returns ``(consumer_cfg, pause_typing_before_finalize)``.
+ This key decides when the pinned per-session context-prompt bytes are
+ reused verbatim vs re-rendered. The maintained invariant (guarded by
+ the parity test in tests/gateway/test_prompt_tail_freeze.py): any
+ input whose change alters the rendered bytes MUST appear here —
+ omission means a stale pinned prompt (cosmetic staleness); inclusion
+ of an extra field only costs a spurious re-render.
"""
- from gateway.stream_consumer import StreamConsumerConfig
+ import hashlib
- _pause_typing_before_finalize = None
- if source.platform == Platform.TELEGRAM and hasattr(adapter, "pause_typing_for_chat"):
- def _pause_typing_before_finalize(
- _adapter=adapter,
- _chat_id=source.chat_id,
- ) -> None:
- _adapter.pause_typing_for_chat(_chat_id)
- # Platforms that don't support editing sent messages
- # (e.g. QQ, WeChat) should skip streaming entirely —
- # without edit support, the consumer sends a partial
- # first message that can never be updated, resulting in
- # duplicate messages (partial + final).
- # (The proxy path instead opts into a cursorless fallback
- # via on_missing_cursor="fallback".)
- _adapter_supports_edit = getattr(adapter, "SUPPORTS_MESSAGE_EDITING", True)
- if not _adapter_supports_edit and on_missing_cursor == "raise":
- raise RuntimeError("skip streaming for non-editable platform")
- _effective_cursor = scfg.cursor if _adapter_supports_edit else ""
- # Some Matrix clients render the streaming cursor
- # as a visible tofu/white-box artifact. Keep
- # streaming text on Matrix, but suppress the cursor.
- _buffer_only = False
- if source.platform == Platform.MATRIX:
- _effective_cursor = ""
- _buffer_only = True
- # Fresh-final applies to Telegram only — other
- # platforms either edit in place cheaply (Discord,
- # Slack) or don't have the timestamp-on-edit /
- # edit-timestamp-stays-stale problem.
- # (Ported from openclaw/openclaw#72038.)
- _fresh_final_secs = (
- float(getattr(scfg, "fresh_final_after_seconds", 0.0) or 0.0)
- if source.platform == Platform.TELEGRAM
- else 0.0
- )
- _consumer_cfg = StreamConsumerConfig(
- edit_interval=scfg.edit_interval,
- buffer_threshold=scfg.buffer_threshold,
- cursor=_effective_cursor,
- buffer_only=_buffer_only,
- fresh_final_after_seconds=_fresh_final_secs,
- transport=scfg.transport or "edit",
- chat_type=getattr(source, "chat_type", "") or "",
- )
- return _consumer_cfg, _pause_typing_before_finalize
+ src = context.source
+ platform = src.platform.value if src.platform else ""
- async def _run_agent_via_proxy(
- self,
- message: str,
- context_prompt: str,
- history: List[Dict[str, Any]],
- source: "SessionSource",
- session_id: str,
- session_key: str = None,
- run_generation: Optional[int] = None,
- event_message_id: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Forward the message to a remote Hermes API server instead of
- running a local AIAgent.
+ discord_ids: tuple = ()
+ discord_tools = ""
+ if src.platform == Platform.DISCORD:
+ from gateway.session import _discord_tools_loaded
- When ``GATEWAY_PROXY_URL`` (or ``gateway.proxy_url`` in config.yaml)
- is set, the gateway becomes a thin relay: it handles platform I/O
- (encryption, threading, media) and delegates all agent work to the
- remote server via ``POST /v1/chat/completions`` with SSE streaming.
+ discord_tools = "1" if _discord_tools_loaded() else "0"
+ discord_ids = (
+ str(src.guild_id or ""),
+ str(src.parent_chat_id or ""),
+ str(src.thread_id or ""),
+ str(src.chat_id or ""),
+ # Only PRESENCE is rendered (the id itself is delivered
+ # per-turn in the user message) — keying on the value would
+ # re-render every message for zero byte change.
+ "1" if src.message_id else "0",
+ )
+
+ # Slack renders a capability-aware platform note gated on
+ # _slack_tools_loaded() — the gate state must appear in the key
+ # (same parity contract as the Discord gate above) so a config /
+ # MCP-registration flip re-renders once instead of serving a
+ # stale pinned note for the rest of the session.
+ slack_tools = ""
+ if src.platform == Platform.SLACK:
+ from gateway.session import _slack_tools_loaded
+
+ slack_tools = "1" if _slack_tools_loaded() else "0"
- This lets a Docker container handle Matrix E2EE while the actual
- agent runs on the host with full access to local files, memory,
- skills, and a unified session store.
- """
try:
- from aiohttp import ClientSession as _AioClientSession, ClientTimeout
- except ImportError:
- return {
- "final_response": "⚠️ Proxy mode requires aiohttp. Install with: pip install aiohttp",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- }
+ from hermes_constants import display_hermes_home
+
+ home_display = str(display_hermes_home())
+ except Exception:
+ home_display = ""
+
+ key_tuple = (
+ platform,
+ str(src.chat_id or ""),
+ str(src.thread_id or ""),
+ str(src.chat_type or ""),
+ str(src.chat_name or ""),
+ str(src.chat_topic or ""),
+ str(src.user_name or ""),
+ str(src.user_id or ""),
+ str(getattr(src, "profile", None) or ""),
+ bool(context.shared_multi_user_session),
+ discord_ids,
+ discord_tools,
+ slack_tools,
+ tuple(p.value for p in context.connected_platforms),
+ tuple(
+ (
+ p.value,
+ str(getattr(hc, "name", "") or ""),
+ str(getattr(hc, "chat_id", "") or ""),
+ )
+ for p, hc in context.home_channels.items()
+ ),
+ bool(redact_pii),
+ home_display,
+ )
+ return hashlib.sha256(repr(key_tuple).encode("utf-8")).hexdigest()
+
+ def _evict_cached_agent(self, session_key: str) -> None:
+ """Remove a cached agent for a session (called on /new, /model, etc).
+
+ Pops the entry AND soft-releases the evicted agent's LLM client
+ pool so the httpx connection (sockets + held buffers) is freed
+ promptly rather than waiting on CPython GC — AIAgent holds
+ reference cycles (callbacks, tool state) that delay refcount
+ collection, so a manual release is required to keep gateway RSS
+ flat across many /new, /model, undo and reset operations (#29298,
+ same leak class as #25315).
+
+ The release is soft (``release_clients()``): it frees the client
+ pool and per-turn child subagents but PRESERVES the session's
+ terminal sandbox, browser daemon, and tracked bg processes (keyed
+ on task_id), because the session may resume with a freshly-built
+ agent. Call sites that want a hard teardown (true conversation
+ boundaries like /new) already call ``_cleanup_agent_resources``
+ before evicting; ``release_clients`` is idempotent and safe to
+ run again after that (the client is already None).
+
+ Cleanup runs on a daemon thread so we never block holding
+ ``_agent_cache_lock`` on slow socket teardown — mirrors the
+ cap-enforcer and idle-sweeper paths.
+ """
+ # Prompt-stability state rides the agent-cache lifecycle: a fresh
+ # agent must re-render its session-context bytes (the pin) and re-see
+ # the current voice-channel state once.
+ _evict_state = self._peek_session_state(session_key)
+ if _evict_state is not None:
+ _evict_state.conversation.ephemeral_pin = None
+ _evict_state.conversation.vc_last = None
- proxy_url = self._get_proxy_url()
- if not proxy_url:
- return {
- "final_response": "⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url)",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- }
+ _lock = getattr(self, "_agent_cache_lock", None)
+ evicted = None
+ if _lock:
+ with _lock:
+ evicted = self._agent_cache.pop(session_key, None)
+ else:
+ _cache = getattr(self, "_agent_cache", None)
+ if _cache is not None:
+ evicted = _cache.pop(session_key, None)
- proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()
+ agent = evicted[0] if isinstance(evicted, tuple) and evicted else evicted
+ if agent is None or agent is _AGENT_PENDING_SENTINEL:
+ return
- def _run_still_current() -> bool:
- if run_generation is None or not session_key:
- return True
- return self._is_session_run_current(session_key, run_generation)
+ # Don't tear down an agent that's actively mid-turn — its client,
+ # sandbox and child subagents are in use by the running request.
+ running_ids = {
+ id(a)
+ for _, a in self._running_agent_items()
+ if a is not None and a is not _AGENT_PENDING_SENTINEL
+ }
+ if id(agent) in running_ids:
+ return
- # Build messages in OpenAI chat format --------------------------
- #
- # The remote api_server can maintain session continuity via
- # X-Hermes-Session-Id, so it loads its own history. We only
- # need to send the current user message. If the remote has
- # no history for this session yet, include what we have locally
- # so the first exchange has context.
- #
- # We always include the current message. For history, send a
- # compact version (text-only user/assistant turns) — the remote
- # handles tool replay and system prompts.
- api_messages: List[Dict[str, str]] = []
+ try:
+ threading.Thread(
+ target=self._release_evicted_agent_soft,
+ args=(agent,),
+ daemon=True,
+ name=f"agent-evict-{str(session_key)[:24]}",
+ ).start()
+ except Exception:
+ # If we can't spawn a thread (interpreter shutdown), release
+ # inline as a best-effort fallback.
+ try:
+ self._release_evicted_agent_soft(agent)
+ except Exception:
+ pass
- if context_prompt:
- api_messages.append({"role": "system", "content": context_prompt})
+ @staticmethod
+ def _init_cached_agent_for_turn(agent: Any, interrupt_depth: int) -> None:
+ """Reset per-turn state on a cached agent before a new turn starts.
- for msg in history:
- role = msg.get("role")
- content = msg.get("content")
- if role in {"user", "assistant"} and content:
- api_messages.append({"role": role, "content": content})
+ Both _last_activity_ts and _last_activity_desc are only reset for
+ fresh external turns (depth 0); they are semantically paired —
+ desc describes the activity *at* ts, so updating one without the
+ other would make get_activity_summary() misleading.
+ For interrupt-recursive turns both are preserved so the inactivity
+ watchdog can accumulate stuck-turn idle time and fire the 30-min
+ timeout (#15654). The depth-0 reset is still needed: a session
+ idle for 29 min would otherwise trip the watchdog before the new
+ turn makes its first API call (#9051).
+ """
+ if interrupt_depth == 0:
+ agent._last_activity_ts = time.time()
+ agent._last_activity_desc = "starting new turn (cached)"
+ # Reset the SessionDB flush cursor so the new turn's messages are
+ # fully persisted — a stale value from the previous turn would
+ # cause `_flush_messages_to_session_db` to skip new rows (#44327).
+ if hasattr(agent, "_last_flushed_db_idx"):
+ agent._last_flushed_db_idx = 0
+ agent._api_call_count = 0
- api_messages.append({"role": "user", "content": message})
+ def _commit_memory_before_soft_evict(self, agent: Any, key: str) -> None:
+ """Fire on_session_end extraction before soft-evicting a live agent.
- # HTTP headers ---------------------------------------------------
- headers: Dict[str, str] = {"Content-Type": "application/json"}
- if proxy_key:
- headers["Authorization"] = f"Bearer {proxy_key}"
- if session_id:
- headers["X-Hermes-Session-Id"] = session_id
+ Soft eviction (``_release_evicted_agent_soft``) deliberately keeps the
+ session resumable and does NOT fire ``on_session_end`` — that hook is
+ reserved for the true session boundary, tear-down done by
+ ``_session_expiry_watcher`` when the session finally expires.
- body = {
- "model": "hermes-agent",
- "messages": api_messages,
- "stream": True,
- }
+ But the watcher tears down whatever agent it finds in ``_agent_cache``
+ at expiry time. If cache pressure (the LRU cap) soft-evicts a
+ finalizable session's agent BEFORE it expires, the watcher later finds
+ no cached agent and ``on_session_end`` is silently skipped — memory
+ providers never see the transcript (#11205, LRU-cap variant).
- # Set up platform streaming if available -------------------------
- _stream_consumer = None
- _scfg = getattr(getattr(self, "config", None), "streaming", None)
- if _scfg is None:
- from gateway.config import StreamingConfig
- _scfg = StreamingConfig()
+ We hold the live, fully-scoped agent right now, so commit its
+ end-of-session memory extraction here using the agent's own memory
+ manager (correct per-user/chat scoping, no reconstruction). This uses
+ ``commit_memory_session`` — extraction WITHOUT provider teardown — so
+ the eviction stays soft and a resumed turn keeps working.
- platform_key = _platform_config_key(source.platform)
- user_config = _load_gateway_config()
- from gateway.display_config import resolve_display_setting
- _plat_streaming = resolve_display_setting(
- user_config, platform_key, "streaming"
- )
- _streaming_enabled = (
- _scfg.enabled and _scfg.transport != "off"
- if _plat_streaming is None
- else bool(_plat_streaming)
- )
+ Only fires for sessions the expiry watcher will eventually finalize
+ (finite reset policy). For ``mode == "none"`` sessions the watcher
+ never runs, so there is no missed-boundary to compensate for and we
+ skip the commit (the agent is simply released). Best-effort: any
+ failure is swallowed so eviction still proceeds.
+ """
+ if agent is None or not hasattr(agent, "commit_memory_session"):
+ return
+ if getattr(agent, "_memory_manager", None) is None:
+ return # no external memory provider — nothing to commit
+ try:
+ _store = getattr(self, "session_store", None)
+ if _store is None:
+ return
+ _store._ensure_loaded()
+ entry = _store._entries.get(key)
+ if entry is None:
+ return
+ # Only compensate when the watcher would otherwise expect to find
+ # this agent at expiry (finite policy, not yet expired). Expired
+ # sessions are torn down by the watcher directly; mode="none"
+ # sessions are never finalized.
+ if not _store.is_session_finalizable(entry):
+ return
+ if _store._is_session_expired(entry):
+ return
+ messages = getattr(agent, "_session_messages", None)
+ agent.commit_memory_session(messages if isinstance(messages, list) else None)
+ logger.debug(
+ "Committed on_session_end extraction before soft-evicting "
+ "finalizable session=%s (cache pressure, pre-expiry)", key,
+ )
+ except Exception as _e:
+ logger.debug("Pre-evict memory commit failed for %s: %s", key, _e)
- _thread_metadata: Optional[Dict[str, Any]] = self._thread_metadata_for_source(source, event_message_id)
+ def _commit_then_release_soft(self, agent: Any, key: str) -> None:
+ """Commit end-of-session memory (if warranted), then soft-release.
- if _streaming_enabled:
- try:
- from gateway.stream_consumer import GatewayStreamConsumer
- _adapter = self._adapter_for_source(source)
- if _adapter:
- _consumer_cfg, _pause_typing_before_finalize = (
- self._build_stream_consumer_config(
- source, _scfg, _adapter,
- on_missing_cursor="fallback",
- )
- )
- _stream_consumer = GatewayStreamConsumer(
- adapter=_adapter,
- chat_id=source.chat_id,
- config=_consumer_cfg,
- metadata=_thread_metadata,
- on_before_finalize=_pause_typing_before_finalize,
- initial_reply_to_id=event_message_id,
- run_still_current=_run_still_current,
- )
- except Exception as _sc_err:
- logger.debug("Proxy: could not set up stream consumer: %s", _sc_err)
+ Runs on the daemon eviction thread so the memory-provider call and the
+ client teardown never block the caller's held cache lock. Order matters:
+ commit uses the live agent's memory manager before ``release_clients``
+ drops the message buffer.
+ """
+ self._commit_memory_before_soft_evict(agent, key)
+ self._release_evicted_agent_soft(agent)
- # Run the stream consumer task in the background
- stream_task = None
- if _stream_consumer:
- stream_task = asyncio.create_task(_stream_consumer.run())
+ def _release_evicted_agent_soft(self, agent: Any) -> None:
+ """Soft cleanup for cache-evicted agents — preserves session tool state.
- # Send typing indicator
- _adapter = self._adapter_for_source(source)
- if _adapter:
- try:
- await _adapter.send_typing(source.chat_id, metadata=_thread_metadata)
- except Exception:
- pass
+ Called from _enforce_agent_cache_cap and _sweep_idle_cached_agents.
+ Distinct from _cleanup_agent_resources (full teardown) because a
+ cache-evicted session may resume at any time — its terminal
+ sandbox, browser daemon, and tracked bg processes must outlive
+ the Python AIAgent instance so the next agent built for the
+ same task_id inherits them.
+ """
+ if agent is None:
+ return
+ try:
+ if hasattr(agent, "release_clients"):
+ agent.release_clients()
+ else:
+ # Older agent instance (shouldn't happen in practice) —
+ # fall back to the legacy full-close path.
+ self._cleanup_agent_resources(agent)
+ except Exception:
+ pass
+ # Free conversation history memory — can be tens of MB with tool
+ # outputs (file reads, terminal output, search results) on heavy
+ # 100+-tool-call sessions. release_clients() deliberately preserves
+ # session tool state for resume, but the message list is rebuilt from
+ # persisted session JSON on the next turn, so dropping it here is safe.
+ if hasattr(agent, "_session_messages"):
+ agent._session_messages = []
- # Make the HTTP request with SSE streaming -----------------------
- full_response = ""
- _start = time.time()
+ def _enforce_agent_cache_cap(self) -> None:
+ """Evict oldest cached agents when cache exceeds _AGENT_CACHE_MAX_SIZE.
+
+ Must be called with _agent_cache_lock held. Resource cleanup
+ (memory provider shutdown, tool resource close) is scheduled
+ on a daemon thread so the caller doesn't block on slow teardown
+ while holding the cache lock.
- try:
- _timeout = ClientTimeout(total=0, sock_read=1800)
- async with _AioClientSession(timeout=_timeout) as session:
- async with session.post(
- f"{proxy_url}/v1/chat/completions",
- json=body,
- headers=headers,
- ) as resp:
- if resp.status != 200:
- error_text = await resp.text()
- logger.warning(
- "Proxy error (%d) from %s: %s",
- resp.status, proxy_url, error_text[:500],
- )
- return {
- "final_response": f"⚠️ Proxy error ({resp.status}): {error_text[:300]}",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- }
+ Agents currently in _running_agents are SKIPPED — their clients,
+ terminal sandboxes, background processes, and child subagents
+ are all in active use by the running turn. Evicting them would
+ tear down those resources mid-turn and crash the request. If
+ every candidate in the LRU order is active, we simply leave the
+ cache over the cap; it will be re-checked on the next insert.
+ """
+ _cache = getattr(self, "_agent_cache", None)
+ if _cache is None:
+ return
+ # OrderedDict.popitem(last=False) pops oldest; plain dict lacks the
+ # arg so skip enforcement if a test fixture swapped the cache type.
+ if not hasattr(_cache, "move_to_end"):
+ return
- # Parse SSE stream
- buffer = ""
- async for chunk in resp.content.iter_any():
- if not _run_still_current():
- logger.info(
- "Discarding stale proxy stream for %s — generation %d is no longer current",
- session_key or "?",
- run_generation or 0,
- )
- return {
- "final_response": "",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- "history_offset": len(history),
- "session_id": session_id,
- "response_previewed": False,
- }
- text = chunk.decode("utf-8", errors="replace")
- buffer += text
+ # Snapshot of agent instances that are actively mid-turn. Use id()
+ # so the lookup is O(1) and doesn't depend on AIAgent.__eq__ (which
+ # MagicMock overrides in tests).
+ running_ids = {
+ id(a)
+ for _, a in self._running_agent_items()
+ if a is not None and a is not _AGENT_PENDING_SENTINEL
+ }
- # Process complete SSE lines
- while "\n" in buffer:
- line, buffer = buffer.split("\n", 1)
- line = line.strip()
- if not line:
- continue
- if line.startswith("data: "):
- data = line[6:]
- if data.strip() == "[DONE]":
- break
- try:
- obj = json.loads(data)
- choices = obj.get("choices", [])
- if choices:
- delta = choices[0].get("delta", {})
- content = delta.get("content", "")
- if content:
- full_response += content
- if _stream_consumer:
- _stream_consumer.on_delta(content)
- except json.JSONDecodeError:
- pass
- if len(buffer) > _GATEWAY_PROXY_SSE_BUFFER_MAX_CHARS:
- raise ValueError(
- "Proxy SSE stream exceeded max buffer size without a line boundary"
- )
+ # Walk LRU → MRU and evict excess-LRU entries that aren't mid-turn.
+ # We only consider entries in the first (size - cap) LRU positions
+ # as eviction candidates. If one of those slots is held by an
+ # active agent, we SKIP it without compensating by evicting a
+ # newer entry — that would penalise a freshly-inserted session
+ # (which has no cache history to retain) while protecting an
+ # already-cached long-running one. The cache may therefore stay
+ # temporarily over cap; it will re-check on the next insert,
+ # after active turns have finished.
+ excess = max(0, len(_cache) - _AGENT_CACHE_MAX_SIZE)
+ evict_plan: List[tuple] = [] # [(key, agent), ...]
+ if excess > 0:
+ ordered_keys = list(_cache.keys())
+ for key in ordered_keys[:excess]:
+ entry = _cache.get(key)
+ agent = entry[0] if isinstance(entry, tuple) and entry else None
+ if agent is not None and id(agent) in running_ids:
+ continue # active mid-turn; don't evict, don't substitute
+ evict_plan.append((key, agent))
- except asyncio.CancelledError:
- raise
- except Exception as e:
- logger.error("Proxy connection error to %s: %s", proxy_url, e)
- if not full_response:
- return {
- "final_response": f"⚠️ Proxy connection error: {e}",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- }
- # Partial response — return what we got
- finally:
- # Finalize stream consumer
- if _stream_consumer:
- _stream_consumer.finish()
- if stream_task:
- try:
- await asyncio.wait_for(stream_task, timeout=5.0)
- except (asyncio.TimeoutError, asyncio.CancelledError):
- stream_task.cancel()
+ for key, _ in evict_plan:
+ _cache.pop(key, None)
- _elapsed = time.time() - _start
- if not _run_still_current():
+ remaining_over_cap = len(_cache) - _AGENT_CACHE_MAX_SIZE
+ if remaining_over_cap > 0:
+ logger.warning(
+ "Agent cache over cap (%d > %d); %d excess slot(s) held by "
+ "mid-turn agents — will re-check on next insert.",
+ len(_cache), _AGENT_CACHE_MAX_SIZE, remaining_over_cap,
+ )
+
+ for key, agent in evict_plan:
logger.info(
- "Discarding stale proxy result for %s — generation %d is no longer current",
- session_key or "?",
- run_generation or 0,
+ "Agent cache at cap; evicting LRU session=%s (cache_size=%d)",
+ key, len(_cache),
)
- return {
- "final_response": "",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- "history_offset": len(history),
- "session_id": session_id,
- "response_previewed": False,
- }
- logger.info(
- "proxy response: url=%s session=%s time=%.1fs response=%d chars",
- proxy_url, (session_id or "")[:20], _elapsed, len(full_response),
- )
+ if agent is not None:
+ # Commit end-of-session memory extraction, then soft-release,
+ # both on the daemon thread so the (possibly network-bound)
+ # provider call never blocks the held cache lock. The commit
+ # only fires for finalizable-not-yet-expired sessions whose
+ # agent would otherwise vanish before the expiry watcher can
+ # fire on_session_end (#11205, LRU-cap variant).
+ threading.Thread(
+ target=self._commit_then_release_soft,
+ args=(agent, key),
+ daemon=True,
+ name=f"agent-cache-evict-{key[:24]}",
+ ).start()
- return {
- "final_response": full_response or "(No response from remote agent)",
- "messages": [
- {"role": "user", "content": message},
- {"role": "assistant", "content": full_response},
- ],
- "api_calls": 1,
- "tools": [],
- "history_offset": len(history),
- "session_id": session_id,
- "response_previewed": _stream_consumer is not None and bool(full_response),
+ def _sweep_idle_cached_agents(self) -> int:
+ """Evict cached agents whose AIAgent has been idle > _AGENT_CACHE_IDLE_TTL_SECS.
+
+ Safe to call from the session expiry watcher without holding the
+ cache lock — acquires it internally. Returns the number of entries
+ evicted. Resource cleanup is scheduled on daemon threads.
+
+ Agents currently in _running_agents are SKIPPED for the same reason
+ as _enforce_agent_cache_cap: tearing down an active turn's clients
+ mid-flight would crash the request.
+ """
+ _cache = getattr(self, "_agent_cache", None)
+ _lock = getattr(self, "_agent_cache_lock", None)
+ if _cache is None or _lock is None:
+ return 0
+ now = time.time()
+ to_evict: List[tuple] = []
+ running_ids = {
+ id(a)
+ for _, a in self._running_agent_items()
+ if a is not None and a is not _AGENT_PENDING_SENTINEL
}
+ with _lock:
+ for key, entry in list(_cache.items()):
+ agent = entry[0] if isinstance(entry, tuple) and entry else None
+ if agent is None:
+ continue
+ if id(agent) in running_ids:
+ continue # mid-turn — don't tear it down
+ last_activity = getattr(agent, "_last_activity_ts", None)
+ if last_activity is None:
+ continue
+ if (now - last_activity) > _AGENT_CACHE_IDLE_TTL_SECS:
+ # Check whether the session has actually expired in the
+ # session store. If it hasn't (e.g. daily-reset mode
+ # where the reset fires hours after the user's last
+ # message), keep the agent in cache so the session-store
+ # expiry watcher can still find it and call
+ # on_session_end() with the live transcript. Skipping
+ # eviction here means the agent stays alive until the
+ # session genuinely expires, at which point the watcher
+ # (gateway/run.py _session_expiry_watcher) tears it down
+ # properly. (#11205 follow-up)
+ #
+ # BUT only defer when the watcher will EVER finalize this
+ # session. For a mode == "none" session the watcher never
+ # fires (is_session_finalizable() is False), so deferring
+ # would pin the agent in cache for the gateway's entire
+ # lifetime — the exact leak this idle sweep exists to
+ # relieve. Those sessions fall through to soft eviction
+ # WITHOUT on_session_end, and that is correct: a mode=="none"
+ # session never reaches a session-end boundary, so there is
+ # no missed on_session_end to compensate for. (The finite
+ # case — a session evicted under LRU-cap pressure before it
+ # expires — is instead covered by _commit_memory_before_soft_
+ # evict on the cap path, which fires on_session_end via the
+ # live agent's memory manager before releasing it.)
+ session_entry = None
+ _store = getattr(self, "session_store", None)
+ try:
+ if _store is not None:
+ _store._ensure_loaded()
+ session_entry = _store._entries.get(key)
+ except Exception:
+ session_entry = None
+ if (
+ session_entry is not None
+ and _store is not None
+ and _store.is_session_finalizable(session_entry)
+ and not _store._is_session_expired(session_entry)
+ ):
+ continue # keep agent — finite session hasn't expired
+ to_evict.append((key, agent))
+ for key, _ in to_evict:
+ _cache.pop(key, None)
+ for key, agent in to_evict:
+ logger.info(
+ "Agent cache idle-TTL evict: session=%s (idle=%.0fs)",
+ key, now - getattr(agent, "_last_activity_ts", now),
+ )
+ threading.Thread(
+ target=self._release_evicted_agent_soft,
+ args=(agent,),
+ daemon=True,
+ name=f"agent-cache-idle-{key[:24]}",
+ ).start()
+ return len(to_evict)
# ------------------------------------------------------------------
+ # Proxy mode: forward messages to a remote Hermes API server
+ # ------------------------------------------------------------------
- async def _run_agent(
- self,
- message: str,
- context_prompt: str,
- history: List[Dict[str, Any]],
- source: SessionSource,
- session_id: str,
- session_key: str = None,
- run_generation: Optional[int] = None,
- _interrupt_depth: int = 0,
- event_message_id: Optional[str] = None,
- channel_prompt: Optional[str] = None,
- moa_config: Optional[dict] = None,
- persist_user_message: Optional[Any] = None,
- persist_user_timestamp: Optional[float] = None,
- message_type: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Profile-scoping wrapper around the agent run.
+ def _get_proxy_url(self) -> Optional[str]:
+ """Return the proxy URL if proxy mode is configured, else None.
- When multiplexing is active, resolve the inbound source's profile and
- run the whole turn inside ``_profile_runtime_scope`` so config/skills/
- memory resolve to that profile's home AND credentials resolve from that
- profile's secret scope (never the process-global ``os.environ``). When
- multiplexing is off this is a transparent pass-through — zero behavior
- change for single-profile gateways.
+ Checks GATEWAY_PROXY_URL env var first (convenient for Docker),
+ then ``gateway.proxy_url`` in config.yaml.
"""
- if not getattr(getattr(self, "config", None), "multiplex_profiles", False):
- return await self._run_agent_inner(
- message, context_prompt, history, source, session_id,
- session_key=session_key, run_generation=run_generation,
- _interrupt_depth=_interrupt_depth, event_message_id=event_message_id,
- channel_prompt=channel_prompt, moa_config=moa_config,
- persist_user_message=persist_user_message,
- persist_user_timestamp=persist_user_timestamp,
- message_type=message_type,
- )
+ url = os.getenv("GATEWAY_PROXY_URL", "").strip()
+ if url:
+ return url.rstrip("/")
+ cfg = _load_gateway_config()
+ url = (cfg.get("gateway") or {}).get("proxy_url")
+ url = (url or "").strip()
+ if url:
+ return url.rstrip("/")
+ return None
- profile_home = self._resolve_profile_home_for_source(source)
- with _profile_runtime_scope(profile_home):
- return await self._run_agent_inner(
- message, context_prompt, history, source, session_id,
- session_key=session_key, run_generation=run_generation,
- _interrupt_depth=_interrupt_depth, event_message_id=event_message_id,
- channel_prompt=channel_prompt, moa_config=moa_config,
- persist_user_message=persist_user_message,
- persist_user_timestamp=persist_user_timestamp,
- message_type=message_type,
- )
+ def _build_stream_consumer_config(
+ self,
+ source: "SessionSource",
+ scfg: Any,
+ adapter: Any,
+ *,
+ on_missing_cursor: str,
+ ) -> "tuple[Any, Optional[Callable[[], None]]]":
+ """Build the shared ``StreamConsumerConfig`` and the optional
+ Telegram pause-typing closure used by both agent-run paths.
- def _profile_name_for_source(self, source: SessionSource) -> Optional[str]:
- """Resolve the profile name for an inbound source via configured routes.
+ ``on_missing_cursor`` controls how platforms whose adapter sets
+ ``SUPPORTS_MESSAGE_EDITING = False`` are handled — both semantics
+ are preserved verbatim from the pre-refactor call sites:
- Returns ``None`` when multiplexing is off, no routes are configured, or
- no route matches. Callers (``build_source``,
- ``_resolve_profile_home_for_source``) treat ``None`` as "use the
- default/active profile". When ``gateway.profile_routes`` is configured,
- the most specific matching route wins (guild < channel < thread). See
- :mod:`gateway.profile_routing` for matching rules.
+ - ``"fallback"`` (proxy path): stream anyway with an empty cursor.
+ - ``"raise"`` (in-process agent path): raise ``RuntimeError`` so
+ the caller's ``except`` skips streaming entirely.
- Gated on ``gateway.multiplex_profiles``: routing stamps
- ``source.profile``, which selects the session-key namespace and batch
- keys — but the profile-scoped agent run only activates under
- multiplexing. Without this gate, a configured route with multiplexing
- off would namespace batch/session keys by profile while the agent
- still runs in ``agent:main``, splitting the two out of agreement.
+ Returns ``(consumer_cfg, pause_typing_before_finalize)``.
"""
- config = getattr(self, "config", None)
- if not getattr(config, "multiplex_profiles", False):
- return None
- routes = getattr(config, "profile_routes", None)
- if not routes:
- return None
- from gateway.profile_routing import match_profile_route
- try:
- matched = match_profile_route(
- routes,
- platform=source.platform.value,
- guild_id=getattr(source, "guild_id", None),
- chat_id=source.chat_id,
- thread_id=getattr(source, "thread_id", None),
- parent_chat_id=getattr(source, "parent_chat_id", None),
- )
- except Exception:
- logger.warning(
- "Profile route matching failed for %s/%s, falling back to default",
- source.platform, source.chat_id, exc_info=True,
- )
- return None
- if matched:
- return matched.profile
- logger.debug(
- "No profile route matched: platform=%s chat_id=%s thread_id=%s parent_chat_id=%s",
- source.platform.value, source.chat_id,
- getattr(source, "thread_id", None), getattr(source, "parent_chat_id", None),
- )
- return None
-
- def _resolve_profile_home_for_source(self, source: SessionSource) -> "Path":
- """Resolve which profile's HERMES_HOME should serve this inbound source.
+ from gateway.stream_consumer import StreamConsumerConfig
- Resolution order:
- 1. ``source.profile`` — set by /p/<profile>/ URL prefix, per-credential
- adapter ownership, OR profile_routes matching at ``build_source`` time.
- 2. ``_profile_name_for_source`` — re-run routing here as a defensive
- fallback for sources that bypass ``build_source``.
- 3. The active profile (the multiplexer's own home).
- """
- from hermes_cli.profiles import (
- get_active_profile_name,
- get_profile_dir,
- profile_exists,
+ _pause_typing_before_finalize = None
+ if source.platform == Platform.TELEGRAM and hasattr(adapter, "pause_typing_for_chat"):
+ def _pause_typing_before_finalize(
+ _adapter=adapter,
+ _chat_id=source.chat_id,
+ ) -> None:
+ _adapter.pause_typing_for_chat(_chat_id)
+ # Platforms that don't support editing sent messages
+ # (e.g. QQ, WeChat) should skip streaming entirely —
+ # without edit support, the consumer sends a partial
+ # first message that can never be updated, resulting in
+ # duplicate messages (partial + final).
+ # (The proxy path instead opts into a cursorless fallback
+ # via on_missing_cursor="fallback".)
+ _adapter_supports_edit = getattr(adapter, "SUPPORTS_MESSAGE_EDITING", True)
+ if not _adapter_supports_edit and on_missing_cursor == "raise":
+ raise RuntimeError("skip streaming for non-editable platform")
+ _effective_cursor = scfg.cursor if _adapter_supports_edit else ""
+ # Some Matrix clients render the streaming cursor
+ # as a visible tofu/white-box artifact. Keep
+ # streaming text on Matrix, but suppress the cursor.
+ _buffer_only = False
+ if source.platform == Platform.MATRIX:
+ _effective_cursor = ""
+ _buffer_only = True
+ # Fresh-final applies to Telegram only — other
+ # platforms either edit in place cheaply (Discord,
+ # Slack) or don't have the timestamp-on-edit /
+ # edit-timestamp-stays-stale problem.
+ # (Ported from openclaw/openclaw#72038.)
+ _fresh_final_secs = (
+ float(getattr(scfg, "fresh_final_after_seconds", 0.0) or 0.0)
+ if source.platform == Platform.TELEGRAM
+ else 0.0
)
- from hermes_constants import get_hermes_home
-
- # Track whether a profile was explicitly requested (vs. falling back to default)
- explicit_profile = None
- try:
- name = (source.profile or "").strip()
- if name:
- explicit_profile = name # User explicitly set this profile
- if not name:
- name = self._profile_name_for_source(source)
- if name:
- explicit_profile = name # Routing explicitly set this profile
- if not name:
- name = get_active_profile_name() or "default"
-
- profile_dir = get_profile_dir(name)
- # Warn if an explicit profile doesn't exist on disk
- if explicit_profile and not profile_exists(name):
- logger.warning(
- "Profile %r does not exist for source %s/%s (guild_id=%s), "
- "falling back to global HERMES_HOME",
- explicit_profile,
- source.platform.value,
- source.chat_id,
- getattr(source, "guild_id", None),
- )
- return get_hermes_home()
- return profile_dir
- except Exception:
- # Catch normalization errors, path errors, etc.
- logger.warning(
- "Failed to resolve profile directory for source %s/%s (guild_id=%s), "
- "falling back to global HERMES_HOME: %s",
- source.platform.value,
- source.chat_id,
- getattr(source, "guild_id", None),
- explicit_profile or "(no profile)",
- exc_info=True,
- )
- return get_hermes_home()
+ _consumer_cfg = StreamConsumerConfig(
+ edit_interval=scfg.edit_interval,
+ buffer_threshold=scfg.buffer_threshold,
+ cursor=_effective_cursor,
+ buffer_only=_buffer_only,
+ fresh_final_after_seconds=_fresh_final_secs,
+ transport=scfg.transport or "edit",
+ chat_type=getattr(source, "chat_type", "") or "",
+ )
+ return _consumer_cfg, _pause_typing_before_finalize
- async def _run_agent_inner(
+ async def _run_agent_via_proxy(
self,
message: str,
context_prompt: str,
history: List[Dict[str, Any]],
- source: SessionSource,
+ source: "SessionSource",
session_id: str,
session_key: str = None,
run_generation: Optional[int] = None,
- _interrupt_depth: int = 0,
- event_message_id: Optional[str] = None,
- channel_prompt: Optional[str] = None,
- moa_config: Optional[dict] = None,
- persist_user_message: Optional[Any] = None,
- persist_user_timestamp: Optional[float] = None,
- message_type: Optional[str] = None,
- ) -> Dict[str, Any]:
- """
- Run the agent with the given message and context.
-
- Returns the full result dict from run_conversation, including:
- - "final_response": str (the text to send back)
- - "messages": list (full conversation including tool calls)
- - "api_calls": int
- - "completed": bool
-
- This is run in a thread pool to not block the event loop.
- Supports interruption via new messages.
+ event_message_id: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Forward the message to a remote Hermes API server instead of
+ running a local AIAgent.
+
+ When ``GATEWAY_PROXY_URL`` (or ``gateway.proxy_url`` in config.yaml)
+ is set, the gateway becomes a thin relay: it handles platform I/O
+ (encryption, threading, media) and delegates all agent work to the
+ remote server via ``POST /v1/chat/completions`` with SSE streaming.
+
+ This lets a Docker container handle Matrix E2EE while the actual
+ agent runs on the host with full access to local files, memory,
+ skills, and a unified session store.
"""
- # ---- Proxy mode: delegate to remote API server ----
- if self._get_proxy_url():
- return await self._run_agent_via_proxy(
- message=message,
- context_prompt=context_prompt,
- history=history,
- source=source,
- session_id=session_id,
- session_key=session_key,
- run_generation=run_generation,
- event_message_id=event_message_id,
- )
+ try:
+ from aiohttp import ClientSession as _AioClientSession, ClientTimeout
+ except ImportError:
+ return {
+ "final_response": "⚠️ Proxy mode requires aiohttp. Install with: pip install aiohttp",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ }
- from run_agent import AIAgent
- import queue
+ proxy_url = self._get_proxy_url()
+ if not proxy_url:
+ return {
+ "final_response": "⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url)",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ }
+
+ proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()
def _run_still_current() -> bool:
if run_generation is None or not session_key:
return True
return self._is_session_run_current(session_key, run_generation)
-
- user_config = _load_gateway_config()
- platform_key = _platform_config_key(source.platform)
- from hermes_cli.tools_config import _get_platform_tools
- enabled_toolsets = sorted(_get_platform_tools(user_config, platform_key))
- agent_cfg_local = user_config.get("agent") or {}
- disabled_toolsets = agent_cfg_local.get("disabled_toolsets") or None
+ # Build messages in OpenAI chat format --------------------------
+ #
+ # The remote api_server can maintain session continuity via
+ # X-Hermes-Session-Id, so it loads its own history. We only
+ # need to send the current user message. If the remote has
+ # no history for this session yet, include what we have locally
+ # so the first exchange has context.
+ #
+ # We always include the current message. For history, send a
+ # compact version (text-only user/assistant turns) — the remote
+ # handles tool replay and system prompts.
+ api_messages: List[Dict[str, str]] = []
- display_config = user_config.get("display", {})
- if not isinstance(display_config, dict):
- display_config = {}
+ if context_prompt:
+ api_messages.append({"role": "system", "content": context_prompt})
- # Per-platform display settings — resolve via display_config module
- # which checks display.platforms.<platform>.<key> first, then
- # display.<key> global, then built-in platform defaults.
- from gateway.display_config import resolve_display_setting
+ for msg in history:
+ role = msg.get("role")
+ content = msg.get("content")
+ if role in {"user", "assistant"} and content:
+ api_messages.append({"role": role, "content": content})
- # Apply tool preview length config (0 = no limit)
- try:
- from agent.display import set_tool_preview_max_len
- _tpl = resolve_display_setting(user_config, platform_key, "tool_preview_length", 0)
- set_tool_preview_max_len(int(_tpl) if _tpl else 0)
- except Exception:
- pass
+ api_messages.append({"role": "user", "content": message})
- # Apply friendly tool labels config (default on) — per-platform aware
- try:
- from agent.display import set_friendly_tool_labels
- _ftl = resolve_display_setting(user_config, platform_key, "friendly_tool_labels", True)
- set_friendly_tool_labels(bool(_ftl))
- except Exception:
- pass
+ # HTTP headers ---------------------------------------------------
+ headers: Dict[str, str] = {"Content-Type": "application/json"}
+ if proxy_key:
+ headers["Authorization"] = f"Bearer {proxy_key}"
+ if session_id:
+ headers["X-Hermes-Session-Id"] = session_id
- # Tool progress mode — resolved per-platform with env var fallback
- _resolved_tp = resolve_display_setting(user_config, platform_key, "tool_progress")
- _env_tp = os.getenv("HERMES_TOOL_PROGRESS_MODE")
- _display_cfg = display_config if isinstance(display_config, dict) else {}
- _platforms_cfg = _display_cfg.get("platforms") or {}
- _platform_cfg = _platforms_cfg.get(platform_key) or {}
- _legacy_tp_overrides = _display_cfg.get("tool_progress_overrides") or {}
- _tool_progress_configured = (
- "tool_progress" in _display_cfg
- or (
- isinstance(_platform_cfg, dict)
- and "tool_progress" in _platform_cfg
- )
- or (
- isinstance(_legacy_tp_overrides, dict)
- and platform_key in _legacy_tp_overrides
- )
+ body = {
+ "model": "hermes-agent",
+ "messages": api_messages,
+ "stream": True,
+ }
+
+ # Set up platform streaming if available -------------------------
+ _stream_consumer = None
+ _scfg = getattr(getattr(self, "config", None), "streaming", None)
+ if _scfg is None:
+ from gateway.config import StreamingConfig
+ _scfg = StreamingConfig()
+
+ platform_key = _platform_config_key(source.platform)
+ user_config = _load_gateway_config()
+ from gateway.display_config import resolve_display_setting
+ _plat_streaming = resolve_display_setting(
+ user_config, platform_key, "streaming"
)
- progress_mode = (
- _env_tp
- if _env_tp and not _tool_progress_configured
- else (_resolved_tp or _env_tp or "all")
+ _streaming_enabled = (
+ _scfg.enabled and _scfg.transport != "off"
+ if _plat_streaming is None
+ else bool(_plat_streaming)
)
- # Tool progress grouping: "accumulate" (edit one bubble) or "separate" (one msg per tool)
- progress_grouping = resolve_display_setting(user_config, platform_key, "tool_progress_grouping") or "accumulate"
- from gateway.status_phrases import choose_status_phrase, resolve_status_phrase_catalog
- _generic_status_recent: List[str] = []
- _generic_status_catalog = resolve_status_phrase_catalog(user_config, platform_key)
- def _display_surface_mode(
- setting: str,
- *,
- default: bool = False,
- require_platform_override_for: set[Any] | None = None,
- allow_generic: bool = False,
- ) -> str:
- """Return off|raw|generic for a gateway visibility surface."""
- if require_platform_override_for:
- current_platform = _gateway_platform_value(source.platform)
- platform_only = {
- _gateway_platform_value(item)
- for item in require_platform_override_for
- }
- if (
- current_platform in platform_only
- and not _has_platform_display_override(user_config, platform_key, setting)
- ):
- return "off"
- value = resolve_display_setting(user_config, platform_key, setting, default)
- if isinstance(value, str) and value.strip().lower() == "generic":
- return "generic" if allow_generic else "off"
- return "raw" if bool(value) else "off"
+ _thread_metadata: Optional[Dict[str, Any]] = self._thread_metadata_for_source(source, event_message_id)
- def _generic_status_phrase(kind: str, *, tool_name: str | None = None, preview: str | None = None, args: Any = None) -> str:
+ if _streaming_enabled:
try:
- return choose_status_phrase(
- kind,
- tool_name=tool_name,
- preview=preview,
- args=args,
- recent=_generic_status_recent,
- catalog=_generic_status_catalog,
- )
- except Exception as _phrase_err:
- logger.debug("generic status phrase selection failed: %s", _phrase_err)
- return "still on it" if kind in {"heartbeat", "waiting", "long_running", "status"} else "one sec"
- # Disable tool progress for webhooks - they don't support message editing,
- # so each progress line would be sent as a separate message.
- from gateway.config import Platform
- tool_progress_enabled = progress_mode not in {"off", "log"} and source.platform != Platform.WEBHOOK
- # Live working-state status for text-rendering typing indicators
- # (Slack's assistant status line). Independent of tool_progress —
- # Slack defaults tool_progress off (permanent lines spam channels)
- # but the status line is ephemeral, so live status stays useful
- # there. Rendering rides the existing _keep_typing refresh: the
- # callback only stores a phrase on the adapter, costing zero extra
- # platform API calls.
- _live_status_mode = resolve_display_setting(
- user_config, platform_key, "live_status", "full"
- )
- _live_status_adapter = self._adapter_for_source(source)
- if not getattr(_live_status_adapter, "supports_status_text", False):
- _live_status_adapter = None
- if _live_status_mode == "off":
- _live_status_adapter = None
- # "log" mode: tool calls are written to ~/.hermes/logs/tool_calls.log
- # instead of the chat (#3459 / #3458). Gateway-only by design.
- log_mode_enabled = progress_mode == "log" and source.platform != Platform.WEBHOOK
- log_queue: "queue.Queue | None" = queue.Queue() if log_mode_enabled else None
- # Natural assistant status messages are intentionally independent from
- # tool progress and token streaming. Users can keep tool_progress quiet
- # in chat platforms while opting into concise mid-turn updates.
- interim_assistant_messages_mode = _display_surface_mode(
- "interim_assistant_messages",
- default=True,
- require_platform_override_for={Platform.MATTERMOST},
- )
- interim_assistant_messages_enabled = (
- source.platform != Platform.WEBHOOK
- and interim_assistant_messages_mode != "off"
- )
- # thinking_progress is independent — if enabled, we need the progress
- # queue even when tool_progress is off (thinking relay uses same infra).
- # Mattermost requires a per-platform opt-in: global scratch-text display
- # is too easy to leak into busy public threads.
- _thinking_mode = _display_surface_mode(
- "thinking_progress",
- default=False,
- require_platform_override_for={Platform.MATTERMOST},
- )
- _thinking_enabled = _thinking_mode != "off"
- needs_progress_queue = tool_progress_enabled or _thinking_enabled
+ from gateway.stream_consumer import GatewayStreamConsumer
+ _adapter = self._adapter_for_source(source)
+ if _adapter:
+ _consumer_cfg, _pause_typing_before_finalize = (
+ self._build_stream_consumer_config(
+ source, _scfg, _adapter,
+ on_missing_cursor="fallback",
+ )
+ )
+ _stream_consumer = GatewayStreamConsumer(
+ adapter=_adapter,
+ chat_id=source.chat_id,
+ config=_consumer_cfg,
+ metadata=_thread_metadata,
+ on_before_finalize=_pause_typing_before_finalize,
+ initial_reply_to_id=event_message_id,
+ run_still_current=_run_still_current,
+ )
+ except Exception as _sc_err:
+ logger.debug("Proxy: could not set up stream consumer: %s", _sc_err)
+
+ # Run the stream consumer task in the background
+ stream_task = None
+ if _stream_consumer:
+ stream_task = asyncio.create_task(_stream_consumer.run())
+ # Send typing indicator
+ _adapter = self._adapter_for_source(source)
+ if _adapter:
+ try:
+ await _adapter.send_typing(source.chat_id, metadata=_thread_metadata)
+ except Exception:
+ pass
- # Queue for progress messages (thread-safe)
- progress_queue = queue.Queue() if needs_progress_queue else None
- last_tool = [None] # Mutable container for tracking in closure
- last_progress_msg = [None] # Track last message for dedup
- repeat_count = [0] # How many times the same message repeated
- # True when the previously enqueued progress line was a terminal
- # fenced code block — consecutive terminal calls then drop the
- # repeated "💻 terminal" header and render back-to-back blocks.
- last_was_terminal_block = [False]
+ # Make the HTTP request with SSE streaming -----------------------
+ full_response = ""
+ _start = time.time()
- # ── Discord voice "verbal ack before tool calls" ────────────────
- # When the bot is in a voice channel with the continuous mixer
- # installed (discord.voice_fx.enabled), speak a short phrase ("let me
- # look into that") over the ambient idle bed on the FIRST tool call of
- # the turn. Fires from tool_start_callback (independent of the
- # tool-progress text gate), at most once per turn. No-op on every
- # other platform / when not in a voice channel.
- _voice_ack_fired = [False]
- _voice_ack_guild: List[Optional[int]] = [None]
- if source.platform == Platform.DISCORD:
- _va = self.adapters.get(Platform.DISCORD)
- # source.chat_id is the linked text channel; resolve the guild whose
- # voice connection is bound to it (mirrors DiscordAdapter.play_tts).
- _vtc = getattr(_va, "_voice_text_channels", None)
- if isinstance(_vtc, dict) and hasattr(_va, "voice_mixer_active"):
- for _gid, _tc in _vtc.items():
- if str(_tc) == str(source.chat_id) and _va.voice_mixer_active(_gid):
- _voice_ack_guild[0] = _gid
- break
- _voice_ack_loop = asyncio.get_running_loop()
+ try:
+ _timeout = ClientTimeout(total=0, sock_read=1800)
+ async with _AioClientSession(timeout=_timeout) as session:
+ async with session.post(
+ f"{proxy_url}/v1/chat/completions",
+ json=body,
+ headers=headers,
+ ) as resp:
+ if resp.status != 200:
+ error_text = await resp.text()
+ logger.warning(
+ "Proxy error (%d) from %s: %s",
+ resp.status, proxy_url, error_text[:500],
+ )
+ return {
+ "final_response": f"⚠️ Proxy error ({resp.status}): {error_text[:300]}",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ }
- def voice_ack_callback(call_id, tool_name, args):
- """tool_start_callback: speak a one-time ack in the voice channel."""
- if _voice_ack_fired[0] or _voice_ack_guild[0] is None:
- return
- if not _run_still_current():
- return
- _voice_ack_fired[0] = True
- _adapter = self.adapters.get(Platform.DISCORD)
- if _adapter is None or not hasattr(_adapter, "play_ack_in_voice"):
- return
- try:
- safe_schedule_threadsafe(
- _adapter.play_ack_in_voice(_voice_ack_guild[0]),
- _voice_ack_loop,
- logger=logger,
- log_message="voice ack scheduling error",
- )
- except Exception as _ack_err:
- logger.debug("voice ack schedule failed: %s", _ack_err)
+ # Parse SSE stream
+ buffer = ""
+ async for chunk in resp.content.iter_any():
+ if not _run_still_current():
+ logger.info(
+ "Discarding stale proxy stream for %s — generation %d is no longer current",
+ session_key or "?",
+ run_generation or 0,
+ )
+ return {
+ "final_response": "",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ "history_offset": len(history),
+ "session_id": session_id,
+ "response_previewed": False,
+ }
+ text = chunk.decode("utf-8", errors="replace")
+ buffer += text
- # Auto-cleanup of temporary progress bubbles (Telegram + any adapter
- # that implements ``delete_message``). When enabled via
- # ``display.platforms.<platform>.cleanup_progress: true``, message IDs
- # from the tool-progress / "⏳ Working — N min" / status-callback bubbles
- # are collected here and deleted after the final response lands.
- # Failed runs skip cleanup so the bubbles remain as breadcrumbs.
- _cleanup_progress = bool(
- resolve_display_setting(user_config, platform_key, "cleanup_progress")
- )
- _cleanup_adapter = self._adapter_for_source(source) if _cleanup_progress else None
- # getattr, not attribute access — same duck-typed-adapter guard as the
- # edit_message check in send_progress_messages below: a fake/minimal
- # adapter without delete_message means "can't delete", not a crash.
- _cleanup_delete = getattr(type(_cleanup_adapter), "delete_message", None) if _cleanup_adapter is not None else None
- if _cleanup_adapter is not None and (
- _cleanup_delete is None
- or _cleanup_delete is BasePlatformAdapter.delete_message
- ):
- # Adapter doesn't support deletion — silently disable.
- _cleanup_progress = False
- _cleanup_adapter = None
- _cleanup_msg_ids: List[str] = []
- # First-touch onboarding latch: fires at most once per run, even if
- # several tools exceed the threshold.
- long_tool_hint_fired = [False]
- _LONG_TOOL_THRESHOLD_S = 30.0
+ # Process complete SSE lines
+ while "\n" in buffer:
+ line, buffer = buffer.split("\n", 1)
+ line = line.strip()
+ if not line:
+ continue
+ if line.startswith("data: "):
+ data = line[6:]
+ if data.strip() == "[DONE]":
+ break
+ try:
+ obj = json.loads(data)
+ choices = obj.get("choices", [])
+ if choices:
+ delta = choices[0].get("delta", {})
+ content = delta.get("content", "")
+ if content:
+ full_response += content
+ if _stream_consumer:
+ _stream_consumer.on_delta(content)
+ except json.JSONDecodeError:
+ pass
+ if len(buffer) > _GATEWAY_PROXY_SSE_BUFFER_MAX_CHARS:
+ raise ValueError(
+ "Proxy SSE stream exceeded max buffer size without a line boundary"
+ )
- turn_ctx = TurnContext(
- source=source,
- _run_still_current=_run_still_current,
- _live_status_adapter=_live_status_adapter,
- _live_status_mode=_live_status_mode,
- _thinking_enabled=_thinking_enabled,
- progress_mode=progress_mode,
- progress_grouping=progress_grouping,
- tool_progress_enabled=tool_progress_enabled,
- progress_queue=progress_queue,
- log_queue=log_queue,
- last_progress_msg=last_progress_msg,
- last_tool=last_tool,
- last_was_terminal_block=last_was_terminal_block,
- repeat_count=repeat_count,
- long_tool_hint_fired=long_tool_hint_fired,
- _LONG_TOOL_THRESHOLD_S=_LONG_TOOL_THRESHOLD_S,
- _cleanup_progress=_cleanup_progress,
- _cleanup_msg_ids=_cleanup_msg_ids,
- )
- turn_runner = TurnRunner(self, turn_ctx)
- # Callback invoked by agent on tool lifecycle events — extracted to
- # TurnRunner.progress_callback (bound method, same signature).
- progress_callback = turn_runner.progress_callback
-
- # Background task to send progress messages
- # Accumulates tool lines into a single message that gets edited.
- #
- # Threading metadata is platform-specific:
- # - Slack DM threading needs event_message_id fallback (reply thread)
- # - Telegram forum topics use message_thread_id; Hermes-created private
- # DM topic lanes require both thread metadata and a reply anchor
- # - Feishu only honors reply_in_thread when sending a reply, so topic
- # progress uses the triggering event message as the reply target
- # - Other platforms should use explicit source.thread_id only
- #
- # Slack honours platforms.slack.extra.reply_in_thread=false: if the
- # user has opted out of threaded replies, don't synthesise a thread
- # for progress messages either — the very first progress message
- # would otherwise create a thread that all subsequent replies
- # (including the final answer) would inherit (#18859).
- _progress_reply_in_thread = True
- if source.platform == Platform.SLACK:
- _slack_adapter_for_progress = self._adapter_for_source(source)
- if _slack_adapter_for_progress is not None:
+ except asyncio.CancelledError:
+ raise
+ except Exception as e:
+ logger.error("Proxy connection error to %s: %s", proxy_url, e)
+ if not full_response:
+ return {
+ "final_response": f"⚠️ Proxy connection error: {e}",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ }
+ # Partial response — return what we got
+ finally:
+ # Finalize stream consumer
+ if _stream_consumer:
+ _stream_consumer.finish()
+ if stream_task:
try:
- # Relay lane: the adapter owns mode resolution (nested
- # platforms.relay.extra.slack subset with flat-key
- # fallback). Native lane: read the flat extra as before.
- _mode_fn = getattr(
- _slack_adapter_for_progress,
- "_effective_reply_in_thread",
- None,
- )
- if callable(_mode_fn):
- _progress_reply_in_thread = bool(_mode_fn())
- else:
- _progress_reply_in_thread = bool(
- _slack_adapter_for_progress.config.extra.get(
- "reply_in_thread", True
- )
- )
- except Exception:
- _progress_reply_in_thread = True
- _progress_thread_id = _resolve_progress_thread_id(
- source.platform, source.thread_id, event_message_id,
- reply_in_thread=_progress_reply_in_thread,
- )
- _progress_metadata = (
- self._thread_metadata_for_source(source, event_message_id)
- if _progress_thread_id == source.thread_id
- else self._thread_metadata_for_target(
- source.platform,
- source.chat_id,
- _progress_thread_id,
- chat_type=getattr(source, "chat_type", None),
- reply_to_message_id=event_message_id,
+ await asyncio.wait_for(stream_task, timeout=5.0)
+ except (asyncio.TimeoutError, asyncio.CancelledError):
+ stream_task.cancel()
+
+ _elapsed = time.time() - _start
+ if not _run_still_current():
+ logger.info(
+ "Discarding stale proxy result for %s — generation %d is no longer current",
+ session_key or "?",
+ run_generation or 0,
)
- ) if _progress_thread_id else None
- _progress_metadata = _non_conversational_metadata(_progress_metadata, platform=source.platform)
- _progress_reply_to = (
- event_message_id
- if source.platform in (Platform.FEISHU, Platform.MATTERMOST) and source.thread_id and event_message_id
- else None
+ return {
+ "final_response": "",
+ "messages": [],
+ "api_calls": 0,
+ "tools": [],
+ "history_offset": len(history),
+ "session_id": session_id,
+ "response_previewed": False,
+ }
+ logger.info(
+ "proxy response: url=%s session=%s time=%.1fs response=%d chars",
+ proxy_url, (session_id or "")[:20], _elapsed, len(full_response),
)
- async def write_tool_log():
- """Drain log_queue and append tool-call lines to tool_calls.log.
+ return {
+ "final_response": full_response or "(No response from remote agent)",
+ "messages": [
+ {"role": "user", "content": message},
+ {"role": "assistant", "content": full_response},
+ ],
+ "api_calls": 1,
+ "tools": [],
+ "history_offset": len(history),
+ "session_id": session_id,
+ "response_previewed": _stream_consumer is not None and bool(full_response),
+ }
- Only active when ``display.tool_progress`` is ``log``. Uses a
- RotatingFileHandler (5MB × 3 backups) so the audit log can't grow
- unbounded, and the shared RedactingFormatter so secrets never land
- on disk.
- """
- if log_queue is None:
- return
- from logging.handlers import RotatingFileHandler
+ # ------------------------------------------------------------------
- from agent.redact import RedactingFormatter
+ async def _run_agent(
+ self,
+ message: str,
+ context_prompt: str,
+ history: List[Dict[str, Any]],
+ source: SessionSource,
+ session_id: str,
+ session_key: str = None,
+ run_generation: Optional[int] = None,
+ _interrupt_depth: int = 0,
+ event_message_id: Optional[str] = None,
+ channel_prompt: Optional[str] = None,
+ moa_config: Optional[dict] = None,
+ persist_user_message: Optional[Any] = None,
+ persist_user_timestamp: Optional[float] = None,
+ message_type: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Profile-scoping wrapper around the agent run.
- log_dir = _hermes_home / "logs"
- log_dir.mkdir(parents=True, exist_ok=True)
- file_handler = RotatingFileHandler(
- log_dir / "tool_calls.log",
- maxBytes=5 * 1024 * 1024,
- backupCount=3,
- encoding="utf-8",
+ When multiplexing is active, resolve the inbound source's profile and
+ run the whole turn inside ``_profile_runtime_scope`` so config/skills/
+ memory resolve to that profile's home AND credentials resolve from that
+ profile's secret scope (never the process-global ``os.environ``). When
+ multiplexing is off this is a transparent pass-through — zero behavior
+ change for single-profile gateways.
+ """
+ if not getattr(getattr(self, "config", None), "multiplex_profiles", False):
+ return await self._run_agent_inner(
+ message, context_prompt, history, source, session_id,
+ session_key=session_key, run_generation=run_generation,
+ _interrupt_depth=_interrupt_depth, event_message_id=event_message_id,
+ channel_prompt=channel_prompt, moa_config=moa_config,
+ persist_user_message=persist_user_message,
+ persist_user_timestamp=persist_user_timestamp,
+ message_type=message_type,
)
- file_handler.setFormatter(RedactingFormatter("%(message)s"))
- tool_logger = logging.getLogger(f"hermes.tool_calls.{id(log_queue)}")
- tool_logger.setLevel(logging.INFO)
- tool_logger.propagate = False
- tool_logger.addHandler(file_handler)
- try:
- while True:
- try:
- tool_logger.info("%s", log_queue.get_nowait())
- except queue.Empty:
- await asyncio.sleep(0.3)
- except Exception as e:
- logger.error("write_tool_log error: %s", e)
- await asyncio.sleep(1)
- except asyncio.CancelledError:
- pass
- finally:
- # Drain remaining entries before closing so late tool calls
- # from the final iteration aren't lost.
- while True:
- try:
- tool_logger.info("%s", log_queue.get_nowait())
- except queue.Empty:
- break
- except Exception:
- break
- tool_logger.removeHandler(file_handler)
- try:
- file_handler.flush()
- file_handler.close()
- except Exception:
- pass
-
- # Extracted to TurnRunner.send_progress_messages. The threading
- # metadata computed above is published onto the shared TurnContext
- # exactly where the original closure's captured locals were bound.
- turn_ctx._progress_metadata = _progress_metadata
- turn_ctx._progress_reply_to = _progress_reply_to
- send_progress_messages = turn_runner.send_progress_messages
-
- # We need to share the agent instance for interrupt support
- agent_holder = [None] # Mutable container for the agent instance
- turn_ctx.agent_holder = agent_holder
- result_holder = [None] # Mutable container for the result
- tools_holder = [None] # Mutable container for the tool definitions
- stream_consumer_holder = [None] # Mutable container for stream consumer
- # #60671 — streaming PCM audio consumer. Created on the gateway
- # event-loop thread (NOT inside run_sync's executor worker) so the
- # outer finalisation / interrupt paths can reference it without a
- # cross-scope NameError.
- streaming_tts_consumer_holder: list = [None]
-
- # Bridge sync step_callback → async hooks.emit for agent:step events
- _loop_for_step = asyncio.get_running_loop()
- _hooks_ref = self.hooks
- def _step_callback_sync(iteration: int, prev_tools: list) -> None:
- if not _run_still_current():
- return
- # prev_tools may be list[str] or list[dict] with "name"/"result"
- # keys. Normalise to keep "tool_names" backward-compatible for
- # user-authored hooks that do ', '.join(tool_names)'.
- _names: list[str] = []
- for _t in (prev_tools or []):
- if isinstance(_t, dict):
- _names.append(_t.get("name") or "")
- else:
- _names.append(str(_t))
- safe_schedule_threadsafe(
- _hooks_ref.emit("agent:step", {
- "platform": source.platform.value if source.platform else "",
- "user_id": source.user_id,
- "session_id": session_id,
- "iteration": iteration,
- "tool_names": _names,
- "tools": prev_tools,
- }),
- _loop_for_step,
- logger=logger,
- log_message="agent:step hook scheduling error",
+ profile_home = self._resolve_profile_home_for_source(source)
+ with _profile_runtime_scope(profile_home):
+ return await self._run_agent_inner(
+ message, context_prompt, history, source, session_id,
+ session_key=session_key, run_generation=run_generation,
+ _interrupt_depth=_interrupt_depth, event_message_id=event_message_id,
+ channel_prompt=channel_prompt, moa_config=moa_config,
+ persist_user_message=persist_user_message,
+ persist_user_timestamp=persist_user_timestamp,
+ message_type=message_type,
)
- # Bridge sync event_callback → async hooks.emit for lifecycle events
- # (e.g. session:compress fires after context compression splits a session)
- def _event_callback_sync(event_type: str, context: dict) -> None:
- try:
- asyncio.run_coroutine_threadsafe(
- _hooks_ref.emit(event_type, context),
- _loop_for_step,
- )
- except Exception as _e:
- logger.debug("event_callback hook error: %s", _e)
-
- # Bridge sync status_callback → async adapter.send for context pressure
- _status_adapter = self._adapter_for_source(source)
- _status_chat_id = source.chat_id
- if source.platform == Platform.FEISHU and source.thread_id and event_message_id:
- # Feishu topics only keep messages inside the topic when they are
- # sent via the reply API with reply_in_thread=true. Status/interim,
- # approval, and stream-consumer paths usually only receive metadata,
- # so carry the triggering message id as a Feishu-specific fallback.
- _status_thread_metadata: Optional[Dict[str, Any]] = {
- "thread_id": _progress_thread_id,
- "reply_to_message_id": event_message_id,
- }
- else:
- _status_thread_metadata = (
- self._thread_metadata_for_source(source, event_message_id)
- if _progress_thread_id == source.thread_id
- else self._thread_metadata_for_target(
- source.platform,
- source.chat_id,
- _progress_thread_id,
- chat_type=getattr(source, "chat_type", None),
- reply_to_message_id=event_message_id,
- )
- ) if _progress_thread_id else None
-
- def _status_callback_sync(event_type: str, message: str) -> None:
- if not _status_adapter or not _run_still_current():
- return
- prepared_message = _prepare_gateway_status_message(
- source.platform,
- event_type,
- message,
- )
- if prepared_message is None:
- logger.debug(
- "status_callback suppressed for %s/%s: %s",
- source.platform.value if source.platform else "unknown",
- event_type,
- _redact_gateway_user_facing_secrets(str(message or ""))[:160],
- )
- return
- _fut = safe_schedule_threadsafe(
- _send_or_update_status_coro(_status_adapter, _status_chat_id, event_type, prepared_message, _status_thread_metadata),
- _loop_for_step,
- logger=logger,
- log_message=f"status_callback ({event_type}) scheduling error",
- )
- if _fut is None:
- return
- if _cleanup_progress:
- def _track_status_id(fut) -> None:
- try:
- res = fut.result()
- except Exception:
- return
- mid = getattr(res, "message_id", None)
- if getattr(res, "success", False) and mid:
- _cleanup_msg_ids.append(str(mid))
- _fut.add_done_callback(_track_status_id)
+ def _profile_name_for_source(self, source: SessionSource) -> Optional[str]:
+ """Resolve the profile name for an inbound source via configured routes.
- # ---- Streaming TTS consumer setup (#60671) ----
- # Created on the gateway event-loop thread (here, in _run_agent_inner),
- # NOT inside run_sync's executor worker. This avoids a cross-scope
- # NameError: the outer interrupt / finalisation paths reference the
- # consumer via ``streaming_tts_consumer_holder[0]``.
- #
- # Gates: voice input, auto-TTS enabled for this chat, adapter
- # supports streaming, and a usable streaming TTS provider configured.
- _stts_adapter = self._adapter_for_source(source)
- _is_voice_input = (
- message_type is not None
- and str(getattr(message_type, "value", message_type)).lower() == "voice"
- )
- if (
- _stts_adapter is not None
- and _is_voice_input
- and _stts_adapter._should_auto_tts_for_chat(source.chat_id)
- ):
- try:
- from gateway.streaming_tts_consumer import StreamingTTSConsumer
- from tools.tts_tool import _load_tts_config
- _tts_cfg = _load_tts_config()
- _gateway_loop = self._gateway_loop or asyncio.get_event_loop()
- _stts_consumer = StreamingTTSConsumer(
- adapter=_stts_adapter,
- chat_id=source.chat_id,
- tts_config=_tts_cfg,
- loop=_gateway_loop,
- metadata=_status_thread_metadata,
- )
- if _stts_consumer.active:
- streaming_tts_consumer_holder[0] = _stts_consumer
- _stts_consumer.start()
- # else: consumer inactive (no streaming provider) — leave
- # the holder as None so the whole-file fallback path runs.
- except Exception as _stts_err:
- logger.debug("Could not set up streaming TTS consumer: %s", _stts_err)
+ Returns ``None`` when multiplexing is off, no routes are configured, or
+ no route matches. Callers (``build_source``,
+ ``_resolve_profile_home_for_source``) treat ``None`` as "use the
+ default/active profile". When ``gateway.profile_routes`` is configured,
+ the most specific matching route wins (guild < channel < thread). See
+ :mod:`gateway.profile_routing` for matching rules.
- def run_sync():
- # The conditional re-assignment of `message` further below
- # (prepending model-switch notes) makes Python treat it as a
- # local variable in the entire function. `nonlocal` lets us
- # read *and* reassign the outer `_run_agent` parameter without
- # triggering an UnboundLocalError on the earlier read at
- # `_resolve_turn_agent_config(message, …)`.
- nonlocal message
-
- # session_key is propagated via contextvars in _set_session_env()
- # (_SESSION_KEY) and via set_current_session_key() (_approval_session_key)
- # below — both concurrency-safe and inherited by tool worker threads.
- # We deliberately do NOT write os.environ["HERMES_SESSION_KEY"] here:
- # os.environ is process-global, so concurrent gateway sessions (e.g.
- # two Discord threads) would clobber each other's value, and a tool
- # thread whose contextvar is unset would fall back to os.environ and
- # read the wrong session key — misrouting command-approval prompts to
- # the wrong thread (#24100). The non-gateway surfaces don't depend on
- # this write: CLI and cron bind the session via contextvars
- # (set_current_session_key / session context), and only the TUI
- # slash-worker *subprocess* exports HERMES_SESSION_KEY (from its own
- # --session-key argv, a separate process) — so removing this in-process
- # gateway write does not affect any of them.
-
- # Map platform enum to the platform hint key the agent understands.
- # Platform.LOCAL ("local") maps to "cli"; others pass through as-is.
- platform_key = "cli" if source.platform == Platform.LOCAL else source.platform.value
-
- # Combine platform context, YAML channel_prompts hint for this chat,
- # channel_overrides system_prompt (or global ephemeral), and gateway
- # ephemeral prompt from _get_system_prompt_for_channel.
- combined_ephemeral = context_prompt or ""
- event_channel_prompt = (channel_prompt or "").strip()
- if event_channel_prompt:
- combined_ephemeral = (combined_ephemeral + "\n\n" + event_channel_prompt).strip()
- cfg_channel_prompt = self._get_system_prompt_for_channel(
- source.platform,
- source.chat_id or "",
+ Gated on ``gateway.multiplex_profiles``: routing stamps
+ ``source.profile``, which selects the session-key namespace and batch
+ keys — but the profile-scoped agent run only activates under
+ multiplexing. Without this gate, a configured route with multiplexing
+ off would namespace batch/session keys by profile while the agent
+ still runs in ``agent:main``, splitting the two out of agreement.
+ """
+ config = getattr(self, "config", None)
+ if not getattr(config, "multiplex_profiles", False):
+ return None
+ routes = getattr(config, "profile_routes", None)
+ if not routes:
+ return None
+ from gateway.profile_routing import match_profile_route
+ try:
+ matched = match_profile_route(
+ routes,
+ platform=source.platform.value,
+ guild_id=getattr(source, "guild_id", None),
+ chat_id=source.chat_id,
thread_id=getattr(source, "thread_id", None),
- parent_id=getattr(source, "parent_chat_id", None),
+ parent_chat_id=getattr(source, "parent_chat_id", None),
+ )
+ except Exception:
+ logger.warning(
+ "Profile route matching failed for %s/%s, falling back to default",
+ source.platform, source.chat_id, exc_info=True,
)
- if cfg_channel_prompt:
- combined_ephemeral = (combined_ephemeral + "\n\n" + cfg_channel_prompt).strip()
+ return None
+ if matched:
+ return matched.profile
+ logger.debug(
+ "No profile route matched: platform=%s chat_id=%s thread_id=%s parent_chat_id=%s",
+ source.platform.value, source.chat_id,
+ getattr(source, "thread_id", None), getattr(source, "parent_chat_id", None),
+ )
+ return None
- max_iterations = _current_max_iterations()
+ def _resolve_profile_home_for_source(self, source: SessionSource) -> "Path":
+ """Resolve which profile's HERMES_HOME should serve this inbound source.
- try:
- model, runtime_kwargs = self._resolve_session_agent_runtime(
- source=source,
- session_key=session_key,
- user_config=user_config,
- )
- logger.debug(
- "run_agent resolved: model=%s provider=%s session=%s",
- model, runtime_kwargs.get("provider"), session_key or "",
+ Resolution order:
+ 1. ``source.profile`` — set by /p/<profile>/ URL prefix, per-credential
+ adapter ownership, OR profile_routes matching at ``build_source`` time.
+ 2. ``_profile_name_for_source`` — re-run routing here as a defensive
+ fallback for sources that bypass ``build_source``.
+ 3. The active profile (the multiplexer's own home).
+ """
+ from hermes_cli.profiles import (
+ get_active_profile_name,
+ get_profile_dir,
+ profile_exists,
+ )
+ from hermes_constants import get_hermes_home
+
+ # Track whether a profile was explicitly requested (vs. falling back to default)
+ explicit_profile = None
+ try:
+ name = (source.profile or "").strip()
+ if name:
+ explicit_profile = name # User explicitly set this profile
+ if not name:
+ name = self._profile_name_for_source(source)
+ if name:
+ explicit_profile = name # Routing explicitly set this profile
+ if not name:
+ name = get_active_profile_name() or "default"
+
+ profile_dir = get_profile_dir(name)
+ # Warn if an explicit profile doesn't exist on disk
+ if explicit_profile and not profile_exists(name):
+ logger.warning(
+ "Profile %r does not exist for source %s/%s (guild_id=%s), "
+ "falling back to global HERMES_HOME",
+ explicit_profile,
+ source.platform.value,
+ source.chat_id,
+ getattr(source, "guild_id", None),
)
- except Exception as exc:
- return {
- "final_response": f"⚠️ Provider authentication failed: {exc}",
- "messages": [],
- "api_calls": 0,
- "tools": [],
- }
+ return get_hermes_home()
+ return profile_dir
+ except Exception:
+ # Catch normalization errors, path errors, etc.
+ logger.warning(
+ "Failed to resolve profile directory for source %s/%s (guild_id=%s), "
+ "falling back to global HERMES_HOME: %s",
+ source.platform.value,
+ source.chat_id,
+ getattr(source, "guild_id", None),
+ explicit_profile or "(no profile)",
+ exc_info=True,
+ )
+ return get_hermes_home()
- pr = self._provider_routing
- reasoning_config = self._resolve_session_reasoning_config(
+ async def _run_agent_inner(
+ self,
+ message: str,
+ context_prompt: str,
+ history: List[Dict[str, Any]],
+ source: SessionSource,
+ session_id: str,
+ session_key: str = None,
+ run_generation: Optional[int] = None,
+ _interrupt_depth: int = 0,
+ event_message_id: Optional[str] = None,
+ channel_prompt: Optional[str] = None,
+ moa_config: Optional[dict] = None,
+ persist_user_message: Optional[Any] = None,
+ persist_user_timestamp: Optional[float] = None,
+ message_type: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Run the agent with the given message and context.
+
+ Returns the full result dict from run_conversation, including:
+ - "final_response": str (the text to send back)
+ - "messages": list (full conversation including tool calls)
+ - "api_calls": int
+ - "completed": bool
+
+ This is run in a thread pool to not block the event loop.
+ Supports interruption via new messages.
+ """
+ # ---- Proxy mode: delegate to remote API server ----
+ if self._get_proxy_url():
+ return await self._run_agent_via_proxy(
+ message=message,
+ context_prompt=context_prompt,
+ history=history,
source=source,
+ session_id=session_id,
session_key=session_key,
- model=model,
+ run_generation=run_generation,
+ event_message_id=event_message_id,
)
- self._reasoning_config = reasoning_config
- self._service_tier = self._resolve_session_service_tier(
- source=source, session_key=session_key
- )
- # Set up stream consumer for token streaming or interim commentary.
- _stream_consumer = None
- _stream_delta_cb = None
- # #60671 — streaming TTS consumer is created on the outer
- # event-loop thread before run_sync launches. run_sync only
- # reads it via ``streaming_tts_consumer_holder[0]`` for delta
- # callback wiring.
- _stts_consumer_ref = streaming_tts_consumer_holder[0]
- _scfg = getattr(getattr(self, 'config', None), 'streaming', None)
- if _scfg is None:
- from gateway.config import StreamingConfig
- _scfg = StreamingConfig()
-
- # Per-platform streaming gate: display.platforms.<plat>.streaming
- # can disable streaming for specific platforms even when the global
- # streaming config is enabled.
- _plat_streaming = resolve_display_setting(
- user_config, platform_key, "streaming"
- )
- # None = no per-platform override → follow global config
- _streaming_enabled = (
- _scfg.enabled and _scfg.transport != "off"
- if _plat_streaming is None
- else bool(_plat_streaming)
- )
- _want_stream_deltas = _streaming_enabled
- _want_interim_messages = interim_assistant_messages_enabled
- _want_interim_consumer = _want_interim_messages
- if _want_stream_deltas or _want_interim_consumer:
- try:
- from gateway.stream_consumer import GatewayStreamConsumer
- _adapter = self._adapter_for_source(source)
- if _adapter:
- _consumer_cfg, _pause_typing_before_finalize = (
- self._build_stream_consumer_config(
- source, _scfg, _adapter,
- on_missing_cursor="raise",
- )
- )
- _stream_consumer = GatewayStreamConsumer(
- adapter=_adapter,
- chat_id=source.chat_id,
- config=_consumer_cfg,
- metadata=_status_thread_metadata,
- on_new_message=(
- (lambda: progress_queue.put(("__reset__",)))
- if progress_queue is not None
- else None
- ),
- on_before_finalize=_pause_typing_before_finalize,
- initial_reply_to_id=event_message_id,
- run_still_current=_run_still_current,
- )
- if _want_stream_deltas:
- def _stream_delta_cb(text: str) -> None:
- if _run_still_current():
- _stream_consumer.on_delta(text)
- # Tee to the streaming-TTS consumer (#60671).
- if _stts_consumer_ref is not None:
- _stts_consumer_ref.on_delta(text)
- stream_consumer_holder[0] = _stream_consumer
- except Exception as _sc_err:
- logger.debug("Could not set up stream consumer: %s", _sc_err)
-
- # When text streaming is off but streaming TTS is active,
- # install a TTS-only delta callback so the consumer still
- # receives LLM deltas for audio synthesis (#60671).
- if _stream_delta_cb is None and _stts_consumer_ref is not None:
- def _stream_delta_cb(text: str) -> None:
- if _run_still_current():
- _stts_consumer_ref.on_delta(text)
-
- def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
- if not _run_still_current():
- return
- display_text = text
- if _stream_consumer is not None:
- if already_streamed:
- _stream_consumer.on_segment_break()
- else:
- _stream_consumer.on_commentary(display_text)
- return
- if already_streamed or not _status_adapter or not str(display_text or "").strip():
- return
- safe_schedule_threadsafe(
- _status_adapter.send(
- _status_chat_id,
- display_text,
- metadata=_status_thread_metadata,
- ),
- _loop_for_step,
- logger=logger,
- log_message="interim_assistant_callback scheduling error",
- )
- turn_route = self._resolve_turn_agent_config(message, model, runtime_kwargs)
-
- # Check agent cache — reuse the AIAgent from the previous message
- # in this session to preserve the frozen system prompt and tool
- # schemas for prompt cache hits.
- _sig = self._agent_config_signature(
- turn_route["model"],
- turn_route["runtime"],
- enabled_toolsets,
- combined_ephemeral,
- cache_keys=self._extract_cache_busting_config(user_config),
- user_id=getattr(source, "user_id", None),
- user_id_alt=getattr(source, "user_id_alt", None),
- )
- agent = None
- reused_cached_agent = False
- _cache_lock = getattr(self, "_agent_cache_lock", None)
- _cache = getattr(self, "_agent_cache", None)
+ from run_agent import AIAgent
+ import queue
- # Peek at the cached entry's snapshot session_id (if any) so we can
- # check, OUTSIDE the cache lock, whether THAT session_id is a DEAD
- # session in state.db. This closes a gap in the #54947 fix: that
- # fix treats "cached session_id != current session_id" as an
- # intentional /resume-style switch and reuses the agent unchanged.
- # But the #54878 self-heal produces the exact same tuple shape
- # when it recovers a routing key away from a session that was
- # already ended — the cached AIAgent still belongs to the DEAD
- # session, not a valid sibling conversation. Reusing it lets that
- # turn's post-run "session split" sync write the routing key
- # straight back onto the dead session_id, undoing the self-heal
- # and looping every message until an interrupt happens to race in
- # first (the #54878 x #54947 interaction — no existing upstream
- # issue tracks this combination as of 2026-07-12).
- _peek_cached_sid = None
- if _cache_lock and _cache is not None:
- with _cache_lock:
- _peek_entry = _cache.get(session_key)
- if _peek_entry and len(_peek_entry) > 3:
- _peek_cached_sid = _peek_entry[3]
- _cached_sid_is_dead = False
- if (
- _peek_cached_sid is not None
- and session_id is not None
- and _peek_cached_sid != session_id
- ):
- try:
- _cached_sid_is_dead = self.session_store._is_session_ended_in_db(
- _peek_cached_sid
- )
- except Exception:
- _cached_sid_is_dead = False
-
- # Detect cross-process writes: when another process (e.g. hermes
- # dashboard) appends to the same session in the shared SessionDB,
- # the cached agent's in-memory transcript becomes stale. Compare
- # the session's current message_count against the count recorded
- # when the agent was cached; on mismatch, invalidate the cache
- # so a fresh agent re-reads from disk. (#45966)
- _current_msg_count = None
- if self._session_db is not None and session_id:
- try:
- # run_sync is off-loop (executor); sync DB is fine.
- _sess_row = self._session_db._db.get_session(session_id)
- if _sess_row:
- _current_msg_count = _sess_row.get("message_count", 0)
- except Exception:
- pass
+ def _run_still_current() -> bool:
+ if run_generation is None or not session_key:
+ return True
+ return self._is_session_run_current(session_key, run_generation)
+
+ user_config = _load_gateway_config()
+ platform_key = _platform_config_key(source.platform)
- _xproc_evicted_agent = None
- if _cache_lock and _cache is not None:
- with _cache_lock:
- cached = _cache.get(session_key)
- if cached and cached[1] == _sig:
- # cached[2] is the message_count at cache time;
- # stale when a second process appended rows.
- # cached[3] (when present) is the session_id the
- # snapshot was taken for — used to skip the guard
- # when the active session_id differs (#54947).
- _cached_mc = cached[2] if len(cached) > 2 else None
- _cached_sid = cached[3] if len(cached) > 3 else None
- # If the snapshot belongs to a different session_id
- # (same session_key, different conversation), the
- # message_count comparison is meaningless — the
- # counts track DIFFERENT DB rows. REUSE the cached
- # agent rather than rebuild and bust the prompt cache
- # on every session switch (#54947).
- _session_id_mismatch = (
- _cached_sid is not None
- and session_id is not None
- and _cached_sid != session_id
- )
- # Re-validate the OUTSIDE-lock dead-session peek
- # against the tuple actually read under THIS lock —
- # the cache entry could have been replaced between
- # the peek and this lock acquisition, and a stale
- # "dead" verdict must never be applied to a
- # different (possibly live) cached agent.
- _stale_dead_sid_reuse = (
- _session_id_mismatch
- and _cached_sid_is_dead
- and _cached_sid == _peek_cached_sid
- )
- if _stale_dead_sid_reuse:
- # #54878 x #54947 interaction: the routing key
- # was just self-healed away from a session that
- # state.db already marked ended, but the cached
- # AIAgent here still belongs to that DEAD
- # session_id. The #54947 "different session_id
- # under the same key = intentional switch, reuse
- # freely" rule does not hold here — this isn't a
- # sibling conversation, it's a stale agent left
- # over from before the self-heal. Reusing it lets
- # this turn's post-run "session split" sync write
- # the routing key straight back onto the dead
- # session_id, undoing the self-heal and looping
- # every message until an interrupt happens to
- # race in first. Discard and rebuild fresh
- # instead, same as a genuine cross-process write.
- logger.info(
- "Agent cache invalidated for session %s: "
- "cached agent's session_id %s is ended in "
- "state.db (stale self-heal artifact, "
- "#54878 x #54947) — discarding instead of "
- "reusing across the routing recovery",
- session_key, _cached_sid,
- )
- evicted = self._agent_cache.pop(session_key, None)
- _ev_agent = evicted[0] if isinstance(evicted, tuple) and evicted else None
- if _ev_agent and _ev_agent is not _AGENT_PENDING_SENTINEL:
- # Same deferred-cleanup rationale as the
- # cross-process branch below (#52197): don't
- # block the event loop / cache lock on
- # memory-provider shutdown or socket teardown.
- _xproc_evicted_agent = _ev_agent
- elif (
- not _session_id_mismatch
- and _cached_mc is not None
- and _current_msg_count is not None
- and _current_msg_count != _cached_mc
- ):
- # Cross-process write detected — discard stale
- # agent so it rebuilds from fresh DB transcript.
- logger.info(
- "Agent cache invalidated for session %s: "
- "message_count changed (%s -> %s), "
- "possible cross-process write",
- session_key, _cached_mc, _current_msg_count,
- )
- evicted = self._agent_cache.pop(session_key, None)
- _ev_agent = evicted[0] if isinstance(evicted, tuple) and evicted else None
- if _ev_agent and _ev_agent is not _AGENT_PENDING_SENTINEL:
- # Defer cleanup until AFTER the lock is
- # released — _cleanup_agent_resources /
- # release_clients can block on memory-provider
- # shutdown and socket teardown, and running it
- # here would stall the gateway event loop while
- # _sweep_idle_cached_agents (session-expiry
- # watcher) waits on the same lock, blocking
- # Discord heartbeats (#52197). The same session
- # rebuilds a fresh agent immediately below, so
- # use the SOFT release that preserves the
- # session's terminal sandbox / browser / bg
- # processes for the rebuilt agent to inherit —
- # mirrors _evict_cached_agent / idle-sweep.
- _xproc_evicted_agent = _ev_agent
- else:
- agent = cached[0]
- # Refresh LRU order so the cap enforcement evicts
- # truly-oldest entries, not the one we just used.
- if hasattr(_cache, "move_to_end"):
- try:
- _cache.move_to_end(session_key)
- except KeyError:
- pass
- self._init_cached_agent_for_turn(agent, _interrupt_depth)
- # Refresh agent max_iterations from current config
- # (cached agent may have been created with old config)
- agent.max_iterations = max_iterations
- logger.debug("Reusing cached agent for session %s", session_key)
- reused_cached_agent = True
-
- # Lock released — refresh the fallback chain from disk for the
- # reused agent OUTSIDE the cache lock (config.yaml read is disk
- # I/O; the idle-sweep watcher contends on this lock and stalls
- # Discord heartbeats — same reasoning as #52197). A chain
- # configured after this agent was cached (or after gateway start)
- # must reach the next turn (#60955). Per-session turn
- # serialization (_running_agents) keeps this safe post-lock.
- if reused_cached_agent and agent is not None:
- self._apply_fallback_chain_to_agent(
- agent, self._refresh_fallback_model(),
- )
+ from hermes_cli.tools_config import _get_platform_tools
+ enabled_toolsets = sorted(_get_platform_tools(user_config, platform_key))
+ agent_cfg_local = user_config.get("agent") or {}
+ disabled_toolsets = agent_cfg_local.get("disabled_toolsets") or None
- # Lock released — now schedule cleanup of any cross-process-evicted
- # agent on a daemon thread so memory-provider shutdown / socket
- # teardown never blocks the gateway event loop or the cache lock
- # the session-expiry watcher needs (#52197).
- if _xproc_evicted_agent is not None:
- try:
- threading.Thread(
- target=self._release_evicted_agent_soft,
- args=(_xproc_evicted_agent,),
- daemon=True,
- name=f"agent-xproc-evict-{str(session_key)[:24]}",
- ).start()
- except Exception:
- # Interpreter shutdown or thread-spawn failure — release
- # inline as a best-effort fallback.
- try:
- self._release_evicted_agent_soft(_xproc_evicted_agent)
- except Exception:
- pass
+ display_config = user_config.get("display", {})
+ if not isinstance(display_config, dict):
+ display_config = {}
- if agent is None:
- # Config changed or first message — create fresh agent
- agent = AIAgent(
- model=turn_route["model"],
- **turn_route["runtime"],
- **_checkpoint_agent_kwargs(user_config),
- max_iterations=max_iterations,
- quiet_mode=True,
- verbose_logging=False,
- enabled_toolsets=enabled_toolsets,
- disabled_toolsets=disabled_toolsets,
- ephemeral_system_prompt=combined_ephemeral or None,
- prefill_messages=self._prefill_messages or None,
- reasoning_config=reasoning_config,
- service_tier=self._service_tier,
- request_overrides=turn_route.get("request_overrides"),
- providers_allowed=pr.get("only"),
- providers_ignored=pr.get("ignore"),
- providers_order=pr.get("order"),
- provider_sort=pr.get("sort"),
- provider_require_parameters=pr.get("require_parameters", False),
- provider_data_collection=pr.get("data_collection"),
- session_id=session_id,
- platform=platform_key,
- user_id=source.user_id,
- user_id_alt=source.user_id_alt,
- user_name=source.user_name,
- chat_id=source.chat_id,
- chat_name=source.chat_name,
- chat_type=source.chat_type,
- thread_id=source.thread_id,
- gateway_session_key=session_key,
- session_db=getattr(self._session_db, "_db", self._session_db),
- # Reload from disk — do not reuse the startup snapshot (#60955).
- fallback_model=self._refresh_fallback_model(),
- )
- if _cache_lock and _cache is not None:
- with _cache_lock:
- # Record the session_id the snapshot was taken for
- # alongside the message_count, so the cross-process
- # guard can skip the (meaningless) count comparison
- # when the active session_id later switches under
- # the same session_key (#54947).
- _cache[session_key] = (
- agent, _sig, _current_msg_count, session_id,
- )
- self._enforce_agent_cache_cap()
- logger.debug("Created new agent for session %s (sig=%s)", session_key, _sig)
-
- # Per-message state — callbacks and reasoning config change every
- # turn and must not be baked into the cached agent constructor.
- # Gate on needs_progress_queue (tool_progress OR thinking_progress)
- # rather than tool_progress alone: the progress_callback also relays
- # _thinking assistant scratch text, which is gated on
- # thinking_progress and is intentionally independent of tool
- # progress. With the old `tool_progress_enabled`-only gate, a user
- # who set thinking_progress:true but kept tool_progress:off got a
- # None callback — so _thinking scratch bubbles never relayed even
- # though the progress queue was created for them.
- agent.tool_progress_callback = (
- progress_callback
- if (
- needs_progress_queue
- or log_mode_enabled
- or _live_status_adapter is not None
- )
- else None
- )
- # Discord voice verbal-ack hook (fires once per turn on first tool
- # call; armed only when in a voice channel with the mixer running).
- agent.tool_start_callback = (
- voice_ack_callback if _voice_ack_guild[0] is not None else None
- )
- agent.step_callback = _step_callback_sync if _hooks_ref.loaded_hooks else None
- agent.stream_delta_callback = _stream_delta_cb
- agent.interim_assistant_callback = _interim_assistant_cb if _want_interim_messages else None
- agent.status_callback = _status_callback_sync
- # Credits / out-of-band notices (usage bands, depletion, restored).
- # Messaging has no persistent status bar, so each notice is a
- # standalone push: render to a single plaintext line and deliver via
- # the shared _deliver_platform_notice rail (honors private/public +
- # thread metadata). Fires from the agent's sync worker thread, so we
- # hop onto the gateway loop with safe_schedule_threadsafe - same
- # pattern as _status_callback_sync. The fired-once latch lives on the
- # cached agent and persists across turns, so a band crosses -> one
- # push (no per-turn re-nag). Recovery ("✓ Credit access restored")
- # rides the same show path (it's emitted as a success notice, not a
- # clear). The clear callback is a no-op: a sent platform message
- # can't be cleanly retracted, and the band already fired once.
- def _notice_callback_sync(notice) -> None:
- if not _status_adapter or not _run_still_current():
- return
- try:
- line = render_notice_line(notice)
- except Exception:
- logger.debug("render_notice_line failed", exc_info=True)
- return
- if not line:
- return
- safe_schedule_threadsafe(
- self._deliver_platform_notice(source, line),
- _loop_for_step,
- logger=logger,
- log_message="notice_callback delivery scheduling error",
- )
+ # Per-platform display settings — resolve via display_config module
+ # which checks display.platforms.<platform>.<key> first, then
+ # display.<key> global, then built-in platform defaults.
+ from gateway.display_config import resolve_display_setting
- agent.notice_callback = _notice_callback_sync
- agent.notice_clear_callback = None
- agent.event_callback = _event_callback_sync
- agent.reasoning_config = reasoning_config
- agent.service_tier = self._service_tier
- agent.request_overrides = turn_route.get("request_overrides") or {}
- # Must-deliver notes for THIS turn ride the current user message
- # (api_content sidecar), never the system prompt: staged by
- # _handle_message_with_agent (auto-reset note, first-contact
- # intro, voice-channel change). Assigned unconditionally so a
- # reused cached agent never replays a stale note.
- agent._gateway_turn_context_notes = "\n\n".join(
- self._consume_pending_turn_sidecar_notes(session_key)
- )
-
- _bg_review_release = threading.Event()
- _bg_review_pending: list[str] = []
- _bg_review_pending_lock = threading.Lock()
-
- def _deliver_bg_review_message(message: str) -> None:
- if not _status_adapter or not _run_still_current():
- return
- safe_schedule_threadsafe(
- _status_adapter.send(
- _status_chat_id,
- message,
- metadata=_non_conversational_metadata(_status_thread_metadata, platform=source.platform),
- ),
- _loop_for_step,
- logger=logger,
- log_message="background_review_callback scheduling error",
- )
+ # Apply tool preview length config (0 = no limit)
+ try:
+ from agent.display import set_tool_preview_max_len
+ _tpl = resolve_display_setting(user_config, platform_key, "tool_preview_length", 0)
+ set_tool_preview_max_len(int(_tpl) if _tpl else 0)
+ except Exception:
+ pass
+
+ # Apply friendly tool labels config (default on) — per-platform aware
+ try:
+ from agent.display import set_friendly_tool_labels
+ _ftl = resolve_display_setting(user_config, platform_key, "friendly_tool_labels", True)
+ set_friendly_tool_labels(bool(_ftl))
+ except Exception:
+ pass
+
+ # Tool progress mode — resolved per-platform with env var fallback
+ _resolved_tp = resolve_display_setting(user_config, platform_key, "tool_progress")
+ _env_tp = os.getenv("HERMES_TOOL_PROGRESS_MODE")
+ _display_cfg = display_config if isinstance(display_config, dict) else {}
+ _platforms_cfg = _display_cfg.get("platforms") or {}
+ _platform_cfg = _platforms_cfg.get(platform_key) or {}
+ _legacy_tp_overrides = _display_cfg.get("tool_progress_overrides") or {}
+ _tool_progress_configured = (
+ "tool_progress" in _display_cfg
+ or (
+ isinstance(_platform_cfg, dict)
+ and "tool_progress" in _platform_cfg
+ )
+ or (
+ isinstance(_legacy_tp_overrides, dict)
+ and platform_key in _legacy_tp_overrides
+ )
+ )
+ progress_mode = (
+ _env_tp
+ if _env_tp and not _tool_progress_configured
+ else (_resolved_tp or _env_tp or "all")
+ )
+ # Tool progress grouping: "accumulate" (edit one bubble) or "separate" (one msg per tool)
+ progress_grouping = resolve_display_setting(user_config, platform_key, "tool_progress_grouping") or "accumulate"
+ from gateway.status_phrases import choose_status_phrase, resolve_status_phrase_catalog
+ _generic_status_recent: List[str] = []
+ _generic_status_catalog = resolve_status_phrase_catalog(user_config, platform_key)
- def _release_bg_review_messages() -> None:
- _bg_review_release.set()
- with _bg_review_pending_lock:
- pending = list(_bg_review_pending)
- _bg_review_pending.clear()
- for queued in pending:
- _deliver_bg_review_message(queued)
-
- # Background review delivery — send "💾 Memory updated" etc. to user
- def _bg_review_send(message: str) -> None:
- if not _status_adapter or not _run_still_current():
- return
- if not _bg_review_release.is_set():
- with _bg_review_pending_lock:
- if not _bg_review_release.is_set():
- _bg_review_pending.append(message)
- return
- _deliver_bg_review_message(message)
-
- agent.background_review_callback = _bg_review_send
- # Register the release hook on the adapter so base.py's finally
- # block can fire it after delivering the main response.
- if _status_adapter and session_key:
- if getattr(type(_status_adapter), "register_post_delivery_callback", None) is not None:
- _status_adapter.register_post_delivery_callback(
- session_key,
- _release_bg_review_messages,
- generation=run_generation,
- )
- else:
- _pdc = getattr(_status_adapter, "_post_delivery_callbacks", None)
- if _pdc is not None:
- _pdc[session_key] = _release_bg_review_messages
- # Memory update notifications in chat. Config: display.memory_notifications
- # off — no chat notification (still logged to stdout)
- # on — generic "💾 Memory updated" (default)
- # verbose — content preview: "💾 Memory ➕ Hermes Repo..."
- _mem_notif = user_config.get("display", {}).get("memory_notifications")
- if isinstance(_mem_notif, bool):
- _mem_notif = "on" if _mem_notif else "off"
- agent.memory_notifications = str(_mem_notif).lower() if _mem_notif else "on"
-
- # ------------------------------------------------------------------
- # Clarify callback: present a clarify prompt and block on a response.
- #
- # Runs on the agent's worker thread (see clarify_tool's synchronous
- # callback contract). Bridges sync→async by scheduling the
- # adapter's send_clarify on the gateway event loop, then blocks on
- # the clarify primitive's threading.Event with a configurable
- # timeout. Returns the user's response string, or a sentinel
- # explaining that no response arrived (so the agent can adapt
- # rather than hang forever).
- # ------------------------------------------------------------------
- def _clarify_callback_sync(question: str, choices, multi_select: bool = False) -> str:
- from tools import clarify_gateway as _clarify_mod
- import uuid as _uuid
-
- if not _status_adapter:
- return ""
+ def _display_surface_mode(
+ setting: str,
+ *,
+ default: bool = False,
+ require_platform_override_for: set[Any] | None = None,
+ allow_generic: bool = False,
+ ) -> str:
+ """Return off|raw|generic for a gateway visibility surface."""
+ if require_platform_override_for:
+ current_platform = _gateway_platform_value(source.platform)
+ platform_only = {
+ _gateway_platform_value(item)
+ for item in require_platform_override_for
+ }
+ if (
+ current_platform in platform_only
+ and not _has_platform_display_override(user_config, platform_key, setting)
+ ):
+ return "off"
+ value = resolve_display_setting(user_config, platform_key, setting, default)
+ if isinstance(value, str) and value.strip().lower() == "generic":
+ return "generic" if allow_generic else "off"
+ return "raw" if bool(value) else "off"
- clarify_id = _uuid.uuid4().hex[:10]
- _clarify_mod.register(
- clarify_id=clarify_id,
- session_key=session_key or "",
- question=question,
- choices=list(choices) if choices else None,
- multi_select=bool(multi_select),
+ def _generic_status_phrase(kind: str, *, tool_name: str | None = None, preview: str | None = None, args: Any = None) -> str:
+ try:
+ return choose_status_phrase(
+ kind,
+ tool_name=tool_name,
+ preview=preview,
+ args=args,
+ recent=_generic_status_recent,
+ catalog=_generic_status_catalog,
)
+ except Exception as _phrase_err:
+ logger.debug("generic status phrase selection failed: %s", _phrase_err)
+ return "still on it" if kind in {"heartbeat", "waiting", "long_running", "status"} else "one sec"
+ # Disable tool progress for webhooks - they don't support message editing,
+ # so each progress line would be sent as a separate message.
+ from gateway.config import Platform
+ tool_progress_enabled = progress_mode not in {"off", "log"} and source.platform != Platform.WEBHOOK
+ # Live working-state status for text-rendering typing indicators
+ # (Slack's assistant status line). Independent of tool_progress —
+ # Slack defaults tool_progress off (permanent lines spam channels)
+ # but the status line is ephemeral, so live status stays useful
+ # there. Rendering rides the existing _keep_typing refresh: the
+ # callback only stores a phrase on the adapter, costing zero extra
+ # platform API calls.
+ _live_status_mode = resolve_display_setting(
+ user_config, platform_key, "live_status", "full"
+ )
+ _live_status_adapter = self._adapter_for_source(source)
+ if not getattr(_live_status_adapter, "supports_status_text", False):
+ _live_status_adapter = None
+ if _live_status_mode == "off":
+ _live_status_adapter = None
+ # "log" mode: tool calls are written to ~/.hermes/logs/tool_calls.log
+ # instead of the chat (#3459 / #3458). Gateway-only by design.
+ log_mode_enabled = progress_mode == "log" and source.platform != Platform.WEBHOOK
+ log_queue: "queue.Queue | None" = queue.Queue() if log_mode_enabled else None
+ # Natural assistant status messages are intentionally independent from
+ # tool progress and token streaming. Users can keep tool_progress quiet
+ # in chat platforms while opting into concise mid-turn updates.
+ interim_assistant_messages_mode = _display_surface_mode(
+ "interim_assistant_messages",
+ default=True,
+ require_platform_override_for={Platform.MATTERMOST},
+ )
+ interim_assistant_messages_enabled = (
+ source.platform != Platform.WEBHOOK
+ and interim_assistant_messages_mode != "off"
+ )
+ # thinking_progress is independent — if enabled, we need the progress
+ # queue even when tool_progress is off (thinking relay uses same infra).
+ # Mattermost requires a per-platform opt-in: global scratch-text display
+ # is too easy to leak into busy public threads.
+ _thinking_mode = _display_surface_mode(
+ "thinking_progress",
+ default=False,
+ require_platform_override_for={Platform.MATTERMOST},
+ )
+ _thinking_enabled = _thinking_mode != "off"
+ needs_progress_queue = tool_progress_enabled or _thinking_enabled
- # Pause typing — like approval, we don't want a "thinking..."
- # status to obscure the prompt or block the user from typing
- # an "Other" response on platforms that disable input while
- # typing is active (Slack Assistant API).
- try:
- _status_adapter.pause_typing_for_chat(_status_chat_id)
- except Exception:
- pass
- # Ordering barrier (#clarify-ordering): flush any buffered
- # assistant prose (interim commentary / streamed deltas) to the
- # platform BEFORE sending the poll. The poll is delivered on a
- # separate, agent-thread-blocking path; without this barrier it
- # races ahead of prose still sitting in the stream consumer's
- # queue, so the question renders ABOVE its own explanation.
- # Best-effort + short timeout: never hang the agent thread if
- # the consumer task isn't running.
- try:
- _sc = stream_consumer_holder[0] if stream_consumer_holder else None
- _flush = getattr(_sc, "flush_pending_sync", None)
- if callable(_flush):
- _flush(timeout=3.0)
- except Exception:
- logger.debug(
- "Stream-consumer flush before clarify prompt failed",
- exc_info=True,
- )
+ # Queue for progress messages (thread-safe)
+ progress_queue = queue.Queue() if needs_progress_queue else None
+ last_tool = [None] # Mutable container for tracking in closure
+ last_progress_msg = [None] # Track last message for dedup
+ repeat_count = [0] # How many times the same message repeated
+ # True when the previously enqueued progress line was a terminal
+ # fenced code block — consecutive terminal calls then drop the
+ # repeated "💻 terminal" header and render back-to-back blocks.
+ last_was_terminal_block = [False]
- send_ok = False
- fut = safe_schedule_threadsafe(
- _status_adapter.send_clarify(
- chat_id=_status_chat_id,
- question=question,
- choices=list(choices) if choices else None,
- clarify_id=clarify_id,
- session_key=session_key or "",
- metadata=_status_thread_metadata,
- ),
- _loop_for_step,
- logger=logger,
- log_message="Clarify send failed to schedule",
- )
- if fut is None:
- send_ok = False
- else:
- try:
- result = fut.result(timeout=15)
- send_ok = bool(getattr(result, "success", False))
- except Exception as exc:
- logger.warning("Clarify send failed: %s", exc)
- send_ok = False
-
- if not send_ok:
- # Couldn't deliver the prompt — clean up and return
- # sentinel so the agent can fall back to a sensible
- # default rather than hanging.
- _clarify_mod.clear_session(session_key or "")
- return "[clarify prompt could not be delivered]"
-
- timeout = _clarify_mod.get_clarify_timeout()
- response = _clarify_mod.wait_for_response(clarify_id, timeout=float(timeout))
- if response is None or response == "":
- # Timeout or session-boundary cancellation
- return f"[user did not respond within {int(timeout / 60)}m]"
- return response
-
- agent.clarify_callback = _clarify_callback_sync
-
- # Show assistant thinking between tool calls — independent of
- # tool_progress mode. Mattermost needs an explicit per-platform
- # opt-in so global scratch-text display does not leak into threads.
- agent.thinking_progress = _thinking_enabled
- # Store agent reference for interrupt support
- agent_holder[0] = agent
- # Capture the full tool definitions for transcript logging
- tools_holder[0] = agent.tools if hasattr(agent, 'tools') else None
-
- # Convert history to agent format.
- # Two cases:
- # 1. Normal path (from transcript): simple {role, content, timestamp} dicts
- # - Strip timestamps, keep role+content
- # 2. Interrupt path (from agent result["messages"]): full agent messages
- # that may include tool_calls, tool_call_id, reasoning, etc.
- # - These must be passed through intact so the API sees valid
- # assistant→tool sequences (dropping tool_calls causes 500 errors)
- #
- # Telegram observed group context is handled structurally here:
- # observed=True transcript rows are withheld from replayable
- # history and attached to the current addressed message as
- # API-only context, so persisted history stores only the real
- # addressed user turn.
- agent_history, observed_group_context = _build_gateway_agent_history(
- history,
- channel_prompt=channel_prompt,
- inject_timestamps=_message_timestamps_enabled(_load_gateway_config()),
- )
-
- # FTS write-corruption guard (#50502): when message persistence
- # fails silently through corrupt FTS triggers, the reloaded
- # transcript above is stale/empty even though the SAME cached agent
- # still holds the full live conversation in `_session_messages`.
- # Replacing the live transcript with that shorter copy causes
- # immediate same-session amnesia. Only applies when we reused a
- # cached agent bound to this exact session_id.
- if reused_cached_agent and getattr(agent, "session_id", None) == session_id:
- _selected = _select_cached_agent_history(
- agent_history, getattr(agent, "_session_messages", None)
- )
- if _selected is not agent_history:
- logger.warning(
- "Persisted transcript lagged live cached history for "
- "session %s (disk=%d, memory=%d); preserving live "
- "conversation context (possible FTS write corruption)",
- session_key, len(agent_history), len(_selected),
- )
- # The live in-memory history bypassed the
- # _build_gateway_agent_history cleanup pipeline above —
- # re-apply the stale-confirmation expiry (#59607) so a
- # dangerous confirmation can't slip through this path
- # either. Idempotent; messages without timestamps are
- # untouched.
- agent_history = _strip_stale_dangerous_confirmations(
- _selected, now=time.time()
- )
-
- # Collect MEDIA paths already in history so we can exclude them
- # from the current turn's extraction. This is compression-safe:
- # even if the message list shrinks, we know which paths are old.
- _history_media_paths: set = _collect_history_media_paths(agent_history)
-
- # Register per-session gateway approval callback so dangerous
- # command approval blocks the agent thread (mirrors CLI input()).
- # The callback bridges sync→async to send the approval request
- # to the user immediately.
- from tools.approval import (
- register_gateway_notify,
- reset_current_session_key,
- set_current_session_key,
- unregister_gateway_notify,
- )
+ # ── Discord voice "verbal ack before tool calls" ────────────────
+ # When the bot is in a voice channel with the continuous mixer
+ # installed (discord.voice_fx.enabled), speak a short phrase ("let me
+ # look into that") over the ambient idle bed on the FIRST tool call of
+ # the turn. Fires from tool_start_callback (independent of the
+ # tool-progress text gate), at most once per turn. No-op on every
+ # other platform / when not in a voice channel.
+ _voice_ack_fired = [False]
+ _voice_ack_guild: List[Optional[int]] = [None]
+ if source.platform == Platform.DISCORD:
+ _va = self.adapters.get(Platform.DISCORD)
+ # source.chat_id is the linked text channel; resolve the guild whose
+ # voice connection is bound to it (mirrors DiscordAdapter.play_tts).
+ _vtc = getattr(_va, "_voice_text_channels", None)
+ if isinstance(_vtc, dict) and hasattr(_va, "voice_mixer_active"):
+ for _gid, _tc in _vtc.items():
+ if str(_tc) == str(source.chat_id) and _va.voice_mixer_active(_gid):
+ _voice_ack_guild[0] = _gid
+ break
+ _voice_ack_loop = asyncio.get_running_loop()
- def _approval_notify_sync(approval_data: dict) -> None:
- """Send the approval request to the user from the agent thread.
+ # voice_ack_callback extracted to TurnRunner.voice_ack_callback
+ # (published onto turn_ctx after the runner is constructed below).
- If the adapter supports interactive button-based approvals
- (e.g. Discord's ``send_exec_approval``), use that for a richer
- UX. Otherwise fall back to a plain text message with
- ``/approve`` instructions.
- """
- # Pause the typing indicator while the agent waits for
- # user approval. Critical for Slack's Assistant API where
- # assistant_threads_setStatus disables the compose box — the
- # user literally cannot type /approve while "is thinking..."
- # is active. The approval message send auto-clears the Slack
- # status; pausing prevents _keep_typing from re-setting it.
- # Typing resumes in _handle_approve_command/_handle_deny_command.
- _status_adapter.pause_typing_for_chat(_status_chat_id)
-
- cmd = approval_data.get("command", "")
- desc = approval_data.get("description", "dangerous command")
-
- # Redact credentials from the command before displaying it in
- # the approval prompt — Tirith's findings are already redacted,
- # but the raw command string still leaks secrets to the chat
- # platform (#48456). Applied here so BOTH the button-based
- # (send_exec_approval) and plain-text fallback paths below use
- # the redacted value.
- cmd = _redact_approval_command(cmd)
-
- # Prefer button-based approval when the adapter supports it.
- # Check the *class* for the method, not the instance — avoids
- # false positives from MagicMock auto-attribute creation in tests.
- if getattr(type(_status_adapter), "send_exec_approval", None) is not None:
- try:
- _approval_fut = safe_schedule_threadsafe(
- _status_adapter.send_exec_approval(
- chat_id=_status_chat_id,
- command=cmd,
- session_key=_approval_session_key,
- description=desc,
- metadata=_status_thread_metadata,
- allow_permanent=approval_data.get("allow_permanent", True),
- allow_session=approval_data.get("allow_session", True),
- smart_denied=approval_data.get("smart_denied", False),
- ),
- _loop_for_step,
- logger=logger,
- log_message="send_exec_approval scheduling error",
- )
- if _approval_fut is None:
- raise RuntimeError("send_exec_approval: loop unavailable")
- _approval_result = _approval_fut.result(timeout=15)
- if _approval_result.success:
- return
- logger.warning(
- "Button-based approval failed (send returned error), falling back to text: %s",
- _approval_result.error,
- )
- except Exception as _e:
- logger.warning(
- "Button-based approval failed, falling back to text: %s", _e
- )
+ # Auto-cleanup of temporary progress bubbles (Telegram + any adapter
+ # that implements ``delete_message``). When enabled via
+ # ``display.platforms.<platform>.cleanup_progress: true``, message IDs
+ # from the tool-progress / "⏳ Working — N min" / status-callback bubbles
+ # are collected here and deleted after the final response lands.
+ # Failed runs skip cleanup so the bubbles remain as breadcrumbs.
+ _cleanup_progress = bool(
+ resolve_display_setting(user_config, platform_key, "cleanup_progress")
+ )
+ _cleanup_adapter = self._adapter_for_source(source) if _cleanup_progress else None
+ # getattr, not attribute access — same duck-typed-adapter guard as the
+ # edit_message check in send_progress_messages below: a fake/minimal
+ # adapter without delete_message means "can't delete", not a crash.
+ _cleanup_delete = getattr(type(_cleanup_adapter), "delete_message", None) if _cleanup_adapter is not None else None
+ if _cleanup_adapter is not None and (
+ _cleanup_delete is None
+ or _cleanup_delete is BasePlatformAdapter.delete_message
+ ):
+ # Adapter doesn't support deletion — silently disable.
+ _cleanup_progress = False
+ _cleanup_adapter = None
+ _cleanup_msg_ids: List[str] = []
+ # First-touch onboarding latch: fires at most once per run, even if
+ # several tools exceed the threshold.
+ long_tool_hint_fired = [False]
+ _LONG_TOOL_THRESHOLD_S = 30.0
- # Fallback: plain text approval prompt. Use the adapter's
- # typed prefix so Slack/Matrix users are told the form they
- # can actually type (`!approve`) — typed "/" is blocked in
- # Slack threads and reserved by Matrix clients.
- _p = getattr(_status_adapter, "typed_command_prefix", "/")
- msg = _format_exec_approval_fallback(
- cmd,
- desc,
- _p,
- allow_permanent=approval_data.get("allow_permanent", True),
- allow_session=approval_data.get("allow_session", True),
- smart_denied=approval_data.get("smart_denied", False),
- )
+ turn_ctx = TurnContext(
+ source=source,
+ _run_still_current=_run_still_current,
+ _live_status_adapter=_live_status_adapter,
+ _live_status_mode=_live_status_mode,
+ _thinking_enabled=_thinking_enabled,
+ progress_mode=progress_mode,
+ progress_grouping=progress_grouping,
+ tool_progress_enabled=tool_progress_enabled,
+ progress_queue=progress_queue,
+ log_queue=log_queue,
+ last_progress_msg=last_progress_msg,
+ last_tool=last_tool,
+ last_was_terminal_block=last_was_terminal_block,
+ repeat_count=repeat_count,
+ long_tool_hint_fired=long_tool_hint_fired,
+ _LONG_TOOL_THRESHOLD_S=_LONG_TOOL_THRESHOLD_S,
+ _cleanup_progress=_cleanup_progress,
+ _cleanup_msg_ids=_cleanup_msg_ids,
+ message=message,
+ AIAgent=AIAgent,
+ resolve_display_setting=resolve_display_setting,
+ user_config=user_config,
+ enabled_toolsets=enabled_toolsets,
+ disabled_toolsets=disabled_toolsets,
+ log_mode_enabled=log_mode_enabled,
+ interim_assistant_messages_enabled=interim_assistant_messages_enabled,
+ needs_progress_queue=needs_progress_queue,
+ _voice_ack_fired=_voice_ack_fired,
+ _voice_ack_guild=_voice_ack_guild,
+ _voice_ack_loop=_voice_ack_loop,
+ history=history,
+ context_prompt=context_prompt,
+ channel_prompt=channel_prompt,
+ session_id=session_id,
+ session_key=session_key,
+ run_generation=run_generation,
+ _interrupt_depth=_interrupt_depth,
+ event_message_id=event_message_id,
+ moa_config=moa_config,
+ persist_user_message=persist_user_message,
+ persist_user_timestamp=persist_user_timestamp,
+ )
+ turn_runner = TurnRunner(self, turn_ctx)
+ # Callback invoked by agent on tool lifecycle events — extracted to
+ # TurnRunner.progress_callback (bound method, same signature).
+ turn_ctx.progress_callback = turn_runner.progress_callback
+ turn_ctx.voice_ack_callback = turn_runner.voice_ack_callback
+
+ # Background task to send progress messages
+ # Accumulates tool lines into a single message that gets edited.
+ #
+ # Threading metadata is platform-specific:
+ # - Slack DM threading needs event_message_id fallback (reply thread)
+ # - Telegram forum topics use message_thread_id; Hermes-created private
+ # DM topic lanes require both thread metadata and a reply anchor
+ # - Feishu only honors reply_in_thread when sending a reply, so topic
+ # progress uses the triggering event message as the reply target
+ # - Other platforms should use explicit source.thread_id only
+ #
+ # Slack honours platforms.slack.extra.reply_in_thread=false: if the
+ # user has opted out of threaded replies, don't synthesise a thread
+ # for progress messages either — the very first progress message
+ # would otherwise create a thread that all subsequent replies
+ # (including the final answer) would inherit (#18859).
+ _progress_reply_in_thread = True
+ if source.platform == Platform.SLACK:
+ _slack_adapter_for_progress = self._adapter_for_source(source)
+ if _slack_adapter_for_progress is not None:
try:
- _approval_send_fut = safe_schedule_threadsafe(
- _status_adapter.send(
- _status_chat_id,
- msg,
- metadata=_status_thread_metadata,
- ),
- _loop_for_step,
- logger=logger,
- log_message="Approval text-send scheduling error",
+ # Relay lane: the adapter owns mode resolution (nested
+ # platforms.relay.extra.slack subset with flat-key
+ # fallback). Native lane: read the flat extra as before.
+ _mode_fn = getattr(
+ _slack_adapter_for_progress,
+ "_effective_reply_in_thread",
+ None,
)
- if _approval_send_fut is not None:
- _approval_send_fut.result(timeout=15)
- except Exception as _e:
- logger.error("Failed to send approval request: %s", _e)
-
- # Keep real user text separate from API-only recovery guidance. If
- # an auto-continue note is prepended below, persist the original
- # message so stale guidance never replays as user-authored text.
- _persist_user_message_override: Optional[Any] = persist_user_message
- _persist_user_timestamp_override: Optional[float] = persist_user_timestamp
-
- # Prepend pending model switch note so the model knows about the switch
- _pending_notes = getattr(self, '_pending_model_notes', {})
- _msn = _pending_notes.pop(session_key, None) if session_key else None
- if _msn:
- message = _msn + "\n\n" + message
-
- # Auto-continue: if the loaded history ends with a tool result,
- # the previous agent turn was interrupted mid-work (gateway
- # restart, crash, SIGTERM). Prepend a system note so the model
- # finishes processing the pending tool results before addressing
- # the user's new message. (#4493)
- #
- # Session-level resume_pending (set on drain-timeout shutdown)
- # escalates the wording — the transcript's last role may be
- # anything (tool, assistant with unfinished work, etc.), so we
- # give a stronger, reason-aware instruction that subsumes the
- # tool-tail case.
- #
- # Freshness gate (#16802): both branches are gated on the age
- # of the last persisted transcript row. That is the correct
- # "when did we last do anything here" signal for both the
- # resume_pending path (restart watchdog) and the tool-tail
- # path (in-flight tool loop killed). We read ``history[-1]``
- # here because ``agent_history`` has already stripped the
- # ``timestamp`` field off tool/tool_call rows for API purity
- # (see the `k != "timestamp"` filter above). Rows without a
- # timestamp (legacy transcripts) are treated as fresh so the
- # historical auto-continue behaviour is preserved.
- _freshness_window = _auto_continue_freshness_window()
- _interruption_is_fresh = _is_fresh_gateway_interruption(
- _last_transcript_timestamp(history),
- window_secs=_freshness_window,
+ if callable(_mode_fn):
+ _progress_reply_in_thread = bool(_mode_fn())
+ else:
+ _progress_reply_in_thread = bool(
+ _slack_adapter_for_progress.config.extra.get(
+ "reply_in_thread", True
+ )
+ )
+ except Exception:
+ _progress_reply_in_thread = True
+ _progress_thread_id = _resolve_progress_thread_id(
+ source.platform, source.thread_id, event_message_id,
+ reply_in_thread=_progress_reply_in_thread,
+ )
+ _progress_metadata = (
+ self._thread_metadata_for_source(source, event_message_id)
+ if _progress_thread_id == source.thread_id
+ else self._thread_metadata_for_target(
+ source.platform,
+ source.chat_id,
+ _progress_thread_id,
+ chat_type=getattr(source, "chat_type", None),
+ reply_to_message_id=event_message_id,
)
+ ) if _progress_thread_id else None
+ _progress_metadata = _non_conversational_metadata(_progress_metadata, platform=source.platform)
+ _progress_reply_to = (
+ event_message_id
+ if source.platform in (Platform.FEISHU, Platform.MATTERMOST) and source.thread_id and event_message_id
+ else None
+ )
- _resume_entry = None
- if session_key:
- try:
- _resume_entry = self.session_store._entries.get(session_key)
- except Exception:
- _resume_entry = None
-
- # resume_pending freshness uses a SECOND signal in addition to the
- # transcript clock above. The restart watchdog stamps the session
- # with ``last_resume_marked_at`` at interrupt time — that is the
- # correct "when were we interrupted" signal. The transcript clock
- # (_interruption_is_fresh) can be far older: an active thread you
- # return to may have its last persisted row hours back, even though
- # the interruption itself just happened. Gating resume_pending on
- # the transcript clock alone makes the recovery note silently drop,
- # and because the startup auto-resume turn carries empty text
- # (_schedule_resume_pending_sessions), the model then receives a
- # blank user message and replies with confused "the message came
- # through blank" noise. Treat the marker as fresh when
- # EITHER signal is fresh so the two freshness checks agree.
- _resume_mark_is_fresh = False
- if _resume_entry is not None and getattr(_resume_entry, "resume_pending", False):
- _resume_mark_is_fresh = _is_fresh_gateway_interruption(
- getattr(_resume_entry, "last_resume_marked_at", None),
- window_secs=_freshness_window,
- )
- _is_resume_pending = bool(
- _resume_entry is not None
- and getattr(_resume_entry, "resume_pending", False)
- and (_interruption_is_fresh or _resume_mark_is_fresh)
- )
- _has_fresh_tool_tail = bool(
- agent_history
- and agent_history[-1].get("role") == "tool"
- and _interruption_is_fresh
- )
-
- if _is_resume_pending:
- _reason = getattr(_resume_entry, "resume_reason", None) or "restart_timeout"
- _persist_user_message_override = message
- # The empty-message case is the auto-resume startup turn
- # synthesized by _schedule_resume_pending_sessions — there is
- # no NEW user message to address. Guidance is adapter-aware:
- # interactive platforms report the restore and ask what next;
- # non-interactive event platforms (webhook, API server)
- # continue the interrupted work instead, because nobody is
- # present to answer and an acknowledgement would silently
- # abandon the task (#57056).
- _resume_adapter = self._adapter_for_source(source)
- _interactive_resume = bool(
- getattr(_resume_adapter, "interactive_resume", True)
- )
- message = build_resume_recovery_note(
- _reason, message, interactive=_interactive_resume,
- )
- elif _has_fresh_tool_tail:
- _persist_user_message_override = message
- message = (
- "[System note: A new message has arrived. The conversation "
- "history contains pending tool outputs from an interrupted turn. "
- "IGNORE those pending results. Address the user's NEW message "
- "below FIRST. Do NOT re-execute old tool calls from the history.]\n\n"
- + message
- )
+ async def write_tool_log():
+ """Drain log_queue and append tool-call lines to tool_calls.log.
- # Consume one-shot /reload-skills note (if the user ran
- # /reload-skills since their last turn in this session). Same
- # queue pattern as CLI: prepend to the NEXT user message, then
- # clear. Nothing was written to the transcript out-of-band, so
- # message alternation stays intact.
- _pending_notes = getattr(self, "_pending_skills_reload_notes", None)
- if _pending_notes and session_key and session_key in _pending_notes:
- _srn = _pending_notes.pop(session_key, None)
- if _srn:
- message = _srn + "\n\n" + message
-
- # Safety net: a startup auto-resume event carries empty
- # text and relies on the resume_pending branch above to supply the
- # recovery note. If that branch did not fire for any reason (e.g.
- # both freshness signals disagreed, or the marker was cleared
- # between scheduling and dispatch) we must NOT hand the model a
- # blank user turn — it responds with confused "the message came
- # through blank" noise. Restricted to resume_pending sessions so
- # legitimately empty user turns (e.g. an image with no caption,
- # wrapped as native content below) are untouched.
- if (
- isinstance(message, str)
- and not message.strip()
- and _resume_entry is not None
- and getattr(_resume_entry, "resume_pending", False)
- ):
- _sn_reason = (
- getattr(_resume_entry, "resume_reason", None) or "restart_timeout"
- )
- _sn_adapter = self._adapter_for_source(source)
- message = build_resume_recovery_note(
- _sn_reason,
- "",
- interactive=bool(
- getattr(_sn_adapter, "interactive_resume", True)
- ),
- )
+ Only active when ``display.tool_progress`` is ``log``. Uses a
+ RotatingFileHandler (5MB × 3 backups) so the audit log can't grow
+ unbounded, and the shared RedactingFormatter so secrets never land
+ on disk.
+ """
+ if log_queue is None:
+ return
+ from logging.handlers import RotatingFileHandler
- _approval_session_key = session_key or ""
- _approval_session_token = set_current_session_key(_approval_session_key)
- register_gateway_notify(_approval_session_key, _approval_notify_sync)
+ from agent.redact import RedactingFormatter
+
+ log_dir = _hermes_home / "logs"
+ log_dir.mkdir(parents=True, exist_ok=True)
+ file_handler = RotatingFileHandler(
+ log_dir / "tool_calls.log",
+ maxBytes=5 * 1024 * 1024,
+ backupCount=3,
+ encoding="utf-8",
+ )
+ file_handler.setFormatter(RedactingFormatter("%(message)s"))
+ tool_logger = logging.getLogger(f"hermes.tool_calls.{id(log_queue)}")
+ tool_logger.setLevel(logging.INFO)
+ tool_logger.propagate = False
+ tool_logger.addHandler(file_handler)
try:
- # If _prepare_inbound_message_text buffered image paths for native
- # attachment, wrap the user turn as an OpenAI-style multimodal
- # content list. Consume-and-clear so subsequent turns on the same
- # runner instance don't re-attach stale images.
- _native_imgs = self._consume_pending_native_image_paths(session_key)
- if _native_imgs:
+ while True:
try:
- from agent.image_routing import build_native_content_parts
- _parts, _skipped = build_native_content_parts(
- message,
- _native_imgs,
- )
- if _skipped:
- logger.warning(
- "Native image attachment: skipped %d unreadable path(s): %s",
- len(_skipped), _skipped,
- )
- if any(p.get("type") == "image_url" for p in _parts):
- _run_message: Any = _parts
- else:
- # All images failed to read — fall back to plain text.
- _run_message = message
- except Exception as _img_exc:
- logger.warning(
- "Native image attachment failed, falling back to text: %s",
- _img_exc,
- )
- _run_message = message
- else:
- _run_message = message
-
- _api_run_message = _wrap_current_message_with_observed_context(
- _run_message,
- observed_group_context,
- )
- _conversation_kwargs = {
- "conversation_history": agent_history,
- "task_id": session_id,
- }
- if _persist_user_message_override is not None:
- _conversation_kwargs["persist_user_message"] = _persist_user_message_override
- elif observed_group_context:
- _conversation_kwargs["persist_user_message"] = message
- if moa_config is not None:
- _conversation_kwargs["moa_config"] = moa_config
- if _persist_user_timestamp_override is not None:
- _conversation_kwargs["persist_user_timestamp"] = _persist_user_timestamp_override
- result = agent.run_conversation(_api_run_message, **_conversation_kwargs)
+ tool_logger.info("%s", log_queue.get_nowait())
+ except queue.Empty:
+ await asyncio.sleep(0.3)
+ except Exception as e:
+ logger.error("write_tool_log error: %s", e)
+ await asyncio.sleep(1)
+ except asyncio.CancelledError:
+ pass
finally:
- unregister_gateway_notify(_approval_session_key)
- # Cancel any pending clarify entries so blocked agent
- # threads don't hang past the end of the run (interrupt,
- # completion, gateway shutdown). Idempotent.
+ # Drain remaining entries before closing so late tool calls
+ # from the final iteration aren't lost.
+ while True:
+ try:
+ tool_logger.info("%s", log_queue.get_nowait())
+ except queue.Empty:
+ break
+ except Exception:
+ break
+ tool_logger.removeHandler(file_handler)
try:
- from tools.clarify_gateway import clear_session as _clear_clarify_session
- _clear_clarify_session(_approval_session_key)
+ file_handler.flush()
+ file_handler.close()
except Exception:
pass
- reset_current_session_key(_approval_session_token)
- result_holder[0] = result
- # Signal the stream consumer that the agent is done
- if _stream_consumer is not None:
- _stream_consumer.finish()
+ # Extracted to TurnRunner.send_progress_messages. The threading
+ # metadata computed above is published onto the shared TurnContext
+ # exactly where the original closure's captured locals were bound.
+ turn_ctx._progress_metadata = _progress_metadata
+ turn_ctx._progress_reply_to = _progress_reply_to
+ send_progress_messages = turn_runner.send_progress_messages
+
+ # We need to share the agent instance for interrupt support
+ agent_holder = [None] # Mutable container for the agent instance
+ turn_ctx.agent_holder = agent_holder
+ result_holder = [None] # Mutable container for the result
+ tools_holder = [None] # Mutable container for the tool definitions
+ stream_consumer_holder = [None] # Mutable container for stream consumer
+ # #60671 — streaming PCM audio consumer. Created on the gateway
+ # event-loop thread (NOT inside run_sync's executor worker) so the
+ # outer finalisation / interrupt paths can reference it without a
+ # cross-scope NameError.
+ streaming_tts_consumer_holder: list = [None]
+ turn_ctx.result_holder = result_holder
+ turn_ctx.tools_holder = tools_holder
+ turn_ctx.stream_consumer_holder = stream_consumer_holder
+ turn_ctx.streaming_tts_consumer_holder = streaming_tts_consumer_holder
+
+ # Bridge sync step_callback → async hooks.emit for agent:step events
+ _loop_for_step = asyncio.get_running_loop()
+ _hooks_ref = self.hooks
- # Signal the streaming-TTS consumer that the agent is done (#60671).
- # finish() is called from the outer event-loop thread after the
- # executor returns, so early returns from run_sync are also
- # finalised. See the outer finally/completion section below.
-
- # Return final response, or a message if something went wrong
- final_response = result.get("final_response")
-
- # Extract actual token counts from the agent instance used for this run
- _last_prompt_toks = 0
- _input_toks = 0
- _output_toks = 0
- _context_length = 0
- _agent = agent_holder[0]
- if _agent and hasattr(_agent, "context_compressor"):
- _last_prompt_toks = getattr(_agent.context_compressor, "last_prompt_tokens", 0)
- _input_toks = getattr(_agent, "session_prompt_tokens", 0)
- _output_toks = getattr(_agent, "session_completion_tokens", 0)
- _context_length = getattr(_agent.context_compressor, "context_length", 0) or 0
- _resolved_model = getattr(_agent, "model", None) if _agent else None
-
- # Sync session_id immediately after run_conversation(). Compression
- # can rotate before a follow-up model call fails; the failure return
- # below must still point the gateway at the compressed child.
- agent = agent_holder[0]
- _session_was_split = False
- # In-place compaction (compression.in_place / #38763) compacts the
- # transcript WITHOUT rotating the id, so the id-change diff below
- # can't detect it. compress_context() sets this rotation-independent
- # flag on the agent; the gateway uses it to re-baseline transcript
- # handling (history_offset=0 + rewrite the JSONL transcript) the
- # same way a split would, even though the session_id is unchanged.
- _compacted_in_place = bool(getattr(agent, "_last_compaction_in_place", False)) if agent else False
- agent_session_id = getattr(agent, 'session_id', session_id) if agent else session_id
- if agent and session_key and agent_session_id != session_id:
- _session_was_split = True
- logger.info(
- "Session split detected: %s → %s (compression)",
- session_id, agent_session_id,
- )
- entry = self.session_store._entries.get(session_key)
- _session_split_entry_persisted = False
- if entry:
- entry_session_id = getattr(entry, "session_id", None)
- if not _run_still_current():
- logger.info(
- "Skipping session split sync for stale run %s — "
- "generation %s is no longer current",
- session_key or "?",
- run_generation,
- )
- elif entry_session_id == agent_session_id:
- _session_split_entry_persisted = True
- elif entry_session_id != session_id:
- logger.info(
- "Skipping session split sync for %s because the "
- "session binding moved from %s to %s before "
- "compression finished",
- session_key or "?",
- session_id,
- entry_session_id,
- )
- else:
- entry.session_id = agent_session_id
- self.session_store._save()
- self.session_store._record_gateway_session_peer(
- agent_session_id,
- session_key,
- source,
- )
- _session_split_entry_persisted = True
-
- # If this is a Telegram DM and source.thread_id was lost during
- # the session split (synthetic / recovered event), restore it
- # from the binding so _thread_metadata_for_source produces the
- # correct message_thread_id instead of routing to the General
- # thread. Failure here is non-fatal — we log and continue;
- # worst case the message lands in General, which is the
- # pre-fix behaviour. Only do this after this run successfully
- # published its session split; a stale /stop→/new predecessor
- # must not mutate routing/binding state for the fresh session.
- if _session_split_entry_persisted and (
- getattr(source, "platform", None) == Platform.TELEGRAM
- and getattr(source, "chat_type", None) == "dm"
- and getattr(source, "thread_id", None) is None
- and self._session_db is not None
- ):
- try:
- # run_sync is off-loop (executor); sync DB is fine.
- _binding = self._session_db._db.get_telegram_topic_binding_by_session(
- session_id=agent_session_id,
- )
- if _binding and _binding.get("thread_id"):
- source.thread_id = str(_binding["thread_id"])
- logger.debug(
- "Restored source.thread_id=%s from binding after session split %s → %s",
- source.thread_id,
- session_id,
- agent_session_id,
- )
- except Exception:
- logger.debug(
- "Failed to restore thread_id from binding after session split",
- exc_info=True,
- )
- if _session_split_entry_persisted:
- self._sync_telegram_topic_binding(
- source, entry, reason="agent-run-compression",
- )
+ # Bridge extracted to TurnRunner._step_callback_sync; the loop and
+ # hooks refs bound just above are published at their original site.
+ turn_ctx._loop_for_step = _loop_for_step
+ turn_ctx._hooks_ref = _hooks_ref
+ turn_ctx._step_callback_sync = turn_runner._step_callback_sync
- effective_session_id = agent_session_id
- self._sync_session_model_from_agent(effective_session_id, agent)
- # history_offset=0 whenever the agent's message list no longer has
- # the original history prefix — i.e. on rotation (split) OR in-place
- # compaction. In both cases the returned `messages` is the compacted
- # set, so the gateway must persist all of it (offset 0), not slice
- # past the pre-compaction length (which would drop everything).
- _effective_history_offset = (
- 0 if (_session_was_split or _compacted_in_place) else len(agent_history)
- )
+ # Bridge sync event_callback → async hooks.emit for lifecycle events
+ # (e.g. session:compress fires after context compression splits a session)
+ # Bridge extracted to TurnRunner._event_callback_sync.
+ turn_ctx._event_callback_sync = turn_runner._event_callback_sync
- if not final_response:
- final_response = _normalize_empty_agent_response(
- result, final_response or "", history_len=len(agent_history),
+ # Bridge sync status_callback → async adapter.send for context pressure
+ _status_adapter = self._adapter_for_source(source)
+ _status_chat_id = source.chat_id
+ if source.platform == Platform.FEISHU and source.thread_id and event_message_id:
+ # Feishu topics only keep messages inside the topic when they are
+ # sent via the reply API with reply_in_thread=true. Status/interim,
+ # approval, and stream-consumer paths usually only receive metadata,
+ # so carry the triggering message id as a Feishu-specific fallback.
+ _status_thread_metadata: Optional[Dict[str, Any]] = {
+ "thread_id": _progress_thread_id,
+ "reply_to_message_id": event_message_id,
+ }
+ else:
+ _status_thread_metadata = (
+ self._thread_metadata_for_source(source, event_message_id)
+ if _progress_thread_id == source.thread_id
+ else self._thread_metadata_for_target(
+ source.platform,
+ source.chat_id,
+ _progress_thread_id,
+ chat_type=getattr(source, "chat_type", None),
+ reply_to_message_id=event_message_id,
)
- final_response = _sanitize_gateway_final_response(source.platform, final_response)
- if not final_response:
- final_response = f"⚠️ {result['error']}" if result.get("error") else ""
- return {
- "final_response": final_response,
- "messages": result.get("messages", []),
- "api_calls": result.get("api_calls", 0),
- "failed": result.get("failed", False),
- # Sibling of the non-empty-response return below (#64686):
- # the classifier's failure_reason must survive the
- # empty-response normalization path too, or downstream
- # consumers (TUI billing surface, transient-failure
- # persistence) lose the structured reason exactly when
- # the run produced no text.
- "failure_reason": result.get("failure_reason"),
- "partial": result.get("partial", False),
- "completed": result.get("completed"),
- "interrupted": result.get("interrupted", False),
- "interrupt_message": result.get("interrupt_message"),
- "error": result.get("error"),
- "compression_exhausted": result.get("compression_exhausted", False),
- "compression_deferred": result.get("compression_deferred", False),
- "tools": tools_holder[0] or [],
- "history_offset": _effective_history_offset,
- "compacted_in_place": _compacted_in_place,
- "session_id": effective_session_id,
- "last_prompt_tokens": _last_prompt_toks,
- "input_tokens": _input_toks,
- "output_tokens": _output_toks,
- "model": _resolved_model,
- "context_length": _context_length,
- }
+ ) if _progress_thread_id else None
- # Scan tool results for MEDIA:<path> tags that need to be delivered
- # as native audio/file attachments. The TTS tool embeds MEDIA: tags
- # in its JSON response, but the model's final text reply usually
- # doesn't include them. We collect unique tags from tool results and
- # append any that aren't already present in the final response, so the
- # adapter's extract_media() can find and deliver the files exactly once.
- #
- # Scope the scan to THIS turn's tool results only. ``agent_history``
- # was passed into run_conversation as ``conversation_history``, so the
- # agent's returned ``messages`` list is ``agent_history`` followed by
- # the messages produced this turn. Slicing at ``len(agent_history)``
- # isolates the current turn precisely, so a stale MEDIA: path emitted
- # by a tool several turns earlier (still present in the full message
- # list) can never leak onto a later text-only reply. (Fixes #34608)
- #
- # Path-based deduplication against _history_media_paths (collected
- # before run_conversation) is retained as a secondary guard. It is
- # also the sole guard on the fallback branch taken when mid-run
- # context compression shrinks the message list below the original
- # history length, preserving the compression-safe behaviour of #160.
- if "MEDIA:" not in final_response:
- media_tags, has_voice_directive = _collect_auto_append_media_tags(
- result.get("messages", []),
- history_offset=len(agent_history),
- history_media_paths=_history_media_paths,
- )
+ # Bridge extracted to TurnRunner._status_callback_sync; publish the
+ # status wiring computed above onto the shared TurnContext at the
+ # exact original binding site.
+ turn_ctx._status_adapter = _status_adapter
+ turn_ctx._status_chat_id = _status_chat_id
+ turn_ctx._status_thread_metadata = _status_thread_metadata
+ turn_ctx._status_callback_sync = turn_runner._status_callback_sync
- if media_tags:
- seen = set()
- unique_tags = []
- for tag in media_tags:
- if tag not in seen:
- seen.add(tag)
- unique_tags.append(tag)
- if has_voice_directive:
- unique_tags.insert(0, "[[audio_as_voice]]")
- final_response = final_response + "\n" + "\n".join(unique_tags)
-
- # Auto-generate session title after first exchange (non-blocking)
- if final_response and self._session_db:
- try:
- from agent.title_generator import maybe_auto_title
- all_msgs = result_holder[0].get("messages", []) if result_holder[0] else []
- # In Gateway mode, auto-title failures must NOT be
- # surfaced as user-visible messages (fixes #23246).
- # Log them at debug level only — they are not actionable
- # to the end user. CLI mode keeps the existing behaviour
- # via the agent's _emit_auxiliary_failure path.
- def _title_failure_cb(task: str, exc: BaseException) -> None:
- logger.debug(
- "Gateway auto-title failure suppressed (not user-visible): %s: %s",
- task, exc,
- )
- # Snapshot the runtime identity; the validator lets the
- # background titler skip its LLM call if the session's
- # model changed before it fires (a stale request would
- # reload an unloaded Ollama model, #19027).
- _title_model = getattr(agent, "model", None) if agent else None
- _title_provider = getattr(agent, "provider", None) if agent else None
- maybe_auto_title_kwargs = {
- "failure_callback": _title_failure_cb,
- "main_runtime": {
- "model": getattr(agent, "model", None),
- "provider": getattr(agent, "provider", None),
- "base_url": getattr(agent, "base_url", None),
- "api_key": getattr(agent, "api_key", None),
- "api_mode": getattr(agent, "api_mode", None),
- } if agent else None,
- "runtime_validator": (lambda: (
- getattr(agent, "model", None) == _title_model
- and getattr(agent, "provider", None) == _title_provider
- )) if agent else None,
- }
- if self._is_telegram_topic_lane(source):
- maybe_auto_title_kwargs["title_callback"] = lambda title: self._schedule_telegram_topic_title_rename(
- source,
- effective_session_id,
- title,
- )
- elif self._is_discord_auto_thread_lane(source):
- maybe_auto_title_kwargs["title_callback"] = lambda title: self._schedule_discord_semantic_thread_rename(
- source,
- effective_session_id,
- title,
- )
- maybe_auto_title(
- getattr(self._session_db, "_db", self._session_db),
- effective_session_id,
- message,
- final_response,
- all_msgs,
- **maybe_auto_title_kwargs,
- )
- except Exception:
- pass
+ # ---- Streaming TTS consumer setup (#60671) ----
+ # Created on the gateway event-loop thread (here, in _run_agent_inner),
+ # NOT inside run_sync's executor worker. This avoids a cross-scope
+ # NameError: the outer interrupt / finalisation paths reference the
+ # consumer via ``streaming_tts_consumer_holder[0]``.
+ #
+ # Gates: voice input, auto-TTS enabled for this chat, adapter
+ # supports streaming, and a usable streaming TTS provider configured.
+ _stts_adapter = self._adapter_for_source(source)
+ _is_voice_input = (
+ message_type is not None
+ and str(getattr(message_type, "value", message_type)).lower() == "voice"
+ )
+ if (
+ _stts_adapter is not None
+ and _is_voice_input
+ and _stts_adapter._should_auto_tts_for_chat(source.chat_id)
+ ):
+ try:
+ from gateway.streaming_tts_consumer import StreamingTTSConsumer
+ from tools.tts_tool import _load_tts_config
+ _tts_cfg = _load_tts_config()
+ _gateway_loop = self._gateway_loop or asyncio.get_event_loop()
+ _stts_consumer = StreamingTTSConsumer(
+ adapter=_stts_adapter,
+ chat_id=source.chat_id,
+ tts_config=_tts_cfg,
+ loop=_gateway_loop,
+ metadata=_status_thread_metadata,
+ )
+ if _stts_consumer.active:
+ streaming_tts_consumer_holder[0] = _stts_consumer
+ _stts_consumer.start()
+ # else: consumer inactive (no streaming provider) — leave
+ # the holder as None so the whole-file fallback path runs.
+ except Exception as _stts_err:
+ logger.debug("Could not set up streaming TTS consumer: %s", _stts_err)
- return {
- "final_response": final_response,
- "last_reasoning": result.get("last_reasoning"),
- "messages": result_holder[0].get("messages", []) if result_holder[0] else [],
- "api_calls": result_holder[0].get("api_calls", 0) if result_holder[0] else 0,
- "failed": result_holder[0].get("failed", False) if result_holder[0] else False,
- "failure_reason": (
- result_holder[0].get("failure_reason") if result_holder[0] else None
- ),
- "completed": result_holder[0].get("completed") if result_holder[0] else None,
- "interrupted": result_holder[0].get("interrupted", False) if result_holder[0] else False,
- "partial": result_holder[0].get("partial", False) if result_holder[0] else False,
- "error": result_holder[0].get("error") if result_holder[0] else None,
- "interrupt_message": result_holder[0].get("interrupt_message") if result_holder[0] else None,
- # Soft lock-contention defer (#69870 consumer): distinct from
- # compression_exhausted so the gateway never auto-resets a
- # session that a concurrent compressor is about to shrink.
- "compression_deferred": (
- result_holder[0].get("compression_deferred", False)
- if result_holder[0] else False
- ),
- "tools": tools_holder[0] or [],
- "history_offset": _effective_history_offset,
- "compacted_in_place": _compacted_in_place,
- "last_prompt_tokens": _last_prompt_toks,
- "input_tokens": _input_toks,
- "output_tokens": _output_toks,
- "model": _resolved_model,
- "context_length": _context_length,
- "session_id": effective_session_id,
- "response_previewed": result.get("response_previewed", False),
- "response_transformed": result.get("response_transformed", False),
- # Pass through the agent_persisted flag so the persistence block
- # above can correctly determine whether the codex app-server path
- # self-persisted (it didn't — see codex_runtime.py). Default
- # True preserves the skip-db behaviour for the standard runtime.
- "agent_persisted": (result_holder[0].get("agent_persisted", True) if result_holder[0] else True),
- }
+ # run_sync extracted to TurnRunner.run_sync (bound method; the
+ # executor call below is unchanged). Its closed-over locals travel
+ # on turn_ctx; `nonlocal message` rebinds became ctx.message writes.
+ run_sync = turn_runner.run_sync
# Start progress message sender if enabled. Gate on needs_progress_queue
# (tool_progress OR thinking_progress), not tool_progress alone: the
diff --git a/gateway/turn_context.py b/gateway/turn_context.py
index 8739ee7e487..03a6d404c16 100644
--- a/gateway/turn_context.py
+++ b/gateway/turn_context.py
@@ -64,3 +64,66 @@ class TurnContext:
# send_progress_messages is scheduled) ----------------------------
_progress_metadata: Optional[dict] = None
_progress_reply_to: Optional[Any] = None
+
+ # ------------------------------------------------------------------
+ # run_sync extraction (second wave of the seam): the closed-over locals
+ # of ``_run_agent_inner`` that ``run_sync`` (and the four sibling bridge
+ # callbacks) captured. Same rules as above: read-only snapshots or
+ # shared mutable containers; ``message`` is the ONE exception — the old
+ # closure rebound it via ``nonlocal``, so the rebind sites now write
+ # ``ctx.message`` and the outer body reads ``ctx.message`` afterwards.
+ # ------------------------------------------------------------------
+
+ # --- the ex-``nonlocal`` turn message (rebindable) --------------------
+ message: Optional[str] = None
+
+ # --- turn parameters / config snapshots (read-only in run_sync) -------
+ history: Any = None
+ context_prompt: Optional[str] = None
+ channel_prompt: Optional[str] = None
+ session_id: Optional[str] = None
+ session_key: Optional[str] = None
+ run_generation: Optional[int] = None
+ _interrupt_depth: int = 0
+ event_message_id: Optional[str] = None
+ moa_config: Optional[dict] = None
+ persist_user_message: Optional[Any] = None
+ persist_user_timestamp: Optional[float] = None
+ user_config: Any = None
+ enabled_toolsets: Any = None
+ disabled_toolsets: Any = None
+ log_mode_enabled: bool = False
+ interim_assistant_messages_enabled: bool = False
+ needs_progress_queue: bool = False
+
+ # --- lazy-imported callables captured from the outer body -------------
+ AIAgent: Any = None
+ resolve_display_setting: Any = None
+
+ # --- mutable holder cells (shared-list pattern; outer body + the
+ # post-executor closures read mutations through the same objects) --
+ result_holder: list = field(default_factory=lambda: [None])
+ tools_holder: list = field(default_factory=lambda: [None])
+ stream_consumer_holder: list = field(default_factory=lambda: [None])
+ streaming_tts_consumer_holder: list = field(default_factory=lambda: [None])
+
+ # --- voice-ack wiring --------------------------------------------------
+ _voice_ack_fired: list = field(default_factory=lambda: [False])
+ _voice_ack_guild: list = field(default_factory=lambda: [None])
+ _voice_ack_loop: Any = None
+
+ # --- hook / status bridge wiring (published at original binding sites) -
+ _loop_for_step: Any = None
+ _hooks_ref: Any = None
+ _status_adapter: Any = None
+ _status_chat_id: Any = None
+ _status_thread_metadata: Optional[dict] = None
+
+ # --- extracted sibling callbacks (bound TurnRunner methods; run_sync
+ # reads them through the ctx exactly where it used to close over
+ # the sibling closures) ---------------------------------------------
+ progress_callback: Optional[Callable] = None
+ voice_ack_callback: Optional[Callable] = None
+ _step_callback_sync: Optional[Callable] = None
+ _event_callback_sync: Optional[Callable] = None
+ _status_callback_sync: Optional[Callable] = None
diff --git a/tests/gateway/test_fallback_chain_reload.py b/tests/gateway/test_fallback_chain_reload.py
index cd5f915c92a..431b100cfa7 100644
--- a/tests/gateway/test_fallback_chain_reload.py
+++ b/tests/gateway/test_fallback_chain_reload.py
@@ -80,13 +80,23 @@ def test_background_and_main_agent_paths_call_refresh():
source = (
Path(__file__).resolve().parent.parent.parent / "gateway" / "run.py"
).read_text(encoding="utf-8")
- assert "fallback_model=self._refresh_fallback_model()" in source
- assert source.count("fallback_model=self._refresh_fallback_model()") >= 2
+ # The agent-construction site inside TurnRunner.run_sync (extracted from
+ # the old _run_agent_inner closure) references the runner as
+ # ``self._runner``; the background-agent site still uses bare ``self``.
+ _refresh_calls = (
+ source.count("fallback_model=self._refresh_fallback_model()")
+ + source.count("fallback_model=self._runner._refresh_fallback_model()")
+ )
+ assert _refresh_calls >= 2
# The cached-agent reuse path (the load-bearing fix for a long-lived
# session in a running gateway) must apply the refreshed chain.
- assert "self._apply_fallback_chain_to_agent(" in source
+ assert (
+ "self._apply_fallback_chain_to_agent(" in source
+ or "self._runner._apply_fallback_chain_to_agent(" in source
+ )
# The stale startup-snapshot form must not remain at create sites.
assert "fallback_model=self._fallback_model," not in source
+ assert "fallback_model=self._runner._fallback_model," not in source
def test_load_fallback_model_static_unchanged_contract(tmp_path, monkeypatch):